blob: c9bc761fc29e29605db24c806918d11ebfa5f9a9 [file] [log] [blame]
Bence Békybac04052022-04-07 15:44:29 -04001// 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 "quiche/quic/core/quic_connection.h"
6
7#include <errno.h>
8
QUICHE teamad0dbe62024-05-21 11:27:01 -07009#include <algorithm>
martindukef33b1da2023-01-12 14:14:29 -080010#include <cstdint>
Bence Békybac04052022-04-07 15:44:29 -040011#include <memory>
QUICHE teamad0dbe62024-05-21 11:27:01 -070012#include <optional>
Bence Békybac04052022-04-07 15:44:29 -040013#include <string>
14#include <utility>
QUICHE teamad0dbe62024-05-21 11:27:01 -070015#include <vector>
Bence Békybac04052022-04-07 15:44:29 -040016
17#include "absl/base/macros.h"
18#include "absl/strings/str_cat.h"
19#include "absl/strings/str_join.h"
20#include "absl/strings/string_view.h"
21#include "quiche/quic/core/congestion_control/loss_detection_interface.h"
22#include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
23#include "quiche/quic/core/crypto/null_decrypter.h"
24#include "quiche/quic/core/crypto/null_encrypter.h"
25#include "quiche/quic/core/crypto/quic_decrypter.h"
Bence Békybac04052022-04-07 15:44:29 -040026#include "quiche/quic/core/frames/quic_connection_close_frame.h"
27#include "quiche/quic/core/frames/quic_new_connection_id_frame.h"
28#include "quiche/quic/core/frames/quic_path_response_frame.h"
martinduke15c43d02024-09-26 14:00:37 -070029#include "quiche/quic/core/frames/quic_reset_stream_at_frame.h"
Bence Békybac04052022-04-07 15:44:29 -040030#include "quiche/quic/core/frames/quic_rst_stream_frame.h"
31#include "quiche/quic/core/quic_connection_id.h"
32#include "quiche/quic/core/quic_constants.h"
33#include "quiche/quic/core/quic_error_codes.h"
34#include "quiche/quic/core/quic_packet_creator.h"
35#include "quiche/quic/core/quic_packets.h"
36#include "quiche/quic/core/quic_path_validator.h"
37#include "quiche/quic/core/quic_types.h"
38#include "quiche/quic/core/quic_utils.h"
39#include "quiche/quic/core/quic_versions.h"
40#include "quiche/quic/platform/api/quic_expect_bug.h"
41#include "quiche/quic/platform/api/quic_flags.h"
42#include "quiche/quic/platform/api/quic_ip_address.h"
bnc96dc1782022-09-06 08:16:01 -070043#include "quiche/quic/platform/api/quic_ip_address_family.h"
Bence Békybac04052022-04-07 15:44:29 -040044#include "quiche/quic/platform/api/quic_logging.h"
45#include "quiche/quic/platform/api/quic_socket_address.h"
46#include "quiche/quic/platform/api/quic_test.h"
47#include "quiche/quic/test_tools/mock_clock.h"
martinduke605dca22022-09-01 10:40:19 -070048#include "quiche/quic/test_tools/mock_connection_id_generator.h"
Bence Békybac04052022-04-07 15:44:29 -040049#include "quiche/quic/test_tools/mock_random.h"
50#include "quiche/quic/test_tools/quic_coalesced_packet_peer.h"
51#include "quiche/quic/test_tools/quic_config_peer.h"
52#include "quiche/quic/test_tools/quic_connection_peer.h"
53#include "quiche/quic/test_tools/quic_framer_peer.h"
54#include "quiche/quic/test_tools/quic_packet_creator_peer.h"
55#include "quiche/quic/test_tools/quic_path_validator_peer.h"
56#include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h"
57#include "quiche/quic/test_tools/quic_test_utils.h"
58#include "quiche/quic/test_tools/simple_data_producer.h"
59#include "quiche/quic/test_tools/simple_session_notifier.h"
Bence Békybac04052022-04-07 15:44:29 -040060#include "quiche/common/simple_buffer_allocator.h"
61
62using testing::_;
63using testing::AnyNumber;
64using testing::AtLeast;
65using testing::DoAll;
awillia202240c2024-07-08 09:47:00 -070066using testing::DoDefault;
Bence Békybac04052022-04-07 15:44:29 -040067using testing::ElementsAre;
68using testing::Ge;
69using testing::IgnoreResult;
70using testing::InSequence;
71using testing::Invoke;
72using testing::InvokeWithoutArgs;
73using testing::Lt;
74using testing::Ref;
75using testing::Return;
76using testing::SaveArg;
77using testing::SetArgPointee;
78using testing::StrictMock;
79
80namespace quic {
81namespace test {
82namespace {
83
84const char data1[] = "foo data";
85const char data2[] = "bar data";
86
87const bool kHasStopWaiting = true;
88
89const int kDefaultRetransmissionTimeMs = 500;
90
91DiversificationNonce kTestDiversificationNonce = {
92 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
93 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
94 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
95};
96
97const StatelessResetToken kTestStatelessResetToken{
98 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
99 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f};
100
101const QuicSocketAddress kPeerAddress =
102 QuicSocketAddress(QuicIpAddress::Loopback6(),
103 /*port=*/12345);
104const QuicSocketAddress kSelfAddress =
105 QuicSocketAddress(QuicIpAddress::Loopback6(),
106 /*port=*/443);
danzh8fdee2e2023-01-05 15:33:02 -0800107const QuicSocketAddress kServerPreferredAddress = QuicSocketAddress(
108 []() {
109 QuicIpAddress address;
110 address.FromString("2604:31c0::");
111 return address;
112 }(),
113 /*port=*/443);
Bence Békybac04052022-04-07 15:44:29 -0400114
115QuicStreamId GetNthClientInitiatedStreamId(int n,
116 QuicTransportVersion version) {
117 return QuicUtils::GetFirstBidirectionalStreamId(version,
118 Perspective::IS_CLIENT) +
119 n * 2;
120}
121
122QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
123 switch (level) {
124 case ENCRYPTION_INITIAL:
125 return INITIAL;
126 case ENCRYPTION_HANDSHAKE:
127 return HANDSHAKE;
128 case ENCRYPTION_ZERO_RTT:
129 return ZERO_RTT_PROTECTED;
130 case ENCRYPTION_FORWARD_SECURE:
131 QUICHE_DCHECK(false);
132 return INVALID_PACKET_TYPE;
133 default:
134 QUICHE_DCHECK(false);
135 return INVALID_PACKET_TYPE;
136 }
137}
138
martinduke9e0811c2022-12-08 20:35:57 -0800139// A TaggingEncrypterWithConfidentialityLimit is a TaggingEncrypter that allows
Bence Békybac04052022-04-07 15:44:29 -0400140// specifying the confidentiality limit on the maximum number of packets that
141// may be encrypted per key phase in TLS+QUIC.
martinduke9e0811c2022-12-08 20:35:57 -0800142class TaggingEncrypterWithConfidentialityLimit : public TaggingEncrypter {
Bence Békybac04052022-04-07 15:44:29 -0400143 public:
martinduke9e0811c2022-12-08 20:35:57 -0800144 TaggingEncrypterWithConfidentialityLimit(
145 uint8_t tag, QuicPacketCount confidentiality_limit)
146 : TaggingEncrypter(tag), confidentiality_limit_(confidentiality_limit) {}
Bence Békybac04052022-04-07 15:44:29 -0400147
148 QuicPacketCount GetConfidentialityLimit() const override {
149 return confidentiality_limit_;
150 }
151
152 private:
153 QuicPacketCount confidentiality_limit_;
154};
155
156class StrictTaggingDecrypterWithIntegrityLimit : public StrictTaggingDecrypter {
157 public:
158 StrictTaggingDecrypterWithIntegrityLimit(uint8_t tag,
159 QuicPacketCount integrity_limit)
160 : StrictTaggingDecrypter(tag), integrity_limit_(integrity_limit) {}
161
162 QuicPacketCount GetIntegrityLimit() const override {
163 return integrity_limit_;
164 }
165
166 private:
167 QuicPacketCount integrity_limit_;
168};
169
170class TestConnectionHelper : public QuicConnectionHelperInterface {
171 public:
172 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
173 : clock_(clock), random_generator_(random_generator) {
174 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
175 }
176 TestConnectionHelper(const TestConnectionHelper&) = delete;
177 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
178
179 // QuicConnectionHelperInterface
180 const QuicClock* GetClock() const override { return clock_; }
181
182 QuicRandom* GetRandomGenerator() override { return random_generator_; }
183
184 quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override {
185 return &buffer_allocator_;
186 }
187
188 private:
189 MockClock* clock_;
190 MockRandom* random_generator_;
191 quiche::SimpleBufferAllocator buffer_allocator_;
192};
193
194class TestConnection : public QuicConnection {
195 public:
196 TestConnection(QuicConnectionId connection_id,
197 QuicSocketAddress initial_self_address,
198 QuicSocketAddress initial_peer_address,
199 TestConnectionHelper* helper, TestAlarmFactory* alarm_factory,
200 TestPacketWriter* writer, Perspective perspective,
martinduke605dca22022-09-01 10:40:19 -0700201 ParsedQuicVersion version,
202 ConnectionIdGeneratorInterface& generator)
Bence Békybac04052022-04-07 15:44:29 -0400203 : QuicConnection(connection_id, initial_self_address,
204 initial_peer_address, helper, alarm_factory, writer,
205 /* owns_writer= */ false, perspective,
martinduke605dca22022-09-01 10:40:19 -0700206 SupportedVersions(version), generator),
Bence Békybac04052022-04-07 15:44:29 -0400207 notifier_(nullptr) {
208 writer->set_perspective(perspective);
209 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800210 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -0400211 SetDataProducer(&producer_);
212 ON_CALL(*this, OnSerializedPacket(_))
213 .WillByDefault([this](SerializedPacket packet) {
214 QuicConnection::OnSerializedPacket(std::move(packet));
215 });
216 }
217 TestConnection(const TestConnection&) = delete;
218 TestConnection& operator=(const TestConnection&) = delete;
219
220 MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket packet), (override));
221
renjietangff3e9602022-10-25 12:16:49 -0700222 void OnEffectivePeerMigrationValidated(bool is_migration_linkable) override {
223 QuicConnection::OnEffectivePeerMigrationValidated(is_migration_linkable);
224 if (is_migration_linkable) {
225 num_linkable_client_migration_++;
226 } else {
227 num_unlinkable_client_migration_++;
228 }
229 }
230
231 uint32_t num_unlinkable_client_migration() const {
232 return num_unlinkable_client_migration_;
233 }
234
235 uint32_t num_linkable_client_migration() const {
236 return num_linkable_client_migration_;
237 }
238
Bence Békybac04052022-04-07 15:44:29 -0400239 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
240 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
241 }
242
243 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
244 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
245 }
246
247 void SendPacket(EncryptionLevel /*level*/, uint64_t packet_number,
248 std::unique_ptr<QuicPacket> packet,
249 HasRetransmittableData retransmittable, bool has_ack,
250 bool has_pending_frames) {
251 ScopedPacketFlusher flusher(this);
252 char buffer[kMaxOutgoingPacketSize];
253 size_t encrypted_length =
254 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
255 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
256 buffer, kMaxOutgoingPacketSize);
257 SerializedPacket serialized_packet(
258 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
259 encrypted_length, has_ack, has_pending_frames);
260 serialized_packet.peer_address = kPeerAddress;
261 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
262 serialized_packet.retransmittable_frames.push_back(
263 QuicFrame(QuicPingFrame()));
264 }
265 OnSerializedPacket(std::move(serialized_packet));
266 }
267
268 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
269 absl::string_view data,
270 QuicStreamOffset offset,
271 StreamSendingState state) {
QUICHE teamac0a8082022-06-13 09:17:05 -0700272 return SaveAndSendStreamData(id, data, offset, state, NOT_RETRANSMISSION);
273 }
274
275 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
276 absl::string_view data,
277 QuicStreamOffset offset,
278 StreamSendingState state,
279 TransmissionType transmission_type) {
Bence Békybac04052022-04-07 15:44:29 -0400280 ScopedPacketFlusher flusher(this);
281 producer_.SaveStreamData(id, data);
282 if (notifier_ != nullptr) {
QUICHE teamac0a8082022-06-13 09:17:05 -0700283 return notifier_->WriteOrBufferData(id, data.length(), state,
284 transmission_type);
Bence Békybac04052022-04-07 15:44:29 -0400285 }
286 return QuicConnection::SendStreamData(id, data.length(), offset, state);
287 }
288
289 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
290 absl::string_view data,
291 QuicStreamOffset offset,
292 StreamSendingState state) {
293 ScopedPacketFlusher flusher(this);
294 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
295 this->encryption_level() == ENCRYPTION_INITIAL) {
296 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
297 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
298 OnHandshakeComplete();
299 }
300 if (version().SupportsAntiAmplificationLimit()) {
301 QuicConnectionPeer::SetAddressValidated(this);
302 }
303 }
304 return SaveAndSendStreamData(id, data, offset, state);
305 }
306
307 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
308 QuicStreamId id,
309 absl::string_view data,
310 QuicStreamOffset offset,
311 StreamSendingState state) {
312 ScopedPacketFlusher flusher(this);
313 QUICHE_DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -0800314 SetEncrypter(encryption_level,
315 std::make_unique<TaggingEncrypter>(encryption_level));
Bence Békybac04052022-04-07 15:44:29 -0400316 SetDefaultEncryptionLevel(encryption_level);
317 return SaveAndSendStreamData(id, data, offset, state);
318 }
319
320 QuicConsumedData SendStreamData3() {
321 return SendStreamDataWithString(
322 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
323 NO_FIN);
324 }
325
326 QuicConsumedData SendStreamData5() {
327 return SendStreamDataWithString(
328 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
329 NO_FIN);
330 }
331
332 // Ensures the connection can write stream data before writing.
333 QuicConsumedData EnsureWritableAndSendStreamData5() {
334 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
335 return SendStreamData5();
336 }
337
338 // The crypto stream has special semantics so that it is not blocked by a
339 // congestion window limitation, and also so that it gets put into a separate
340 // packet (so that it is easier to reason about a crypto frame not being
341 // split needlessly across packet boundaries). As a result, we have separate
342 // tests for some cases for this stream.
343 QuicConsumedData SendCryptoStreamData() {
dschinazi54f21232024-12-03 13:46:46 -0800344 return SendCryptoStreamDataAtLevel(ENCRYPTION_INITIAL);
345 }
346
347 QuicConsumedData SendCryptoStreamDataAtLevel(
348 EncryptionLevel encryption_level) {
Bence Békybac04052022-04-07 15:44:29 -0400349 QuicStreamOffset offset = 0;
350 absl::string_view data("chlo");
351 if (!QuicVersionUsesCryptoFrames(transport_version())) {
352 return SendCryptoDataWithString(data, offset);
353 }
dschinazi54f21232024-12-03 13:46:46 -0800354 producer_.SaveCryptoData(encryption_level, offset, data);
Bence Békybac04052022-04-07 15:44:29 -0400355 size_t bytes_written;
356 if (notifier_) {
357 bytes_written =
dschinazi54f21232024-12-03 13:46:46 -0800358 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
Bence Békybac04052022-04-07 15:44:29 -0400359 } else {
dschinazi54f21232024-12-03 13:46:46 -0800360 bytes_written = QuicConnection::SendCryptoData(encryption_level,
Bence Békybac04052022-04-07 15:44:29 -0400361 data.length(), offset);
362 }
363 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
364 }
365
366 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
367 QuicStreamOffset offset) {
368 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
369 }
370
371 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
372 QuicStreamOffset offset,
373 EncryptionLevel encryption_level) {
374 if (!QuicVersionUsesCryptoFrames(transport_version())) {
375 return SendStreamDataWithString(
376 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
377 NO_FIN);
378 }
379 producer_.SaveCryptoData(encryption_level, offset, data);
380 size_t bytes_written;
381 if (notifier_) {
382 bytes_written =
383 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
384 } else {
385 bytes_written = QuicConnection::SendCryptoData(encryption_level,
386 data.length(), offset);
387 }
388 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
389 }
390
391 void set_version(ParsedQuicVersion version) {
392 QuicConnectionPeer::GetFramer(this)->set_version(version);
393 }
394
395 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
396 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
397 writer()->SetSupportedVersions(versions);
398 }
399
400 // This should be called before setting customized encrypters/decrypters for
401 // connection and peer creator.
402 void set_perspective(Perspective perspective) {
403 writer()->set_perspective(perspective);
404 QuicConnectionPeer::ResetPeerIssuedConnectionIdManager(this);
405 QuicConnectionPeer::SetPerspective(this, perspective);
406 QuicSentPacketManagerPeer::SetPerspective(
407 QuicConnectionPeer::GetSentPacketManager(this), perspective);
408 QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators(
409 TestConnectionId());
Bence Békybac04052022-04-07 15:44:29 -0400410 }
411
412 // Enable path MTU discovery. Assumes that the test is performed from the
413 // server perspective and the higher value of MTU target is used.
414 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
415 ASSERT_EQ(Perspective::IS_SERVER, perspective());
416
417 if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) {
418 OnConfigNegotiated();
419 } else {
420 QuicConfig config;
421 QuicTagVector connection_options;
422 connection_options.push_back(kMTUH);
423 config.SetInitialReceivedConnectionOptions(connection_options);
424 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -0800425 EXPECT_CALL(*send_algorithm, EnableECT1()).WillOnce(Return(false));
426 EXPECT_CALL(*send_algorithm, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -0400427 SetFromConfig(config);
428 }
429
430 // Normally, the pacing would be disabled in the test, but calling
431 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
432 // pacing algorithm work.
433 EXPECT_CALL(*send_algorithm, PacingRate(_))
434 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
435 }
436
vasilvve16ac6e2024-10-25 14:08:14 -0700437 QuicTestAlarmProxy GetAckAlarm() {
438 return QuicTestAlarmProxy(QuicConnectionPeer::GetAckAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400439 }
440
vasilvve16ac6e2024-10-25 14:08:14 -0700441 QuicTestAlarmProxy GetPingAlarm() {
442 return QuicTestAlarmProxy(QuicConnectionPeer::GetPingAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400443 }
444
vasilvve16ac6e2024-10-25 14:08:14 -0700445 QuicTestAlarmProxy GetRetransmissionAlarm() {
446 return QuicTestAlarmProxy(QuicConnectionPeer::GetRetransmissionAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400447 }
448
vasilvve16ac6e2024-10-25 14:08:14 -0700449 QuicTestAlarmProxy GetSendAlarm() {
450 return QuicTestAlarmProxy(QuicConnectionPeer::GetSendAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400451 }
452
vasilvve16ac6e2024-10-25 14:08:14 -0700453 QuicTestAlarmProxy GetTimeoutAlarm() {
454 return QuicTestAlarmProxy(
455 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400456 }
457
vasilvve16ac6e2024-10-25 14:08:14 -0700458 QuicTestAlarmProxy GetMtuDiscoveryAlarm() {
459 return QuicTestAlarmProxy(QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400460 }
461
vasilvve16ac6e2024-10-25 14:08:14 -0700462 QuicTestAlarmProxy GetProcessUndecryptablePacketsAlarm() {
463 return QuicTestAlarmProxy(
464 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400465 }
466
vasilvve16ac6e2024-10-25 14:08:14 -0700467 QuicTestAlarmProxy GetDiscardPreviousOneRttKeysAlarm() {
468 return QuicTestAlarmProxy(
469 QuicConnectionPeer::GetDiscardPreviousOneRttKeysAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400470 }
471
vasilvve16ac6e2024-10-25 14:08:14 -0700472 QuicTestAlarmProxy GetDiscardZeroRttDecryptionKeysAlarm() {
473 return QuicTestAlarmProxy(
474 QuicConnectionPeer::GetDiscardZeroRttDecryptionKeysAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400475 }
476
vasilvve16ac6e2024-10-25 14:08:14 -0700477 QuicTestAlarmProxy GetBlackholeDetectorAlarm() {
478 return QuicTestAlarmProxy(
479 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400480 }
481
482 TestAlarmFactory::TestAlarm* GetRetirePeerIssuedConnectionIdAlarm() {
483 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
484 QuicConnectionPeer::GetRetirePeerIssuedConnectionIdAlarm(this));
485 }
486
487 TestAlarmFactory::TestAlarm* GetRetireSelfIssuedConnectionIdAlarm() {
488 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
489 QuicConnectionPeer::GetRetireSelfIssuedConnectionIdAlarm(this));
490 }
491
vasilvve16ac6e2024-10-25 14:08:14 -0700492 QuicTestAlarmProxy GetMultiPortProbingAlarm() {
493 return QuicTestAlarmProxy(
494 QuicConnectionPeer::GetMultiPortProbingAlarm(this));
renjietangfca5c772022-08-25 13:48:21 -0700495 }
496
Bence Békybac04052022-04-07 15:44:29 -0400497 void PathDegradingTimeout() {
498 QUICHE_DCHECK(PathDegradingDetectionInProgress());
499 GetBlackholeDetectorAlarm()->Fire();
500 }
501
502 bool PathDegradingDetectionInProgress() {
503 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
504 }
505
506 bool BlackholeDetectionInProgress() {
507 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
508 .IsInitialized();
509 }
510
511 bool PathMtuReductionDetectionInProgress() {
512 return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this)
513 .IsInitialized();
514 }
515
Bence Békybac04052022-04-07 15:44:29 -0400516 QuicByteCount GetBytesInFlight() {
517 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
518 }
519
520 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
521
522 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
523 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
524 }
525
Bence Békybac04052022-04-07 15:44:29 -0400526 void SendOrQueuePacket(SerializedPacket packet) override {
527 QuicConnection::SendOrQueuePacket(std::move(packet));
528 self_address_on_default_path_while_sending_packet_ = self_address();
529 }
530
531 QuicSocketAddress self_address_on_default_path_while_sending_packet() {
532 return self_address_on_default_path_while_sending_packet_;
533 }
534
535 SimpleDataProducer* producer() { return &producer_; }
536
537 using QuicConnection::active_effective_peer_migration_type;
538 using QuicConnection::IsCurrentPacketConnectivityProbing;
539 using QuicConnection::SelectMutualVersion;
Bence Békybac04052022-04-07 15:44:29 -0400540 using QuicConnection::set_defer_send_in_response_to_packets;
541
542 protected:
543 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
544 if (next_effective_peer_addr_) {
545 return *std::move(next_effective_peer_addr_);
546 }
547 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
548 }
549
550 private:
551 TestPacketWriter* writer() {
552 return static_cast<TestPacketWriter*>(QuicConnection::writer());
553 }
554
555 SimpleDataProducer producer_;
556
557 SimpleSessionNotifier* notifier_;
558
559 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
560
561 QuicSocketAddress self_address_on_default_path_while_sending_packet_;
renjietangff3e9602022-10-25 12:16:49 -0700562
563 uint32_t num_unlinkable_client_migration_ = 0;
564
565 uint32_t num_linkable_client_migration_ = 0;
Bence Békybac04052022-04-07 15:44:29 -0400566};
567
568enum class AckResponse { kDefer, kImmediate };
569
570// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
571struct TestParams {
fayangfc04b8a2023-05-18 09:26:25 -0700572 TestParams(ParsedQuicVersion version, AckResponse ack_response)
573 : version(version), ack_response(ack_response) {}
Bence Békybac04052022-04-07 15:44:29 -0400574
575 ParsedQuicVersion version;
576 AckResponse ack_response;
Bence Békybac04052022-04-07 15:44:29 -0400577};
578
579// Used by ::testing::PrintToStringParamName().
580std::string PrintToString(const TestParams& p) {
581 return absl::StrCat(
582 ParsedQuicVersionToString(p.version), "_",
fayangfc04b8a2023-05-18 09:26:25 -0700583 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"));
Bence Békybac04052022-04-07 15:44:29 -0400584}
585
586// Constructs various test permutations.
587std::vector<TestParams> GetTestParams() {
588 QuicFlagSaver flags;
589 std::vector<TestParams> params;
590 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
591 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
592 for (AckResponse ack_response :
593 {AckResponse::kDefer, AckResponse::kImmediate}) {
fayangfc04b8a2023-05-18 09:26:25 -0700594 params.push_back(TestParams(all_supported_versions[i], ack_response));
Bence Békybac04052022-04-07 15:44:29 -0400595 }
596 }
597 return params;
598}
599
600class QuicConnectionTest : public QuicTestWithParam<TestParams> {
601 public:
602 // For tests that do silent connection closes, no such packet is generated. In
603 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
604 // should invoke this method, saving the frame, and then the test can verify
605 // the contents.
606 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
607 ConnectionCloseSource /*source*/) {
608 saved_connection_close_frame_ = frame;
609 connection_close_frame_count_++;
610 }
611
612 protected:
613 QuicConnectionTest()
614 : connection_id_(TestConnectionId()),
615 framer_(SupportedVersions(version()), QuicTime::Zero(),
616 Perspective::IS_CLIENT, connection_id_.length()),
617 send_algorithm_(new StrictMock<MockSendAlgorithm>),
618 loss_algorithm_(new MockLossAlgorithm()),
619 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
620 alarm_factory_(new TestAlarmFactory()),
621 peer_framer_(SupportedVersions(version()), QuicTime::Zero(),
622 Perspective::IS_SERVER, connection_id_.length()),
623 peer_creator_(connection_id_, &peer_framer_,
624 /*delegate=*/nullptr),
625 writer_(
626 new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)),
627 connection_(connection_id_, kSelfAddress, kPeerAddress, helper_.get(),
628 alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT,
martinduke605dca22022-09-01 10:40:19 -0700629 version(), connection_id_generator_),
Bence Békybac04052022-04-07 15:44:29 -0400630 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
631 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
632 frame1_(0, false, 0, absl::string_view(data1)),
633 frame2_(0, false, 3, absl::string_view(data2)),
634 crypto_frame_(ENCRYPTION_INITIAL, 0, absl::string_view(data1)),
635 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
636 connection_id_included_(CONNECTION_ID_PRESENT),
637 notifier_(&connection_),
638 connection_close_frame_count_(0) {
639 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
640 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
641 AckResponse::kDefer);
642 framer_.SetInitialObfuscators(TestConnectionId());
643 connection_.InstallInitialCrypters(TestConnectionId());
644 CrypterPair crypters;
645 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
646 TestConnectionId(), &crypters);
647 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
648 std::move(crypters.encrypter));
649 if (version().KnowsWhichDecrypterToUse()) {
650 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
651 std::move(crypters.decrypter));
652 } else {
653 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
654 std::move(crypters.decrypter));
655 }
656 for (EncryptionLevel level :
657 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
martinduke9e0811c2022-12-08 20:35:57 -0800658 peer_creator_.SetEncrypter(level,
659 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400660 }
661 QuicFramerPeer::SetLastSerializedServerConnectionId(
662 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
663 QuicFramerPeer::SetLastWrittenPacketNumberLength(
664 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
Bence Békybac04052022-04-07 15:44:29 -0400665 QuicStreamId stream_id;
666 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
667 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
668 version().transport_version, Perspective::IS_CLIENT);
669 } else {
670 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
671 }
672 frame1_.stream_id = stream_id;
673 frame2_.stream_id = stream_id;
674 connection_.set_visitor(&visitor_);
675 connection_.SetSessionNotifier(&notifier_);
676 connection_.set_notifier(&notifier_);
677 connection_.SetSendAlgorithm(send_algorithm_);
678 connection_.SetLossAlgorithm(loss_algorithm_.get());
679 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
680 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
681 .Times(AnyNumber());
682 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
683 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
684 .WillRepeatedly(Return(kDefaultTCPMSS));
685 EXPECT_CALL(*send_algorithm_, PacingRate(_))
686 .WillRepeatedly(Return(QuicBandwidth::Zero()));
687 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
688 .Times(AnyNumber())
689 .WillRepeatedly(Return(QuicBandwidth::Zero()));
690 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
691 .Times(AnyNumber());
692 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
693 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
694 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
695 .Times(AnyNumber());
696 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
697 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
698 .Times(AnyNumber());
wubc9fd4292023-08-14 13:00:21 -0700699 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
700 .WillRepeatedly(
701 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
Bence Békybac04052022-04-07 15:44:29 -0400702 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
703 EXPECT_CALL(visitor_, OnCanWrite())
704 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
705 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
706 .WillRepeatedly(Return(false));
707 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
708 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
709 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
wub2e302c82024-07-16 18:21:36 -0700710 EXPECT_CALL(visitor_, MaybeBundleOpportunistically()).Times(AnyNumber());
711 EXPECT_CALL(visitor_, GetFlowControlSendWindowSize(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -0400712 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
713 .Times(testing::AtMost(1));
714 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
715 .WillRepeatedly(Return(QuicTime::Zero()));
716 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
717 .Times(AnyNumber());
718 EXPECT_CALL(visitor_, GetHandshakeState())
719 .WillRepeatedly(Return(HANDSHAKE_START));
720 if (connection_.version().KnowsWhichDecrypterToUse()) {
721 connection_.InstallDecrypter(
722 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800723 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
724 } else {
725 connection_.SetAlternativeDecrypter(
726 ENCRYPTION_FORWARD_SECURE,
727 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE),
728 false);
Bence Békybac04052022-04-07 15:44:29 -0400729 }
730 peer_creator_.SetDefaultPeerAddress(kSelfAddress);
731 }
732
733 QuicConnectionTest(const QuicConnectionTest&) = delete;
734 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
735
736 ParsedQuicVersion version() { return GetParam().version; }
737
Bence Békybac04052022-04-07 15:44:29 -0400738 void SetClientConnectionId(const QuicConnectionId& client_connection_id) {
739 connection_.set_client_connection_id(client_connection_id);
740 writer_->framer()->framer()->SetExpectedClientConnectionIdLength(
741 client_connection_id.length());
742 }
743
744 void SetDecrypter(EncryptionLevel level,
745 std::unique_ptr<QuicDecrypter> decrypter) {
746 if (connection_.version().KnowsWhichDecrypterToUse()) {
747 connection_.InstallDecrypter(level, std::move(decrypter));
748 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800749 connection_.SetAlternativeDecrypter(level, std::move(decrypter), false);
Bence Békybac04052022-04-07 15:44:29 -0400750 }
751 }
752
753 void ProcessPacket(uint64_t number) {
754 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
755 ProcessDataPacket(number);
756 if (connection_.GetSendAlarm()->IsSet()) {
757 connection_.GetSendAlarm()->Fire();
758 }
759 }
760
761 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
762 const QuicSocketAddress& peer_address,
763 const QuicReceivedPacket& packet) {
764 connection_.ProcessUdpPacket(self_address, peer_address, packet);
765 if (connection_.GetSendAlarm()->IsSet()) {
766 connection_.GetSendAlarm()->Fire();
767 }
768 }
769
770 QuicFrame MakeCryptoFrame() const {
771 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
772 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
773 }
774 return QuicFrame(QuicStreamFrame(
775 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
776 0u, absl::string_view()));
777 }
778
779 void ProcessFramePacket(QuicFrame frame) {
780 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress,
781 ENCRYPTION_FORWARD_SECURE);
782 }
783
784 void ProcessFramePacketWithAddresses(QuicFrame frame,
785 QuicSocketAddress self_address,
786 QuicSocketAddress peer_address,
787 EncryptionLevel level) {
788 QuicFrames frames;
789 frames.push_back(QuicFrame(frame));
790 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address,
791 level);
792 }
793
794 std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames,
795 EncryptionLevel level,
796 char* buffer,
797 size_t buffer_len) {
798 QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level));
799 peer_creator_.set_encryption_level(level);
800 QuicPacketCreatorPeer::SetSendVersionInPacket(
801 &peer_creator_,
802 level < ENCRYPTION_FORWARD_SECURE &&
803 connection_.perspective() == Perspective::IS_SERVER);
804
805 SerializedPacket serialized_packet =
806 QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
807 buffer, buffer_len);
808 return std::make_unique<QuicReceivedPacket>(
809 serialized_packet.encrypted_buffer, serialized_packet.encrypted_length,
810 clock_.Now());
811 }
812
813 void ProcessFramesPacketWithAddresses(QuicFrames frames,
814 QuicSocketAddress self_address,
815 QuicSocketAddress peer_address,
816 EncryptionLevel level) {
817 char buffer[kMaxOutgoingPacketSize];
818 connection_.ProcessUdpPacket(
819 self_address, peer_address,
820 *ConstructPacket(std::move(frames), level, buffer,
821 kMaxOutgoingPacketSize));
822 if (connection_.GetSendAlarm()->IsSet()) {
823 connection_.GetSendAlarm()->Fire();
824 }
825 }
826
827 // Bypassing the packet creator is unrealistic, but allows us to process
828 // packets the QuicPacketCreator won't allow us to create.
829 void ForceProcessFramePacket(QuicFrame frame) {
830 QuicFrames frames;
831 frames.push_back(QuicFrame(frame));
832 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
833 if (connection_.version().KnowsWhichDecrypterToUse()) {
834 send_version = true;
835 }
836 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
837 QuicPacketHeader header;
838 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
839 char encrypted_buffer[kMaxOutgoingPacketSize];
840 size_t length = peer_framer_.BuildDataPacket(
841 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
842 ENCRYPTION_INITIAL);
843 QUICHE_DCHECK_GT(length, 0u);
844
845 const size_t encrypted_length = peer_framer_.EncryptInPlace(
846 ENCRYPTION_INITIAL, header.packet_number,
847 GetStartOfEncryptedData(peer_framer_.version().transport_version,
848 header),
849 length, kMaxOutgoingPacketSize, encrypted_buffer);
850 QUICHE_DCHECK_GT(encrypted_length, 0u);
851
852 connection_.ProcessUdpPacket(
853 kSelfAddress, kPeerAddress,
854 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
855 }
856
857 size_t ProcessFramePacketAtLevel(uint64_t number, QuicFrame frame,
858 EncryptionLevel level) {
martindukef33b1da2023-01-12 14:14:29 -0800859 return ProcessFramePacketAtLevelWithEcn(number, frame, level, ECN_NOT_ECT);
Bence Békybac04052022-04-07 15:44:29 -0400860 }
861
martindukef33b1da2023-01-12 14:14:29 -0800862 size_t ProcessFramePacketAtLevelWithEcn(uint64_t number, QuicFrame frame,
863 EncryptionLevel level,
864 QuicEcnCodepoint ecn_codepoint) {
865 QuicFrames frames;
866 frames.push_back(frame);
867 return ProcessFramesPacketAtLevelWithEcn(number, frames, level,
868 ecn_codepoint);
869 }
870
871 size_t ProcessFramesPacketAtLevel(uint64_t number, QuicFrames frames,
Bence Békybac04052022-04-07 15:44:29 -0400872 EncryptionLevel level) {
martindukef33b1da2023-01-12 14:14:29 -0800873 return ProcessFramesPacketAtLevelWithEcn(number, frames, level,
874 ECN_NOT_ECT);
875 }
876
877 size_t ProcessFramesPacketAtLevelWithEcn(uint64_t number,
878 const QuicFrames& frames,
879 EncryptionLevel level,
880 QuicEcnCodepoint ecn_codepoint) {
Bence Békybac04052022-04-07 15:44:29 -0400881 QuicPacketHeader header = ConstructPacketHeader(number, level);
882 // Set the correct encryption level and encrypter on peer_creator and
883 // peer_framer, respectively.
884 peer_creator_.set_encryption_level(level);
martinduke9e0811c2022-12-08 20:35:57 -0800885 if (level > ENCRYPTION_INITIAL) {
886 peer_framer_.SetEncrypter(level,
887 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400888 // Set the corresponding decrypter.
889 if (connection_.version().KnowsWhichDecrypterToUse()) {
890 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800891 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400892 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800893 connection_.SetAlternativeDecrypter(
894 level, std::make_unique<StrictTaggingDecrypter>(level), false);
Bence Békybac04052022-04-07 15:44:29 -0400895 }
896 }
897 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
898
899 char buffer[kMaxOutgoingPacketSize];
900 size_t encrypted_length =
901 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
902 buffer, kMaxOutgoingPacketSize);
903 connection_.ProcessUdpPacket(
904 kSelfAddress, kPeerAddress,
martindukef33b1da2023-01-12 14:14:29 -0800905 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false, 0,
906 true, nullptr, 0, false, ecn_codepoint));
Bence Békybac04052022-04-07 15:44:29 -0400907 if (connection_.GetSendAlarm()->IsSet()) {
908 connection_.GetSendAlarm()->Fire();
909 }
910 return encrypted_length;
911 }
912
913 struct PacketInfo {
914 PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level)
915 : packet_number(packet_number), frames(frames), level(level) {}
916
917 uint64_t packet_number;
918 QuicFrames frames;
919 EncryptionLevel level;
920 };
921
922 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) {
martindukef33b1da2023-01-12 14:14:29 -0800923 return ProcessCoalescedPacket(packets, ECN_NOT_ECT);
924 }
925
926 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets,
927 QuicEcnCodepoint ecn_codepoint) {
Bence Békybac04052022-04-07 15:44:29 -0400928 char coalesced_buffer[kMaxOutgoingPacketSize];
929 size_t coalesced_size = 0;
930 bool contains_initial = false;
931 for (const auto& packet : packets) {
932 QuicPacketHeader header =
933 ConstructPacketHeader(packet.packet_number, packet.level);
934 // Set the correct encryption level and encrypter on peer_creator and
935 // peer_framer, respectively.
936 peer_creator_.set_encryption_level(packet.level);
937 if (packet.level == ENCRYPTION_INITIAL) {
938 contains_initial = true;
939 }
martinduke9e0811c2022-12-08 20:35:57 -0800940 EncryptionLevel level =
941 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_);
942 if (level > ENCRYPTION_INITIAL) {
943 peer_framer_.SetEncrypter(level,
944 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400945 // Set the corresponding decrypter.
946 if (connection_.version().KnowsWhichDecrypterToUse()) {
947 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800948 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400949 } else {
950 connection_.SetDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800951 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400952 }
953 }
954 std::unique_ptr<QuicPacket> constructed_packet(
955 ConstructPacket(header, packet.frames));
956
957 char buffer[kMaxOutgoingPacketSize];
958 size_t encrypted_length = peer_framer_.EncryptPayload(
959 packet.level, QuicPacketNumber(packet.packet_number),
960 *constructed_packet, buffer, kMaxOutgoingPacketSize);
961 QUICHE_DCHECK_LE(coalesced_size + encrypted_length,
962 kMaxOutgoingPacketSize);
963 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
964 coalesced_size += encrypted_length;
965 }
966 if (contains_initial) {
967 // Padded coalesced packet to full if it contains initial packet.
968 memset(coalesced_buffer + coalesced_size, '0',
969 kMaxOutgoingPacketSize - coalesced_size);
970 }
971 connection_.ProcessUdpPacket(
972 kSelfAddress, kPeerAddress,
973 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(),
martindukef33b1da2023-01-12 14:14:29 -0800974 false, 0, true, nullptr, 0, false, ecn_codepoint));
Bence Békybac04052022-04-07 15:44:29 -0400975 if (connection_.GetSendAlarm()->IsSet()) {
976 connection_.GetSendAlarm()->Fire();
977 }
978 return coalesced_size;
979 }
980
981 size_t ProcessDataPacket(uint64_t number) {
982 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
983 }
984
985 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
986 return ProcessDataPacketAtLevel(packet_number, false,
987 ENCRYPTION_FORWARD_SECURE);
988 }
989
990 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
991 bool has_stop_waiting,
992 EncryptionLevel level) {
993 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
994 level);
995 }
996
rch92b45f72024-10-16 11:04:51 -0700997 size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting,
998 EncryptionLevel level) {
999 return ProcessDataPacketAtLevel(number, has_stop_waiting, level, 0);
1000 }
1001
Bence Békybac04052022-04-07 15:44:29 -04001002 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
1003 QuicPacketHeader header = ConstructPacketHeader(number, level);
1004 QuicFrames frames;
1005 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1006 frames.push_back(QuicFrame(&crypto_frame_));
1007 } else {
1008 frames.push_back(QuicFrame(frame1_));
1009 }
1010 if (level == ENCRYPTION_INITIAL) {
1011 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
1012 }
1013 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1014 char buffer[kMaxOutgoingPacketSize];
1015 peer_creator_.set_encryption_level(level);
1016 size_t encrypted_length =
1017 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1018 buffer, kMaxOutgoingPacketSize);
1019 connection_.ProcessUdpPacket(
1020 kSelfAddress, kPeerAddress,
1021 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1022 if (connection_.GetSendAlarm()->IsSet()) {
1023 connection_.GetSendAlarm()->Fire();
1024 }
1025 return encrypted_length;
1026 }
1027
1028 size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting,
rch92b45f72024-10-16 11:04:51 -07001029 EncryptionLevel level, uint32_t flow_label) {
Bence Békybac04052022-04-07 15:44:29 -04001030 std::unique_ptr<QuicPacket> packet(
1031 ConstructDataPacket(number, has_stop_waiting, level));
1032 char buffer[kMaxOutgoingPacketSize];
1033 peer_creator_.set_encryption_level(level);
1034 size_t encrypted_length =
1035 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1036 buffer, kMaxOutgoingPacketSize);
1037 connection_.ProcessUdpPacket(
1038 kSelfAddress, kPeerAddress,
rch92b45f72024-10-16 11:04:51 -07001039 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false,
1040 0 /* ttl */, true /* ttl_valid */,
1041 nullptr /* packet_headers */, 0 /* headers_length */,
1042 false /* owns_header_buffer */, ECN_NOT_ECT,
1043 flow_label));
1044
Bence Békybac04052022-04-07 15:44:29 -04001045 if (connection_.GetSendAlarm()->IsSet()) {
1046 connection_.GetSendAlarm()->Fire();
1047 }
1048 return encrypted_length;
1049 }
1050
1051 void ProcessClosePacket(uint64_t number) {
1052 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
1053 char buffer[kMaxOutgoingPacketSize];
1054 size_t encrypted_length = peer_framer_.EncryptPayload(
1055 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
1056 kMaxOutgoingPacketSize);
1057 connection_.ProcessUdpPacket(
1058 kSelfAddress, kPeerAddress,
1059 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1060 }
1061
1062 QuicByteCount SendStreamDataToPeer(QuicStreamId id, absl::string_view data,
1063 QuicStreamOffset offset,
1064 StreamSendingState state,
1065 QuicPacketNumber* last_packet) {
QUICHE team24a23852022-10-31 18:03:52 -07001066 QuicByteCount packet_size = 0;
Bence Békybac04052022-04-07 15:44:29 -04001067 // Save the last packet's size.
1068 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1069 .Times(AnyNumber())
1070 .WillRepeatedly(SaveArg<3>(&packet_size));
1071 connection_.SendStreamDataWithString(id, data, offset, state);
1072 if (last_packet != nullptr) {
1073 *last_packet = creator_->packet_number();
1074 }
1075 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1076 .Times(AnyNumber());
1077 return packet_size;
1078 }
1079
1080 void SendAckPacketToPeer() {
1081 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1082 {
1083 QuicConnection::ScopedPacketFlusher flusher(&connection_);
1084 connection_.SendAck();
1085 }
1086 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1087 .Times(AnyNumber());
1088 }
1089
1090 void SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error,
1091 QuicStreamOffset bytes_written) {
1092 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1093 connection_.OnStreamReset(id, error);
1094 }
1095
1096 void SendPing() { notifier_.WriteOrBufferPing(); }
1097
1098 MessageStatus SendMessage(absl::string_view message) {
1099 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1100 quiche::QuicheMemSlice slice(quiche::QuicheBuffer::Copy(
1101 connection_.helper()->GetStreamSendBufferAllocator(), message));
1102 return connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false);
1103 }
1104
1105 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1106 if (packet_number > 1) {
1107 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1108 } else {
1109 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1110 }
1111 ProcessFramePacket(QuicFrame(frame));
1112 }
1113
1114 void ProcessAckPacket(QuicAckFrame* frame) {
1115 ProcessFramePacket(QuicFrame(frame));
1116 }
1117
1118 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1119 ProcessFramePacket(QuicFrame(frame));
1120 }
1121
1122 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1123 QuicStopWaitingFrame frame,
1124 EncryptionLevel /*level*/) {
1125 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1126 ENCRYPTION_ZERO_RTT);
1127 }
1128
1129 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1130 ProcessFramePacket(QuicFrame(frame));
1131 }
1132
1133 bool IsMissing(uint64_t number) {
1134 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
1135 QuicPacketNumber());
1136 }
1137
1138 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1139 const QuicFrames& frames) {
1140 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1141 EXPECT_NE(nullptr, packet.get());
1142 return packet;
1143 }
1144
1145 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1146 EncryptionLevel level) {
1147 QuicPacketHeader header;
fayangfc04b8a2023-05-18 09:26:25 -07001148 if (level < ENCRYPTION_FORWARD_SECURE) {
Bence Békybac04052022-04-07 15:44:29 -04001149 // Set long header type accordingly.
1150 header.version_flag = true;
1151 header.form = IETF_QUIC_LONG_HEADER_PACKET;
1152 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1153 if (QuicVersionHasLongHeaderLengths(
1154 peer_framer_.version().transport_version)) {
dschinazi35c0ff72022-08-16 12:10:06 -07001155 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04001156 if (header.long_packet_type == INITIAL) {
dschinazi35c0ff72022-08-16 12:10:06 -07001157 header.retry_token_length_length =
1158 quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
Bence Békybac04052022-04-07 15:44:29 -04001159 }
1160 }
1161 }
1162 // Set connection_id to peer's in memory representation as this data packet
1163 // is created by peer_framer.
1164 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1165 header.source_connection_id = connection_id_;
1166 header.source_connection_id_included = connection_id_included_;
1167 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1168 } else {
1169 header.destination_connection_id = connection_id_;
1170 header.destination_connection_id_included = connection_id_included_;
1171 }
fayangfc04b8a2023-05-18 09:26:25 -07001172 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
Bence Békybac04052022-04-07 15:44:29 -04001173 if (!connection_.client_connection_id().IsEmpty()) {
1174 header.destination_connection_id = connection_.client_connection_id();
1175 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
1176 } else {
1177 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1178 }
1179 if (header.version_flag) {
1180 header.source_connection_id = connection_id_;
1181 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1182 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1183 header.long_packet_type == ZERO_RTT_PROTECTED) {
1184 header.nonce = &kTestDiversificationNonce;
1185 }
1186 }
1187 }
1188 header.packet_number_length = packet_number_length_;
1189 header.packet_number = QuicPacketNumber(number);
1190 return header;
1191 }
1192
1193 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1194 bool has_stop_waiting,
1195 EncryptionLevel level) {
1196 QuicPacketHeader header = ConstructPacketHeader(number, level);
1197 QuicFrames frames;
1198 if (VersionHasIetfQuicFrames(version().transport_version) &&
1199 (level == ENCRYPTION_INITIAL || level == ENCRYPTION_HANDSHAKE)) {
1200 frames.push_back(QuicFrame(QuicPingFrame()));
1201 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
1202 } else {
1203 frames.push_back(QuicFrame(frame1_));
1204 if (has_stop_waiting) {
1205 frames.push_back(QuicFrame(stop_waiting_));
1206 }
1207 }
1208 return ConstructPacket(header, frames);
1209 }
1210
1211 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
1212 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1213 if (VersionHasIetfQuicFrames(version().transport_version)) {
1214 QuicPathFrameBuffer payload = {
1215 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1216 return QuicPacketCreatorPeer::
1217 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1218 payload);
1219 }
danzh65153092023-06-16 10:59:32 -07001220 QUICHE_DCHECK(!GetQuicReloadableFlag(quic_ignore_gquic_probing));
Bence Békybac04052022-04-07 15:44:29 -04001221 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1222 &peer_creator_);
1223 }
1224
1225 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1226 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1227 QuicPacketHeader header;
1228 // Set connection_id to peer's in memory representation as this connection
1229 // close packet is created by peer_framer.
1230 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1231 header.source_connection_id = connection_id_;
1232 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04001233 } else {
1234 header.destination_connection_id = connection_id_;
fayangfc04b8a2023-05-18 09:26:25 -07001235 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04001236 }
1237
1238 header.packet_number = QuicPacketNumber(number);
1239
1240 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
1241 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1242 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
1243 /*transport_close_frame_type=*/0);
1244 QuicFrames frames;
1245 frames.push_back(QuicFrame(&qccf));
1246 return ConstructPacket(header, frames);
1247 }
1248
1249 QuicTime::Delta DefaultRetransmissionTime() {
1250 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1251 }
1252
1253 QuicTime::Delta DefaultDelayedAckTime() {
wub349df3d2024-04-26 11:37:32 -07001254 return QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
Bence Békybac04052022-04-07 15:44:29 -04001255 }
1256
1257 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1258 QuicStopWaitingFrame frame;
1259 frame.least_unacked = QuicPacketNumber(least_unacked);
1260 return frame;
1261 }
1262
1263 // Construct a ack_frame that acks all packet numbers between 1 and
1264 // |largest_acked|, except |missing|.
1265 // REQUIRES: 1 <= |missing| < |largest_acked|
1266 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1267 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1268 QuicPacketNumber(missing));
1269 }
1270
1271 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1272 QuicPacketNumber missing) {
1273 if (missing == QuicPacketNumber(1)) {
1274 return InitAckFrame({{missing + 1, largest_acked + 1}});
1275 }
1276 return InitAckFrame(
1277 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1278 }
1279
1280 // Undo nacking a packet within the frame.
1281 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1282 EXPECT_FALSE(frame->packets.Contains(arrived));
1283 frame->packets.Add(arrived);
1284 }
1285
1286 void TriggerConnectionClose() {
1287 // Send an erroneous packet to close the connection.
1288 EXPECT_CALL(visitor_,
1289 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1290 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1291
1292 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1293 // Triggers a connection by receiving ACK of unsent packet.
1294 QuicAckFrame frame = InitAckFrame(10000);
1295 ProcessAckPacket(1, &frame);
1296 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1297 nullptr);
1298 EXPECT_EQ(1, connection_close_frame_count_);
1299 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1300 IsError(QUIC_INVALID_ACK_DATA));
1301 }
1302
1303 void BlockOnNextWrite() {
1304 writer_->BlockOnNextWrite();
1305 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1306 }
1307
1308 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1309
fayangf6607db2022-04-21 18:10:41 -07001310 void ExpectNextPacketUnprocessable() {
1311 writer_->ExpectNextPacketUnprocessable();
1312 }
1313
Bence Békybac04052022-04-07 15:44:29 -04001314 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1315
1316 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1317 writer_->SetWritePauseTimeDelta(delta);
1318 }
1319
1320 void CongestionBlockWrites() {
1321 EXPECT_CALL(*send_algorithm_, CanSend(_))
1322 .WillRepeatedly(testing::Return(false));
1323 }
1324
1325 void CongestionUnblockWrites() {
1326 EXPECT_CALL(*send_algorithm_, CanSend(_))
1327 .WillRepeatedly(testing::Return(true));
1328 }
1329
1330 void set_perspective(Perspective perspective) {
1331 connection_.set_perspective(perspective);
1332 if (perspective == Perspective::IS_SERVER) {
Bence Békybac04052022-04-07 15:44:29 -04001333 connection_.set_can_truncate_connection_ids(true);
1334 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
1335 connection_.OnSuccessfulVersionNegotiation();
1336 }
1337 QuicFramerPeer::SetPerspective(&peer_framer_,
1338 QuicUtils::InvertPerspective(perspective));
1339 peer_framer_.SetInitialObfuscators(TestConnectionId());
1340 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
1341 ENCRYPTION_FORWARD_SECURE}) {
1342 if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) {
martinduke9e0811c2022-12-08 20:35:57 -08001343 peer_creator_.SetEncrypter(level,
1344 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -04001345 }
1346 }
1347 }
1348
1349 void set_packets_between_probes_base(
1350 const QuicPacketCount packets_between_probes_base) {
1351 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1352 &connection_, packets_between_probes_base,
1353 QuicPacketNumber(packets_between_probes_base));
1354 }
1355
1356 bool IsDefaultTestConfiguration() {
1357 TestParams p = GetParam();
1358 return p.ack_response == AckResponse::kImmediate &&
fayangfc04b8a2023-05-18 09:26:25 -07001359 p.version == AllSupportedVersions()[0];
Bence Békybac04052022-04-07 15:44:29 -04001360 }
1361
1362 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1363 // Not strictly needed for this test, but is commonly done.
1364 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1365 nullptr);
1366 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1367 writer_->connection_close_frames();
1368 ASSERT_EQ(1u, connection_close_frames.size());
1369
1370 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1371 IsError(expected_code));
1372
1373 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1374 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1375 IsError(expected_code));
1376 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1377 connection_close_frames[0].close_type);
1378 return;
1379 }
1380
1381 QuicErrorCodeToIetfMapping mapping =
1382 QuicErrorCodeToTransportErrorCode(expected_code);
1383
1384 if (mapping.is_transport_close) {
1385 // This Google QUIC Error Code maps to a transport close,
1386 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1387 connection_close_frames[0].close_type);
1388 } else {
1389 // This maps to an application close.
1390 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1391 connection_close_frames[0].close_type);
1392 }
1393 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
1394 }
1395
1396 void MtuDiscoveryTestInit() {
1397 set_perspective(Perspective::IS_SERVER);
1398 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1399 if (version().SupportsAntiAmplificationLimit()) {
1400 QuicConnectionPeer::SetAddressValidated(&connection_);
1401 }
1402 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1403 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04001404 // Prevent packets from being coalesced.
1405 EXPECT_CALL(visitor_, GetHandshakeState())
1406 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1407 EXPECT_TRUE(connection_.connected());
1408 }
1409
1410 void PathProbeTestInit(Perspective perspective,
1411 bool receive_new_server_connection_id = true) {
1412 set_perspective(perspective);
1413 connection_.CreateConnectionIdManager();
1414 EXPECT_EQ(connection_.perspective(), perspective);
1415 if (perspective == Perspective::IS_SERVER) {
1416 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1417 }
1418 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1419 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1420 // Discard INITIAL key.
1421 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1422 connection_.NeuterUnencryptedPackets();
1423 // Prevent packets from being coalesced.
1424 EXPECT_CALL(visitor_, GetHandshakeState())
1425 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1426 if (version().SupportsAntiAmplificationLimit() &&
1427 perspective == Perspective::IS_SERVER) {
1428 QuicConnectionPeer::SetAddressValidated(&connection_);
1429 }
1430 // Clear direct_peer_address.
1431 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1432 // Clear effective_peer_address, it is the same as direct_peer_address for
1433 // this test.
1434 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1435 QuicSocketAddress());
1436 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1437
1438 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1439 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1440 } else {
1441 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1442 }
1443 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1444 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1445 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1446 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1447 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1448 if (perspective == Perspective::IS_CLIENT &&
1449 receive_new_server_connection_id && version().HasIetfQuicFrames()) {
1450 QuicNewConnectionIdFrame frame;
1451 frame.connection_id = TestConnectionId(1234);
1452 ASSERT_NE(frame.connection_id, connection_.connection_id());
1453 frame.stateless_reset_token =
1454 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
1455 frame.retire_prior_to = 0u;
1456 frame.sequence_number = 1u;
1457 connection_.OnNewConnectionIdFrame(frame);
1458 }
1459 }
1460
danzhb159ab02023-01-30 10:58:46 -08001461 void ServerHandlePreferredAddressInit() {
1462 ASSERT_TRUE(GetParam().version.HasIetfQuicFrames());
1463 set_perspective(Perspective::IS_SERVER);
1464 connection_.CreateConnectionIdManager();
1465 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang1f578d32023-03-20 11:36:15 -07001466 SetQuicReloadableFlag(quic_use_received_client_addresses_cache, true);
danzhb159ab02023-01-30 10:58:46 -08001467 EXPECT_CALL(visitor_, AllowSelfAddressChange())
1468 .WillRepeatedly(Return(true));
1469
1470 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1471 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1472 // Discard INITIAL key.
1473 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1474 connection_.NeuterUnencryptedPackets();
1475 // Prevent packets from being coalesced.
1476 EXPECT_CALL(visitor_, GetHandshakeState())
1477 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1478 if (version().SupportsAntiAmplificationLimit()) {
1479 QuicConnectionPeer::SetAddressValidated(&connection_);
1480 }
1481 // Clear direct_peer_address.
1482 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1483 // Clear effective_peer_address, it is the same as direct_peer_address for
1484 // this test.
1485 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1486 QuicSocketAddress());
1487 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1488
1489 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1490 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1491 } else {
1492 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1493 }
1494 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1495 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1496 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1497 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1498 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1499 QuicConfig config;
danzhb159ab02023-01-30 10:58:46 -08001500 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08001501 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
1502 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
danzhb159ab02023-01-30 10:58:46 -08001503 connection_.SetFromConfig(config);
rchacbdda42024-04-08 13:35:17 -07001504 connection_.set_expected_server_preferred_address(kServerPreferredAddress);
danzhb159ab02023-01-30 10:58:46 -08001505 }
1506
fayangdbd6a302022-12-21 16:24:27 -08001507 // Receive server preferred address.
fayanga0618a62022-12-28 19:31:24 -08001508 void ServerPreferredAddressInit(QuicConfig& config) {
fayangdbd6a302022-12-21 16:24:27 -08001509 ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1510 ASSERT_TRUE(version().HasIetfQuicFrames());
1511 ASSERT_TRUE(connection_.self_address().host().IsIPv6());
fayangdbd6a302022-12-21 16:24:27 -08001512 const QuicConnectionId connection_id = TestConnectionId(17);
1513 const StatelessResetToken reset_token =
1514 QuicUtils::GenerateStatelessResetToken(connection_id);
1515
1516 connection_.CreateConnectionIdManager();
1517
1518 connection_.SendCryptoStreamData();
1519 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07001520 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangdbd6a302022-12-21 16:24:27 -08001521 QuicAckFrame frame = InitAckFrame(1);
1522 // Received ACK for packet 1.
1523 ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
fayang37765f62022-12-27 17:49:13 -08001524 // Discard INITIAL key.
1525 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
fayanga0618a62022-12-28 19:31:24 -08001526 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangdbd6a302022-12-21 16:24:27 -08001527
fayangdbd6a302022-12-21 16:24:27 -08001528 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
1529 kTestStatelessResetToken);
1530 QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
danzh8fdee2e2023-01-05 15:33:02 -08001531 kServerPreferredAddress);
fayangdbd6a302022-12-21 16:24:27 -08001532 QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
1533 &config, connection_id, reset_token);
1534 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08001535 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
1536 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
fayangdbd6a302022-12-21 16:24:27 -08001537 connection_.SetFromConfig(config);
1538
danzhb159ab02023-01-30 10:58:46 -08001539 ASSERT_TRUE(
1540 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)
1541 .IsInitialized());
1542 EXPECT_EQ(
1543 kServerPreferredAddress,
1544 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_));
fayangdbd6a302022-12-21 16:24:27 -08001545 }
1546
wubc9fd4292023-08-14 13:00:21 -07001547 // If defer sending is enabled, tell |visitor_| to return true on the next
1548 // call to WillingAndAbleToWrite().
1549 // This function can be used before a call to ProcessXxxPacket, to allow the
1550 // process function to schedule and fire the send alarm at the end.
1551 void ForceWillingAndAbleToWriteOnceForDeferSending() {
1552 if (GetParam().ack_response == AckResponse::kDefer) {
1553 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
1554 .WillOnce(Return(true))
1555 .RetiresOnSaturation();
1556 }
1557 }
1558
Bence Békybac04052022-04-07 15:44:29 -04001559 void TestClientRetryHandling(bool invalid_retry_tag,
1560 bool missing_original_id_in_config,
1561 bool wrong_original_id_in_config,
1562 bool missing_retry_id_in_config,
1563 bool wrong_retry_id_in_config);
1564
1565 void TestReplaceConnectionIdFromInitial();
1566
1567 QuicConnectionId connection_id_;
1568 QuicFramer framer_;
1569
1570 MockSendAlgorithm* send_algorithm_;
1571 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1572 MockClock clock_;
1573 MockRandom random_generator_;
1574 quiche::SimpleBufferAllocator buffer_allocator_;
1575 std::unique_ptr<TestConnectionHelper> helper_;
1576 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1577 QuicFramer peer_framer_;
1578 QuicPacketCreator peer_creator_;
1579 std::unique_ptr<TestPacketWriter> writer_;
1580 TestConnection connection_;
1581 QuicPacketCreator* creator_;
1582 QuicSentPacketManager* manager_;
1583 StrictMock<MockQuicConnectionVisitor> visitor_;
1584
1585 QuicStreamFrame frame1_;
1586 QuicStreamFrame frame2_;
1587 QuicCryptoFrame crypto_frame_;
1588 QuicAckFrame ack_;
1589 QuicStopWaitingFrame stop_waiting_;
1590 QuicPacketNumberLength packet_number_length_;
1591 QuicConnectionIdIncluded connection_id_included_;
1592
1593 SimpleSessionNotifier notifier_;
1594
1595 QuicConnectionCloseFrame saved_connection_close_frame_;
1596 int connection_close_frame_count_;
martinduke605dca22022-09-01 10:40:19 -07001597 MockConnectionIdGenerator connection_id_generator_;
Bence Békybac04052022-04-07 15:44:29 -04001598};
1599
1600// Run all end to end tests with all supported versions.
1601INSTANTIATE_TEST_SUITE_P(QuicConnectionTests, QuicConnectionTest,
1602 ::testing::ValuesIn(GetTestParams()),
1603 ::testing::PrintToStringParamName());
1604
wub9f543d02024-10-23 12:29:45 -07001605// Regression test for b/372756997.
1606TEST_P(QuicConnectionTest, NoNestedCloseConnection) {
1607 if (!GetQuicReloadableFlag(quic_avoid_nested_close_connection)) {
1608 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
1609 if (!IsDefaultTestConfiguration()) {
1610 return;
1611 }
1612 }
1613 EXPECT_TRUE(connection_.connected());
1614 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1615 .WillRepeatedly(
1616 Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1617 EXPECT_CALL(connection_, OnSerializedPacket(_)).Times(AnyNumber());
1618
1619 // Prepare the writer to fail to send the first connection close packet due
1620 // to the packet being too large.
1621 writer_->SetShouldWriteFail();
1622 writer_->SetWriteError(*writer_->MessageTooBigErrorCode());
1623
1624 if (GetQuicReloadableFlag(quic_avoid_nested_close_connection)) {
1625 connection_.CloseConnection(
1626 QUIC_CRYPTO_TOO_MANY_ENTRIES, "Closed by test",
1627 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1628 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1629 IsError(QUIC_CRYPTO_TOO_MANY_ENTRIES));
1630 } else {
1631 EXPECT_QUIC_BUG(
1632 connection_.CloseConnection(
1633 QUIC_CRYPTO_TOO_MANY_ENTRIES, "Closed by test",
1634 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET),
1635 // 30=QUIC_CRYPTO_TOO_MANY_ENTRIES, 27=QUIC_PACKET_WRITE_ERROR.
1636 "Initial error code: 30, new error code: 27");
1637 }
1638}
1639
Bence Békybac04052022-04-07 15:44:29 -04001640// These two tests ensure that the QuicErrorCode mapping works correctly.
1641// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1642// If running IETF QUIC, the first will generate a transport connection
1643// close, the second an application connection close.
1644// The connection close codes for the two tests are manually chosen;
1645// they are expected to always map to transport- and application-
1646// closes, respectively. If that changes, new codes should be chosen.
1647TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1648 EXPECT_TRUE(connection_.connected());
1649 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1650 connection_.CloseConnection(
1651 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1652 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1653 EXPECT_FALSE(connection_.connected());
1654 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1655}
1656
1657// Test that the IETF QUIC Error code mapping function works
1658// properly for application connection close codes.
1659TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1660 EXPECT_TRUE(connection_.connected());
1661 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1662 connection_.CloseConnection(
1663 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1664 "Should be application close",
1665 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1666 EXPECT_FALSE(connection_.connected());
1667 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1668}
1669
1670TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1671 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1672
1673 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1674 EXPECT_TRUE(connection_.connected());
1675
1676 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1677 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1678 } else {
1679 EXPECT_CALL(visitor_, OnStreamFrame(_));
1680 }
1681 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1682 ENCRYPTION_INITIAL);
1683 // Cause change in self_address.
1684 QuicIpAddress host;
1685 host.FromString("1.1.1.1");
1686 QuicSocketAddress self_address(host, 123);
1687 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1688 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1689 } else {
1690 EXPECT_CALL(visitor_, OnStreamFrame(_));
1691 }
1692 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1693 ENCRYPTION_INITIAL);
1694 EXPECT_TRUE(connection_.connected());
danzh65153092023-06-16 10:59:32 -07001695 EXPECT_NE(connection_.self_address(), self_address);
Bence Békybac04052022-04-07 15:44:29 -04001696}
1697
1698TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1699 set_perspective(Perspective::IS_SERVER);
1700 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1701
1702 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1703 EXPECT_TRUE(connection_.connected());
1704
1705 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1706 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1707 } else {
1708 EXPECT_CALL(visitor_, OnStreamFrame(_));
1709 }
1710 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1711 ENCRYPTION_INITIAL);
1712 // Cause change in self_address.
1713 QuicIpAddress host;
1714 host.FromString("1.1.1.1");
1715 QuicSocketAddress self_address(host, 123);
1716 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
1717 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fayang19027942022-05-16 10:29:29 -07001718 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1719 ENCRYPTION_INITIAL);
1720 EXPECT_TRUE(connection_.connected());
Bence Békybac04052022-04-07 15:44:29 -04001721 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
1722}
1723
1724TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1725 set_perspective(Perspective::IS_SERVER);
1726 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1727
1728 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1729 EXPECT_TRUE(connection_.connected());
1730
1731 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1732 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1733 } else {
1734 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1735 }
1736 QuicIpAddress host;
1737 host.FromString("1.1.1.1");
1738 QuicSocketAddress self_address1(host, 443);
1739 connection_.SetSelfAddress(self_address1);
1740 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1741 kPeerAddress, ENCRYPTION_INITIAL);
1742 // Cause self_address change to mapped Ipv4 address.
1743 QuicIpAddress host2;
1744 host2.FromString(
1745 absl::StrCat("::ffff:", connection_.self_address().host().ToString()));
1746 QuicSocketAddress self_address2(host2, connection_.self_address().port());
1747 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1748 kPeerAddress, ENCRYPTION_INITIAL);
1749 EXPECT_TRUE(connection_.connected());
1750 // self_address change back to Ipv4 address.
1751 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1752 kPeerAddress, ENCRYPTION_INITIAL);
1753 EXPECT_TRUE(connection_.connected());
1754}
1755
1756TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1757 set_perspective(Perspective::IS_SERVER);
1758 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1759 EXPECT_CALL(visitor_, GetHandshakeState())
1760 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1761
1762 // Clear direct_peer_address.
1763 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1764 // Clear effective_peer_address, it is the same as direct_peer_address for
1765 // this test.
1766 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1767 QuicSocketAddress());
1768
1769 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1770 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1771 } else {
1772 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1773 }
1774 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1775 const QuicSocketAddress kNewPeerAddress =
1776 QuicSocketAddress(QuicIpAddress::Loopback6(),
1777 /*port=*/23456);
1778 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1779 kNewPeerAddress, ENCRYPTION_INITIAL);
1780 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1781 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1782
1783 // Decrease packet number to simulate out-of-order packets.
1784 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1785 // This is an old packet, do not migrate.
1786 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1787 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1788 ENCRYPTION_INITIAL);
1789 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1790 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1791}
1792
1793TEST_P(QuicConnectionTest, PeerPortChangeAtServer) {
1794 set_perspective(Perspective::IS_SERVER);
1795 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1796 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1797 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1798 // Prevent packets from being coalesced.
1799 EXPECT_CALL(visitor_, GetHandshakeState())
1800 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1801 if (version().SupportsAntiAmplificationLimit()) {
1802 QuicConnectionPeer::SetAddressValidated(&connection_);
1803 }
1804
1805 // Clear direct_peer_address.
1806 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1807 // Clear effective_peer_address, it is the same as direct_peer_address for
1808 // this test.
1809 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1810 QuicSocketAddress());
1811 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1812
1813 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
1814 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
1815 rtt_stats->set_initial_rtt(default_init_rtt * 2);
1816 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
1817
fayang339f0c82022-04-30 14:20:02 -07001818 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
1819 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001820
1821 const QuicSocketAddress kNewPeerAddress =
1822 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1823 EXPECT_CALL(visitor_, OnStreamFrame(_))
1824 .WillOnce(Invoke(
QUICHE teamf8ca4ff2024-07-17 12:06:18 -07001825 [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1826 .WillOnce(Invoke([=, this]() {
1827 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1828 }));
Bence Békybac04052022-04-07 15:44:29 -04001829 QuicFrames frames;
1830 frames.push_back(QuicFrame(frame1_));
1831 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1832 ENCRYPTION_FORWARD_SECURE);
1833 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1834 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1835
1836 // Process another packet with a different peer address on server side will
1837 // start connection migration.
1838 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1839 QuicFrames frames2;
1840 frames2.push_back(QuicFrame(frame2_));
1841 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1842 ENCRYPTION_FORWARD_SECURE);
1843 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1844 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1845 // PORT_CHANGE shouldn't state change in sent packet manager.
1846 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07001847 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001848 EXPECT_EQ(manager_->GetSendAlgorithm(), send_algorithm_);
danzh4d58dae2023-06-06 11:13:10 -07001849 if (version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04001850 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1851 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001852 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001853 }
1854}
1855
1856TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServer) {
1857 set_perspective(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -07001858 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07001859 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04001860 return;
1861 }
1862 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1863 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1864 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1865 // Discard INITIAL key.
1866 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1867 connection_.NeuterUnencryptedPackets();
1868 // Prevent packets from being coalesced.
1869 EXPECT_CALL(visitor_, GetHandshakeState())
1870 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1871 QuicConnectionPeer::SetAddressValidated(&connection_);
1872 connection_.OnHandshakeComplete();
1873
1874 // Enable 5 RTO
1875 QuicConfig config;
1876 QuicTagVector connection_options;
1877 connection_options.push_back(k5RTO);
1878 config.SetInitialReceivedConnectionOptions(connection_options);
1879 QuicConfigPeer::SetNegotiated(&config, true);
1880 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
1881 connection_.connection_id());
1882 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
1883 QuicConnectionId());
1884 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08001885 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
1886 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04001887 connection_.SetFromConfig(config);
1888
1889 // Clear direct_peer_address.
1890 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1891 // Clear effective_peer_address, it is the same as direct_peer_address for
1892 // this test.
1893 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1894 QuicSocketAddress());
1895 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1896
1897 const QuicSocketAddress kNewPeerAddress =
1898 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1899 EXPECT_CALL(visitor_, OnStreamFrame(_))
1900 .WillOnce(Invoke(
QUICHE teamf8ca4ff2024-07-17 12:06:18 -07001901 [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1902 .WillOnce(Invoke([=, this]() {
1903 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1904 }));
Bence Békybac04052022-04-07 15:44:29 -04001905 QuicFrames frames;
1906 frames.push_back(QuicFrame(frame1_));
1907 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1908 ENCRYPTION_FORWARD_SECURE);
1909 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1910 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1911
1912 // Send some data to make connection has packets in flight.
1913 connection_.SendStreamData3();
1914 EXPECT_EQ(1u, writer_->packets_write_attempts());
1915 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
1916 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1917
1918 // Process another packet with a different peer address on server side will
1919 // start connection migration.
1920 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1921 // IETF QUIC send algorithm should be changed to a different object, so no
1922 // OnPacketSent() called on the old send algorithm.
1923 EXPECT_CALL(*send_algorithm_,
1924 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
1925 .Times(0);
1926 // Do not propagate OnCanWrite() to session notifier.
wubc9fd4292023-08-14 13:00:21 -07001927 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04001928
1929 QuicFrames frames2;
1930 frames2.push_back(QuicFrame(frame2_));
1931 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1932 ENCRYPTION_FORWARD_SECURE);
1933 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1934 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1935 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1936 connection_.active_effective_peer_migration_type());
1937 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
1938 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1939
1940 EXPECT_EQ(2u, writer_->packets_write_attempts());
1941 EXPECT_FALSE(writer_->path_challenge_frames().empty());
1942 QuicPathFrameBuffer payload =
1943 writer_->path_challenge_frames().front().data_buffer;
1944 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
1945 send_algorithm_);
1946 // Switch to use the mock send algorithm.
1947 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
1948 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1949 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1950 .WillRepeatedly(Return(kDefaultTCPMSS));
1951 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1952 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1953 .Times(AnyNumber())
1954 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1955 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1956 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1957 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
1958 connection_.SetSendAlgorithm(send_algorithm_);
1959
1960 // PATH_CHALLENGE is expanded upto the max packet size which may exceeds the
1961 // anti-amplification limit.
1962 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
1963 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1964 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1965 EXPECT_EQ(1u,
1966 connection_.GetStats().num_reverse_path_validtion_upon_migration);
1967
1968 // Verify server is throttled by anti-amplification limit.
1969 connection_.SendCryptoDataWithString("foo", 0);
1970 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1971
1972 // Receiving an ACK to the packet sent after changing peer address doesn't
1973 // finish migration validation.
1974 QuicAckFrame ack_frame = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07001975 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04001976 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1977 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
1978 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1979 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1980 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1981 connection_.active_effective_peer_migration_type());
1982
1983 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
1984 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -07001985 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04001986 EXPECT_CALL(visitor_, MaybeSendAddressToken());
1987 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1988 .Times(testing::AtLeast(1u));
1989 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
1990 ENCRYPTION_FORWARD_SECURE);
1991 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1992
1993 // Verify the anti-amplification limit is lifted by sending a packet larger
1994 // than the anti-amplification limit.
1995 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
1996 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001997 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001998}
1999
2000TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServerWithMissingConnectionId) {
2001 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -07002002 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002003 return;
2004 }
2005 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2006 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2007
2008 QuicConnectionId client_cid0 = TestConnectionId(1);
2009 QuicConnectionId client_cid1 = TestConnectionId(3);
2010 QuicConnectionId server_cid1;
2011 SetClientConnectionId(client_cid0);
2012 connection_.CreateConnectionIdManager();
2013 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2014 // Prevent packets from being coalesced.
2015 EXPECT_CALL(visitor_, GetHandshakeState())
2016 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2017 QuicConnectionPeer::SetAddressValidated(&connection_);
2018
2019 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07002020 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002021 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2022 .WillOnce(Return(TestConnectionId(456)));
2023 }
haoyuewangada6b822022-06-23 13:41:18 -07002024 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2025 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2026 server_cid1 = cid;
2027 return true;
2028 }));
Bence Békybac04052022-04-07 15:44:29 -04002029 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2030 connection_.OnHandshakeComplete();
2031
2032 // Clear direct_peer_address.
2033 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2034 // Clear effective_peer_address, it is the same as direct_peer_address for
2035 // this test.
2036 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2037 QuicSocketAddress());
2038 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2039
2040 const QuicSocketAddress kNewPeerAddress =
2041 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2042 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
2043 QuicFrames frames;
2044 frames.push_back(QuicFrame(frame1_));
2045 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
2046 ENCRYPTION_FORWARD_SECURE);
2047 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2048 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2049
2050 // Send some data to make connection has packets in flight.
2051 connection_.SendStreamData3();
2052 EXPECT_EQ(1u, writer_->packets_write_attempts());
2053
2054 // Process another packet with a different peer address on server side will
2055 // start connection migration.
2056 peer_creator_.SetServerConnectionId(server_cid1);
2057 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2058 // Do not propagate OnCanWrite() to session notifier.
wubc9fd4292023-08-14 13:00:21 -07002059 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04002060
2061 QuicFrames frames2;
2062 frames2.push_back(QuicFrame(frame2_));
birenroyef686222022-09-12 11:34:34 -07002063 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07002064 frames2.push_back(QuicFrame(QuicPaddingFrame(-1)));
2065 }
Bence Békybac04052022-04-07 15:44:29 -04002066 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2067 ENCRYPTION_FORWARD_SECURE);
2068 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2069 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2070
2071 // Writing path response & reverse path challenge is blocked due to missing
2072 // client connection ID, i.e., packets_write_attempts is unchanged.
2073 EXPECT_EQ(1u, writer_->packets_write_attempts());
2074
2075 // Receives new client CID from client would unblock write.
2076 QuicNewConnectionIdFrame new_cid_frame;
2077 new_cid_frame.connection_id = client_cid1;
2078 new_cid_frame.sequence_number = 1u;
2079 new_cid_frame.retire_prior_to = 0u;
2080 connection_.OnNewConnectionIdFrame(new_cid_frame);
2081 connection_.SendStreamData3();
2082
2083 EXPECT_EQ(2u, writer_->packets_write_attempts());
2084}
2085
2086TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
birenroyef686222022-09-12 11:34:34 -07002087 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07002088 return;
2089 }
Bence Békybac04052022-04-07 15:44:29 -04002090 set_perspective(Perspective::IS_SERVER);
2091 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2092 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2093 if (version().SupportsAntiAmplificationLimit()) {
2094 QuicConnectionPeer::SetAddressValidated(&connection_);
2095 }
2096 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2097 // Discard INITIAL key.
2098 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2099 connection_.NeuterUnencryptedPackets();
2100 EXPECT_CALL(visitor_, GetHandshakeState())
2101 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2102
2103 // Clear direct_peer_address.
2104 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2105 // Clear effective_peer_address, it is different from direct_peer_address for
2106 // this test.
2107 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2108 QuicSocketAddress());
2109 const QuicSocketAddress kEffectivePeerAddress =
2110 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2111 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2112
2113 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2114 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2115 } else {
2116 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2117 }
2118 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2119 ENCRYPTION_FORWARD_SECURE);
2120 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2121 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2122
2123 // Process another packet with the same direct peer address and different
2124 // effective peer address on server side will start connection migration.
2125 const QuicSocketAddress kNewEffectivePeerAddress =
2126 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2127 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2128 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2129 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2130 ENCRYPTION_FORWARD_SECURE);
2131 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2132 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2133 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
danzh4d58dae2023-06-06 11:13:10 -07002134 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002135 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2136 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07002137 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04002138 }
2139
2140 // Process another packet with a different direct peer address and the same
2141 // effective peer address on server side will not start connection migration.
2142 const QuicSocketAddress kNewPeerAddress =
2143 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2144 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2145 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2146
danzh4d58dae2023-06-06 11:13:10 -07002147 if (!GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002148 // ack_frame is used to complete the migration started by the last packet,
2149 // we need to make sure a new migration does not start after the previous
2150 // one is completed.
2151 QuicAckFrame ack_frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07002152 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04002153 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2154 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2155 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2156 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2157 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2158 }
2159
2160 // Process another packet with different direct peer address and different
2161 // effective peer address on server side will start connection migration.
2162 const QuicSocketAddress kNewerEffectivePeerAddress =
2163 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2164 const QuicSocketAddress kFinalPeerAddress =
2165 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2166 connection_.ReturnEffectivePeerAddressForNextPacket(
2167 kNewerEffectivePeerAddress);
2168 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2169 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2170 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2171 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2172 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
danzh4d58dae2023-06-06 11:13:10 -07002173 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002174 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2175 EXPECT_EQ(send_algorithm_,
2176 connection_.sent_packet_manager().GetSendAlgorithm());
2177 EXPECT_EQ(2u, connection_.GetStats().num_validated_peer_migration);
2178 }
2179
2180 // While the previous migration is ongoing, process another packet with the
2181 // same direct peer address and different effective peer address on server
2182 // side will start a new connection migration.
2183 const QuicSocketAddress kNewestEffectivePeerAddress =
2184 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2185 connection_.ReturnEffectivePeerAddressForNextPacket(
2186 kNewestEffectivePeerAddress);
2187 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
danzh4d58dae2023-06-06 11:13:10 -07002188 if (!GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002189 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
2190 }
2191 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2192 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2193 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2194 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2195 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2196 connection_.active_effective_peer_migration_type());
danzh4d58dae2023-06-06 11:13:10 -07002197 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002198 EXPECT_NE(send_algorithm_,
2199 connection_.sent_packet_manager().GetSendAlgorithm());
2200 EXPECT_EQ(kFinalPeerAddress, writer_->last_write_peer_address());
2201 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2202 EXPECT_EQ(0u, connection_.GetStats()
2203 .num_peer_migration_while_validating_default_path);
2204 EXPECT_TRUE(connection_.HasPendingPathValidation());
2205 }
2206}
2207
2208// Regression test for b/200020764.
2209TEST_P(QuicConnectionTest, ConnectionMigrationWithPendingPaddingBytes) {
2210 // TODO(haoyuewang) Move these test setup code to a common member function.
2211 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -07002212 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002213 return;
2214 }
2215 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2216 connection_.CreateConnectionIdManager();
2217 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2218 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2219 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2220 QuicConnectionPeer::SetAddressValidated(&connection_);
2221
2222 // Sends new server CID to client.
2223 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002224 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002225 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2226 .WillOnce(Return(TestConnectionId(456)));
2227 }
haoyuewangada6b822022-06-23 13:41:18 -07002228 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2229 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2230 new_cid = cid;
2231 return true;
2232 }));
Bence Békybac04052022-04-07 15:44:29 -04002233 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2234 // Discard INITIAL key.
2235 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2236 connection_.NeuterUnencryptedPackets();
2237 connection_.OnHandshakeComplete();
2238 EXPECT_CALL(visitor_, GetHandshakeState())
2239 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2240
2241 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2242 packet_creator->FlushCurrentPacket();
2243 packet_creator->AddPendingPadding(50u);
2244 const QuicSocketAddress kPeerAddress3 =
2245 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2246 auto ack_frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07002247 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04002248 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2249 ProcessFramesPacketWithAddresses({QuicFrame(&ack_frame)}, kSelfAddress,
2250 kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
haoyuewang16f86e82023-07-26 14:13:26 -07002251 // Any pending frames/padding should be flushed before default_path_ is
2252 // temporarily reset.
2253 ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2254 .host()
2255 .address_family(),
2256 IpAddressFamily::IP_V6);
Bence Békybac04052022-04-07 15:44:29 -04002257}
2258
2259// Regression test for b/196208556.
2260TEST_P(QuicConnectionTest,
2261 ReversePathValidationResponseReceivedFromUnexpectedPeerAddress) {
2262 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -07002263 if (!version().HasIetfQuicFrames() ||
birenroyef686222022-09-12 11:34:34 -07002264 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04002265 return;
2266 }
2267 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2268 connection_.CreateConnectionIdManager();
2269 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2270 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2271 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2272 QuicConnectionPeer::SetAddressValidated(&connection_);
2273 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2274 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2275
2276 // Sends new server CID to client.
2277 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002278 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002279 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2280 .WillOnce(Return(TestConnectionId(456)));
2281 }
haoyuewangada6b822022-06-23 13:41:18 -07002282 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2283 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2284 new_cid = cid;
2285 return true;
2286 }));
Bence Békybac04052022-04-07 15:44:29 -04002287 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2288 // Discard INITIAL key.
2289 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2290 connection_.NeuterUnencryptedPackets();
2291 connection_.OnHandshakeComplete();
2292 EXPECT_CALL(visitor_, GetHandshakeState())
2293 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2294
2295 // Process a non-probing packet to migrate to path 2 and kick off reverse path
2296 // validation.
2297 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2298 const QuicSocketAddress kPeerAddress2 =
2299 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2300 peer_creator_.SetServerConnectionId(new_cid);
2301 ProcessFramesPacketWithAddresses({QuicFrame(QuicPingFrame())}, kSelfAddress,
2302 kPeerAddress2, ENCRYPTION_FORWARD_SECURE);
2303 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2304 QuicPathFrameBuffer reverse_path_challenge_payload =
2305 writer_->path_challenge_frames().front().data_buffer;
2306
2307 // Receiveds a packet from path 3 with PATH_RESPONSE frame intended to
2308 // validate path 2 and a non-probing frame.
2309 {
2310 QuicConnection::ScopedPacketFlusher flusher(&connection_);
2311 const QuicSocketAddress kPeerAddress3 =
2312 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2313 auto ack_frame = InitAckFrame(1);
2314 EXPECT_CALL(visitor_, OnConnectionMigration(IPV4_TO_IPV6_CHANGE)).Times(1);
2315 EXPECT_CALL(visitor_, MaybeSendAddressToken()).WillOnce(Invoke([this]() {
2316 connection_.SendControlFrame(
2317 QuicFrame(new QuicNewTokenFrame(1, "new_token")));
2318 return true;
2319 }));
wubd0152ca2022-04-08 08:26:44 -07002320 ProcessFramesPacketWithAddresses(
2321 {QuicFrame(QuicPathResponseFrame(0, reverse_path_challenge_payload)),
2322 QuicFrame(&ack_frame)},
2323 kSelfAddress, kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04002324 }
2325}
2326
2327TEST_P(QuicConnectionTest, ReversePathValidationFailureAtServer) {
2328 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -07002329 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002330 return;
2331 }
2332 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2333 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2334 SetClientConnectionId(TestConnectionId(1));
2335 connection_.CreateConnectionIdManager();
2336 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2337 // Discard INITIAL key.
2338 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2339 connection_.NeuterUnencryptedPackets();
2340 // Prevent packets from being coalesced.
2341 EXPECT_CALL(visitor_, GetHandshakeState())
2342 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2343 QuicConnectionPeer::SetAddressValidated(&connection_);
2344
2345 QuicConnectionId client_cid0 = connection_.client_connection_id();
2346 QuicConnectionId client_cid1 = TestConnectionId(2);
2347 QuicConnectionId server_cid0 = connection_.connection_id();
2348 QuicConnectionId server_cid1;
2349 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07002350 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002351 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2352 .WillOnce(Return(TestConnectionId(456)));
2353 }
haoyuewangada6b822022-06-23 13:41:18 -07002354 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2355 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2356 server_cid1 = cid;
2357 return true;
2358 }));
Bence Békybac04052022-04-07 15:44:29 -04002359 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2360 connection_.OnHandshakeComplete();
2361 // Receives new client CID from client.
2362 QuicNewConnectionIdFrame new_cid_frame;
2363 new_cid_frame.connection_id = client_cid1;
2364 new_cid_frame.sequence_number = 1u;
2365 new_cid_frame.retire_prior_to = 0u;
2366 connection_.OnNewConnectionIdFrame(new_cid_frame);
2367 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2368 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2369 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2370
2371 // Clear direct_peer_address.
2372 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2373 // Clear effective_peer_address, it is the same as direct_peer_address for
2374 // this test.
2375 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2376 QuicSocketAddress());
2377 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2378
2379 const QuicSocketAddress kNewPeerAddress =
2380 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2381 EXPECT_CALL(visitor_, OnStreamFrame(_))
2382 .WillOnce(Invoke(
QUICHE teamf8ca4ff2024-07-17 12:06:18 -07002383 [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
2384 .WillOnce(Invoke([=, this]() {
2385 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2386 }));
Bence Békybac04052022-04-07 15:44:29 -04002387 QuicFrames frames;
2388 frames.push_back(QuicFrame(frame1_));
2389 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
2390 ENCRYPTION_FORWARD_SECURE);
2391 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2392 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2393
2394 // Process another packet with a different peer address on server side will
2395 // start connection migration.
2396 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2397 // IETF QUIC send algorithm should be changed to a different object, so no
2398 // OnPacketSent() called on the old send algorithm.
2399 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0);
2400
2401 QuicFrames frames2;
2402 frames2.push_back(QuicFrame(frame2_));
2403 QuicPaddingFrame padding;
2404 frames2.push_back(QuicFrame(padding));
2405 peer_creator_.SetServerConnectionId(server_cid1);
2406 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2407 ENCRYPTION_FORWARD_SECURE);
2408 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2409 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2410 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2411 connection_.active_effective_peer_migration_type());
2412 EXPECT_LT(0u, writer_->packets_write_attempts());
2413 EXPECT_TRUE(connection_.HasPendingPathValidation());
2414 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
2415 send_algorithm_);
2416 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2417 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2418 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2419 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
2420 const auto* alternative_path =
2421 QuicConnectionPeer::GetAlternativePath(&connection_);
2422 EXPECT_EQ(default_path->client_connection_id, client_cid1);
2423 EXPECT_EQ(default_path->server_connection_id, server_cid1);
2424 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
2425 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
2426 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
2427 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
2428
2429 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes; ++i) {
2430 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2431 static_cast<TestAlarmFactory::TestAlarm*>(
2432 QuicPathValidatorPeer::retry_timer(
2433 QuicConnectionPeer::path_validator(&connection_)))
2434 ->Fire();
2435 }
2436 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2437 connection_.active_effective_peer_migration_type());
2438
2439 // Make sure anti-amplification limit is not reached.
2440 ProcessFramesPacketWithAddresses(
2441 {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
2442 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2443 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2444 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2445
2446 // Advance the time so that the reverse path validation times out.
2447 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2448 static_cast<TestAlarmFactory::TestAlarm*>(
2449 QuicPathValidatorPeer::retry_timer(
2450 QuicConnectionPeer::path_validator(&connection_)))
2451 ->Fire();
2452 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2453 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2454 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2455 EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
2456 send_algorithm_);
2457 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2458
2459 // Verify that default_path_ is reverted and alternative_path_ is cleared.
2460 EXPECT_EQ(default_path->client_connection_id, client_cid0);
2461 EXPECT_EQ(default_path->server_connection_id, server_cid0);
2462 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
2463 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
2464 auto* retire_peer_issued_cid_alarm =
2465 connection_.GetRetirePeerIssuedConnectionIdAlarm();
2466 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
2467 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
2468 retire_peer_issued_cid_alarm->Fire();
2469 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2470 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2471}
2472
2473TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
danzh65153092023-06-16 10:59:32 -07002474 if (!version().HasIetfQuicFrames() &&
2475 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2476 return;
2477 }
Bence Békybac04052022-04-07 15:44:29 -04002478 PathProbeTestInit(Perspective::IS_SERVER);
2479
2480 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2481 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
2482
2483 // Process a padded PING packet with no peer address change on server side
2484 // will be ignored. But a PATH CHALLENGE packet with no peer address change
2485 // will be considered as path probing.
2486 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2487
2488 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2489 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2490 probing_packet->encrypted_length),
2491 clock_.Now()));
2492
2493 uint64_t num_probing_received =
2494 connection_.GetStats().num_connectivity_probing_received;
2495 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2496
2497 EXPECT_EQ(
2498 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2499 connection_.GetStats().num_connectivity_probing_received);
2500 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2501 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2502}
2503
2504// Regression test for b/150161358.
2505TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
2506 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2507 writer_->SetWriteBlocked();
2508
2509 // Send a MTU packet while blocked. It should be buffered.
2510 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2511 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2512 EXPECT_TRUE(writer_->IsWriteBlocked());
2513
2514 writer_->AlwaysGetPacketTooLarge();
2515 writer_->SetWritable();
2516 connection_.OnCanWrite();
2517}
2518
2519TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2520 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2521 if (!IsDefaultTestConfiguration()) {
2522 return;
2523 }
2524
2525 set_perspective(Perspective::IS_CLIENT);
2526
2527 BlockOnNextWrite();
2528
2529 QuicStreamId stream_id = 2;
2530 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2531
2532 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2533
2534 writer_->SetWritable();
2535 connection_.SendConnectivityProbingPacket(writer_.get(),
2536 connection_.peer_address());
2537 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2538 connection_.OnCanWrite();
2539}
2540
2541TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2542 // Regression test for b/74073386.
2543 {
2544 InSequence seq;
2545 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2546 .Times(AtLeast(1));
2547 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
2548 }
2549
2550 set_perspective(Perspective::IS_CLIENT);
2551
2552 writer_->SimulateNextPacketTooLarge();
2553
2554 // This packet write should fail, which should cause the connection to close
2555 // after sending a connection close packet, then the failed packet should be
2556 // queued.
2557 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2558
2559 EXPECT_FALSE(connection_.connected());
2560 // No need to buffer packets.
2561 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2562
2563 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2564 connection_.OnCanWrite();
2565 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2566}
2567
2568class TestQuicPathValidationContext : public QuicPathValidationContext {
2569 public:
2570 TestQuicPathValidationContext(const QuicSocketAddress& self_address,
2571 const QuicSocketAddress& peer_address,
2572
2573 QuicPacketWriter* writer)
2574 : QuicPathValidationContext(self_address, peer_address),
2575 writer_(writer) {}
2576
2577 QuicPacketWriter* WriterToUse() override { return writer_; }
2578
2579 private:
2580 QuicPacketWriter* writer_;
2581};
2582
2583class TestValidationResultDelegate : public QuicPathValidator::ResultDelegate {
2584 public:
2585 TestValidationResultDelegate(QuicConnection* connection,
2586 const QuicSocketAddress& expected_self_address,
2587 const QuicSocketAddress& expected_peer_address,
2588 bool* success)
2589 : QuicPathValidator::ResultDelegate(),
2590 connection_(connection),
2591 expected_self_address_(expected_self_address),
2592 expected_peer_address_(expected_peer_address),
2593 success_(success) {}
2594 void OnPathValidationSuccess(
wub130bde92022-08-01 14:33:14 -07002595 std::unique_ptr<QuicPathValidationContext> context,
2596 QuicTime /*start_time*/) override {
Bence Békybac04052022-04-07 15:44:29 -04002597 EXPECT_EQ(expected_self_address_, context->self_address());
2598 EXPECT_EQ(expected_peer_address_, context->peer_address());
2599 *success_ = true;
2600 }
2601
2602 void OnPathValidationFailure(
2603 std::unique_ptr<QuicPathValidationContext> context) override {
2604 EXPECT_EQ(expected_self_address_, context->self_address());
2605 EXPECT_EQ(expected_peer_address_, context->peer_address());
2606 if (connection_->perspective() == Perspective::IS_CLIENT) {
danzh8fdee2e2023-01-05 15:33:02 -08002607 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2608 *context);
Bence Békybac04052022-04-07 15:44:29 -04002609 }
2610 *success_ = false;
2611 }
2612
2613 private:
2614 QuicConnection* connection_;
2615 QuicSocketAddress expected_self_address_;
2616 QuicSocketAddress expected_peer_address_;
2617 bool* success_;
2618};
2619
danzh8fdee2e2023-01-05 15:33:02 -08002620// A test implementation which migrates to server preferred address
2621// on path validation suceeds. Otherwise, client cleans up alternative path.
fayang5c6e7012023-01-08 20:06:01 -08002622class ServerPreferredAddressTestResultDelegate
danzh8fdee2e2023-01-05 15:33:02 -08002623 : public QuicPathValidator::ResultDelegate {
2624 public:
2625 explicit ServerPreferredAddressTestResultDelegate(QuicConnection* connection)
2626 : connection_(connection) {}
2627 void OnPathValidationSuccess(
2628 std::unique_ptr<QuicPathValidationContext> context,
2629 QuicTime /*start_time*/) override {
2630 connection_->OnServerPreferredAddressValidated(*context, false);
2631 }
2632
2633 void OnPathValidationFailure(
2634 std::unique_ptr<QuicPathValidationContext> context) override {
2635 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2636 *context);
2637 }
2638
2639 protected:
2640 QuicConnection* connection() { return connection_; }
2641
2642 private:
2643 QuicConnection* connection_;
2644};
2645
danzh65153092023-06-16 10:59:32 -07002646// Receive a path probe request at the server side, in IETF version: receive a
2647// packet contains PATH CHALLENGE with peer address change.
danzhb159ab02023-01-30 10:58:46 -08002648TEST_P(QuicConnectionTest, ReceivePathProbingFromNewPeerAddressAtServer) {
danzh65153092023-06-16 10:59:32 -07002649 if (!version().HasIetfQuicFrames() &&
2650 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2651 return;
2652 }
Bence Békybac04052022-04-07 15:44:29 -04002653 PathProbeTestInit(Perspective::IS_SERVER);
2654
2655 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2656 QuicPathFrameBuffer payload;
2657 if (!GetParam().version.HasIetfQuicFrames()) {
2658 EXPECT_CALL(visitor_,
2659 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2660 .Times(1);
2661 } else {
2662 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
danzh4d58dae2023-06-06 11:13:10 -07002663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2664 .Times(AtLeast(1u))
2665 .WillOnce(Invoke([&]() {
2666 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2667 EXPECT_EQ(1u, writer_->path_response_frames().size());
2668 payload = writer_->path_challenge_frames().front().data_buffer;
awillia202240c2024-07-08 09:47:00 -07002669 }))
2670 .WillRepeatedly(DoDefault());
Bence Békybac04052022-04-07 15:44:29 -04002671 }
2672 // Process a probing packet from a new peer address on server side
2673 // is effectively receiving a connectivity probing.
2674 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2675 /*port=*/23456);
2676
2677 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2678 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2679 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2680 probing_packet->encrypted_length),
2681 clock_.Now()));
2682 uint64_t num_probing_received =
2683 connection_.GetStats().num_connectivity_probing_received;
2684 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2685
2686 EXPECT_EQ(num_probing_received + 1,
2687 connection_.GetStats().num_connectivity_probing_received);
2688 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2689 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhaf2e52a2022-04-20 07:37:03 -07002690 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002691 QuicByteCount bytes_sent =
2692 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_);
2693 EXPECT_LT(0u, bytes_sent);
2694 EXPECT_EQ(received->length(),
2695 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2696
2697 // Receiving one more probing packet should update the bytes count.
2698 probing_packet = ConstructProbingPacket();
2699 received.reset(ConstructReceivedPacket(
2700 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2701 probing_packet->encrypted_length),
2702 clock_.Now()));
2703 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2704
2705 EXPECT_EQ(num_probing_received + 2,
2706 connection_.GetStats().num_connectivity_probing_received);
2707 EXPECT_EQ(2 * bytes_sent,
2708 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2709 EXPECT_EQ(2 * received->length(),
2710 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2711
danzh4d58dae2023-06-06 11:13:10 -07002712 EXPECT_EQ(2 * bytes_sent,
Bence Békybac04052022-04-07 15:44:29 -04002713 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2714 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -07002715 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04002716 ProcessFramesPacketWithAddresses(frames, connection_.self_address(),
2717 kNewPeerAddress,
2718 ENCRYPTION_FORWARD_SECURE);
2719 EXPECT_LT(2 * received->length(),
2720 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
danzh4d58dae2023-06-06 11:13:10 -07002721 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
Bence Békybac04052022-04-07 15:44:29 -04002722 // Receiving another probing packet from a newer address with a different
2723 // port shouldn't trigger another reverse path validation.
2724 QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
2725 /*port=*/34567);
2726 probing_packet = ConstructProbingPacket();
2727 received.reset(ConstructReceivedPacket(
2728 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2729 probing_packet->encrypted_length),
2730 clock_.Now()));
2731 ProcessReceivedPacket(kSelfAddress, kNewerPeerAddress, *received);
2732 EXPECT_FALSE(connection_.HasPendingPathValidation());
danzh4d58dae2023-06-06 11:13:10 -07002733 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
Bence Békybac04052022-04-07 15:44:29 -04002734 }
2735
2736 // Process another packet with the old peer address on server side will not
2737 // start peer migration.
2738 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2739 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2740 ENCRYPTION_INITIAL);
2741 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2742 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2743}
2744
danzhb159ab02023-01-30 10:58:46 -08002745// Receive a packet contains PATH CHALLENGE with self address change.
2746TEST_P(QuicConnectionTest, ReceivePathProbingToPreferredAddressAtServer) {
2747 if (!GetParam().version.HasIetfQuicFrames()) {
2748 return;
2749 }
2750 ServerHandlePreferredAddressInit();
2751
2752 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2753 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2754
2755 // Process a probing packet to the server preferred address.
2756 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2757 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2758 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2759 probing_packet->encrypted_length),
2760 clock_.Now()));
2761 uint64_t num_probing_received =
2762 connection_.GetStats().num_connectivity_probing_received;
2763 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2764 .Times(AtLeast(1u))
2765 .WillOnce(Invoke([&]() {
2766 EXPECT_EQ(1u, writer_->path_response_frames().size());
2767 // Verify that the PATH_RESPONSE is sent from the original self address.
2768 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
2769 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
2770 }));
2771 ProcessReceivedPacket(kServerPreferredAddress, kPeerAddress, *received);
2772
2773 EXPECT_EQ(num_probing_received + 1,
2774 connection_.GetStats().num_connectivity_probing_received);
2775 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
2776 &connection_, kServerPreferredAddress, kPeerAddress));
2777 EXPECT_NE(kServerPreferredAddress, connection_.self_address());
2778
2779 // Receiving another probing packet from a new client address.
2780 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2781 /*port=*/34567);
2782 probing_packet = ConstructProbingPacket();
2783 received.reset(ConstructReceivedPacket(
2784 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2785 probing_packet->encrypted_length),
2786 clock_.Now()));
2787 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2788 .Times(AtLeast(1u))
2789 .WillOnce(Invoke([&]() {
2790 EXPECT_EQ(1u, writer_->path_response_frames().size());
2791 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
fayang1f578d32023-03-20 11:36:15 -07002792 EXPECT_EQ(kServerPreferredAddress.host(),
2793 writer_->last_write_source_address());
2794 // The responses should be sent from preferred address given server
2795 // has not received packet on original address from the new client
2796 // address.
danzhb159ab02023-01-30 10:58:46 -08002797 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2798 }));
2799 ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received);
2800
2801 EXPECT_EQ(num_probing_received + 2,
2802 connection_.GetStats().num_connectivity_probing_received);
2803 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
2804 kNewPeerAddress));
2805 EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2806 EXPECT_EQ(received->length(),
2807 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2808}
2809
Bence Békybac04052022-04-07 15:44:29 -04002810// Receive a padded PING packet with a port change on server side.
2811TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2812 set_perspective(Perspective::IS_SERVER);
2813 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2814 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2815 if (version().SupportsAntiAmplificationLimit()) {
2816 QuicConnectionPeer::SetAddressValidated(&connection_);
2817 }
2818
2819 // Clear direct_peer_address.
2820 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2821 // Clear effective_peer_address, it is the same as direct_peer_address for
2822 // this test.
2823 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2824 QuicSocketAddress());
2825 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2826
2827 if (GetParam().version.UsesCryptoFrames()) {
2828 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2829 } else {
2830 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2831 }
2832 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2833 ENCRYPTION_INITIAL);
2834 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2835 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2836
danzh65153092023-06-16 10:59:32 -07002837 if (GetParam().version.HasIetfQuicFrames() ||
2838 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002839 // In IETF version, a padded PING packet with port change is not taken as
2840 // connectivity probe.
2841 EXPECT_CALL(visitor_, GetHandshakeState())
2842 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2843 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2844 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2845 } else {
2846 // In non-IETF version, process a padded PING packet from a new peer
2847 // address on server side is effectively receiving a connectivity probing.
2848 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2849 EXPECT_CALL(visitor_,
2850 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2851 .Times(1);
2852 }
2853 const QuicSocketAddress kNewPeerAddress =
2854 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2855
2856 QuicFrames frames;
2857 // Write a PING frame, which has no data payload.
2858 QuicPingFrame ping_frame;
2859 frames.push_back(QuicFrame(ping_frame));
2860
2861 // Add padding to the rest of the packet.
2862 QuicPaddingFrame padding_frame;
2863 frames.push_back(QuicFrame(padding_frame));
2864
2865 uint64_t num_probing_received =
2866 connection_.GetStats().num_connectivity_probing_received;
2867
2868 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
2869 ENCRYPTION_INITIAL);
2870
danzh65153092023-06-16 10:59:32 -07002871 if (GetParam().version.HasIetfQuicFrames() ||
2872 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002873 // Padded PING with port changen is not considered as connectivity probe but
2874 // a PORT CHANGE.
2875 EXPECT_EQ(num_probing_received,
2876 connection_.GetStats().num_connectivity_probing_received);
2877 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2878 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2879 } else {
2880 EXPECT_EQ(num_probing_received + 1,
2881 connection_.GetStats().num_connectivity_probing_received);
2882 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2883 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2884 }
2885
danzh65153092023-06-16 10:59:32 -07002886 if (GetParam().version.HasIetfQuicFrames() ||
2887 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002888 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2889 }
danzh65153092023-06-16 10:59:32 -07002890 // Process another packet with the old peer address on server side.
Bence Békybac04052022-04-07 15:44:29 -04002891 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2892 ENCRYPTION_INITIAL);
2893 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2894 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2895}
2896
2897TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
danzh65153092023-06-16 10:59:32 -07002898 if (!GetParam().version.HasIetfQuicFrames() &&
2899 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2900 return;
2901 }
Bence Békybac04052022-04-07 15:44:29 -04002902 PathProbeTestInit(Perspective::IS_SERVER);
2903
2904 // Decrease packet number to simulate out-of-order packets.
2905 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2906
2907 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2908 if (!GetParam().version.HasIetfQuicFrames()) {
2909 EXPECT_CALL(visitor_,
2910 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2911 .Times(1);
2912 } else {
2913 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2914 }
2915
2916 // Process a padded PING packet from a new peer address on server side
2917 // is effectively receiving a connectivity probing, even if a newer packet has
2918 // been received before this one.
2919 const QuicSocketAddress kNewPeerAddress =
2920 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2921
2922 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2923 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2924 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2925 probing_packet->encrypted_length),
2926 clock_.Now()));
2927
2928 uint64_t num_probing_received =
2929 connection_.GetStats().num_connectivity_probing_received;
2930 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2931
danzh65153092023-06-16 10:59:32 -07002932 EXPECT_EQ(num_probing_received +
2933 (!version().HasIetfQuicFrames() &&
2934 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2935 ? 0u
2936 : 1u),
Bence Békybac04052022-04-07 15:44:29 -04002937 connection_.GetStats().num_connectivity_probing_received);
danzh65153092023-06-16 10:59:32 -07002938 EXPECT_EQ((!version().HasIetfQuicFrames() &&
2939 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2940 ? kNewPeerAddress
2941 : kPeerAddress),
2942 connection_.peer_address());
2943 EXPECT_EQ((!version().HasIetfQuicFrames() &&
2944 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2945 ? kNewPeerAddress
2946 : kPeerAddress),
2947 connection_.effective_peer_address());
Bence Békybac04052022-04-07 15:44:29 -04002948}
2949
2950TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
danzh65153092023-06-16 10:59:32 -07002951 if (!GetParam().version.HasIetfQuicFrames() &&
2952 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2953 return;
2954 }
Bence Békybac04052022-04-07 15:44:29 -04002955 PathProbeTestInit(Perspective::IS_SERVER);
2956
2957 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2958 if (!GetParam().version.HasIetfQuicFrames()) {
2959 EXPECT_CALL(visitor_,
2960 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2961 .Times(1);
2962 } else {
2963 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2964 }
2965
2966 // Process a padded PING packet from a new peer address on server side
2967 // is effectively receiving a connectivity probing.
2968 const QuicSocketAddress kNewPeerAddress =
2969 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2970
2971 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2972 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2973 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2974 probing_packet->encrypted_length),
2975 clock_.Now()));
2976 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2977 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2978 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2979
2980 // Process another non-probing packet with the new peer address on server
2981 // side will start peer migration.
2982 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2983
2984 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2985 kNewPeerAddress, ENCRYPTION_INITIAL);
2986 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2987 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2988}
2989
2990TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) {
danzh65153092023-06-16 10:59:32 -07002991 if (!version().HasIetfQuicFrames() &&
2992 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2993 return;
2994 }
Bence Békybac04052022-04-07 15:44:29 -04002995 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2996 PathProbeTestInit(Perspective::IS_CLIENT);
2997
2998 // Client takes all padded PING packet as speculative connectivity
2999 // probing packet, and reports to visitor.
3000 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
3001
3002 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
3003 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
3004 QuicEncryptedPacket(probing_packet->encrypted_buffer,
3005 probing_packet->encrypted_length),
3006 clock_.Now()));
3007 uint64_t num_probing_received =
3008 connection_.GetStats().num_connectivity_probing_received;
3009 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
3010
3011 EXPECT_EQ(
3012 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
3013 connection_.GetStats().num_connectivity_probing_received);
3014 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3015 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3016}
3017
3018TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
danzh65153092023-06-16 10:59:32 -07003019 if (GetParam().version.HasIetfQuicFrames() ||
3020 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04003021 return;
3022 }
3023 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3024 PathProbeTestInit(Perspective::IS_CLIENT);
3025
3026 // Process a padded PING packet with a different self address on client side
3027 // is effectively receiving a connectivity probing.
3028 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
3029 if (!GetParam().version.HasIetfQuicFrames()) {
3030 EXPECT_CALL(visitor_,
3031 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
3032 .Times(1);
3033 } else {
3034 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
3035 }
3036
3037 const QuicSocketAddress kNewSelfAddress =
3038 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3039
3040 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
3041 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
3042 QuicEncryptedPacket(probing_packet->encrypted_buffer,
3043 probing_packet->encrypted_length),
3044 clock_.Now()));
3045 uint64_t num_probing_received =
3046 connection_.GetStats().num_connectivity_probing_received;
3047 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
3048
3049 EXPECT_EQ(num_probing_received + 1,
3050 connection_.GetStats().num_connectivity_probing_received);
3051 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3052 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3053}
3054
3055TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
3056 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3057 set_perspective(Perspective::IS_CLIENT);
3058 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3059
3060 // Clear direct_peer_address.
3061 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
3062 // Clear effective_peer_address, it is the same as direct_peer_address for
3063 // this test.
3064 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
3065 QuicSocketAddress());
3066 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
3067
fayangd1f2c992022-12-21 10:34:55 -08003068 if (connection_.version().HasIetfQuicFrames()) {
3069 // Verify the 2nd packet from unknown server address gets dropped.
3070 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3071 } else if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3072 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -04003073 } else {
fayangd1f2c992022-12-21 10:34:55 -08003074 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -04003075 }
3076 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3077 ENCRYPTION_INITIAL);
3078 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3079 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
Bence Békybac04052022-04-07 15:44:29 -04003080 const QuicSocketAddress kNewPeerAddress =
3081 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3082 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
3083 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3084 kNewPeerAddress, ENCRYPTION_INITIAL);
3085 if (connection_.version().HasIetfQuicFrames()) {
3086 // IETF QUIC disallows server initiated address change.
3087 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3088 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3089 } else {
3090 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
3091 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
3092 }
3093}
3094
wub3cab5622024-02-20 08:30:32 -08003095TEST_P(QuicConnectionTest, NoNormalizedPeerAddressChangeAtClient) {
3096 if (!version().HasIetfQuicFrames()) {
3097 return;
3098 }
3099 QuicIpAddress peer_ip;
3100 peer_ip.FromString("1.1.1.1");
3101
3102 QuicSocketAddress peer_addr = QuicSocketAddress(peer_ip, /*port=*/443);
3103 QuicSocketAddress dualstack_peer_addr =
3104 QuicSocketAddress(peer_addr.host().DualStacked(), peer_addr.port());
3105
3106 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
3107 set_perspective(Perspective::IS_CLIENT);
3108 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3109
3110 QuicConnectionPeer::SetDirectPeerAddress(&connection_, dualstack_peer_addr);
3111
3112 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
3113 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
3114 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, peer_addr,
3115 ENCRYPTION_INITIAL);
3116 EXPECT_TRUE(connection_.connected());
3117
3118 if (GetQuicReloadableFlag(quic_test_peer_addr_change_after_normalize)) {
3119 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
3120 } else {
3121 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
3122 }
3123}
3124
fayangd1f2c992022-12-21 10:34:55 -08003125TEST_P(QuicConnectionTest, ServerAddressChangesToKnownAddress) {
3126 if (!connection_.version().HasIetfQuicFrames()) {
3127 return;
3128 }
3129 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3130 set_perspective(Perspective::IS_CLIENT);
3131 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3132
3133 // Clear direct_peer_address.
3134 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
3135 // Clear effective_peer_address, it is the same as direct_peer_address for
3136 // this test.
3137 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
3138 QuicSocketAddress());
3139 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
3140
3141 // Verify all 3 packets get processed.
3142 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
3143 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3144 ENCRYPTION_INITIAL);
3145 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3146 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3147
3148 // Process another packet with a different but known server address.
3149 const QuicSocketAddress kNewPeerAddress =
3150 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3151 connection_.AddKnownServerAddress(kNewPeerAddress);
3152 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(0);
3153 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3154 kNewPeerAddress, ENCRYPTION_INITIAL);
3155 // Verify peer address does not change.
3156 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3157 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3158
3159 // Process 3rd packet from previous server address.
3160 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3161 ENCRYPTION_INITIAL);
3162 // Verify peer address does not change.
3163 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3164 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3165}
3166
danzh8fdee2e2023-01-05 15:33:02 -08003167TEST_P(QuicConnectionTest,
3168 PeerAddressChangesToPreferredAddressBeforeClientInitiates) {
3169 if (!version().HasIetfQuicFrames()) {
3170 return;
3171 }
3172 ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3173 ASSERT_TRUE(connection_.self_address().host().IsIPv6());
danzh8fdee2e2023-01-05 15:33:02 -08003174 const QuicConnectionId connection_id = TestConnectionId(17);
3175 const StatelessResetToken reset_token =
3176 QuicUtils::GenerateStatelessResetToken(connection_id);
3177
3178 connection_.CreateConnectionIdManager();
3179
3180 connection_.SendCryptoStreamData();
3181 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07003182 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
danzh8fdee2e2023-01-05 15:33:02 -08003183 QuicAckFrame frame = InitAckFrame(1);
3184 // Received ACK for packet 1.
3185 ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
3186 // Discard INITIAL key.
3187 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
3188 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3189
3190 QuicConfig config;
danzh8fdee2e2023-01-05 15:33:02 -08003191 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
3192 kTestStatelessResetToken);
3193 QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
3194 kServerPreferredAddress);
3195 QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
3196 &config, connection_id, reset_token);
3197 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08003198 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
3199 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
danzh8fdee2e2023-01-05 15:33:02 -08003200 connection_.SetFromConfig(config);
3201 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3202 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhb159ab02023-01-30 10:58:46 -08003203 ASSERT_TRUE(
3204 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)
3205 .IsInitialized());
3206 EXPECT_EQ(
3207 kServerPreferredAddress,
3208 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_));
danzh8fdee2e2023-01-05 15:33:02 -08003209
3210 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(0);
3211 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3212 kServerPreferredAddress, ENCRYPTION_INITIAL);
3213}
3214
Bence Békybac04052022-04-07 15:44:29 -04003215TEST_P(QuicConnectionTest, MaxPacketSize) {
3216 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3217 EXPECT_EQ(1250u, connection_.max_packet_length());
3218}
3219
3220TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
3221 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3222
3223 // SetFromConfig is always called after construction from InitializeSession.
3224 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08003225 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
3226 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04003227 constexpr uint32_t kTestMaxPacketSize = 1233u;
3228 QuicConfig config;
3229 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3230 connection_.SetFromConfig(config);
3231
3232 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
3233}
3234
3235TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
3236 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3237
3238 // SetFromConfig is always called after construction from InitializeSession.
3239 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08003240 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
3241 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04003242 constexpr uint32_t kTestMaxPacketSize = 1450u;
3243 QuicConfig config;
3244 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3245 connection_.SetFromConfig(config);
3246
3247 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3248}
3249
3250TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
3251 TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress,
3252 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003253 Perspective::IS_SERVER, version(),
3254 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003255 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
3256 EXPECT_EQ(1000u, connection.max_packet_length());
3257}
3258
3259TEST_P(QuicConnectionTest, LowerServerResponseMtuTest) {
3260 set_perspective(Perspective::IS_SERVER);
3261 connection_.SetMaxPacketLength(1000);
3262 EXPECT_EQ(1000u, connection_.max_packet_length());
3263
birenroyef686222022-09-12 11:34:34 -07003264 SetQuicFlag(quic_use_lower_server_response_mtu_for_test, true);
Bence Békybac04052022-04-07 15:44:29 -04003265 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(::testing::AtMost(1));
3266 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(::testing::AtMost(1));
3267 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3268 EXPECT_EQ(1250u, connection_.max_packet_length());
3269}
3270
3271TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
3272 set_perspective(Perspective::IS_SERVER);
3273 connection_.SetMaxPacketLength(1000);
3274
3275 QuicPacketHeader header;
3276 header.destination_connection_id = connection_id_;
3277 header.version_flag = true;
3278 header.packet_number = QuicPacketNumber(12);
3279
3280 if (QuicVersionHasLongHeaderLengths(
3281 peer_framer_.version().transport_version)) {
3282 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07003283 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3284 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04003285 }
3286
3287 QuicFrames frames;
3288 QuicPaddingFrame padding;
3289 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3290 frames.push_back(QuicFrame(&crypto_frame_));
3291 } else {
3292 frames.push_back(QuicFrame(frame1_));
3293 }
3294 frames.push_back(QuicFrame(padding));
3295 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3296 char buffer[kMaxOutgoingPacketSize];
3297 size_t encrypted_length =
3298 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3299 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08003300 EXPECT_EQ(kMaxOutgoingPacketSize,
3301 encrypted_length +
3302 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003303
3304 framer_.set_version(version());
3305 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3306 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3307 } else {
3308 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3309 }
3310 connection_.ProcessUdpPacket(
3311 kSelfAddress, kPeerAddress,
3312 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3313 false));
3314
martinduke9e0811c2022-12-08 20:35:57 -08003315 EXPECT_EQ(kMaxOutgoingPacketSize,
3316 connection_.max_packet_length() +
3317 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003318}
3319
3320TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
3321 const QuicByteCount lower_max_packet_size = 1240;
3322 writer_->set_max_packet_size(lower_max_packet_size);
3323 set_perspective(Perspective::IS_SERVER);
3324 connection_.SetMaxPacketLength(1000);
3325 EXPECT_EQ(1000u, connection_.max_packet_length());
3326
3327 QuicPacketHeader header;
3328 header.destination_connection_id = connection_id_;
3329 header.version_flag = true;
3330 header.packet_number = QuicPacketNumber(12);
3331
3332 if (QuicVersionHasLongHeaderLengths(
3333 peer_framer_.version().transport_version)) {
3334 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07003335 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3336 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04003337 }
3338
3339 QuicFrames frames;
3340 QuicPaddingFrame padding;
3341 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3342 frames.push_back(QuicFrame(&crypto_frame_));
3343 } else {
3344 frames.push_back(QuicFrame(frame1_));
3345 }
3346 frames.push_back(QuicFrame(padding));
3347 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3348 char buffer[kMaxOutgoingPacketSize];
3349 size_t encrypted_length =
3350 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3351 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08003352 EXPECT_EQ(kMaxOutgoingPacketSize,
3353 encrypted_length +
3354 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003355
3356 framer_.set_version(version());
3357 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3358 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3359 } else {
3360 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3361 }
3362 connection_.ProcessUdpPacket(
3363 kSelfAddress, kPeerAddress,
3364 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3365 false));
3366
3367 // Here, the limit imposed by the writer is lower than the size of the packet
3368 // received, so the writer max packet size is used.
3369 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3370}
3371
3372TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
3373 const QuicByteCount lower_max_packet_size = 1240;
3374 writer_->set_max_packet_size(lower_max_packet_size);
3375
3376 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
3377 "Default maximum packet size is too low");
3378 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
3379
3380 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3381}
3382
3383TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
3384 const QuicConnectionId connection_id = TestConnectionId(17);
3385 const QuicByteCount lower_max_packet_size = 1240;
3386 writer_->set_max_packet_size(lower_max_packet_size);
3387 TestConnection connection(connection_id, kSelfAddress, kPeerAddress,
3388 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003389 Perspective::IS_CLIENT, version(),
3390 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003391 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
3392 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
3393}
3394
3395TEST_P(QuicConnectionTest, PacketsInOrder) {
3396 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3397
3398 ProcessPacket(1);
3399 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
3400 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3401
3402 ProcessPacket(2);
3403 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
3404 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3405
3406 ProcessPacket(3);
3407 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3408 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3409}
3410
3411TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
3412 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3413
3414 ProcessPacket(3);
3415 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3416 EXPECT_TRUE(IsMissing(2));
3417 EXPECT_TRUE(IsMissing(1));
3418
3419 ProcessPacket(2);
3420 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3421 EXPECT_FALSE(IsMissing(2));
3422 EXPECT_TRUE(IsMissing(1));
3423
3424 ProcessPacket(1);
3425 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3426 EXPECT_FALSE(IsMissing(2));
3427 EXPECT_FALSE(IsMissing(1));
3428}
3429
3430TEST_P(QuicConnectionTest, DuplicatePacket) {
3431 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3432
3433 ProcessPacket(3);
3434 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3435 EXPECT_TRUE(IsMissing(2));
3436 EXPECT_TRUE(IsMissing(1));
3437
3438 // Send packet 3 again, but do not set the expectation that
3439 // the visitor OnStreamFrame() will be called.
3440 ProcessDataPacket(3);
3441 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3442 EXPECT_TRUE(IsMissing(2));
3443 EXPECT_TRUE(IsMissing(1));
3444}
3445
3446TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
3447 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3448 return;
3449 }
3450 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3451
3452 ProcessPacket(3);
3453 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3454 EXPECT_TRUE(IsMissing(2));
3455 EXPECT_TRUE(IsMissing(1));
3456
3457 ProcessPacket(2);
3458 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3459 EXPECT_TRUE(IsMissing(1));
3460
3461 ProcessPacket(5);
3462 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
3463 EXPECT_TRUE(IsMissing(1));
3464 EXPECT_TRUE(IsMissing(4));
3465
3466 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
3467 // packet the peer will not retransmit. It indicates this by sending 'least
3468 // awaiting' is 4. The connection should then realize 1 will not be
3469 // retransmitted, and will remove it from the missing list.
3470 QuicAckFrame frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07003471 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003472 ProcessAckPacket(6, &frame);
3473
3474 // Force an ack to be sent.
3475 SendAckPacketToPeer();
3476 EXPECT_TRUE(IsMissing(4));
3477}
3478
3479TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
3480 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
3481 if (!IsDefaultTestConfiguration() ||
3482 VersionHasIetfQuicFrames(version().transport_version)) {
3483 return;
3484 }
3485
3486 // Process an unencrypted packet from the non-crypto stream.
3487 frame1_.stream_id = 3;
3488 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3489 EXPECT_CALL(visitor_,
3490 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3491 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
3492 "");
3493 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
3494}
3495
3496TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
3497 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3498
3499 ProcessPacket(3);
3500 // Should not cause an ack.
3501 EXPECT_EQ(0u, writer_->packets_write_attempts());
3502
3503 ProcessPacket(2);
3504 // Should ack immediately, since this fills the last hole.
3505 EXPECT_EQ(1u, writer_->packets_write_attempts());
3506
3507 ProcessPacket(1);
3508 // Should ack immediately, since this fills the last hole.
3509 EXPECT_EQ(2u, writer_->packets_write_attempts());
3510
3511 ProcessPacket(4);
3512 // Should not cause an ack.
3513 EXPECT_EQ(2u, writer_->packets_write_attempts());
3514}
3515
3516TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
3517 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3518
3519 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3520 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3521 EXPECT_EQ(2u, writer_->packets_write_attempts());
3522
3523 QuicAckFrame ack1 = InitAckFrame(1);
3524 QuicAckFrame ack2 = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07003525 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003526 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3527 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
3528 }
3529 ProcessAckPacket(2, &ack2);
3530 // Should ack immediately since we have missing packets.
3531 EXPECT_EQ(2u, writer_->packets_write_attempts());
3532
3533 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3534 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
3535 }
3536 ProcessAckPacket(1, &ack1);
3537 // Should not ack an ack filling a missing packet.
3538 EXPECT_EQ(2u, writer_->packets_write_attempts());
3539}
3540
3541TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
3542 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3543 QuicPacketNumber original, second;
3544
3545 QuicByteCount packet_size =
3546 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3547 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3548
3549 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3550 // First nack triggers early retransmit.
3551 LostPacketVector lost_packets;
3552 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
3553 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3554 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3555 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07003556 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003557 QuicPacketNumber retransmission;
3558 // Packet 1 is short header for IETF QUIC because the encryption level
3559 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangfc04b8a2023-05-18 09:26:25 -07003560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _))
Bence Békybac04052022-04-07 15:44:29 -04003561 .WillOnce(SaveArg<2>(&retransmission));
3562
3563 ProcessAckPacket(&frame);
3564
3565 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
martindukeba002452023-03-21 08:10:46 -07003566 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003567 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3568 ProcessAckPacket(&frame2);
3569
3570 // Now if the peer sends an ack which still reports the retransmitted packet
3571 // as missing, that will bundle an ack with data after two acks in a row
3572 // indicate the high water mark needs to be raised.
3573 EXPECT_CALL(*send_algorithm_,
3574 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3575 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
3576 // No ack sent.
3577 size_t padding_frame_count = writer_->padding_frames().size();
3578 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3579 EXPECT_EQ(1u, writer_->stream_frames().size());
3580
3581 // No more packet loss for the rest of the test.
3582 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3583 .Times(AnyNumber());
3584 ProcessAckPacket(&frame2);
3585 EXPECT_CALL(*send_algorithm_,
3586 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3587 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
3588 // Ack bundled.
fayangfc04b8a2023-05-18 09:26:25 -07003589 // Do not ACK acks.
3590 EXPECT_EQ(1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04003591 EXPECT_EQ(1u, writer_->stream_frames().size());
fayangfc04b8a2023-05-18 09:26:25 -07003592 EXPECT_TRUE(writer_->ack_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04003593
3594 // But an ack with no missing packets will not send an ack.
3595 AckPacket(original, &frame2);
3596 ProcessAckPacket(&frame2);
3597 ProcessAckPacket(&frame2);
3598}
3599
3600TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) {
3601 if (!GetParam().version.HasIetfQuicFrames()) {
3602 return;
3603 }
3604 connection_.set_can_receive_ack_frequency_frame();
3605
3606 // Expect 13 acks, every 3rd packet including the first packet with
3607 // AckFrequencyFrame.
3608 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
3609 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3610
3611 QuicAckFrequencyFrame ack_frequency_frame;
3612 ack_frequency_frame.packet_tolerance = 3;
3613 ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
3614 ENCRYPTION_FORWARD_SECURE);
3615
3616 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38);
3617 // Receives packets 2 - 39.
3618 for (size_t i = 2; i <= 39; ++i) {
3619 ProcessDataPacket(i);
3620 }
3621}
3622
3623TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
3624 const size_t kMinRttMs = 40;
3625 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
3626 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
3627 QuicTime::Delta::Zero(), QuicTime::Zero());
3628 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
3629
3630 // Start ack decimation from 10th packet.
3631 connection_.set_min_received_before_ack_decimation(10);
3632
3633 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3634 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
3635
3636 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
3637 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
3638 // Receives packets 1 - 29.
3639 for (size_t i = 1; i <= 29; ++i) {
3640 ProcessDataPacket(i);
3641 }
3642
3643 // We now receive the 30th packet, and so we send an ack.
3644 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3645 ProcessDataPacket(30);
3646}
3647
3648TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
3649 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3650 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3651 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3652
3653 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3654 // Receives packets 1 - 39.
3655 for (size_t i = 1; i <= 39; ++i) {
3656 ProcessDataPacket(i);
3657 }
3658 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3659 // WINDOW_UPDATE.
3660 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3661 .WillOnce(Invoke([this]() {
3662 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3663 }));
3664 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3665 EXPECT_EQ(0u, writer_->window_update_frames().size());
3666 ProcessDataPacket(40);
3667 EXPECT_EQ(1u, writer_->window_update_frames().size());
3668
3669 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3670 // Receives packets 41 - 59.
3671 for (size_t i = 41; i <= 59; ++i) {
3672 ProcessDataPacket(i);
3673 }
3674 // Send a packet containing stream frame.
3675 SendStreamDataToPeer(
3676 QuicUtils::GetFirstBidirectionalStreamId(
3677 connection_.version().transport_version, Perspective::IS_CLIENT),
3678 "bar", 0, NO_FIN, nullptr);
3679
3680 // Session will not be informed until receiving another 20 packets.
3681 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3682 for (size_t i = 60; i <= 98; ++i) {
3683 ProcessDataPacket(i);
3684 EXPECT_EQ(0u, writer_->window_update_frames().size());
3685 }
3686 // Session does not add a retransmittable frame.
3687 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3688 .WillOnce(Invoke([this]() {
3689 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3690 }));
3691 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3692 EXPECT_EQ(0u, writer_->ping_frames().size());
3693 ProcessDataPacket(99);
3694 EXPECT_EQ(0u, writer_->window_update_frames().size());
3695 // A ping frame will be added.
3696 EXPECT_EQ(1u, writer_->ping_frames().size());
3697}
3698
3699TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
Bence Békybac04052022-04-07 15:44:29 -04003700 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08003701 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
3702 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04003703 QuicConfig config;
3704 QuicTagVector connection_options;
3705 connection_options.push_back(kEACK);
3706 config.SetConnectionOptionsToSend(connection_options);
3707 connection_.SetFromConfig(config);
3708
3709 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3710 connection_.OnHandshakeComplete();
3711
3712 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3713 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3714
3715 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3716 // Receive packets 1 - 9.
3717 for (size_t i = 1; i <= 9; ++i) {
3718 ProcessDataPacket(i);
3719 }
3720
3721 // Send a ping and fire the retransmission alarm.
3722 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3723 SendPing();
3724 QuicTime retransmission_time =
3725 connection_.GetRetransmissionAlarm()->deadline();
3726 clock_.AdvanceTime(retransmission_time - clock_.Now());
3727 connection_.GetRetransmissionAlarm()->Fire();
fayang339f0c82022-04-30 14:20:02 -07003728 ASSERT_LT(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04003729
3730 // Process a packet, which requests a retransmittable frame be bundled
3731 // with the ACK.
3732 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3733 .WillOnce(Invoke([this]() {
3734 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3735 }));
3736 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3737 ProcessDataPacket(11);
3738 EXPECT_EQ(1u, writer_->window_update_frames().size());
3739}
3740
Bence Békybac04052022-04-07 15:44:29 -04003741TEST_P(QuicConnectionTest, TooManySentPackets) {
3742 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3743
3744 QuicPacketCount max_tracked_packets = 50;
3745 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3746
3747 const int num_packets = max_tracked_packets + 5;
3748
3749 for (int i = 0; i < num_packets; ++i) {
3750 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3751 }
3752
3753 EXPECT_CALL(visitor_,
3754 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3755
3756 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3757
3758 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
3759}
3760
3761TEST_P(QuicConnectionTest, LargestObservedLower) {
3762 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3763
3764 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3765 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3766 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
martindukeba002452023-03-21 08:10:46 -07003767 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003768
3769 // Start out saying the largest observed is 2.
3770 QuicAckFrame frame1 = InitAckFrame(1);
3771 QuicAckFrame frame2 = InitAckFrame(2);
3772 ProcessAckPacket(&frame2);
3773
wubc9fd4292023-08-14 13:00:21 -07003774 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04003775 ProcessAckPacket(&frame1);
3776}
3777
3778TEST_P(QuicConnectionTest, AckUnsentData) {
3779 // Ack a packet which has not been sent.
3780 EXPECT_CALL(visitor_,
3781 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3782 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3783 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3784 QuicAckFrame frame = InitAckFrame(1);
3785 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3786 ProcessAckPacket(&frame);
3787 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
3788}
3789
3790TEST_P(QuicConnectionTest, BasicSending) {
3791 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3792 return;
3793 }
3794 const QuicConnectionStats& stats = connection_.GetStats();
3795 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
3796 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3797 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3798 ProcessDataPacket(1);
3799 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3800 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3801 QuicPacketNumber last_packet;
3802 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3803 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3804 SendAckPacketToPeer(); // Packet 2
3805
Bence Békybac04052022-04-07 15:44:29 -04003806 SendAckPacketToPeer(); // Packet 3
Bence Békybac04052022-04-07 15:44:29 -04003807
3808 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3809 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3810 SendAckPacketToPeer(); // Packet 5
Bence Békybac04052022-04-07 15:44:29 -04003811
martindukeba002452023-03-21 08:10:46 -07003812 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003813
3814 // Peer acks up to packet 3.
3815 QuicAckFrame frame = InitAckFrame(3);
3816 ProcessAckPacket(&frame);
3817 SendAckPacketToPeer(); // Packet 6
3818
martindukeba002452023-03-21 08:10:46 -07003819 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003820
3821 // Peer acks up to packet 4, the last packet.
3822 QuicAckFrame frame2 = InitAckFrame(6);
3823 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3824
3825 // Verify that we did not send an ack.
3826 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3827
Bence Békybac04052022-04-07 15:44:29 -04003828 // If we force an ack, we shouldn't change our retransmit state.
3829 SendAckPacketToPeer(); // Packet 7
Bence Békybac04052022-04-07 15:44:29 -04003830
3831 // But if we send more data it should.
3832 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3833 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3834 SendAckPacketToPeer(); // Packet 9
Bence Békybac04052022-04-07 15:44:29 -04003835 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3836}
3837
3838// QuicConnection should record the packet sent-time prior to sending the
3839// packet.
3840TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3841 // We're using a MockClock for the tests, so we have complete control over the
3842 // time.
3843 // Our recorded timestamp for the last packet sent time will be passed in to
3844 // the send_algorithm. Make sure that it is set to the correct value.
3845 QuicTime actual_recorded_send_time = QuicTime::Zero();
3846 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3847 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3848
3849 // First send without any pause and check the result.
3850 QuicTime expected_recorded_send_time = clock_.Now();
3851 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3852 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3853 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3854 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3855
3856 // Now pause during the write, and check the results.
3857 actual_recorded_send_time = QuicTime::Zero();
3858 const QuicTime::Delta write_pause_time_delta =
3859 QuicTime::Delta::FromMilliseconds(5000);
3860 SetWritePauseTimeDelta(write_pause_time_delta);
3861 expected_recorded_send_time = clock_.Now();
3862
3863 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3864 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3865 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3866 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3867 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3868 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3869}
3870
QUICHE teamac0a8082022-06-13 09:17:05 -07003871TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithRetransmissions) {
3872 // Send two stream frames in 1 packet by queueing them.
3873 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3874
3875 {
3876 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3877 connection_.SaveAndSendStreamData(
3878 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3879 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3880 connection_.SaveAndSendStreamData(
3881 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3882 "helloworld", 0, NO_FIN, LOSS_RETRANSMISSION);
3883 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3884 }
3885
3886 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3887 EXPECT_FALSE(connection_.HasQueuedData());
3888
3889 EXPECT_EQ(2u, writer_->frame_count());
3890 for (auto& frame : writer_->stream_frames()) {
3891 EXPECT_EQ(frame->data_length, 10u);
3892 }
3893
3894 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3895 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 20u);
3896}
3897
3898TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithMixedFrames) {
3899 // Send two stream frames in 1 packet by queueing them.
3900 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3901
3902 {
3903 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3904 // First frame is retransmission. Second is NOT_RETRANSMISSION but the
3905 // packet retains the PTO_RETRANSMISSION type.
3906 connection_.SaveAndSendStreamData(
3907 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3908 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3909 connection_.SaveAndSendStreamData(
3910 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3911 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3912 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3913 }
3914
3915 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3916 EXPECT_FALSE(connection_.HasQueuedData());
3917
3918 EXPECT_EQ(2u, writer_->frame_count());
3919 for (auto& frame : writer_->stream_frames()) {
3920 EXPECT_EQ(frame->data_length, 10u);
3921 }
3922
3923 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3924 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 10u);
3925}
3926
3927TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_NoRetransmission) {
3928 // Send two stream frames in 1 packet by queueing them.
3929 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3930
3931 {
3932 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3933 // Both frames are NOT_RETRANSMISSION
3934 connection_.SaveAndSendStreamData(
3935 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3936 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3937 connection_.SaveAndSendStreamData(
3938 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3939 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3940 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3941 }
3942
3943 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3944 EXPECT_FALSE(connection_.HasQueuedData());
3945
3946 EXPECT_EQ(2u, writer_->frame_count());
3947 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 0u);
3948 ASSERT_EQ(connection_.GetStats().bytes_retransmitted, 0u);
3949}
3950
Bence Békybac04052022-04-07 15:44:29 -04003951TEST_P(QuicConnectionTest, FramePacking) {
3952 // Send two stream frames in 1 packet by queueing them.
3953 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3954 {
3955 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3956 connection_.SendStreamData3();
3957 connection_.SendStreamData5();
3958 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3959 }
3960 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3961 EXPECT_FALSE(connection_.HasQueuedData());
3962
3963 // Parse the last packet and ensure it's an ack and two stream frames from
3964 // two different streams.
fayangfc04b8a2023-05-18 09:26:25 -07003965 EXPECT_EQ(2u, writer_->frame_count());
3966 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04003967
3968 EXPECT_TRUE(writer_->ack_frames().empty());
3969
3970 ASSERT_EQ(2u, writer_->stream_frames().size());
3971 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3972 writer_->stream_frames()[0]->stream_id);
3973 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3974 writer_->stream_frames()[1]->stream_id);
3975}
3976
3977TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3978 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3979 // queueing them.
3980 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3981 {
3982 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3983 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3984 connection_.SendStreamData3();
3985 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08003986 // Set the crypters for INITIAL packets in the TestPacketWriter.
3987 if (!connection_.version().KnowsWhichDecrypterToUse()) {
3988 writer_->framer()->framer()->SetAlternativeDecrypter(
3989 ENCRYPTION_INITIAL,
3990 std::make_unique<NullDecrypter>(Perspective::IS_SERVER), false);
3991 }
Bence Békybac04052022-04-07 15:44:29 -04003992 connection_.SendCryptoStreamData();
3993 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3994 }
3995 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3996 EXPECT_FALSE(connection_.HasQueuedData());
3997
3998 // Parse the last packet and ensure it contains a crypto stream frame.
3999 EXPECT_LE(2u, writer_->frame_count());
4000 ASSERT_LE(1u, writer_->padding_frames().size());
4001 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
4002 ASSERT_EQ(1u, writer_->stream_frames().size());
4003 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
4004 writer_->stream_frames()[0]->stream_id);
4005 } else {
4006 EXPECT_LE(1u, writer_->crypto_frames().size());
4007 }
4008}
4009
4010TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
4011 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
4012 // queueing them.
4013 {
4014 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
4016 QuicConnection::ScopedPacketFlusher flusher(&connection_);
dschinazi54f21232024-12-03 13:46:46 -08004017 connection_.SendCryptoStreamDataAtLevel(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04004018 connection_.SendStreamData3();
4019 }
4020 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4021 EXPECT_FALSE(connection_.HasQueuedData());
4022
4023 // Parse the last packet and ensure it's the stream frame from stream 3.
4024 size_t padding_frame_count = writer_->padding_frames().size();
4025 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4026 ASSERT_EQ(1u, writer_->stream_frames().size());
4027 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4028 writer_->stream_frames()[0]->stream_id);
4029}
4030
4031TEST_P(QuicConnectionTest, FramePackingAckResponse) {
4032 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4033 // Process a data packet to queue up a pending ack.
4034 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
4035 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
4036 } else {
4037 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4038 }
4039 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
4040
4041 QuicPacketNumber last_packet;
4042 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
4043 connection_.SendCryptoDataWithString("foo", 0);
4044 } else {
4045 SendStreamDataToPeer(
4046 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
4047 NO_FIN, &last_packet);
4048 }
4049 // Verify ack is bundled with outging packet.
4050 EXPECT_FALSE(writer_->ack_frames().empty());
4051
4052 EXPECT_CALL(visitor_, OnCanWrite())
4053 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
4054 &connection_, &TestConnection::SendStreamData3)),
4055 IgnoreResult(InvokeWithoutArgs(
4056 &connection_, &TestConnection::SendStreamData5))));
4057
4058 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4059
4060 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
4061 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martinduke9e0811c2022-12-08 20:35:57 -08004062 peer_framer_.SetEncrypter(
4063 ENCRYPTION_FORWARD_SECURE,
4064 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
4065 SetDecrypter(
4066 ENCRYPTION_FORWARD_SECURE,
4067 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
wubc9fd4292023-08-14 13:00:21 -07004068 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04004069 ProcessDataPacket(2);
4070
4071 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4072 EXPECT_FALSE(connection_.HasQueuedData());
4073
4074 // Parse the last packet and ensure it's an ack and two stream frames from
4075 // two different streams.
fayangfc04b8a2023-05-18 09:26:25 -07004076 EXPECT_EQ(3u, writer_->frame_count());
4077 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04004078 EXPECT_FALSE(writer_->ack_frames().empty());
4079 ASSERT_EQ(2u, writer_->stream_frames().size());
4080 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4081 writer_->stream_frames()[0]->stream_id);
4082 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4083 writer_->stream_frames()[1]->stream_id);
4084}
4085
4086TEST_P(QuicConnectionTest, FramePackingSendv) {
4087 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4088 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4089
4090 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4091 connection_.transport_version(), Perspective::IS_CLIENT);
4092 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4093
4094 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4095 EXPECT_FALSE(connection_.HasQueuedData());
4096
4097 // Parse the last packet and ensure multiple iovector blocks have
4098 // been packed into a single stream frame from one stream.
4099 EXPECT_EQ(1u, writer_->frame_count());
4100 EXPECT_EQ(1u, writer_->stream_frames().size());
4101 EXPECT_EQ(0u, writer_->padding_frames().size());
4102 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4103 EXPECT_EQ(stream_id, frame->stream_id);
4104 EXPECT_EQ("ABCDEF",
4105 absl::string_view(frame->data_buffer, frame->data_length));
4106}
4107
4108TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
4109 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4110 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4111
4112 BlockOnNextWrite();
4113 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4114 connection_.transport_version(), Perspective::IS_CLIENT);
4115 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4116
4117 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4118 EXPECT_TRUE(connection_.HasQueuedData());
4119
4120 // Unblock the writes and actually send.
4121 writer_->SetWritable();
4122 connection_.OnCanWrite();
4123 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4124
4125 // Parse the last packet and ensure it's one stream frame from one stream.
4126 EXPECT_EQ(1u, writer_->frame_count());
4127 EXPECT_EQ(1u, writer_->stream_frames().size());
4128 EXPECT_EQ(0u, writer_->padding_frames().size());
4129 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4130 EXPECT_EQ(stream_id, frame->stream_id);
4131 EXPECT_EQ("ABCDEF",
4132 absl::string_view(frame->data_buffer, frame->data_length));
4133}
4134
4135TEST_P(QuicConnectionTest, SendingZeroBytes) {
4136 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4137 // Send a zero byte write with a fin using writev.
4138 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4139 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4140 connection_.transport_version(), Perspective::IS_CLIENT);
4141 connection_.SaveAndSendStreamData(stream_id, {}, 0, FIN);
4142
4143 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4144 EXPECT_FALSE(connection_.HasQueuedData());
4145
4146 // Padding frames are added by v99 to ensure a minimum packet size.
4147 size_t extra_padding_frames = 0;
4148 if (GetParam().version.HasHeaderProtection()) {
4149 extra_padding_frames = 1;
4150 }
4151
4152 // Parse the last packet and ensure it's one stream frame from one stream.
4153 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
4154 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
4155 ASSERT_EQ(1u, writer_->stream_frames().size());
4156 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
4157 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4158}
4159
4160TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
4161 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4162 EXPECT_CALL(visitor_, GetHandshakeState())
4163 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
4164 // Set the ack alarm by processing a ping frame.
4165 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4166
4167 // Processs a PING frame.
4168 ProcessFramePacket(QuicFrame(QuicPingFrame()));
4169 // Ensure that this has caused the ACK alarm to be set.
4170 EXPECT_TRUE(connection_.HasPendingAcks());
4171
4172 // Send data and ensure the ack is bundled.
4173 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
4174 const std::string data(10000, '?');
4175 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
4176 GetNthClientInitiatedStreamId(0, connection_.transport_version()), data,
4177 0, FIN);
4178 EXPECT_EQ(data.length(), consumed.bytes_consumed);
4179 EXPECT_TRUE(consumed.fin_consumed);
4180 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4181 EXPECT_FALSE(connection_.HasQueuedData());
4182
4183 // Parse the last packet and ensure it's one stream frame with a fin.
4184 EXPECT_EQ(1u, writer_->frame_count());
4185 ASSERT_EQ(1u, writer_->stream_frames().size());
4186 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4187 writer_->stream_frames()[0]->stream_id);
4188 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4189 // Ensure the ack alarm was cancelled when the ack was sent.
4190 EXPECT_FALSE(connection_.HasPendingAcks());
4191}
4192
4193TEST_P(QuicConnectionTest, OnCanWrite) {
4194 // Visitor's OnCanWrite will send data, but will have more pending writes.
4195 EXPECT_CALL(visitor_, OnCanWrite())
4196 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
4197 &connection_, &TestConnection::SendStreamData3)),
4198 IgnoreResult(InvokeWithoutArgs(
4199 &connection_, &TestConnection::SendStreamData5))));
4200 {
4201 InSequence seq;
4202 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
4203 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
4204 .WillRepeatedly(Return(false));
4205 }
4206
4207 EXPECT_CALL(*send_algorithm_, CanSend(_))
4208 .WillRepeatedly(testing::Return(true));
4209
4210 connection_.OnCanWrite();
4211
4212 // Parse the last packet and ensure it's the two stream frames from
4213 // two different streams.
4214 EXPECT_EQ(2u, writer_->frame_count());
4215 EXPECT_EQ(2u, writer_->stream_frames().size());
4216 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4217 writer_->stream_frames()[0]->stream_id);
4218 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4219 writer_->stream_frames()[1]->stream_id);
4220}
4221
4222TEST_P(QuicConnectionTest, RetransmitOnNack) {
4223 QuicPacketNumber last_packet;
4224 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
4225 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet);
4226 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet);
4227
4228 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4229
4230 // Don't lose a packet on an ack, and nothing is retransmitted.
martindukeba002452023-03-21 08:10:46 -07004231 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004232 QuicAckFrame ack_one = InitAckFrame(1);
4233 ProcessAckPacket(&ack_one);
4234
4235 // Lose a packet and ensure it triggers retransmission.
4236 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4237 LostPacketVector lost_packets;
4238 lost_packets.push_back(
4239 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4240 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4241 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4242 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004243 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004244 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4245 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4246 ProcessAckPacket(&nack_two);
4247}
4248
4249TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
4250 // Block the connection to queue the packet.
4251 BlockOnNextWrite();
4252
4253 QuicStreamId stream_id = 2;
4254 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4255
4256 // Now that there is a queued packet, reset the stream.
4257 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4258
4259 // Unblock the connection and verify that only the RST_STREAM is sent.
4260 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4261 writer_->SetWritable();
4262 connection_.OnCanWrite();
4263 size_t padding_frame_count = writer_->padding_frames().size();
4264 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4265 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4266}
4267
4268TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
4269 // Block the connection to queue the packet.
4270 BlockOnNextWrite();
4271
4272 QuicStreamId stream_id = 2;
4273 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4274 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4275
4276 // Now that there is a queued packet, reset the stream.
4277 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4278
4279 // Unblock the connection and verify that the RST_STREAM is sent and the data
4280 // packet is sent.
4281 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4282 writer_->SetWritable();
4283 connection_.OnCanWrite();
4284 size_t padding_frame_count = writer_->padding_frames().size();
4285 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4286 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4287}
4288
4289TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
4290 QuicStreamId stream_id = 2;
4291 QuicPacketNumber last_packet;
4292 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4293 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4294 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4295
4296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4297 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4298
4299 // Lose a packet and ensure it does not trigger retransmission.
4300 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4301 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4302 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004303 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004304 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4305 ProcessAckPacket(&nack_two);
4306}
4307
4308TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
4309 QuicStreamId stream_id = 2;
4310 QuicPacketNumber last_packet;
4311 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4312 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4313 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4314
4315 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4316 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4317
4318 // Lose a packet, ensure it triggers retransmission.
4319 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4320 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4321 LostPacketVector lost_packets;
4322 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4323 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4324 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4325 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004326 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004327 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4328 ProcessAckPacket(&nack_two);
4329}
4330
4331TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
4332 QuicStreamId stream_id = 2;
4333 QuicPacketNumber last_packet;
4334 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4335
4336 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4337 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4338
4339 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
4340 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4341 clock_.AdvanceTime(DefaultRetransmissionTime());
4342 connection_.GetRetransmissionAlarm()->Fire();
4343 size_t padding_frame_count = writer_->padding_frames().size();
4344 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4345 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4346 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4347}
4348
4349// Ensure that if the only data in flight is non-retransmittable, the
4350// retransmission alarm is not set.
4351TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
4352 QuicStreamId stream_id = 2;
4353 QuicPacketNumber last_data_packet;
4354 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
4355
4356 // Cancel the stream.
4357 const QuicPacketNumber rst_packet = last_data_packet + 1;
4358 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
4359 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4360
4361 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
4362 // packet, which is no longer retransmittable since the stream was cancelled.
4363 QuicAckFrame nack_stream_data =
4364 ConstructAckFrame(rst_packet, last_data_packet);
4365 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07004366 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004367 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4368 ProcessAckPacket(&nack_stream_data);
4369
4370 // Ensure that the data is still in flight, but the retransmission alarm is no
4371 // longer set.
4372 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
4373 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4374}
4375
fayang339f0c82022-04-30 14:20:02 -07004376TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnPTO) {
Bence Békybac04052022-04-07 15:44:29 -04004377 QuicStreamId stream_id = 2;
4378 QuicPacketNumber last_packet;
4379 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4380
4381 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4382 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4383
4384 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
4385 // is sent.
fayang339f0c82022-04-30 14:20:02 -07004386 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
Bence Békybac04052022-04-07 15:44:29 -04004387 clock_.AdvanceTime(DefaultRetransmissionTime());
4388 connection_.GetRetransmissionAlarm()->Fire();
4389 size_t padding_frame_count = writer_->padding_frames().size();
4390 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04004391}
4392
4393TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
4394 QuicStreamId stream_id = 2;
4395 QuicPacketNumber last_packet;
4396 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4397 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4398 BlockOnNextWrite();
4399 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4400
4401 // Lose a packet which will trigger a pending retransmission.
4402 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4403 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4404 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004405 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004406 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4407 ProcessAckPacket(&ack);
4408
4409 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4410
4411 // Unblock the connection and verify that the RST_STREAM is sent but not the
4412 // second data packet nor a retransmit.
4413 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4414 writer_->SetWritable();
4415 connection_.OnCanWrite();
4416 size_t padding_frame_count = writer_->padding_frames().size();
4417 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4418 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
4419 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4420}
4421
4422TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
4423 QuicStreamId stream_id = 2;
4424 QuicPacketNumber last_packet;
4425 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4426 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4427 BlockOnNextWrite();
4428 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4429
4430 // Lose a packet which will trigger a pending retransmission.
4431 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4432 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4433 LostPacketVector lost_packets;
4434 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4435 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4436 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4437 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004438 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004439 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4440 ProcessAckPacket(&ack);
4441
4442 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4443
4444 // Unblock the connection and verify that the RST_STREAM is sent and the
4445 // second data packet or a retransmit is sent.
4446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
4447 writer_->SetWritable();
4448 connection_.OnCanWrite();
4449 // The RST_STREAM_FRAME is sent after queued packets and pending
4450 // retransmission.
4451 connection_.SendControlFrame(QuicFrame(
4452 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
4453 size_t padding_frame_count = writer_->padding_frames().size();
4454 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4455 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4456}
4457
4458TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
4459 QuicPacketNumber last_packet;
4460 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4461 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
4462 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
4463
4464 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4465
4466 // Instigate a loss with an ack.
4467 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4468 // The first nack should trigger a fast retransmission, but we'll be
4469 // write blocked, so the packet will be queued.
4470 BlockOnNextWrite();
4471
4472 LostPacketVector lost_packets;
4473 lost_packets.push_back(
4474 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4475 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4476 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4477 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004478 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004479 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4480 .Times(1);
4481 ProcessAckPacket(&nack_two);
4482 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4483
4484 // Now, ack the previous transmission.
4485 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004486 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004487 QuicAckFrame ack_all = InitAckFrame(3);
4488 ProcessAckPacket(&ack_all);
4489
4490 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4491 .Times(0);
4492
4493 writer_->SetWritable();
4494 connection_.OnCanWrite();
4495
4496 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4497 // We do not store retransmittable frames of this retransmission.
4498 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
4499}
4500
4501TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
4502 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4503 QuicPacketNumber original, second;
4504
4505 QuicByteCount packet_size =
4506 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
4507 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
4508
4509 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
4510 // The first nack should retransmit the largest observed packet.
4511 LostPacketVector lost_packets;
4512 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
4513 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4514 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4515 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004516 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004517 // Packet 1 is short header for IETF QUIC because the encryption level
4518 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangfc04b8a2023-05-18 09:26:25 -07004519 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _));
Bence Békybac04052022-04-07 15:44:29 -04004520 ProcessAckPacket(&frame);
4521}
4522
Bence Békybac04052022-04-07 15:44:29 -04004523TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
4524 BlockOnNextWrite();
4525 writer_->set_is_write_blocked_data_buffered(true);
4526 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4527 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4528 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4529
4530 writer_->SetWritable();
4531 connection_.OnCanWrite();
4532 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4533}
4534
4535TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
4536 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4537 BlockOnNextWrite();
4538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4539 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4540 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4541 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4542
4543 // The second packet should also be queued, in order to ensure packets are
4544 // never sent out of order.
4545 writer_->SetWritable();
4546 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4547 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4548 EXPECT_EQ(2u, connection_.NumQueuedPackets());
4549
4550 // Now both are sent in order when we unblock.
4551 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4552 connection_.OnCanWrite();
4553 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4554 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4555}
4556
4557TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
4558 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4559 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4560 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4561
4562 BlockOnNextWrite();
4563 writer_->set_is_write_blocked_data_buffered(true);
4564 // Simulate the retransmission alarm firing.
4565 clock_.AdvanceTime(DefaultRetransmissionTime());
4566 connection_.GetRetransmissionAlarm()->Fire();
4567
4568 // Ack the sent packet before the callback returns, which happens in
4569 // rare circumstances with write blocked sockets.
4570 QuicAckFrame ack = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07004571 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004572 ProcessAckPacket(&ack);
4573
4574 writer_->SetWritable();
4575 connection_.OnCanWrite();
4576 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang339f0c82022-04-30 14:20:02 -07004577 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 3));
Bence Békybac04052022-04-07 15:44:29 -04004578}
4579
4580TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4581 // Block the connection.
4582 BlockOnNextWrite();
4583 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4584 EXPECT_EQ(1u, writer_->packets_write_attempts());
4585 EXPECT_TRUE(writer_->IsWriteBlocked());
4586
4587 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4588 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4589 connection_.GetSendAlarm()->Fire();
4590 EXPECT_TRUE(writer_->IsWriteBlocked());
4591 EXPECT_EQ(1u, writer_->packets_write_attempts());
4592}
4593
4594TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4595 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4596
4597 // Block the connection.
4598 BlockOnNextWrite();
4599 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4600 EXPECT_TRUE(writer_->IsWriteBlocked());
4601 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4602 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4603
4604 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4605 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4606 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4607 // is returned.
4608 const uint64_t received_packet_num = 1;
4609 const bool has_stop_waiting = false;
4610 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4611 std::unique_ptr<QuicPacket> packet(
4612 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4613 char buffer[kMaxOutgoingPacketSize];
4614 size_t encrypted_length =
4615 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4616 *packet, buffer, kMaxOutgoingPacketSize);
4617 connection_.ProcessUdpPacket(
4618 kSelfAddress, kPeerAddress,
4619 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4620
4621 EXPECT_TRUE(writer_->IsWriteBlocked());
4622 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4623}
4624
QUICHE team32d62792023-04-27 11:47:01 -07004625TEST_P(QuicConnectionTest, SendAlarmNonZeroDelay) {
4626 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4627 // Set a 10 ms send alarm delay. The send alarm after processing the packet
4628 // should fire after waiting 10ms, not immediately.
4629 connection_.set_defer_send_in_response_to_packets(true);
4630 connection_.sent_packet_manager().SetDeferredSendAlarmDelay(
4631 QuicTime::Delta::FromMilliseconds(10));
4632 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4633
4634 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4635 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4636 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4637 // is returned.
4638 const uint64_t received_packet_num = 1;
4639 const bool has_stop_waiting = false;
4640 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4641 std::unique_ptr<QuicPacket> packet(
4642 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4643 char buffer[kMaxOutgoingPacketSize];
4644 size_t encrypted_length =
4645 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4646 *packet, buffer, kMaxOutgoingPacketSize);
wubc9fd4292023-08-14 13:00:21 -07004647 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
QUICHE team32d62792023-04-27 11:47:01 -07004648 connection_.ProcessUdpPacket(
4649 kSelfAddress, kPeerAddress,
4650 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4651
4652 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
4653 // It was set to be 10 ms in the future, so it should at the least be greater
4654 // than now + 5 ms.
4655 EXPECT_TRUE(connection_.GetSendAlarm()->deadline() >
4656 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5));
4657}
4658
Bence Békybac04052022-04-07 15:44:29 -04004659TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4660 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4661 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4662
4663 // Simulate the case where a shared writer gets blocked by another connection.
4664 writer_->SetWriteBlocked();
4665
4666 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4667 QuicAckFrame ack1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07004668 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004669 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4670 ProcessAckPacket(1, &ack1);
4671}
4672
4673TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4674 writer_->SetBatchMode(true);
4675 EXPECT_TRUE(connection_.connected());
4676 // Have to explicitly grab the OnConnectionClosed frame and check
4677 // its parameters because this is a silent connection close and the
4678 // frame is not also transmitted to the peer.
4679 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4680 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4681
4682 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4683
4684 {
4685 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4686 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4687 ConnectionCloseBehavior::SILENT_CLOSE);
4688
4689 EXPECT_FALSE(connection_.connected());
4690 writer_->SetWriteBlocked();
4691 }
4692 EXPECT_EQ(1, connection_close_frame_count_);
4693 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4694 IsError(QUIC_PEER_GOING_AWAY));
4695}
4696
4697TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4698 writer_->SetBatchMode(true);
4699 writer_->BlockOnNextFlush();
4700
4701 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4702 {
4703 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4704 // flusher's destructor will call connection_.FlushPackets, which should add
4705 // the connection to the write blocked list.
4706 }
4707}
4708
4709TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4710 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4711 int offset = 0;
4712 // Send packets 1 to 15.
4713 for (int i = 0; i < 15; ++i) {
4714 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4715 offset += 3;
4716 }
4717
4718 // Ack 15, nack 1-14.
4719
4720 QuicAckFrame nack =
4721 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4722
4723 // 14 packets have been NACK'd and lost.
4724 LostPacketVector lost_packets;
4725 for (int i = 1; i < 15; ++i) {
4726 lost_packets.push_back(
4727 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
4728 }
4729 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4730 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4731 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004732 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004733 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4734 ProcessAckPacket(&nack);
4735}
4736
4737// Test sending multiple acks from the connection to the session.
4738TEST_P(QuicConnectionTest, MultipleAcks) {
4739 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4740 return;
4741 }
4742 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4743 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4744 ProcessDataPacket(1);
4745 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4746 QuicPacketNumber last_packet;
4747 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4748 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4749 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4750 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4751 SendAckPacketToPeer(); // Packet 3
4752 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4753 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4754 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4755 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4756 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4757 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4758
4759 // Client will ack packets 1, 2, [!3], 4, 5.
martindukeba002452023-03-21 08:10:46 -07004760 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004761 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4762 ProcessAckPacket(&frame1);
4763
4764 // Now the client implicitly acks 3, and explicitly acks 6.
martindukeba002452023-03-21 08:10:46 -07004765 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004766 QuicAckFrame frame2 = InitAckFrame(6);
4767 ProcessAckPacket(&frame2);
4768}
4769
4770TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
4771 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4772 return;
4773 }
4774 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4775 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4776 ProcessDataPacket(1);
4777 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4778 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4779 // From now on, we send acks, so the send algorithm won't mark them pending.
4780 SendAckPacketToPeer(); // Packet 2
4781
martindukeba002452023-03-21 08:10:46 -07004782 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004783 QuicAckFrame frame = InitAckFrame(1);
4784 ProcessAckPacket(&frame);
4785
martindukeba002452023-03-21 08:10:46 -07004786 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004787 frame = InitAckFrame(2);
4788 ProcessAckPacket(&frame);
Bence Békybac04052022-04-07 15:44:29 -04004789
4790 // When we send an ack, we make sure our least-unacked makes sense. In this
4791 // case since we're not waiting on an ack for 2 and all packets are acked, we
4792 // set it to 3.
4793 SendAckPacketToPeer(); // Packet 3
Bence Békybac04052022-04-07 15:44:29 -04004794
4795 // Ack the ack, which updates the rtt and raises the least unacked.
martindukeba002452023-03-21 08:10:46 -07004796 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004797 frame = InitAckFrame(3);
4798 ProcessAckPacket(&frame);
4799
4800 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
haoyuewang16f86e82023-07-26 14:13:26 -07004801 SendAckPacketToPeer(); // Packet 5
Bence Békybac04052022-04-07 15:44:29 -04004802
4803 // Send two data packets at the end, and ensure if the last one is acked,
4804 // the least unacked is raised above the ack packets.
4805 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4806 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4807
martindukeba002452023-03-21 08:10:46 -07004808 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004809 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4810 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4811 ProcessAckPacket(&frame);
Bence Békybac04052022-04-07 15:44:29 -04004812}
4813
Bence Békybac04052022-04-07 15:44:29 -04004814TEST_P(QuicConnectionTest, SendHandshakeMessages) {
Bence Békybac04052022-04-07 15:44:29 -04004815 // Attempt to send a handshake message and have the socket block.
4816 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4817 BlockOnNextWrite();
4818 connection_.SendCryptoDataWithString("foo", 0);
4819 // The packet should be serialized, but not queued.
4820 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4821
4822 // Switch to the new encrypter.
martinduke9e0811c2022-12-08 20:35:57 -08004823 connection_.SetEncrypter(
4824 ENCRYPTION_ZERO_RTT,
4825 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004826 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4827
4828 // Now become writeable and flush the packets.
4829 writer_->SetWritable();
4830 EXPECT_CALL(visitor_, OnCanWrite());
4831 connection_.OnCanWrite();
4832 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4833
martinduke9e0811c2022-12-08 20:35:57 -08004834 // Verify that the handshake packet went out with Initial encryption.
4835 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -04004836}
4837
martinduke9e0811c2022-12-08 20:35:57 -08004838TEST_P(QuicConnectionTest, DropRetransmitsForInitialPacketAfterForwardSecure) {
Bence Békybac04052022-04-07 15:44:29 -04004839 connection_.SendCryptoStreamData();
Bence Békybac04052022-04-07 15:44:29 -04004840 // Simulate the retransmission alarm firing and the socket blocking.
4841 BlockOnNextWrite();
4842 clock_.AdvanceTime(DefaultRetransmissionTime());
4843 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4844 connection_.GetRetransmissionAlarm()->Fire();
4845 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4846
4847 // Go forward secure.
4848 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4849 std::make_unique<TaggingEncrypter>(0x02));
4850 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4851 notifier_.NeuterUnencryptedData();
4852 connection_.NeuterUnencryptedPackets();
4853 connection_.OnHandshakeComplete();
4854
4855 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4856 // Unblock the socket and ensure that no packets are sent.
4857 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4858 writer_->SetWritable();
4859 connection_.OnCanWrite();
4860}
4861
4862TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
Bence Békybac04052022-04-07 15:44:29 -04004863 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
4864
4865 connection_.SendCryptoDataWithString("foo", 0);
4866
martinduke9e0811c2022-12-08 20:35:57 -08004867 connection_.SetEncrypter(
4868 ENCRYPTION_ZERO_RTT,
4869 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004870 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -08004871 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4872 writer_->framer()->framer()->SetAlternativeDecrypter(
4873 ENCRYPTION_ZERO_RTT,
4874 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT), false);
4875 }
Bence Békybac04052022-04-07 15:44:29 -04004876
4877 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4878 EXPECT_FALSE(notifier_.HasLostStreamData());
4879 connection_.MarkZeroRttPacketsForRetransmission(0);
4880 EXPECT_TRUE(notifier_.HasLostStreamData());
4881}
4882
4883TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
4884 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4885 return;
4886 }
4887 // SetFromConfig is always called after construction from InitializeSession.
4888 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08004889 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
4890 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04004891 QuicConfig config;
4892 connection_.SetFromConfig(config);
4893 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004894
martinduke9e0811c2022-12-08 20:35:57 -08004895 peer_framer_.SetEncrypter(
4896 ENCRYPTION_ZERO_RTT,
4897 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4898 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4899 writer_->framer()->framer()->SetDecrypter(
4900 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4901 }
Bence Békybac04052022-04-07 15:44:29 -04004902
4903 // Process an encrypted packet which can not yet be decrypted which should
4904 // result in the packet being buffered.
4905 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4906
4907 // Transition to the new encryption state and process another encrypted packet
4908 // which should result in the original packet being processed.
4909 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004910 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
4911 connection_.SetEncrypter(
4912 ENCRYPTION_ZERO_RTT,
4913 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004914 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4915 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4916 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4917
4918 // Finally, process a third packet and note that we do not reprocess the
4919 // buffered packet.
4920 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4921 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4922}
4923
Bence Békybac04052022-04-07 15:44:29 -04004924TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
4925 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4926 return;
4927 }
4928 // SetFromConfig is always called after construction from InitializeSession.
4929 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08004930 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
4931 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04004932 QuicConfig config;
4933 config.set_max_undecryptable_packets(100);
4934 connection_.SetFromConfig(config);
4935 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004936
martinduke9e0811c2022-12-08 20:35:57 -08004937 peer_framer_.SetEncrypter(
4938 ENCRYPTION_ZERO_RTT,
4939 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004940
4941 // Process an encrypted packet which can not yet be decrypted which should
4942 // result in the packet being buffered.
4943 for (uint64_t i = 1; i <= 100; ++i) {
4944 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4945 }
4946
4947 // Transition to the new encryption state and process another encrypted packet
4948 // which should result in the original packets being processed.
4949 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4950 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004951 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004952 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -08004953 connection_.SetEncrypter(
4954 ENCRYPTION_ZERO_RTT,
4955 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004956 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4957
4958 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
martinduke9e0811c2022-12-08 20:35:57 -08004959 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4960 writer_->framer()->framer()->SetDecrypter(
4961 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4962 }
Bence Békybac04052022-04-07 15:44:29 -04004963 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4964
4965 // Finally, process a third packet and note that we do not reprocess the
4966 // buffered packet.
4967 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4968 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4969}
4970
4971TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4972 BlockOnNextWrite();
4973 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4974 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4975 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4976
4977 // Test that RTO is started once we write to the socket.
4978 writer_->SetWritable();
4979 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4980 connection_.OnCanWrite();
4981 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4982}
4983
Bence Békybac04052022-04-07 15:44:29 -04004984TEST_P(QuicConnectionTest, TestQueued) {
Bence Békybac04052022-04-07 15:44:29 -04004985 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4986 BlockOnNextWrite();
4987 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4988 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4989
4990 // Unblock the writes and actually send.
4991 writer_->SetWritable();
4992 connection_.OnCanWrite();
4993 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4994}
4995
4996TEST_P(QuicConnectionTest, InitialTimeout) {
4997 EXPECT_TRUE(connection_.connected());
4998 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4999 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5000
5001 // SetFromConfig sets the initial timeouts before negotiation.
5002 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08005003 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
5004 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04005005 QuicConfig config;
5006 connection_.SetFromConfig(config);
5007 // Subtract a second from the idle timeout on the client side.
5008 QuicTime default_timeout =
5009 clock_.ApproximateNow() +
5010 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5011 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5012
5013 EXPECT_CALL(visitor_,
5014 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5015 // Simulate the timeout alarm firing.
5016 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
5017 connection_.GetTimeoutAlarm()->Fire();
5018
5019 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5020 EXPECT_FALSE(connection_.connected());
5021
5022 EXPECT_FALSE(connection_.HasPendingAcks());
5023 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5024 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5025 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5026 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5027 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
5028 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5029}
5030
5031TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
5032 EXPECT_TRUE(connection_.connected());
5033 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5034 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5035
5036 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08005037 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
5038 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04005039 QuicConfig config;
5040 connection_.SetFromConfig(config);
5041 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5042 QuicTime initial_ddl =
5043 clock_.ApproximateNow() +
5044 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5045 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
5046 EXPECT_TRUE(connection_.connected());
5047
5048 // Advance the time and send the first packet to the peer.
5049 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
5050 QuicPacketNumber last_packet;
5051 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5052 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
5053 // This will be the updated deadline for the connection to idle time out.
5054 QuicTime new_ddl = clock_.ApproximateNow() +
5055 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5056
5057 // Simulate the timeout alarm firing, the connection should not be closed as
5058 // a new packet has been sent.
5059 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
5060 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
5061 clock_.AdvanceTime(delay);
5062 // Verify the timeout alarm deadline is updated.
5063 EXPECT_TRUE(connection_.connected());
5064 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5065 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
5066
5067 // Simulate the timeout alarm firing again, the connection now should be
5068 // closed.
5069 EXPECT_CALL(visitor_,
5070 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5071 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
5072 connection_.GetTimeoutAlarm()->Fire();
5073 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5074 EXPECT_FALSE(connection_.connected());
5075
5076 EXPECT_FALSE(connection_.HasPendingAcks());
5077 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5078 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5079 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5080 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5081 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5082}
5083
5084TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
5085 EXPECT_TRUE(connection_.connected());
5086 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5087 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5088
5089 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08005090 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
5091 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04005092 QuicConfig config;
5093 connection_.SetFromConfig(config);
5094 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5095 QuicTime initial_ddl =
5096 clock_.ApproximateNow() +
5097 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5098 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
5099 EXPECT_TRUE(connection_.connected());
5100
5101 // Immediately send the first packet, this is a rare case but test code will
5102 // hit this issue often as MockClock used for tests doesn't move with code
5103 // execution until manually adjusted.
5104 QuicPacketNumber last_packet;
5105 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5106 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
5107
5108 // Advance the time and send the second packet to the peer.
5109 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
5110 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5111 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
5112
5113 // Simulate the timeout alarm firing, the connection will be closed.
5114 EXPECT_CALL(visitor_,
5115 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5116 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
5117 connection_.GetTimeoutAlarm()->Fire();
5118
5119 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5120 EXPECT_FALSE(connection_.connected());
5121
5122 EXPECT_FALSE(connection_.HasPendingAcks());
5123 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5124 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5125 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5126 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5127 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5128}
5129
5130TEST_P(QuicConnectionTest, HandshakeTimeout) {
5131 // Use a shorter handshake timeout than idle timeout for this test.
5132 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
5133 connection_.SetNetworkTimeouts(timeout, timeout);
5134 EXPECT_TRUE(connection_.connected());
5135 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5136
5137 QuicTime handshake_timeout =
5138 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
5139 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
5140 EXPECT_TRUE(connection_.connected());
5141
5142 // Send and ack new data 3 seconds later to lengthen the idle timeout.
5143 SendStreamDataToPeer(
5144 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5145 "GET /", 0, FIN, nullptr);
5146 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
5147 QuicAckFrame frame = InitAckFrame(1);
5148 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005149 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005150 ProcessAckPacket(&frame);
5151
5152 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5153 EXPECT_TRUE(connection_.connected());
5154
5155 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
5156
5157 EXPECT_CALL(visitor_,
5158 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5159 // Simulate the timeout alarm firing.
5160 connection_.GetTimeoutAlarm()->Fire();
5161
5162 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5163 EXPECT_FALSE(connection_.connected());
5164
5165 EXPECT_FALSE(connection_.HasPendingAcks());
5166 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5167 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5168 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5169 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
5170}
5171
5172TEST_P(QuicConnectionTest, PingAfterSend) {
5173 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5174 return;
5175 }
5176 EXPECT_TRUE(connection_.connected());
5177 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5178 .WillRepeatedly(Return(true));
5179 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5180
5181 // Advance to 5ms, and send a packet to the peer, which will set
5182 // the ping alarm.
5183 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5184 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5185 SendStreamDataToPeer(
5186 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5187 "GET /", 0, FIN, nullptr);
5188 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5189 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
5190 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5191
5192 // Now recevie an ACK of the previous packet, which will move the
5193 // ping alarm forward.
5194 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5195 QuicAckFrame frame = InitAckFrame(1);
5196 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005197 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005198 ProcessAckPacket(&frame);
5199 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5200 // The ping timer is set slightly less than 15 seconds in the future, because
5201 // of the 1s ping timer alarm granularity.
5202 EXPECT_EQ(
5203 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
5204 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5205
5206 writer_->Reset();
5207 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
5208 connection_.GetPingAlarm()->Fire();
5209 size_t padding_frame_count = writer_->padding_frames().size();
5210 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5211 ASSERT_EQ(1u, writer_->ping_frames().size());
5212 writer_->Reset();
5213
5214 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5215 .WillRepeatedly(Return(false));
5216 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5217 SendAckPacketToPeer();
5218
5219 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5220}
5221
5222TEST_P(QuicConnectionTest, ReducedPingTimeout) {
5223 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5224 return;
5225 }
5226 EXPECT_TRUE(connection_.connected());
5227 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5228 .WillRepeatedly(Return(true));
5229 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5230
5231 // Use a reduced ping timeout for this connection.
fayang5d393332022-04-18 13:34:54 -07005232 connection_.set_keep_alive_ping_timeout(QuicTime::Delta::FromSeconds(10));
Bence Békybac04052022-04-07 15:44:29 -04005233
5234 // Advance to 5ms, and send a packet to the peer, which will set
5235 // the ping alarm.
5236 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5237 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5238 SendStreamDataToPeer(
5239 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5240 "GET /", 0, FIN, nullptr);
5241 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5242 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
5243 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5244
5245 // Now recevie an ACK of the previous packet, which will move the
5246 // ping alarm forward.
5247 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5248 QuicAckFrame frame = InitAckFrame(1);
5249 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005250 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005251 ProcessAckPacket(&frame);
5252 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5253 // The ping timer is set slightly less than 10 seconds in the future, because
5254 // of the 1s ping timer alarm granularity.
5255 EXPECT_EQ(
5256 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5257 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5258
5259 writer_->Reset();
5260 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5261 connection_.GetPingAlarm()->Fire();
5262 size_t padding_frame_count = writer_->padding_frames().size();
5263 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5264 ASSERT_EQ(1u, writer_->ping_frames().size());
5265 writer_->Reset();
5266
5267 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5268 .WillRepeatedly(Return(false));
5269 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5270 SendAckPacketToPeer();
5271
5272 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5273}
5274
5275// Tests whether sending an MTU discovery packet to peer successfully causes the
5276// maximum packet size to increase.
5277TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
5278 MtuDiscoveryTestInit();
5279
5280 // Send an MTU probe.
5281 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5282 QuicByteCount mtu_probe_size;
5283 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5284 .WillOnce(SaveArg<3>(&mtu_probe_size));
5285 connection_.SendMtuDiscoveryPacket(new_mtu);
5286 EXPECT_EQ(new_mtu, mtu_probe_size);
5287 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5288
5289 // Send more than MTU worth of data. No acknowledgement was received so far,
5290 // so the MTU should be at its old value.
5291 const std::string data(kDefaultMaxPacketSize + 1, '.');
5292 QuicByteCount size_before_mtu_change;
5293 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5294 .Times(2)
5295 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5296 .WillOnce(Return());
5297 connection_.SendStreamDataWithString(3, data, 0, FIN);
5298 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5299 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5300
5301 // Acknowledge all packets so far.
5302 QuicAckFrame probe_ack = InitAckFrame(3);
martindukeba002452023-03-21 08:10:46 -07005303 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005304 ProcessAckPacket(&probe_ack);
5305 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5306
5307 // Send the same data again. Check that it fits into a single packet now.
5308 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5309 connection_.SendStreamDataWithString(3, data, 0, FIN);
5310 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5311}
5312
5313// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5314// the writer is flushed immediately.
5315TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5316 writer_->SetBatchMode(true);
5317 MtuDiscoveryTestInit();
5318
5319 // Send an MTU probe.
5320 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5321 QuicByteCount mtu_probe_size;
5322 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5323 .WillOnce(SaveArg<3>(&mtu_probe_size));
5324 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5325 connection_.SendMtuDiscoveryPacket(target_mtu);
5326 EXPECT_EQ(target_mtu, mtu_probe_size);
5327 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
5328}
5329
5330// Tests whether MTU discovery does not happen when it is not explicitly enabled
5331// by the connection options.
5332TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
5333 MtuDiscoveryTestInit();
5334
5335 const QuicPacketCount packets_between_probes_base = 10;
5336 set_packets_between_probes_base(packets_between_probes_base);
5337
5338 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5339 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5340 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5341 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5342 EXPECT_EQ(0u, connection_.mtu_probe_count());
5343 }
5344}
5345
5346// Tests whether MTU discovery works when all probes are acknowledged on the
5347// first try.
5348TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
5349 MtuDiscoveryTestInit();
5350
5351 const QuicPacketCount packets_between_probes_base = 5;
5352 set_packets_between_probes_base(packets_between_probes_base);
5353
5354 connection_.EnablePathMtuDiscovery(send_algorithm_);
5355
5356 // Send enough packets so that the next one triggers path MTU discovery.
5357 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5358 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5359 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5360 }
5361
5362 // Trigger the probe.
5363 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5364 nullptr);
5365 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5366 QuicByteCount probe_size;
5367 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5368 .WillOnce(SaveArg<3>(&probe_size));
5369 connection_.GetMtuDiscoveryAlarm()->Fire();
5370
5371 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5372 kMtuDiscoveryTargetPacketSizeHigh));
5373
5374 const QuicPacketNumber probe_packet_number =
5375 FirstSendingPacketNumber() + packets_between_probes_base;
5376 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5377
5378 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005379 {
5380 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5381 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5382 .Times(AnyNumber());
5383 ProcessAckPacket(&probe_ack);
5384 EXPECT_EQ(probe_size, connection_.max_packet_length());
5385 EXPECT_EQ(0u, connection_.GetBytesInFlight());
Bence Békybac04052022-04-07 15:44:29 -04005386
QUICHE teame2a24ee2024-01-09 06:34:35 -08005387 EXPECT_EQ(1u, connection_.mtu_probe_count());
5388 }
Bence Békybac04052022-04-07 15:44:29 -04005389
5390 QuicStreamOffset stream_offset = packets_between_probes_base;
5391 QuicByteCount last_probe_size = 0;
5392 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5393 ++num_probes) {
5394 // Send just enough packets without triggering the next probe.
5395 for (QuicPacketCount i = 0;
5396 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5397 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5398 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5399 }
5400
5401 // Trigger the next probe.
5402 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5403 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5404 QuicByteCount new_probe_size;
5405 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5406 .WillOnce(SaveArg<3>(&new_probe_size));
5407 connection_.GetMtuDiscoveryAlarm()->Fire();
5408 EXPECT_THAT(new_probe_size,
5409 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5410 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5411
5412 // Acknowledge all packets sent so far.
5413 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5414 ProcessAckPacket(&probe_ack);
5415 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5416 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5417
5418 last_probe_size = probe_size;
5419 probe_size = new_probe_size;
5420 }
5421
5422 // The last probe size should be equal to the target.
5423 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
5424
5425 writer_->SetShouldWriteFail();
5426
5427 // Ignore PACKET_WRITE_ERROR once.
5428 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5429 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5430 EXPECT_TRUE(connection_.connected());
5431
5432 // Close connection on another PACKET_WRITE_ERROR.
5433 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5434 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5435 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5436 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5437 EXPECT_FALSE(connection_.connected());
5438 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5439 IsError(QUIC_PACKET_WRITE_ERROR));
5440}
5441
5442// After a successful MTU probe, one and only one write error should be ignored
5443// if it happened in QuicConnection::FlushPacket.
5444TEST_P(QuicConnectionTest,
5445 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5446 MtuDiscoveryTestInit();
5447 writer_->SetBatchMode(true);
5448
5449 const QuicPacketCount packets_between_probes_base = 5;
5450 set_packets_between_probes_base(packets_between_probes_base);
5451
5452 connection_.EnablePathMtuDiscovery(send_algorithm_);
5453
5454 const QuicByteCount original_max_packet_length =
5455 connection_.max_packet_length();
5456 // Send enough packets so that the next one triggers path MTU discovery.
5457 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5458 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5459 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5460 }
5461
5462 // Trigger the probe.
5463 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5464 nullptr);
5465 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5466 QuicByteCount probe_size;
5467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5468 .WillOnce(SaveArg<3>(&probe_size));
5469 connection_.GetMtuDiscoveryAlarm()->Fire();
5470
5471 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5472 kMtuDiscoveryTargetPacketSizeHigh));
5473
5474 const QuicPacketNumber probe_packet_number =
5475 FirstSendingPacketNumber() + packets_between_probes_base;
5476 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5477
5478 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005479 {
5480 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5481 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5482 .Times(AnyNumber());
5483 ProcessAckPacket(&probe_ack);
5484 EXPECT_EQ(probe_size, connection_.max_packet_length());
5485 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5486 }
Bence Békybac04052022-04-07 15:44:29 -04005487
5488 EXPECT_EQ(1u, connection_.mtu_probe_count());
5489
5490 writer_->SetShouldWriteFail();
5491
5492 // Ignore PACKET_WRITE_ERROR once.
5493 {
5494 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5495 // flusher's destructor will call connection_.FlushPackets, which should
5496 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5497 }
5498 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5499 EXPECT_TRUE(connection_.connected());
5500
5501 // Close connection on another PACKET_WRITE_ERROR.
5502 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5503 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5504 {
5505 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5506 // flusher's destructor will call connection_.FlushPackets, which should
5507 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5508 }
5509 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5510 EXPECT_FALSE(connection_.connected());
5511 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5512 IsError(QUIC_PACKET_WRITE_ERROR));
5513}
5514
5515// Simulate the case where the first attempt to send a probe is write blocked,
5516// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5517TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
5518 MtuDiscoveryTestInit();
5519
5520 const QuicPacketCount packets_between_probes_base = 5;
5521 set_packets_between_probes_base(packets_between_probes_base);
5522
5523 connection_.EnablePathMtuDiscovery(send_algorithm_);
5524
5525 // Send enough packets so that the next one triggers path MTU discovery.
5526 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5527 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5528 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5529 }
5530
5531 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5532
5533 // Trigger the probe.
5534 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5535 nullptr);
5536 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5538 BlockOnNextWrite();
5539 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5540 connection_.GetMtuDiscoveryAlarm()->Fire();
5541 EXPECT_EQ(1u, connection_.mtu_probe_count());
5542 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5543 ASSERT_TRUE(connection_.connected());
5544
5545 writer_->SetWritable();
5546 SimulateNextPacketTooLarge();
5547 connection_.OnCanWrite();
5548 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5549 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5550 EXPECT_TRUE(connection_.connected());
5551}
5552
5553// Tests whether MTU discovery works correctly when the probes never get
5554// acknowledged.
5555TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5556 MtuDiscoveryTestInit();
5557
5558 // Lower the number of probes between packets in order to make the test go
5559 // much faster.
5560 const QuicPacketCount packets_between_probes_base = 5;
5561 set_packets_between_probes_base(packets_between_probes_base);
5562
5563 connection_.EnablePathMtuDiscovery(send_algorithm_);
5564
5565 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5566
5567 EXPECT_EQ(packets_between_probes_base,
5568 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5569
5570 // This tests sends more packets than strictly necessary to make sure that if
5571 // the connection was to send more discovery packets than needed, those would
5572 // get caught as well.
5573 const QuicPacketCount number_of_packets =
5574 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5575 std::vector<QuicPacketNumber> mtu_discovery_packets;
5576 // Called on many acks.
martindukeba002452023-03-21 08:10:46 -07005577 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04005578 .Times(AnyNumber());
5579 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5580 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5581 clock_.AdvanceTime(rtt);
5582
5583 // Receive an ACK, which marks all data packets as received, and all MTU
5584 // discovery packets as missing.
5585
5586 QuicAckFrame ack;
5587
5588 if (!mtu_discovery_packets.empty()) {
5589 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5590 mtu_discovery_packets.end());
5591 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5592 mtu_discovery_packets.end());
5593 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5594 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5595 creator_->packet_number() + 1);
5596 ack.largest_acked = creator_->packet_number();
5597
5598 } else {
5599 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5600 ack.largest_acked = creator_->packet_number();
5601 }
5602
5603 ProcessAckPacket(&ack);
5604
5605 // Trigger MTU probe if it would be scheduled now.
5606 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5607 continue;
5608 }
5609
5610 // Fire the alarm. The alarm should cause a packet to be sent.
5611 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5612 connection_.GetMtuDiscoveryAlarm()->Fire();
5613 // Record the packet number of the MTU discovery packet in order to
5614 // mark it as NACK'd.
5615 mtu_discovery_packets.push_back(creator_->packet_number());
5616 }
5617
5618 // Ensure the number of packets between probes grows exponentially by checking
5619 // it against the closed-form expression for the packet number.
5620 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5621 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5622 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5623 const QuicPacketCount packets_between_probes =
5624 packets_between_probes_base * ((1 << (i + 1)) - 1);
5625 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5626 mtu_discovery_packets[i]);
5627 }
5628
5629 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5630 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5631 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5632}
5633
5634// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5635TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
5636 MtuDiscoveryTestInit();
5637
5638 const QuicPacketCount packets_between_probes_base = 5;
5639 set_packets_between_probes_base(packets_between_probes_base);
5640
5641 connection_.EnablePathMtuDiscovery(send_algorithm_);
5642
5643 // Send enough packets so that the next one triggers path MTU discovery.
5644 QuicStreamOffset stream_offset = 0;
5645 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5646 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5647 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5648 }
5649
5650 // Trigger the probe.
5651 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5652 nullptr);
5653 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5654 QuicByteCount probe_size;
5655 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5656 .WillOnce(SaveArg<3>(&probe_size));
5657 connection_.GetMtuDiscoveryAlarm()->Fire();
5658 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5659 kMtuDiscoveryTargetPacketSizeHigh));
5660
5661 const QuicPacketNumber probe_packet_number =
5662 FirstSendingPacketNumber() + packets_between_probes_base;
5663 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5664
5665 // Acknowledge all packets sent so far.
5666 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
martindukeba002452023-03-21 08:10:46 -07005667 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04005668 .Times(AnyNumber());
5669 ProcessAckPacket(&first_ack);
5670 EXPECT_EQ(probe_size, connection_.max_packet_length());
5671 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5672
5673 EXPECT_EQ(1u, connection_.mtu_probe_count());
5674
5675 // Send just enough packets without triggering the second probe.
5676 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5677 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5678 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5679 }
5680
5681 // Trigger the second probe.
5682 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5683 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5684 QuicByteCount second_probe_size;
5685 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5686 .WillOnce(SaveArg<3>(&second_probe_size));
5687 connection_.GetMtuDiscoveryAlarm()->Fire();
5688 EXPECT_THAT(second_probe_size,
5689 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5690 EXPECT_EQ(2u, connection_.mtu_probe_count());
5691
5692 // Acknowledge all packets sent so far, except the second probe.
5693 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5694 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5695 ProcessAckPacket(&first_ack);
5696 EXPECT_EQ(probe_size, connection_.max_packet_length());
5697
5698 // Send just enough packets without triggering the third probe.
5699 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5700 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5701 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5702 }
5703
5704 // Trigger the third probe.
5705 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5706 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5707 QuicByteCount third_probe_size;
5708 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5709 .WillOnce(SaveArg<3>(&third_probe_size));
5710 connection_.GetMtuDiscoveryAlarm()->Fire();
5711 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5712 EXPECT_EQ(3u, connection_.mtu_probe_count());
5713
5714 // Acknowledge all packets sent so far, except the second probe.
5715 QuicAckFrame third_ack =
5716 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5717 ProcessAckPacket(&third_ack);
5718 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5719
5720 SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr);
5721 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5722
5723 if (connection_.PathDegradingDetectionInProgress() &&
5724 QuicConnectionPeer::GetPathDegradingDeadline(&connection_) <
5725 QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(
5726 &connection_)) {
5727 // Fire path degrading alarm first.
5728 connection_.PathDegradingTimeout();
5729 }
5730
5731 // Verify the max packet size has not reduced.
5732 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5733
5734 // Fire alarm to get path mtu reduction callback called.
5735 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5736 connection_.GetBlackholeDetectorAlarm()->Fire();
5737
5738 // Verify the max packet size has reduced to the previous value.
5739 EXPECT_EQ(probe_size, connection_.max_packet_length());
5740}
5741
5742// Tests whether MTU discovery works when the writer has a limit on how large a
5743// packet can be.
5744TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5745 MtuDiscoveryTestInit();
5746
5747 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5748 writer_->set_max_packet_size(mtu_limit);
5749
5750 const QuicPacketCount packets_between_probes_base = 5;
5751 set_packets_between_probes_base(packets_between_probes_base);
5752
5753 connection_.EnablePathMtuDiscovery(send_algorithm_);
5754
5755 // Send enough packets so that the next one triggers path MTU discovery.
5756 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5757 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5758 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5759 }
5760
5761 // Trigger the probe.
5762 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5763 nullptr);
5764 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5765 QuicByteCount probe_size;
5766 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5767 .WillOnce(SaveArg<3>(&probe_size));
5768 connection_.GetMtuDiscoveryAlarm()->Fire();
5769
5770 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
5771
5772 const QuicPacketNumber probe_sequence_number =
5773 FirstSendingPacketNumber() + packets_between_probes_base;
5774 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5775
5776 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005777 {
5778 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5779 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5780 .Times(AnyNumber());
5781 ProcessAckPacket(&probe_ack);
5782 EXPECT_EQ(probe_size, connection_.max_packet_length());
5783 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5784 }
Bence Békybac04052022-04-07 15:44:29 -04005785
5786 EXPECT_EQ(1u, connection_.mtu_probe_count());
5787
5788 QuicStreamOffset stream_offset = packets_between_probes_base;
5789 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5790 ++num_probes) {
5791 // Send just enough packets without triggering the next probe.
5792 for (QuicPacketCount i = 0;
5793 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5794 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5795 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5796 }
5797
5798 // Trigger the next probe.
5799 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5800 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5801 QuicByteCount new_probe_size;
5802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5803 .WillOnce(SaveArg<3>(&new_probe_size));
5804 connection_.GetMtuDiscoveryAlarm()->Fire();
5805 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5806 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5807
5808 // Acknowledge all packets sent so far.
5809 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5810 ProcessAckPacket(&probe_ack);
5811 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5812 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5813
5814 probe_size = new_probe_size;
5815 }
5816
5817 // The last probe size should be equal to the target.
5818 EXPECT_EQ(probe_size, mtu_limit);
5819}
5820
5821// Tests whether MTU discovery works when the writer returns an error despite
5822// advertising higher packet length.
5823TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5824 MtuDiscoveryTestInit();
5825
5826 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5827 const QuicByteCount initial_mtu = connection_.max_packet_length();
5828 EXPECT_LT(initial_mtu, mtu_limit);
5829 writer_->set_max_packet_size(mtu_limit);
5830
5831 const QuicPacketCount packets_between_probes_base = 5;
5832 set_packets_between_probes_base(packets_between_probes_base);
5833
5834 connection_.EnablePathMtuDiscovery(send_algorithm_);
5835
5836 // Send enough packets so that the next one triggers path MTU discovery.
5837 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5838 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5839 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5840 }
5841
5842 // Trigger the probe.
5843 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5844 nullptr);
5845 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5846 writer_->SimulateNextPacketTooLarge();
5847 connection_.GetMtuDiscoveryAlarm()->Fire();
5848 ASSERT_TRUE(connection_.connected());
5849
5850 // Send more data.
5851 QuicPacketNumber probe_number = creator_->packet_number();
5852 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5853 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5854 connection_.EnsureWritableAndSendStreamData5();
5855 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5856 }
5857
5858 // Acknowledge all packets sent so far, except for the lost probe.
5859 QuicAckFrame probe_ack =
5860 ConstructAckFrame(creator_->packet_number(), probe_number);
martindukeba002452023-03-21 08:10:46 -07005861 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005862 ProcessAckPacket(&probe_ack);
5863 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5864
5865 // Send more packets, and ensure that none of them sets the alarm.
5866 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5867 connection_.EnsureWritableAndSendStreamData5();
5868 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5869 }
5870
5871 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5872 EXPECT_EQ(1u, connection_.mtu_probe_count());
5873}
5874
5875TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5876 MtuDiscoveryTestInit();
5877
5878 const QuicPacketCount packets_between_probes_base = 10;
5879 set_packets_between_probes_base(packets_between_probes_base);
5880
5881 connection_.EnablePathMtuDiscovery(send_algorithm_);
5882
5883 // Send enough packets so that the next one triggers path MTU discovery.
5884 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5885 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5886 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5887 }
5888
5889 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5890 nullptr);
5891 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5892
5893 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
5894 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5895 ConnectionCloseBehavior::SILENT_CLOSE);
5896 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5897}
5898
5899TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
5900 EXPECT_TRUE(connection_.connected());
5901 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08005902 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
5903 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04005904 QuicConfig config;
5905 connection_.SetFromConfig(config);
5906
5907 const QuicTime::Delta initial_idle_timeout =
5908 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5909 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5910 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5911
5912 // When we send a packet, the timeout will change to 5ms +
5913 // kInitialIdleTimeoutSecs.
5914 clock_.AdvanceTime(five_ms);
5915 SendStreamDataToPeer(
5916 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5917 0, FIN, nullptr);
5918 EXPECT_EQ(default_timeout + five_ms,
5919 connection_.GetTimeoutAlarm()->deadline());
5920
5921 // Now send more data. This will not move the timeout because
5922 // no data has been received since the previous write.
5923 clock_.AdvanceTime(five_ms);
5924 SendStreamDataToPeer(
5925 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5926 3, FIN, nullptr);
5927 EXPECT_EQ(default_timeout + five_ms,
5928 connection_.GetTimeoutAlarm()->deadline());
5929
5930 // The original alarm will fire. We should not time out because we had a
5931 // network event at t=5ms. The alarm will reregister.
5932 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5933 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5934 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5935 EXPECT_TRUE(connection_.connected());
5936 EXPECT_EQ(default_timeout + five_ms,
5937 connection_.GetTimeoutAlarm()->deadline());
5938
5939 // This time, we should time out.
5940 EXPECT_CALL(visitor_,
5941 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5942 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5943 clock_.AdvanceTime(five_ms);
5944 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5945 connection_.GetTimeoutAlarm()->Fire();
5946 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5947 EXPECT_FALSE(connection_.connected());
5948 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5949}
5950
Bence Békybac04052022-04-07 15:44:29 -04005951TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5952 // When the idle timeout fires, verify that by default we do not send any
5953 // connection close packets.
5954 EXPECT_TRUE(connection_.connected());
5955 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08005956 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
5957 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04005958 QuicConfig config;
5959
5960 // Create a handshake message that also enables silent close.
5961 CryptoHandshakeMessage msg;
5962 std::string error_details;
5963 QuicConfig client_config;
5964 client_config.SetInitialStreamFlowControlWindowToSend(
5965 kInitialStreamFlowControlWindowForTest);
5966 client_config.SetInitialSessionFlowControlWindowToSend(
5967 kInitialSessionFlowControlWindowForTest);
5968 client_config.SetIdleNetworkTimeout(
5969 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5970 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5971 const QuicErrorCode error =
5972 config.ProcessPeerHello(msg, CLIENT, &error_details);
5973 EXPECT_THAT(error, IsQuicNoError());
5974
5975 if (connection_.version().UsesTls()) {
5976 QuicConfigPeer::SetReceivedOriginalConnectionId(
5977 &config, connection_.connection_id());
5978 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5979 &config, connection_.connection_id());
5980 }
5981 connection_.SetFromConfig(config);
5982
5983 const QuicTime::Delta default_idle_timeout =
5984 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5985 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5986 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5987
5988 // When we send a packet, the timeout will change to 5ms +
5989 // kInitialIdleTimeoutSecs.
5990 clock_.AdvanceTime(five_ms);
5991 SendStreamDataToPeer(
5992 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5993 0, FIN, nullptr);
5994 EXPECT_EQ(default_timeout + five_ms,
5995 connection_.GetTimeoutAlarm()->deadline());
5996
5997 // Now send more data. This will not move the timeout because
5998 // no data has been received since the previous write.
5999 clock_.AdvanceTime(five_ms);
6000 SendStreamDataToPeer(
6001 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6002 3, FIN, nullptr);
6003 EXPECT_EQ(default_timeout + five_ms,
6004 connection_.GetTimeoutAlarm()->deadline());
6005
6006 // The original alarm will fire. We should not time out because we had a
6007 // network event at t=5ms. The alarm will reregister.
6008 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
6009 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6010 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6011 EXPECT_TRUE(connection_.connected());
6012 EXPECT_EQ(default_timeout + five_ms,
6013 connection_.GetTimeoutAlarm()->deadline());
6014
6015 // This time, we should time out.
6016 // This results in a SILENT_CLOSE, so the writer will not be invoked
6017 // and will not save the frame. Grab the frame from OnConnectionClosed
6018 // directly.
6019 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6020 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6021
6022 clock_.AdvanceTime(five_ms);
6023 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6024 connection_.GetTimeoutAlarm()->Fire();
6025 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6026 EXPECT_FALSE(connection_.connected());
6027 EXPECT_EQ(1, connection_close_frame_count_);
6028 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6029 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
6030}
6031
Bence Békybac04052022-04-07 15:44:29 -04006032TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
6033 // Same test as above, but having open streams causes a connection close
6034 // to be sent.
6035 EXPECT_TRUE(connection_.connected());
6036 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08006037 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
6038 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04006039 QuicConfig config;
6040
6041 // Create a handshake message that also enables silent close.
6042 CryptoHandshakeMessage msg;
6043 std::string error_details;
6044 QuicConfig client_config;
6045 client_config.SetInitialStreamFlowControlWindowToSend(
6046 kInitialStreamFlowControlWindowForTest);
6047 client_config.SetInitialSessionFlowControlWindowToSend(
6048 kInitialSessionFlowControlWindowForTest);
6049 client_config.SetIdleNetworkTimeout(
6050 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
6051 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
6052 const QuicErrorCode error =
6053 config.ProcessPeerHello(msg, CLIENT, &error_details);
6054 EXPECT_THAT(error, IsQuicNoError());
6055
6056 if (connection_.version().UsesTls()) {
6057 QuicConfigPeer::SetReceivedOriginalConnectionId(
6058 &config, connection_.connection_id());
6059 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
6060 &config, connection_.connection_id());
6061 }
6062 connection_.SetFromConfig(config);
6063
6064 const QuicTime::Delta default_idle_timeout =
6065 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
6066 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6067 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
6068
6069 // When we send a packet, the timeout will change to 5ms +
6070 // kInitialIdleTimeoutSecs.
6071 clock_.AdvanceTime(five_ms);
6072 SendStreamDataToPeer(
6073 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6074 0, FIN, nullptr);
6075 EXPECT_EQ(default_timeout + five_ms,
6076 connection_.GetTimeoutAlarm()->deadline());
6077
6078 // Indicate streams are still open.
6079 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
6080 .WillRepeatedly(Return(true));
6081 if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) {
6082 EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return(""));
6083 }
6084
6085 // This time, we should time out and send a connection close due to the TLP.
6086 EXPECT_CALL(visitor_,
6087 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6088 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6089 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
6090 clock_.ApproximateNow() + five_ms);
6091 connection_.GetTimeoutAlarm()->Fire();
6092 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6093 EXPECT_FALSE(connection_.connected());
6094 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6095}
6096
6097TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
6098 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6099 EXPECT_TRUE(connection_.connected());
6100 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08006101 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
6102 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04006103 QuicConfig config;
6104 connection_.SetFromConfig(config);
6105
6106 const QuicTime::Delta initial_idle_timeout =
6107 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6108 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6109 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6110
6111 connection_.SendStreamDataWithString(
6112 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6113 0, NO_FIN);
6114 connection_.SendStreamDataWithString(
6115 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6116 3, NO_FIN);
6117
6118 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6119 clock_.AdvanceTime(five_ms);
6120
6121 // When we receive a packet, the timeout will change to 5ms +
6122 // kInitialIdleTimeoutSecs.
6123 QuicAckFrame ack = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07006124 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006125 ProcessAckPacket(&ack);
6126
6127 // The original alarm will fire. We should not time out because we had a
6128 // network event at t=5ms. The alarm will reregister.
6129 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6130 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6131 EXPECT_TRUE(connection_.connected());
6132 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6133 EXPECT_EQ(default_timeout + five_ms,
6134 connection_.GetTimeoutAlarm()->deadline());
6135
6136 // This time, we should time out.
6137 EXPECT_CALL(visitor_,
6138 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6140 clock_.AdvanceTime(five_ms);
6141 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6142 connection_.GetTimeoutAlarm()->Fire();
6143 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6144 EXPECT_FALSE(connection_.connected());
6145 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6146}
6147
6148TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6149 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6150 EXPECT_TRUE(connection_.connected());
6151 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08006152 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
6153 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04006154 QuicConfig config;
6155 connection_.SetFromConfig(config);
6156
6157 const QuicTime::Delta initial_idle_timeout =
6158 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6159 connection_.SetNetworkTimeouts(
6160 QuicTime::Delta::Infinite(),
6161 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6162 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6163 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6164
6165 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6166 connection_.SendStreamDataWithString(
6167 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6168 0, NO_FIN);
6169 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6170 connection_.SendStreamDataWithString(
6171 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6172 3, NO_FIN);
6173
6174 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6175
6176 clock_.AdvanceTime(five_ms);
6177
6178 // When we receive a packet, the timeout will change to 5ms +
6179 // kInitialIdleTimeoutSecs.
6180 QuicAckFrame ack = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07006181 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006182 ProcessAckPacket(&ack);
6183
6184 // The original alarm will fire. We should not time out because we had a
6185 // network event at t=5ms. The alarm will reregister.
6186 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6187 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6188 EXPECT_TRUE(connection_.connected());
6189 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6190 EXPECT_EQ(default_timeout + five_ms,
6191 connection_.GetTimeoutAlarm()->deadline());
6192
6193 // Now, send packets while advancing the time and verify that the connection
6194 // eventually times out.
6195 EXPECT_CALL(visitor_,
6196 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6197 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6198 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6199 QUIC_LOG(INFO) << "sending data packet";
6200 connection_.SendStreamDataWithString(
6201 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6202 "foo", 0, NO_FIN);
6203 connection_.GetTimeoutAlarm()->Fire();
6204 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6205 }
6206 EXPECT_FALSE(connection_.connected());
6207 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6208 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6209}
6210
Bence Békybac04052022-04-07 15:44:29 -04006211TEST_P(QuicConnectionTest, SendScheduler) {
6212 // Test that if we send a packet without delay, it is not queued.
6213 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6214 std::unique_ptr<QuicPacket> packet =
6215 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6216 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6217 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6218 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6219 HAS_RETRANSMITTABLE_DATA, false, false);
6220 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6221}
6222
6223TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6224 // Test that the connection does not crash when it fails to send the first
6225 // packet at which point self_address_ might be uninitialized.
6226 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6227 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
6228 std::unique_ptr<QuicPacket> packet =
6229 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6230 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6231 writer_->SetShouldWriteFail();
6232 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6233 HAS_RETRANSMITTABLE_DATA, false, false);
6234}
6235
6236TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6237 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6238 std::unique_ptr<QuicPacket> packet =
6239 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6240 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6241 BlockOnNextWrite();
6242 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6243 .Times(0);
6244 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6245 HAS_RETRANSMITTABLE_DATA, false, false);
6246 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6247}
6248
6249TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
6250 // Queue the first packet.
6251 size_t payload_length = connection_.max_packet_length();
6252 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
6253 const std::string payload(payload_length, 'a');
6254 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6255 connection_.version().transport_version, Perspective::IS_CLIENT));
6256 EXPECT_EQ(0u, connection_
6257 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6258 NO_FIN)
6259 .bytes_consumed);
6260 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6261}
6262
6263TEST_P(QuicConnectionTest, SendingThreePackets) {
6264 // Make the payload twice the size of the packet, so 3 packets are written.
6265 size_t total_payload_length = 2 * connection_.max_packet_length();
6266 const std::string payload(total_payload_length, 'a');
6267 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6268 connection_.version().transport_version, Perspective::IS_CLIENT));
6269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6270 EXPECT_EQ(payload.size(), connection_
6271 .SendStreamDataWithString(first_bidi_stream_id,
6272 payload, 0, NO_FIN)
6273 .bytes_consumed);
6274}
6275
6276TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6277 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -04006278 // Set up a larger payload than will fit in one packet.
6279 const std::string payload(connection_.max_packet_length(), 'a');
6280 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
martindukeeaf27602024-11-12 14:34:40 -08006281 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillRepeatedly(Return(false));
6282 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillRepeatedly(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04006283
6284 // Now send some packets with no truncation.
6285 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6286 EXPECT_EQ(payload.size(),
6287 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6288 .bytes_consumed);
6289 // Track the size of the second packet here. The overhead will be the largest
6290 // we see in this test, due to the non-truncated connection id.
6291 size_t non_truncated_packet_size = writer_->last_packet_size();
6292
6293 // Change to a 0 byte connection id.
6294 QuicConfig config;
6295 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6296 connection_.SetFromConfig(config);
6297 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6298 EXPECT_EQ(payload.size(),
6299 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6300 .bytes_consumed);
fayangfc04b8a2023-05-18 09:26:25 -07006301 // Short header packets sent from server omit connection ID already, and
6302 // stream offset size increases from 0 to 2.
6303 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
Bence Békybac04052022-04-07 15:44:29 -04006304}
6305
6306TEST_P(QuicConnectionTest, SendDelayedAck) {
6307 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6308 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6309 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006310 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006311 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6312 peer_framer_.SetEncrypter(
6313 ENCRYPTION_ZERO_RTT,
6314 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006315 // Process a packet from the non-crypto stream.
6316 frame1_.stream_id = 3;
6317
6318 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6319 // instead of ENCRYPTION_INITIAL.
6320 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6321 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6322
6323 // Check if delayed ack timer is running for the expected interval.
6324 EXPECT_TRUE(connection_.HasPendingAcks());
6325 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6326 // Simulate delayed ack alarm firing.
6327 clock_.AdvanceTime(DefaultDelayedAckTime());
6328 connection_.GetAckAlarm()->Fire();
6329 // Check that ack is sent and that delayed ack alarm is reset.
6330 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006331 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6332 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006333 EXPECT_FALSE(writer_->ack_frames().empty());
6334 EXPECT_FALSE(connection_.HasPendingAcks());
6335}
6336
6337TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6338 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6339
6340 const size_t kMinRttMs = 40;
6341 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6342 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6343 QuicTime::Delta::Zero(), QuicTime::Zero());
6344 // The ack time should be based on min_rtt/4, since it's less than the
6345 // default delayed ack time.
6346 QuicTime ack_time = clock_.ApproximateNow() +
6347 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6348 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6349 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006350 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006351 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6352 peer_framer_.SetEncrypter(
6353 ENCRYPTION_ZERO_RTT,
6354 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006355 // Process a packet from the non-crypto stream.
6356 frame1_.stream_id = 3;
6357
6358 // Process all the initial packets in order so there aren't missing packets.
6359 uint64_t kFirstDecimatedPacket = 101;
6360 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6361 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6362 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6363 }
6364 EXPECT_FALSE(connection_.HasPendingAcks());
6365 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6366 // instead of ENCRYPTION_INITIAL.
6367 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6368 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6369 ENCRYPTION_ZERO_RTT);
6370
6371 // Check if delayed ack timer is running for the expected interval.
6372 EXPECT_TRUE(connection_.HasPendingAcks());
6373 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6374
6375 // The 10th received packet causes an ack to be sent.
6376 for (int i = 0; i < 9; ++i) {
6377 EXPECT_TRUE(connection_.HasPendingAcks());
6378 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6379 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6380 ENCRYPTION_ZERO_RTT);
6381 }
6382 // Check that ack is sent and that delayed ack alarm is reset.
6383 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006384 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6385 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006386 EXPECT_FALSE(writer_->ack_frames().empty());
6387 EXPECT_FALSE(connection_.HasPendingAcks());
6388}
6389
6390TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6391 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6392 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08006393 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
6394 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04006395 QuicConfig config;
6396 QuicTagVector connection_options;
6397 // No limit on the number of packets received before sending an ack.
6398 connection_options.push_back(kAKDU);
6399 config.SetConnectionOptionsToSend(connection_options);
6400 connection_.SetFromConfig(config);
6401
6402 const size_t kMinRttMs = 40;
6403 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6404 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6405 QuicTime::Delta::Zero(), QuicTime::Zero());
6406 // The ack time should be based on min_rtt/4, since it's less than the
6407 // default delayed ack time.
6408 QuicTime ack_time = clock_.ApproximateNow() +
6409 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6410 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6411 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006412 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006413 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6414 peer_framer_.SetEncrypter(
6415 ENCRYPTION_ZERO_RTT,
6416 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006417 // Process a packet from the non-crypto stream.
6418 frame1_.stream_id = 3;
6419
6420 // Process all the initial packets in order so there aren't missing packets.
6421 uint64_t kFirstDecimatedPacket = 101;
6422 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6423 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6424 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6425 }
6426 EXPECT_FALSE(connection_.HasPendingAcks());
6427 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6428 // instead of ENCRYPTION_INITIAL.
6429 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6430 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6431 ENCRYPTION_ZERO_RTT);
6432
6433 // Check if delayed ack timer is running for the expected interval.
6434 EXPECT_TRUE(connection_.HasPendingAcks());
6435 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6436
6437 // 18 packets will not cause an ack to be sent. 19 will because when
6438 // stop waiting frames are in use, we ack every 20 packets no matter what.
6439 for (int i = 0; i < 18; ++i) {
6440 EXPECT_TRUE(connection_.HasPendingAcks());
6441 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6442 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6443 ENCRYPTION_ZERO_RTT);
6444 }
6445 // The delayed ack timer should still be set to the expected deadline.
6446 EXPECT_TRUE(connection_.HasPendingAcks());
6447 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6448}
6449
6450TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6451 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6452 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6453
6454 const size_t kMinRttMs = 40;
6455 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6456 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6457 QuicTime::Delta::Zero(), QuicTime::Zero());
6458 // The ack time should be based on min_rtt/8, since it's less than the
6459 // default delayed ack time.
6460 QuicTime ack_time = clock_.ApproximateNow() +
6461 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6462 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6463 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006464 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006465 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6466 peer_framer_.SetEncrypter(
6467 ENCRYPTION_ZERO_RTT,
6468 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006469 // Process a packet from the non-crypto stream.
6470 frame1_.stream_id = 3;
6471
6472 // Process all the initial packets in order so there aren't missing packets.
6473 uint64_t kFirstDecimatedPacket = 101;
6474 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6475 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6476 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6477 }
6478 EXPECT_FALSE(connection_.HasPendingAcks());
6479 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6480 // instead of ENCRYPTION_INITIAL.
6481 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6482 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6483 ENCRYPTION_ZERO_RTT);
6484
6485 // Check if delayed ack timer is running for the expected interval.
6486 EXPECT_TRUE(connection_.HasPendingAcks());
6487 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6488
6489 // The 10th received packet causes an ack to be sent.
6490 for (int i = 0; i < 9; ++i) {
6491 EXPECT_TRUE(connection_.HasPendingAcks());
6492 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6493 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6494 ENCRYPTION_ZERO_RTT);
6495 }
6496 // Check that ack is sent and that delayed ack alarm is reset.
6497 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006498 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6499 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006500 EXPECT_FALSE(writer_->ack_frames().empty());
6501 EXPECT_FALSE(connection_.HasPendingAcks());
6502}
6503
6504TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6505 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6506 ProcessPacket(1);
6507 // Check that ack is sent and that delayed ack alarm is set.
6508 EXPECT_TRUE(connection_.HasPendingAcks());
6509 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6510 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6511
6512 // Completing the handshake as the server does nothing.
6513 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6514 connection_.OnHandshakeComplete();
6515 EXPECT_TRUE(connection_.HasPendingAcks());
6516 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6517
6518 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6519 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6520 connection_.OnHandshakeComplete();
6521 EXPECT_TRUE(connection_.HasPendingAcks());
6522 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6523 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6524 connection_.GetAckAlarm()->deadline());
6525 } else {
6526 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6527 }
6528}
6529
6530TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6531 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6532 ProcessPacket(1);
6533 ProcessPacket(2);
6534 // Check that ack is sent and that delayed ack alarm is reset.
6535 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006536 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6537 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006538 EXPECT_FALSE(writer_->ack_frames().empty());
6539 EXPECT_FALSE(connection_.HasPendingAcks());
6540}
6541
6542TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6543 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6544 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6545 ProcessPacket(2);
fayangfc04b8a2023-05-18 09:26:25 -07006546 size_t frames_per_ack = 1;
Bence Békybac04052022-04-07 15:44:29 -04006547
6548 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6549 ProcessPacket(3);
6550 size_t padding_frame_count = writer_->padding_frames().size();
6551 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6552 EXPECT_FALSE(writer_->ack_frames().empty());
6553 writer_->Reset();
6554
6555 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6556 ProcessPacket(4);
6557 EXPECT_EQ(0u, writer_->frame_count());
6558
6559 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6560 ProcessPacket(5);
6561 padding_frame_count = writer_->padding_frames().size();
6562 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6563 EXPECT_FALSE(writer_->ack_frames().empty());
6564 writer_->Reset();
6565
6566 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6567 // Now only set the timer on the 6th packet, instead of sending another ack.
6568 ProcessPacket(6);
6569 padding_frame_count = writer_->padding_frames().size();
6570 EXPECT_EQ(padding_frame_count, writer_->frame_count());
6571 EXPECT_TRUE(connection_.HasPendingAcks());
6572}
6573
6574TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6575 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6576 EXPECT_CALL(visitor_, OnStreamFrame(_));
martinduke9e0811c2022-12-08 20:35:57 -08006577 peer_framer_.SetEncrypter(
6578 ENCRYPTION_FORWARD_SECURE,
6579 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
6580 SetDecrypter(
6581 ENCRYPTION_FORWARD_SECURE,
6582 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04006583 ProcessDataPacket(1);
6584 connection_.SendStreamDataWithString(
6585 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6586 0, NO_FIN);
6587 // Check that ack is bundled with outgoing data and that delayed ack
6588 // alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006589 EXPECT_EQ(2u, writer_->frame_count());
6590 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006591 EXPECT_FALSE(writer_->ack_frames().empty());
6592 EXPECT_FALSE(connection_.HasPendingAcks());
6593}
6594
6595TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6596 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6597 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6598 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6599 } else {
6600 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6601 }
6602 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6603 connection_.SendCryptoDataWithString("foo", 0);
6604 // Check that ack is bundled with outgoing crypto data.
dschinazi351e8282024-10-16 09:25:21 -07006605 EXPECT_FALSE(writer_->ack_frames().empty());
6606 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6607 EXPECT_FALSE(writer_->stream_frames().empty());
6608 } else {
6609 EXPECT_FALSE(writer_->crypto_frames().empty());
6610 }
6611 EXPECT_FALSE(writer_->padding_frames().empty());
fayangfc04b8a2023-05-18 09:26:25 -07006612 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006613 EXPECT_FALSE(connection_.HasPendingAcks());
6614}
6615
6616TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6617 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6618 ProcessPacket(1);
6619 BlockOnNextWrite();
6620 writer_->set_is_write_blocked_data_buffered(true);
6621 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6623 } else {
6624 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6625 }
6626 connection_.SendCryptoDataWithString("foo", 0);
6627 EXPECT_TRUE(writer_->IsWriteBlocked());
6628 EXPECT_FALSE(connection_.HasQueuedData());
6629 connection_.SendCryptoDataWithString("bar", 3);
6630 EXPECT_TRUE(writer_->IsWriteBlocked());
6631 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6632 // CRYPTO frames are not flushed when writer is blocked.
6633 EXPECT_FALSE(connection_.HasQueuedData());
6634 } else {
6635 EXPECT_TRUE(connection_.HasQueuedData());
6636 }
6637}
6638
6639TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6640 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6641 EXPECT_FALSE(connection_.HasPendingAcks());
6642 EXPECT_CALL(visitor_, OnCanWrite())
6643 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6644 &connection_, &TestConnection::SendCryptoStreamData)));
6645 // Process a packet from the crypto stream, which is frame1_'s default.
6646 // Receiving the CHLO as packet 2 first will cause the connection to
6647 // immediately send an ack, due to the packet gap.
6648 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6649 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6650 } else {
6651 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6652 }
wubc9fd4292023-08-14 13:00:21 -07006653 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006654 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6655 // Check that ack is sent and that delayed ack alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006656 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006657 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
dschinazi351e8282024-10-16 09:25:21 -07006658 EXPECT_FALSE(writer_->stream_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006659 } else {
dschinazi351e8282024-10-16 09:25:21 -07006660 EXPECT_FALSE(writer_->crypto_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006661 }
dschinazi351e8282024-10-16 09:25:21 -07006662 EXPECT_FALSE(writer_->padding_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006663 ASSERT_FALSE(writer_->ack_frames().empty());
6664 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6665 EXPECT_FALSE(connection_.HasPendingAcks());
6666}
6667
6668TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6669 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6670 EXPECT_FALSE(connection_.HasPendingAcks());
6671
6672 // Process two packets from the crypto stream, which is frame1_'s default,
6673 // simulating a 2 packet reject.
6674 {
6675 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6676 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6677 } else {
6678 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6679 }
6680 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6681 // Send the new CHLO when the REJ is processed.
6682 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6683 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6684 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6685 &connection_, &TestConnection::SendCryptoStreamData)));
6686 } else {
6687 EXPECT_CALL(visitor_, OnStreamFrame(_))
6688 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6689 &connection_, &TestConnection::SendCryptoStreamData)));
6690 }
wubc9fd4292023-08-14 13:00:21 -07006691 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006692 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6693 }
6694 // Check that ack is sent and that delayed ack alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006695 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006696 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
dschinazi351e8282024-10-16 09:25:21 -07006697 EXPECT_FALSE(writer_->stream_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006698 } else {
dschinazi351e8282024-10-16 09:25:21 -07006699 EXPECT_FALSE(writer_->crypto_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006700 }
dschinazi351e8282024-10-16 09:25:21 -07006701 EXPECT_FALSE(writer_->padding_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006702 ASSERT_FALSE(writer_->ack_frames().empty());
6703 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6704 EXPECT_FALSE(connection_.HasPendingAcks());
6705}
6706
6707TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6708 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6709 connection_.SendStreamDataWithString(
6710 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6711 0, NO_FIN);
6712 connection_.SendStreamDataWithString(
6713 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6714 3, NO_FIN);
6715 // Ack the second packet, which will retransmit the first packet.
6716 QuicAckFrame ack = ConstructAckFrame(2, 1);
6717 LostPacketVector lost_packets;
6718 lost_packets.push_back(
6719 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6720 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6721 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
6722 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07006723 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006724 ProcessAckPacket(&ack);
6725 size_t padding_frame_count = writer_->padding_frames().size();
6726 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6727 EXPECT_EQ(1u, writer_->stream_frames().size());
6728 writer_->Reset();
6729
6730 // Now ack the retransmission, which will both raise the high water mark
6731 // and see if there is more data to send.
6732 ack = ConstructAckFrame(3, 1);
6733 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07006734 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006735 ProcessAckPacket(&ack);
6736
6737 // Check that no packet is sent and the ack alarm isn't set.
6738 EXPECT_EQ(0u, writer_->frame_count());
6739 EXPECT_FALSE(connection_.HasPendingAcks());
6740 writer_->Reset();
6741
6742 // Send the same ack, but send both data and an ack together.
6743 ack = ConstructAckFrame(3, 1);
6744 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6745 EXPECT_CALL(visitor_, OnCanWrite())
6746 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6747 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
wubc9fd4292023-08-14 13:00:21 -07006748 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006749 ProcessAckPacket(&ack);
6750
6751 // Check that ack is bundled with outgoing data and the delayed ack
6752 // alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006753 // Do not ACK acks.
6754 EXPECT_EQ(1u, writer_->frame_count());
6755 EXPECT_TRUE(writer_->ack_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006756 EXPECT_EQ(1u, writer_->stream_frames().size());
6757 EXPECT_FALSE(connection_.HasPendingAcks());
6758}
6759
6760TEST_P(QuicConnectionTest, NoAckSentForClose) {
6761 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6762 ProcessPacket(1);
6763 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6764 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6765 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6766 ProcessClosePacket(2);
6767 EXPECT_EQ(1, connection_close_frame_count_);
6768 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6769 IsError(QUIC_PEER_GOING_AWAY));
6770}
6771
6772TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6773 EXPECT_TRUE(connection_.connected());
6774 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6775 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6776 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6777 ConnectionCloseBehavior::SILENT_CLOSE);
6778 EXPECT_FALSE(connection_.connected());
6779 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6780 EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
6781 /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
6782}
6783
6784TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6785 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
6786 if (!IsDefaultTestConfiguration()) {
6787 return;
6788 }
6789
6790 EXPECT_TRUE(connection_.connected());
6791 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6792 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6793 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6794 ConnectionCloseBehavior::SILENT_CLOSE);
6795 EXPECT_FALSE(connection_.connected());
6796 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6797
6798 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6799 .Times(0);
6800
6801 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6802 writer_.get(), connection_.peer_address()),
6803 "Not sending connectivity probing packet as connection is "
6804 "disconnected.");
6805 EXPECT_EQ(1, connection_close_frame_count_);
6806 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6807 IsError(QUIC_PEER_GOING_AWAY));
6808}
6809
6810TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6811 PathProbeTestInit(Perspective::IS_CLIENT);
6812 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6813 // Block next write so that sending connectivity probe will encounter a
6814 // blocked write when send a connectivity probe to the peer.
6815 probing_writer.BlockOnNextWrite();
6816 // Connection will not be marked as write blocked as connectivity probe only
6817 // affects the probing_writer which is not the default.
6818 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6819
6820 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6821 .Times(1);
6822 connection_.SendConnectivityProbingPacket(&probing_writer,
6823 connection_.peer_address());
6824}
6825
6826TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6827 PathProbeTestInit(Perspective::IS_SERVER);
6828 if (version().SupportsAntiAmplificationLimit()) {
6829 QuicConnectionPeer::SetAddressValidated(&connection_);
6830 }
6831
6832 // Block next write so that sending connectivity probe will encounter a
6833 // blocked write when send a connectivity probe to the peer.
6834 writer_->BlockOnNextWrite();
6835 // Connection will be marked as write blocked as server uses the default
6836 // writer to send connectivity probes.
6837 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6838
6839 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6840 .Times(1);
6841 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6842 QuicPathFrameBuffer payload{
6843 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
6844 QuicConnection::ScopedPacketFlusher flusher(&connection_);
6845 connection_.SendPathChallenge(
6846 payload, connection_.self_address(), connection_.peer_address(),
6847 connection_.effective_peer_address(), writer_.get());
6848 } else {
6849 connection_.SendConnectivityProbingPacket(writer_.get(),
6850 connection_.peer_address());
6851 }
6852}
6853
6854TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6855 PathProbeTestInit(Perspective::IS_CLIENT);
6856 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6857 probing_writer.SetShouldWriteFail();
6858
6859 // Connection should not be closed if a connectivity probe is failed to be
6860 // sent.
6861 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6862
6863 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6864 .Times(0);
6865 connection_.SendConnectivityProbingPacket(&probing_writer,
6866 connection_.peer_address());
6867}
6868
6869TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6870 PathProbeTestInit(Perspective::IS_SERVER);
6871
6872 writer_->SetShouldWriteFail();
6873 // Connection should not be closed if a connectivity probe is failed to be
6874 // sent.
6875 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6876
6877 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6878 .Times(0);
6879 connection_.SendConnectivityProbingPacket(writer_.get(),
6880 connection_.peer_address());
6881}
6882
Bence Békybac04052022-04-07 15:44:29 -04006883TEST_P(QuicConnectionTest, IetfStatelessReset) {
Bence Békybac04052022-04-07 15:44:29 -04006884 QuicConfig config;
6885 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6886 kTestStatelessResetToken);
6887 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08006888 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
6889 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04006890 connection_.SetFromConfig(config);
6891 std::unique_ptr<QuicEncryptedPacket> packet(
6892 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6893 /*received_packet_length=*/100,
6894 kTestStatelessResetToken));
6895 std::unique_ptr<QuicReceivedPacket> received(
6896 ConstructReceivedPacket(*packet, QuicTime::Zero()));
Bence Békybac04052022-04-07 15:44:29 -04006897 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6898 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6899 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6900 EXPECT_EQ(1, connection_close_frame_count_);
6901 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6902 IsError(QUIC_PUBLIC_RESET));
6903}
6904
6905TEST_P(QuicConnectionTest, GoAway) {
6906 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6907 // GoAway is not available in version 99.
6908 return;
6909 }
6910
6911 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6912
6913 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
6914 goaway->last_good_stream_id = 1;
6915 goaway->error_code = QUIC_PEER_GOING_AWAY;
6916 goaway->reason_phrase = "Going away.";
6917 EXPECT_CALL(visitor_, OnGoAway(_));
6918 ProcessGoAwayPacket(goaway);
6919}
6920
6921TEST_P(QuicConnectionTest, WindowUpdate) {
6922 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6923
6924 QuicWindowUpdateFrame window_update;
6925 window_update.stream_id = 3;
6926 window_update.max_data = 1234;
6927 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6928 ProcessFramePacket(QuicFrame(window_update));
6929}
6930
6931TEST_P(QuicConnectionTest, Blocked) {
6932 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6933
6934 QuicBlockedFrame blocked;
6935 blocked.stream_id = 3;
6936 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6937 ProcessFramePacket(QuicFrame(blocked));
6938 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6939 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6940}
6941
6942TEST_P(QuicConnectionTest, ZeroBytePacket) {
6943 // Don't close the connection for zero byte packets.
6944 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6945 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6946 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6947}
6948
Bence Békybac04052022-04-07 15:44:29 -04006949TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
6950 // All supported versions except the one the connection supports.
6951 ParsedQuicVersionVector versions;
6952 for (auto version : AllSupportedVersions()) {
6953 if (version != connection_.version()) {
6954 versions.push_back(version);
6955 }
6956 }
6957
6958 // Send a version negotiation packet.
6959 std::unique_ptr<QuicEncryptedPacket> encrypted(
6960 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07006961 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04006962 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6963 std::unique_ptr<QuicReceivedPacket> received(
6964 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6965 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6966 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6967 // Verify no connection close packet gets sent.
6968 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6969 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6970 EXPECT_FALSE(connection_.connected());
6971 EXPECT_EQ(1, connection_close_frame_count_);
6972 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6973 IsError(QUIC_INVALID_VERSION));
6974}
6975
6976TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiationWithConnectionClose) {
6977 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08006978 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
6979 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04006980 QuicConfig config;
6981 QuicTagVector connection_options;
6982 connection_options.push_back(kINVC);
6983 config.SetClientConnectionOptions(connection_options);
6984 connection_.SetFromConfig(config);
6985
6986 // All supported versions except the one the connection supports.
6987 ParsedQuicVersionVector versions;
6988 for (auto version : AllSupportedVersions()) {
6989 if (version != connection_.version()) {
6990 versions.push_back(version);
6991 }
6992 }
6993
6994 // Send a version negotiation packet.
6995 std::unique_ptr<QuicEncryptedPacket> encrypted(
6996 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07006997 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04006998 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6999 std::unique_ptr<QuicReceivedPacket> received(
7000 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7001 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7002 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7003 // Verify connection close packet gets sent.
7004 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1u));
7005 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
7006 EXPECT_FALSE(connection_.connected());
7007 EXPECT_EQ(1, connection_close_frame_count_);
7008 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7009 IsError(QUIC_INVALID_VERSION));
7010}
7011
7012TEST_P(QuicConnectionTest, BadVersionNegotiation) {
7013 // Send a version negotiation packet with the version the client started with.
7014 // It should be rejected.
7015 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7016 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7017 std::unique_ptr<QuicEncryptedPacket> encrypted(
7018 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07007019 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04007020 connection_.version().HasLengthPrefixedConnectionIds(),
7021 AllSupportedVersions()));
7022 std::unique_ptr<QuicReceivedPacket> received(
7023 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
7024 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
7025 EXPECT_EQ(1, connection_close_frame_count_);
7026 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7027 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
7028}
7029
Bence Békybac04052022-04-07 15:44:29 -04007030TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7031 // Construct a packet with stream frame and connection close frame.
7032 QuicPacketHeader header;
7033 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
7034 header.source_connection_id = connection_id_;
7035 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04007036 } else {
7037 header.destination_connection_id = connection_id_;
fayangfc04b8a2023-05-18 09:26:25 -07007038 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04007039 }
7040 header.packet_number = QuicPacketNumber(1);
7041 header.version_flag = false;
7042
7043 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7044 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7045 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7046 // depending on the mapping.
7047 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7048 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
7049 /*transport_close_frame_type=*/0);
7050 QuicFrames frames;
7051 frames.push_back(QuicFrame(frame1_));
7052 frames.push_back(QuicFrame(&qccf));
7053 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7054 EXPECT_TRUE(nullptr != packet);
7055 char buffer[kMaxOutgoingPacketSize];
7056 size_t encrypted_length = peer_framer_.EncryptPayload(
7057 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7058 kMaxOutgoingPacketSize);
7059
7060 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7061 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7062 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7063 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7064
7065 connection_.ProcessUdpPacket(
7066 kSelfAddress, kPeerAddress,
7067 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
7068 EXPECT_EQ(1, connection_close_frame_count_);
7069 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7070 IsError(QUIC_PEER_GOING_AWAY));
7071}
7072
7073TEST_P(QuicConnectionTest, SelectMutualVersion) {
7074 connection_.SetSupportedVersions(AllSupportedVersions());
7075 // Set the connection to speak the lowest quic version.
7076 connection_.set_version(QuicVersionMin());
7077 EXPECT_EQ(QuicVersionMin(), connection_.version());
7078
7079 // Pass in available versions which includes a higher mutually supported
7080 // version. The higher mutually supported version should be selected.
7081 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7082 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7083 EXPECT_EQ(QuicVersionMax(), connection_.version());
7084
7085 // Expect that the lowest version is selected.
7086 // Ensure the lowest supported version is less than the max, unless they're
7087 // the same.
7088 ParsedQuicVersionVector lowest_version_vector;
7089 lowest_version_vector.push_back(QuicVersionMin());
7090 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7091 EXPECT_EQ(QuicVersionMin(), connection_.version());
7092
7093 // Shouldn't be able to find a mutually supported version.
7094 ParsedQuicVersionVector unsupported_version;
7095 unsupported_version.push_back(UnsupportedQuicVersion());
7096 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7097}
7098
7099TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7100 EXPECT_FALSE(writer_->IsWriteBlocked());
7101
7102 // Send a packet.
7103 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7104 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7105 EXPECT_EQ(1u, writer_->packets_write_attempts());
7106
7107 TriggerConnectionClose();
7108 EXPECT_LE(2u, writer_->packets_write_attempts());
7109}
7110
7111TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7112 BlockOnNextWrite();
7113 TriggerConnectionClose();
7114 EXPECT_EQ(1u, writer_->packets_write_attempts());
7115 EXPECT_TRUE(writer_->IsWriteBlocked());
7116}
7117
7118TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7119 BlockOnNextWrite();
7120 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7121 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7122 EXPECT_EQ(1u, writer_->packets_write_attempts());
7123 EXPECT_TRUE(writer_->IsWriteBlocked());
7124 TriggerConnectionClose();
7125 EXPECT_EQ(1u, writer_->packets_write_attempts());
7126}
7127
7128TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7129 PathProbeTestInit(Perspective::IS_CLIENT);
7130 MockQuicConnectionDebugVisitor debug_visitor;
7131 connection_.set_debug_visitor(&debug_visitor);
7132
wub92727922023-07-13 08:47:39 -07007133 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007134 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7135
wub92727922023-07-13 08:47:39 -07007136 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007137 connection_.SendConnectivityProbingPacket(writer_.get(),
7138 connection_.peer_address());
7139}
7140
7141TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7142 QuicPacketHeader header;
7143 header.packet_number = QuicPacketNumber(1);
fayangfc04b8a2023-05-18 09:26:25 -07007144 header.form = IETF_QUIC_LONG_HEADER_PACKET;
Bence Békybac04052022-04-07 15:44:29 -04007145
7146 MockQuicConnectionDebugVisitor debug_visitor;
7147 connection_.set_debug_visitor(&debug_visitor);
7148 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header), _, _)).Times(1);
7149 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7150 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7151 connection_.OnPacketHeader(header);
7152}
7153
7154TEST_P(QuicConnectionTest, Pacing) {
7155 TestConnection server(connection_id_, kPeerAddress, kSelfAddress,
7156 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07007157 Perspective::IS_SERVER, version(),
7158 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04007159 TestConnection client(connection_id_, kSelfAddress, kPeerAddress,
7160 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07007161 Perspective::IS_CLIENT, version(),
7162 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04007163 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7164 static_cast<const QuicSentPacketManager*>(
7165 &client.sent_packet_manager())));
7166 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7167 static_cast<const QuicSentPacketManager*>(
7168 &server.sent_packet_manager())));
7169}
7170
7171TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7172 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7173
7174 // Send a WINDOW_UPDATE frame.
7175 QuicWindowUpdateFrame window_update;
7176 window_update.stream_id = 3;
7177 window_update.max_data = 1234;
7178 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7179 ProcessFramePacket(QuicFrame(window_update));
7180
7181 // Ensure that this has caused the ACK alarm to be set.
7182 EXPECT_TRUE(connection_.HasPendingAcks());
7183}
7184
7185TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7186 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7187
7188 // Send a BLOCKED frame.
7189 QuicBlockedFrame blocked;
7190 blocked.stream_id = 3;
7191 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7192 ProcessFramePacket(QuicFrame(blocked));
7193
7194 // Ensure that this has caused the ACK alarm to be set.
7195 EXPECT_TRUE(connection_.HasPendingAcks());
7196}
7197
7198TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7199 // Enable pacing.
7200 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08007201 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
7202 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04007203 QuicConfig config;
7204 connection_.SetFromConfig(config);
7205
7206 // Send two packets. One packet is not sufficient because if it gets acked,
7207 // there will be no packets in flight after that and the pacer will always
7208 // allow the next packet in that situation.
7209 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7210 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7211 connection_.SendStreamDataWithString(
7212 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7213 0, NO_FIN);
7214 connection_.SendStreamDataWithString(
7215 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7216 3, NO_FIN);
7217 connection_.OnCanWrite();
7218
7219 // Schedule the next packet for a few milliseconds in future.
7220 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7221 QuicTime scheduled_pacing_time =
7222 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7223 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7224 scheduled_pacing_time);
7225
7226 // Send a packet and have it be blocked by congestion control.
7227 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7228 connection_.SendStreamDataWithString(
7229 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7230 6, NO_FIN);
7231 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7232
7233 // Process an ack and the send alarm will be set to the new 5ms delay.
7234 QuicAckFrame ack = InitAckFrame(1);
7235 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07007236 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007237 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7238 ProcessAckPacket(&ack);
7239 size_t padding_frame_count = writer_->padding_frames().size();
7240 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
7241 EXPECT_EQ(1u, writer_->stream_frames().size());
7242 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7243 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7244 writer_->Reset();
7245}
7246
7247TEST_P(QuicConnectionTest, SendAcksImmediately) {
7248 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7249 return;
7250 }
7251 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7252 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7253 ProcessDataPacket(1);
7254 CongestionBlockWrites();
7255 SendAckPacketToPeer();
7256}
7257
7258TEST_P(QuicConnectionTest, SendPingImmediately) {
7259 MockQuicConnectionDebugVisitor debug_visitor;
7260 connection_.set_debug_visitor(&debug_visitor);
7261
7262 CongestionBlockWrites();
7263 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7264 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wub92727922023-07-13 08:47:39 -07007265 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007266 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7267 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7268 EXPECT_FALSE(connection_.HasQueuedData());
7269}
7270
7271TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7272 MockQuicConnectionDebugVisitor debug_visitor;
7273 connection_.set_debug_visitor(&debug_visitor);
7274
7275 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wub92727922023-07-13 08:47:39 -07007277 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007278 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
QUICHE team1a271082022-05-18 10:22:22 -07007279 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04007280 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7281 EXPECT_FALSE(connection_.HasQueuedData());
7282}
7283
7284TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7285 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7286 return;
7287 }
7288 MockQuicConnectionDebugVisitor debug_visitor;
7289 connection_.set_debug_visitor(&debug_visitor);
QUICHE team1a271082022-05-18 10:22:22 -07007290 QuicBlockedFrame blocked(1, 3, 0);
Bence Békybac04052022-04-07 15:44:29 -04007291
7292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
wub92727922023-07-13 08:47:39 -07007293 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(0);
Bence Békybac04052022-04-07 15:44:29 -04007294 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7295 connection_.SendControlFrame(QuicFrame(blocked));
7296 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7297 EXPECT_FALSE(connection_.HasQueuedData());
7298}
7299
7300TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7301 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7302 if (!IsDefaultTestConfiguration()) {
7303 return;
7304 }
7305
vasilvvac2e30d2022-06-02 14:26:59 -07007306 EXPECT_QUIC_BUG(
7307 {
7308 EXPECT_CALL(visitor_,
7309 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7310 .WillOnce(
7311 Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7312 connection_.SaveAndSendStreamData(3, {}, 0, FIN);
7313 EXPECT_FALSE(connection_.connected());
7314 EXPECT_EQ(1, connection_close_frame_count_);
7315 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7316 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
7317 },
7318 "Cannot send stream data with level: ENCRYPTION_INITIAL");
Bence Békybac04052022-04-07 15:44:29 -04007319}
7320
7321TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7322 EXPECT_TRUE(connection_.connected());
7323 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7324
7325 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7326 connection_.SendCryptoStreamData();
7327
7328 // Verify retransmission timer is correctly set after crypto packet has been
7329 // sent.
7330 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7331 QuicTime retransmission_time =
7332 QuicConnectionPeer::GetSentPacketManager(&connection_)
7333 ->GetRetransmissionTime();
7334 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7335 EXPECT_EQ(retransmission_time,
7336 connection_.GetRetransmissionAlarm()->deadline());
7337
7338 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7339 connection_.GetRetransmissionAlarm()->Fire();
7340}
7341
7342// Includes regression test for b/69979024.
7343TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
7344 EXPECT_TRUE(connection_.connected());
7345 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7346 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007347 EXPECT_CALL(visitor_, GetHandshakeState())
7348 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7349 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007350
7351 const char data[] = "data";
7352 size_t data_size = strlen(data);
7353 QuicStreamOffset offset = 0;
7354
7355 for (int i = 0; i < 2; ++i) {
7356 // Send a packet. Now there's a retransmittable packet on the wire, so the
7357 // path degrading detection should be set.
7358 connection_.SendStreamDataWithString(
7359 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7360 offset, NO_FIN);
7361 offset += data_size;
7362 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7363 // Check the deadline of the path degrading detection.
7364 QuicTime::Delta delay =
7365 QuicConnectionPeer::GetSentPacketManager(&connection_)
7366 ->GetPathDegradingDelay();
7367 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7368 clock_.ApproximateNow());
7369
7370 // Send a second packet. The path degrading detection's deadline should
7371 // remain the same.
7372 // Regression test for b/69979024.
7373 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7374 QuicTime prev_deadline =
7375 connection_.GetBlackholeDetectorAlarm()->deadline();
7376 connection_.SendStreamDataWithString(
7377 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7378 offset, NO_FIN);
7379 offset += data_size;
7380 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7381 EXPECT_EQ(prev_deadline,
7382 connection_.GetBlackholeDetectorAlarm()->deadline());
7383
7384 // Now receive an ACK of the first packet. This should advance the path
7385 // degrading detection's deadline since forward progress has been made.
7386 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7387 if (i == 0) {
7388 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7389 }
martindukeba002452023-03-21 08:10:46 -07007390 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007391 QuicAckFrame frame = InitAckFrame(
7392 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7393 ProcessAckPacket(&frame);
7394 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7395 // Check the deadline of the path degrading detection.
7396 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7397 ->GetPathDegradingDelay();
7398 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7399 clock_.ApproximateNow());
7400
7401 if (i == 0) {
7402 // Now receive an ACK of the second packet. Since there are no more
7403 // retransmittable packets on the wire, this should cancel the path
7404 // degrading detection.
7405 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007406 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007407 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7408 ProcessAckPacket(&frame);
7409 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7410 } else {
7411 // Advance time to the path degrading alarm's deadline and simulate
7412 // firing the alarm.
7413 clock_.AdvanceTime(delay);
7414 EXPECT_CALL(visitor_, OnPathDegrading());
7415 connection_.PathDegradingTimeout();
7416 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7417 }
7418 }
7419 EXPECT_TRUE(connection_.IsPathDegrading());
7420}
7421
7422TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7423 const QuicTime::Delta retransmittable_on_wire_timeout =
7424 QuicTime::Delta::FromMilliseconds(50);
7425 connection_.set_initial_retransmittable_on_wire_timeout(
7426 retransmittable_on_wire_timeout);
7427
7428 EXPECT_TRUE(connection_.connected());
7429 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7430 .WillRepeatedly(Return(true));
7431
7432 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7433 EXPECT_FALSE(connection_.IsPathDegrading());
7434 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
fayang59e518a2022-11-29 11:16:45 -08007435 EXPECT_CALL(visitor_, GetHandshakeState())
7436 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7437 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007438
7439 const char data[] = "data";
7440 size_t data_size = strlen(data);
7441 QuicStreamOffset offset = 0;
7442
7443 // Send a packet.
7444 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7445 offset += data_size;
7446 // Now there's a retransmittable packet on the wire, so the path degrading
7447 // alarm should be set.
7448 // The retransmittable-on-wire alarm should not be set.
7449 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7450 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7451 ->GetPathDegradingDelay();
7452 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7453 clock_.ApproximateNow());
7454 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7455 // The ping alarm is set for the ping timeout, not the shorter
7456 // retransmittable_on_wire_timeout.
7457 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7458 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7459 EXPECT_EQ(ping_delay,
7460 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7461
7462 // Now receive an ACK of the packet.
7463 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7464 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007465 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007466 QuicAckFrame frame =
7467 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7468 ProcessAckPacket(&frame);
7469 // No more retransmittable packets on the wire, so the path degrading alarm
7470 // should be cancelled, and the ping alarm should be set to the
7471 // retransmittable_on_wire_timeout.
7472 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7473 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7474 EXPECT_EQ(retransmittable_on_wire_timeout,
7475 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7476
7477 // Simulate firing the ping alarm and sending a PING.
7478 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7479 connection_.GetPingAlarm()->Fire();
7480
7481 // Now there's a retransmittable packet (PING) on the wire, so the path
7482 // degrading alarm should be set.
fayang59e518a2022-11-29 11:16:45 -08007483 ASSERT_TRUE(connection_.PathDegradingDetectionInProgress());
Bence Békybac04052022-04-07 15:44:29 -04007484 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7485 ->GetPathDegradingDelay();
7486 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7487 clock_.ApproximateNow());
7488}
7489
7490TEST_P(QuicConnectionTest, ServerRetransmittableOnWire) {
7491 set_perspective(Perspective::IS_SERVER);
7492 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7493 SetQuicReloadableFlag(quic_enable_server_on_wire_ping, true);
7494
7495 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08007496 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
7497 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04007498 QuicConfig config;
7499 QuicTagVector connection_options;
7500 connection_options.push_back(kSRWP);
7501 config.SetInitialReceivedConnectionOptions(connection_options);
7502 connection_.SetFromConfig(config);
7503
7504 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7505 .WillRepeatedly(Return(true));
7506
7507 ProcessPacket(1);
7508
7509 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7510 QuicTime::Delta ping_delay = QuicTime::Delta::FromMilliseconds(200);
7511 EXPECT_EQ(ping_delay,
7512 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7513
7514 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
7515 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
7516 // Verify PING alarm gets cancelled.
7517 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7518
7519 // Now receive an ACK of the packet.
7520 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
martindukeba002452023-03-21 08:10:46 -07007521 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007522 QuicAckFrame frame =
7523 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7524 ProcessAckPacket(2, &frame);
7525 // Verify PING alarm gets scheduled.
7526 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7527 EXPECT_EQ(ping_delay,
7528 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7529}
7530
fayangf6607db2022-04-21 18:10:41 -07007531TEST_P(QuicConnectionTest, RetransmittableOnWireSendFirstPacket) {
fayang9b455102022-11-29 18:19:20 -08007532 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007533 return;
7534 }
7535 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7536 .WillRepeatedly(Return(true));
7537 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7538
7539 const QuicTime::Delta kRetransmittableOnWireTimeout =
7540 QuicTime::Delta::FromMilliseconds(200);
7541 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7542
7543 connection_.set_initial_retransmittable_on_wire_timeout(
7544 kRetransmittableOnWireTimeout);
7545
7546 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08007547 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
7548 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
fayangf6607db2022-04-21 18:10:41 -07007549 QuicConfig config;
7550 QuicTagVector connection_options;
7551 connection_options.push_back(kROWF);
7552 config.SetClientConnectionOptions(connection_options);
7553 connection_.SetFromConfig(config);
7554
7555 // Send a request.
7556 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7557 // Receive an ACK after 1-RTT.
7558 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007559 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007560 QuicAckFrame frame =
7561 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7562 ProcessAckPacket(&frame);
7563 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7564 EXPECT_EQ(kRetransmittableOnWireTimeout,
7565 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7566 EXPECT_EQ(1u, writer_->packets_write_attempts());
7567
7568 // Fire retransmittable-on-wire alarm.
7569 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7570 connection_.GetPingAlarm()->Fire();
7571 EXPECT_EQ(2u, writer_->packets_write_attempts());
7572 // Verify alarm is set in keep-alive mode.
7573 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7574 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7575 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7576}
7577
7578TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytes) {
fayang9b455102022-11-29 18:19:20 -08007579 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007580 return;
7581 }
7582 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7583 .WillRepeatedly(Return(true));
7584 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7585
7586 const QuicTime::Delta kRetransmittableOnWireTimeout =
7587 QuicTime::Delta::FromMilliseconds(200);
7588 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7589
7590 connection_.set_initial_retransmittable_on_wire_timeout(
7591 kRetransmittableOnWireTimeout);
7592
7593 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08007594 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
7595 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
fayangf6607db2022-04-21 18:10:41 -07007596 QuicConfig config;
7597 QuicTagVector connection_options;
7598 connection_options.push_back(kROWR);
7599 config.SetClientConnectionOptions(connection_options);
7600 connection_.SetFromConfig(config);
7601
7602 // Send a request.
7603 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7604 // Receive an ACK after 1-RTT.
7605 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007606 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007607 QuicAckFrame frame =
7608 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7609 ProcessAckPacket(&frame);
7610 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7611 EXPECT_EQ(kRetransmittableOnWireTimeout,
7612 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7613 EXPECT_EQ(1u, writer_->packets_write_attempts());
7614
7615 // Fire retransmittable-on-wire alarm.
7616 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7617 // Next packet is not processable by the framer in the test writer.
7618 ExpectNextPacketUnprocessable();
7619 connection_.GetPingAlarm()->Fire();
7620 EXPECT_EQ(2u, writer_->packets_write_attempts());
7621 // Verify alarm is set in keep-alive mode.
7622 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7623 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7624 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7625}
7626
7627TEST_P(QuicConnectionTest,
7628 RetransmittableOnWireSendRandomBytesWithWriterBlocked) {
fayang9b455102022-11-29 18:19:20 -08007629 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007630 return;
7631 }
7632 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7633 .WillRepeatedly(Return(true));
7634 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7635 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7636
7637 const QuicTime::Delta kRetransmittableOnWireTimeout =
7638 QuicTime::Delta::FromMilliseconds(200);
7639 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7640
7641 connection_.set_initial_retransmittable_on_wire_timeout(
7642 kRetransmittableOnWireTimeout);
7643
7644 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08007645 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
7646 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
fayangf6607db2022-04-21 18:10:41 -07007647 QuicConfig config;
7648 QuicTagVector connection_options;
7649 connection_options.push_back(kROWR);
7650 config.SetClientConnectionOptions(connection_options);
7651 connection_.SetFromConfig(config);
7652
7653 // Send a request.
7654 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7655 // Receive an ACK after 1-RTT.
7656 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007657 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007658 QuicAckFrame frame =
7659 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7660 ProcessAckPacket(&frame);
7661 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7662 EXPECT_EQ(kRetransmittableOnWireTimeout,
7663 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7664 EXPECT_EQ(1u, writer_->packets_write_attempts());
7665 // Receive an out of order data packet and block the ACK packet.
7666 BlockOnNextWrite();
7667 ProcessDataPacket(3);
7668 EXPECT_EQ(2u, writer_->packets_write_attempts());
7669 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7670
7671 // Fire retransmittable-on-wire alarm.
7672 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7673 connection_.GetPingAlarm()->Fire();
7674 // Verify the random bytes packet gets queued.
7675 EXPECT_EQ(2u, connection_.NumQueuedPackets());
7676}
7677
Bence Békybac04052022-04-07 15:44:29 -04007678// This test verifies that the connection marks path as degrading and does not
7679// spin timer to detect path degrading when a new packet is sent on the
7680// degraded path.
7681TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
7682 EXPECT_TRUE(connection_.connected());
7683 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7684 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007685 EXPECT_CALL(visitor_, GetHandshakeState())
7686 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7687 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007688
7689 const char data[] = "data";
7690 size_t data_size = strlen(data);
7691 QuicStreamOffset offset = 0;
7692
7693 // Send the first packet. Now there's a retransmittable packet on the wire, so
7694 // the path degrading alarm should be set.
7695 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7696 offset += data_size;
7697 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7698 // Check the deadline of the path degrading detection.
7699 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7700 ->GetPathDegradingDelay();
7701 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7702 clock_.ApproximateNow());
7703
7704 // Send a second packet. The path degrading detection's deadline should remain
7705 // the same.
7706 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7707 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7708 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7709 offset += data_size;
7710 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7711 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7712
7713 // Now receive an ACK of the first packet. This should advance the path
7714 // degrading detection's deadline since forward progress has been made.
7715 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7716 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007717 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007718 QuicAckFrame frame =
7719 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7720 ProcessAckPacket(&frame);
7721 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7722 // Check the deadline of the path degrading alarm.
7723 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7724 ->GetPathDegradingDelay();
7725 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7726 clock_.ApproximateNow());
7727
7728 // Advance time to the path degrading detection's deadline and simulate
7729 // firing the path degrading detection. This path will be considered as
7730 // degrading.
7731 clock_.AdvanceTime(delay);
7732 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7733 connection_.PathDegradingTimeout();
7734 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7735 EXPECT_TRUE(connection_.IsPathDegrading());
7736
7737 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7738 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7739 // Send a third packet. The path degrading detection is no longer set but path
7740 // should still be marked as degrading.
7741 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7742 offset += data_size;
7743 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7744 EXPECT_TRUE(connection_.IsPathDegrading());
7745}
7746
fayang59e518a2022-11-29 11:16:45 -08007747TEST_P(QuicConnectionTest, NoPathDegradingDetectionBeforeHandshakeConfirmed) {
7748 EXPECT_TRUE(connection_.connected());
7749 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7750 EXPECT_FALSE(connection_.IsPathDegrading());
7751 EXPECT_CALL(visitor_, GetHandshakeState())
7752 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
7753
7754 connection_.SendStreamDataWithString(1, "data", 0, NO_FIN);
7755 if (GetQuicReloadableFlag(
7756 quic_no_path_degrading_before_handshake_confirmed) &&
7757 connection_.SupportsMultiplePacketNumberSpaces()) {
7758 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7759 } else {
7760 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7761 }
7762}
7763
Bence Békybac04052022-04-07 15:44:29 -04007764// This test verifies that the connection unmarks path as degrarding and spins
7765// the timer to detect future path degrading when forward progress is made
7766// after path has been marked degrading.
7767TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7768 EXPECT_TRUE(connection_.connected());
7769 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7770 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007771 EXPECT_CALL(visitor_, GetHandshakeState())
7772 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7773 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007774
7775 const char data[] = "data";
7776 size_t data_size = strlen(data);
7777 QuicStreamOffset offset = 0;
7778
7779 // Send the first packet. Now there's a retransmittable packet on the wire, so
7780 // the path degrading alarm should be set.
7781 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7782 offset += data_size;
7783 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7784 // Check the deadline of the path degrading alarm.
7785 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7786 ->GetPathDegradingDelay();
7787 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7788 clock_.ApproximateNow());
7789
7790 // Send a second packet. The path degrading alarm's deadline should remain
7791 // the same.
7792 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7793 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7794 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7795 offset += data_size;
7796 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7797 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7798
7799 // Now receive an ACK of the first packet. This should advance the path
7800 // degrading alarm's deadline since forward progress has been made.
7801 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7802 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007803 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007804 QuicAckFrame frame =
7805 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7806 ProcessAckPacket(&frame);
7807 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7808 // Check the deadline of the path degrading alarm.
7809 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7810 ->GetPathDegradingDelay();
7811 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7812 clock_.ApproximateNow());
7813
7814 // Advance time to the path degrading alarm's deadline and simulate
7815 // firing the alarm.
7816 clock_.AdvanceTime(delay);
7817 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7818 connection_.PathDegradingTimeout();
7819 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7820 EXPECT_TRUE(connection_.IsPathDegrading());
7821
7822 // Send a third packet. The path degrading alarm is no longer set but path
7823 // should still be marked as degrading.
7824 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7825 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7826 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7827 offset += data_size;
7828 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7829 EXPECT_TRUE(connection_.IsPathDegrading());
7830
7831 // Now receive an ACK of the second packet. This should unmark the path as
7832 // degrading. And will set a timer to detect new path degrading.
7833 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007834 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007835 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
7836 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7837 ProcessAckPacket(&frame);
renjietang201bfa52023-04-24 18:12:27 -07007838 EXPECT_EQ(1,
7839 connection_.GetStats().num_forward_progress_after_path_degrading);
Bence Békybac04052022-04-07 15:44:29 -04007840 EXPECT_FALSE(connection_.IsPathDegrading());
7841 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7842}
7843
7844TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
7845 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7846 return;
7847 }
7848 set_perspective(Perspective::IS_SERVER);
7849 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7850
7851 EXPECT_FALSE(connection_.IsPathDegrading());
7852 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7853
7854 // Send data.
7855 const char data[] = "data";
7856 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7857 EXPECT_FALSE(connection_.IsPathDegrading());
7858 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7859
7860 // Ack data.
7861 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007862 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007863 QuicAckFrame frame =
7864 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7865 ProcessAckPacket(&frame);
7866 EXPECT_FALSE(connection_.IsPathDegrading());
7867 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7868}
7869
7870TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
7871 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7872 return;
7873 }
7874 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7875 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7876 ProcessDataPacket(1);
7877 SendAckPacketToPeer();
7878 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7879 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7880 EXPECT_FALSE(connection_.IsPathDegrading());
7881 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7882}
7883
7884TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7885 // Verifies that multiple calls to CloseConnection do not
7886 // result in multiple attempts to close the connection - it will be marked as
7887 // disconnected after the first call.
7888 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
7889 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7890 ConnectionCloseBehavior::SILENT_CLOSE);
7891 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7892 ConnectionCloseBehavior::SILENT_CLOSE);
7893}
7894
7895TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7896 set_perspective(Perspective::IS_SERVER);
7897 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang161ce6e2022-07-01 18:02:11 -07007898 QuicConnectionPeer::SetAddressValidated(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04007899
7900 CryptoHandshakeMessage message;
7901 CryptoFramer framer;
7902 message.set_tag(kCHLO);
7903 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7904 frame1_.stream_id = 10;
7905 frame1_.data_buffer = data->data();
7906 frame1_.data_length = data->length();
7907
7908 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7909 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7910 }
7911 EXPECT_CALL(visitor_,
7912 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7913 ForceProcessFramePacket(QuicFrame(frame1_));
7914 if (VersionHasIetfQuicFrames(version().transport_version)) {
7915 // INITIAL packet should not contain STREAM frame.
7916 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7917 } else {
7918 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7919 }
7920}
7921
7922TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7923 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7924
7925 CryptoHandshakeMessage message;
7926 CryptoFramer framer;
7927 message.set_tag(kREJ);
7928 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7929 frame1_.stream_id = 10;
7930 frame1_.data_buffer = data->data();
7931 frame1_.data_length = data->length();
7932
7933 EXPECT_CALL(visitor_,
7934 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7935 ForceProcessFramePacket(QuicFrame(frame1_));
7936 if (VersionHasIetfQuicFrames(version().transport_version)) {
7937 // INITIAL packet should not contain STREAM frame.
7938 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7939 } else {
7940 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7941 }
7942}
7943
7944TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7945 SimulateNextPacketTooLarge();
7946 // A connection close packet is sent
7947 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7948 .Times(1);
7949 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7950 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7951}
7952
7953TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7954 // Test even we always get packet too large, we do not infinitely try to send
7955 // close packet.
7956 AlwaysGetPacketTooLarge();
7957 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7958 .Times(1);
7959 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7960 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7961}
7962
7963TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
7964 // Regression test for crbug.com/979507.
7965 //
7966 // If we get a write error when writing queued packets, we should attempt to
7967 // send a connection close packet, but if sending that fails, it shouldn't get
7968 // queued.
7969
7970 // Queue a packet to write.
7971 BlockOnNextWrite();
7972 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7973 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7974
7975 // Configure writer to always fail.
7976 AlwaysGetPacketTooLarge();
7977
7978 // Expect that we attempt to close the connection exactly once.
7979 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7980 .Times(1);
7981
7982 // Unblock the writes and actually send.
7983 writer_->SetWritable();
7984 connection_.OnCanWrite();
7985 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7986
7987 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7988}
7989
7990// Verify that if connection has no outstanding data, it notifies the send
7991// algorithm after the write.
7992TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7993 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7994 {
7995 InSequence seq;
7996 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7997 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7998 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7999 .WillRepeatedly(Return(false));
8000 }
8001
8002 connection_.SendStreamData3();
8003}
8004
8005// Verify that the connection does not become app-limited if there is
8006// outstanding data to send after the write.
8007TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
8008 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8009 {
8010 InSequence seq;
8011 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
8012 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8013 }
8014
8015 connection_.SendStreamData3();
8016}
8017
8018// Verify that the connection does not become app-limited after blocked write
8019// even if there is outstanding data to send after the write.
8020TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
8021 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
8022 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
8023 BlockOnNextWrite();
8024
8025 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8026 connection_.SendStreamData3();
8027
8028 // Now unblock the writer, become congestion control blocked,
8029 // and ensure we become app-limited after writing.
8030 writer_->SetWritable();
8031 CongestionBlockWrites();
8032 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
8033 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8034 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8035 connection_.OnCanWrite();
8036}
8037
Bence Békybac04052022-04-07 15:44:29 -04008038TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
8039 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8040 // Send an ack by simulating delayed ack alarm firing.
8041 ProcessPacket(1);
8042 EXPECT_TRUE(connection_.HasPendingAcks());
8043 connection_.GetAckAlarm()->Fire();
8044 // Simulate data packet causes write error.
8045 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8046 SimulateNextPacketTooLarge();
8047 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8048 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8049 // Ack frame is not bundled in connection close packet.
8050 EXPECT_TRUE(writer_->ack_frames().empty());
8051 if (writer_->padding_frames().empty()) {
8052 EXPECT_EQ(1u, writer_->frame_count());
8053 } else {
8054 EXPECT_EQ(2u, writer_->frame_count());
8055 }
8056
8057 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8058}
8059
8060TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
8061 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8062 return;
8063 }
8064
8065 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8066 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8067 connection_.CloseConnection(
8068 kQuicErrorCode, "Some random error message",
8069 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8070
8071 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8072
8073 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8074 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8075
8076 if (!connection_.version().CanSendCoalescedPackets()) {
8077 // Each connection close packet should be sent in distinct UDP packets.
8078 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8079 writer_->connection_close_packets());
8080 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8081 writer_->packets_write_attempts());
8082 return;
8083 }
8084
8085 // A single UDP packet should be sent with multiple connection close packets
8086 // coalesced together.
8087 EXPECT_EQ(1u, writer_->packets_write_attempts());
8088
8089 // Only the first packet has been processed yet.
8090 EXPECT_EQ(1u, writer_->connection_close_packets());
8091
8092 // ProcessPacket resets the visitor and frees the coalesced packet.
8093 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
8094 auto packet = writer_->coalesced_packet()->Clone();
8095 writer_->framer()->ProcessPacket(*packet);
8096 EXPECT_EQ(1u, writer_->connection_close_packets());
8097 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8098}
8099
8100TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
8101 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8102 return;
8103 }
8104
8105 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8106 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8107 connection_.CloseConnection(
8108 kQuicErrorCode, "Some random error message",
8109 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8110
8111 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8112
8113 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8114 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8115 EXPECT_EQ(1u, writer_->connection_close_packets());
8116 EXPECT_EQ(1u, writer_->packets_write_attempts());
8117 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8118}
8119
8120TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8121 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8122 return;
8123 }
8124 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07008125 // Receives packet 1000 in initial data.
8126 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8127 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -04008128
8129 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
8130 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
8131 }
8132 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8133 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8134 connection_.CloseConnection(
8135 kQuicErrorCode, "Some random error message",
8136 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8137
8138 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8139
8140 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8141 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8142 EXPECT_TRUE(writer_->padding_frames().empty());
8143 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8144}
8145
8146// Regression test for b/63620844.
8147TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8148 SimulateNextPacketTooLarge();
8149 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8150 .Times(1);
8151
8152 connection_.SendCryptoStreamData();
8153 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8154}
8155
8156TEST_P(QuicConnectionTest, MaxPacingRate) {
8157 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8158 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8159 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8160}
8161
8162TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8163 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8164 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8165 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8166 EXPECT_EQ(CONNECTION_ID_PRESENT,
8167 writer_->last_packet_header().destination_connection_id_included);
8168
8169 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08008170 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
8171 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04008172 QuicConfig config;
8173 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8174 connection_.SetFromConfig(config);
8175
8176 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8177 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8178 // Verify connection id is still sent in the packet.
8179 EXPECT_EQ(CONNECTION_ID_PRESENT,
8180 writer_->last_packet_header().destination_connection_id_included);
8181}
8182
Bence Békybac04052022-04-07 15:44:29 -04008183TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8184 const QuicTime::Delta retransmittable_on_wire_timeout =
8185 QuicTime::Delta::FromMilliseconds(50);
8186 connection_.set_initial_retransmittable_on_wire_timeout(
8187 retransmittable_on_wire_timeout);
8188
8189 EXPECT_TRUE(connection_.connected());
8190 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8191 .WillRepeatedly(Return(true));
8192
8193 const char data[] = "data";
8194 size_t data_size = strlen(data);
8195 QuicStreamOffset offset = 0;
8196
8197 // Advance 5ms, send a retransmittable packet to the peer.
8198 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8199 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8200 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8201 offset += data_size;
8202 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8203 // The ping alarm is set for the ping timeout, not the shorter
8204 // retransmittable_on_wire_timeout.
8205 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8206 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8207 EXPECT_EQ(ping_delay,
8208 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8209
8210 // Advance 5ms, send a second retransmittable packet to the peer.
8211 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8212 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8213 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8214 offset += data_size;
8215 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8216
8217 // Now receive an ACK of the first packet. This should not set the
8218 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8219 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8220 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07008221 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008222 QuicAckFrame frame =
8223 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8224 ProcessAckPacket(&frame);
8225 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8226 // The ping alarm is set for the ping timeout, not the shorter
8227 // retransmittable_on_wire_timeout.
8228 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8229 // The ping alarm has a 1 second granularity, and the clock has been advanced
8230 // 10ms since it was originally set.
8231 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8232 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8233
8234 // Now receive an ACK of the second packet. This should set the
8235 // retransmittable-on-wire alarm now that no retransmittable packets are on
8236 // the wire.
8237 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07008238 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008239 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8240 ProcessAckPacket(&frame);
8241 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8242 EXPECT_EQ(retransmittable_on_wire_timeout,
8243 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8244
8245 // Now receive a duplicate ACK of the second packet. This should not update
8246 // the ping alarm.
8247 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8248 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8249 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8250 ProcessAckPacket(&frame);
8251 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8252 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8253
8254 // Now receive a non-ACK packet. This should not update the ping alarm.
8255 prev_deadline = connection_.GetPingAlarm()->deadline();
8256 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8257 ProcessPacket(4);
8258 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8259 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8260
8261 // Simulate the alarm firing and check that a PING is sent.
8262 connection_.GetPingAlarm()->Fire();
8263 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07008264 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04008265 ASSERT_EQ(1u, writer_->ping_frames().size());
8266}
8267
8268TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8269 const QuicTime::Delta retransmittable_on_wire_timeout =
8270 QuicTime::Delta::FromMilliseconds(50);
8271 connection_.set_initial_retransmittable_on_wire_timeout(
8272 retransmittable_on_wire_timeout);
8273
8274 EXPECT_TRUE(connection_.connected());
8275 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8276 .WillRepeatedly(Return(true));
8277
8278 const char data[] = "data";
8279 size_t data_size = strlen(data);
8280 QuicStreamOffset offset = 0;
8281
8282 // Advance 5ms, send a retransmittable packet to the peer.
8283 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8284 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8285 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8286 offset += data_size;
8287 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8288 // The ping alarm is set for the ping timeout, not the shorter
8289 // retransmittable_on_wire_timeout.
8290 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8291 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8292 EXPECT_EQ(ping_delay,
8293 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8294
8295 // Now receive an ACK of the first packet. This should set the
8296 // retransmittable-on-wire alarm now that no retransmittable packets are on
8297 // the wire.
8298 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8299 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07008300 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008301 QuicAckFrame frame =
8302 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8303 ProcessAckPacket(&frame);
8304 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8305 EXPECT_EQ(retransmittable_on_wire_timeout,
8306 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8307
8308 // Before the alarm fires, send another retransmittable packet. This should
8309 // cancel the retransmittable-on-wire alarm since now there's a
8310 // retransmittable packet on the wire.
8311 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8312 offset += data_size;
8313 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8314
8315 // Now receive an ACK of the second packet. This should set the
8316 // retransmittable-on-wire alarm now that no retransmittable packets are on
8317 // the wire.
8318 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07008319 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008320 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8321 ProcessAckPacket(&frame);
8322 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8323 EXPECT_EQ(retransmittable_on_wire_timeout,
8324 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8325
8326 // Simulate the alarm firing and check that a PING is sent.
8327 writer_->Reset();
8328 connection_.GetPingAlarm()->Fire();
8329 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07008330 // Do not ACK acks.
8331 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04008332 ASSERT_EQ(1u, writer_->ping_frames().size());
8333}
8334
8335// When there is no stream data received but are open streams, send the
8336// first few consecutive pings with aggressive retransmittable-on-wire
8337// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8338// afterwards until it exceeds the default ping timeout.
8339TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8340 int max_aggressive_retransmittable_on_wire_ping_count = 5;
birenroyef686222022-09-12 11:34:34 -07008341 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008342 max_aggressive_retransmittable_on_wire_ping_count);
8343 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8344 QuicTime::Delta::FromMilliseconds(200);
8345 connection_.set_initial_retransmittable_on_wire_timeout(
8346 initial_retransmittable_on_wire_timeout);
8347
8348 EXPECT_TRUE(connection_.connected());
8349 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8350 .WillRepeatedly(Return(true));
8351
8352 const char data[] = "data";
8353 // Advance 5ms, send a retransmittable data packet to the peer.
8354 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8355 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8356 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8357 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8358 // The ping alarm is set for the ping timeout, not the shorter
8359 // retransmittable_on_wire_timeout.
8360 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008361 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008362 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8363
8364 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008365 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008366 .Times(AnyNumber());
8367
8368 // Verify that the first few consecutive retransmittable on wire pings are
8369 // sent with aggressive timeout.
8370 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8371 // Receive an ACK of the previous packet. This should set the ping alarm
8372 // with the initial retransmittable-on-wire timeout.
8373 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8374 QuicPacketNumber ack_num = creator_->packet_number();
8375 QuicAckFrame frame = InitAckFrame(
8376 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8377 ProcessAckPacket(&frame);
8378 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8379 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8380 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8381 // Simulate the alarm firing and check that a PING is sent.
8382 writer_->Reset();
8383 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8384 connection_.GetPingAlarm()->Fire();
8385 }
8386
8387 QuicTime::Delta retransmittable_on_wire_timeout =
8388 initial_retransmittable_on_wire_timeout;
8389
8390 // Verify subsequent pings are sent with timeout that is exponentially backed
8391 // off.
fayang5d393332022-04-18 13:34:54 -07008392 while (retransmittable_on_wire_timeout * 2 <
8393 QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) {
Bence Békybac04052022-04-07 15:44:29 -04008394 // Receive an ACK for the previous PING. This should set the
8395 // ping alarm with backed off retransmittable-on-wire timeout.
8396 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8397 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8398 QuicPacketNumber ack_num = creator_->packet_number();
8399 QuicAckFrame frame = InitAckFrame(
8400 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8401 ProcessAckPacket(&frame);
8402 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8403 EXPECT_EQ(retransmittable_on_wire_timeout,
8404 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8405
8406 // Simulate the alarm firing and check that a PING is sent.
8407 writer_->Reset();
8408 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8409 connection_.GetPingAlarm()->Fire();
8410 }
8411
8412 // The ping alarm is set with default ping timeout.
8413 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008414 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008415 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8416
8417 // Receive an ACK for the previous PING. The ping alarm is set with an
8418 // earlier deadline.
8419 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8420 QuicPacketNumber ack_num = creator_->packet_number();
8421 QuicAckFrame frame = InitAckFrame(
8422 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8423 ProcessAckPacket(&frame);
8424 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008425 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) -
8426 QuicTime::Delta::FromMilliseconds(5),
Bence Békybac04052022-04-07 15:44:29 -04008427 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8428}
8429
8430// This test verify that the count of consecutive aggressive pings is reset
8431// when new data is received. And it also verifies the connection resets
8432// the exponential back-off of the retransmittable-on-wire ping timeout
8433// after receiving new stream data.
8434TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8435 int max_aggressive_retransmittable_on_wire_ping_count = 3;
birenroyef686222022-09-12 11:34:34 -07008436 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
Bence Békybac04052022-04-07 15:44:29 -04008437 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8438 QuicTime::Delta::FromMilliseconds(200);
8439 connection_.set_initial_retransmittable_on_wire_timeout(
8440 initial_retransmittable_on_wire_timeout);
8441
8442 EXPECT_TRUE(connection_.connected());
8443 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8444 .WillRepeatedly(Return(true));
8445 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008446 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008447 .Times(AnyNumber());
8448
8449 const char data[] = "data";
8450 // Advance 5ms, send a retransmittable data packet to the peer.
8451 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8452 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8453 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8454 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8455 // The ping alarm is set for the ping timeout, not the shorter
8456 // retransmittable_on_wire_timeout.
8457 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008458 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008459 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8460
8461 // Receive an ACK of the first packet. This should set the ping alarm with
8462 // initial retransmittable-on-wire timeout since there is no retransmittable
8463 // packet on the wire.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008464 {
8465 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8466 QuicAckFrame frame =
8467 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8468 ProcessAckPacket(&frame);
8469 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8470 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8471 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8472 }
Bence Békybac04052022-04-07 15:44:29 -04008473
8474 // Simulate the alarm firing and check that a PING is sent.
8475 writer_->Reset();
8476 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8477 connection_.GetPingAlarm()->Fire();
8478
8479 // Receive an ACK for the previous PING. Ping alarm will be set with
8480 // aggressive timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008481 {
8482 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8483 QuicPacketNumber ack_num = creator_->packet_number();
8484 QuicAckFrame frame = InitAckFrame(
8485 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8486 ProcessAckPacket(&frame);
8487 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8488 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8489 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8490 }
Bence Békybac04052022-04-07 15:44:29 -04008491
8492 // Process a data packet.
8493 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8494 ProcessDataPacket(peer_creator_.packet_number() + 1);
8495 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8496 peer_creator_.packet_number() + 1);
8497 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8498 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
fayang327663d2022-05-10 18:25:36 -07008499 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8500 connection_.GetPingAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -04008501
8502 // Verify the count of consecutive aggressive pings is reset.
8503 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8504 // Receive an ACK of the previous packet. This should set the ping alarm
8505 // with the initial retransmittable-on-wire timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008506 const QuicPacketNumber ack_num = creator_->packet_number();
Bence Békybac04052022-04-07 15:44:29 -04008507 QuicAckFrame frame = InitAckFrame(
8508 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8509 ProcessAckPacket(&frame);
8510 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8511 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8512 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8513 // Simulate the alarm firing and check that a PING is sent.
8514 writer_->Reset();
8515 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8516 connection_.GetPingAlarm()->Fire();
8517 // Advance 5ms to receive next packet.
8518 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8519 }
8520
8521 // Receive another ACK for the previous PING. This should set the
8522 // ping alarm with backed off retransmittable-on-wire timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008523 {
8524 const QuicPacketNumber ack_num = creator_->packet_number();
8525 QuicAckFrame frame = InitAckFrame(
8526 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8527 ProcessAckPacket(&frame);
8528 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8529 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8530 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8531 }
Bence Békybac04052022-04-07 15:44:29 -04008532
8533 writer_->Reset();
8534 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8535 connection_.GetPingAlarm()->Fire();
8536
8537 // Process another data packet and a new ACK packet. The ping alarm is set
8538 // with aggressive ping timeout again.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008539 {
8540 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8541 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8542 ProcessDataPacket(peer_creator_.packet_number() + 1);
8543 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8544 peer_creator_.packet_number() + 1);
8545 const QuicPacketNumber ack_num = creator_->packet_number();
8546 QuicAckFrame frame = InitAckFrame(
8547 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8548 ProcessAckPacket(&frame);
8549 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8550 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8551 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8552 }
Bence Békybac04052022-04-07 15:44:29 -04008553}
8554
8555// Make sure that we never send more retransmissible on the wire pings than
8556// the limit in FLAGS_quic_max_retransmittable_on_wire_ping_count.
8557TEST_P(QuicConnectionTest, RetransmittableOnWirePingLimit) {
8558 static constexpr int kMaxRetransmittableOnWirePingCount = 3;
birenroyef686222022-09-12 11:34:34 -07008559 SetQuicFlag(quic_max_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008560 kMaxRetransmittableOnWirePingCount);
8561 static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout =
8562 QuicTime::Delta::FromMilliseconds(200);
8563 static constexpr QuicTime::Delta short_delay =
8564 QuicTime::Delta::FromMilliseconds(5);
8565 ASSERT_LT(short_delay * 10, initial_retransmittable_on_wire_timeout);
8566 connection_.set_initial_retransmittable_on_wire_timeout(
8567 initial_retransmittable_on_wire_timeout);
8568
8569 EXPECT_TRUE(connection_.connected());
8570 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8571 .WillRepeatedly(Return(true));
8572
8573 const char data[] = "data";
8574 // Advance 5ms, send a retransmittable data packet to the peer.
8575 clock_.AdvanceTime(short_delay);
8576 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8577 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8578 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8579 // The ping alarm is set for the ping timeout, not the shorter
8580 // retransmittable_on_wire_timeout.
8581 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008582 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008583 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8584
8585 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008586 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008587 .Times(AnyNumber());
8588
8589 // Verify that the first few consecutive retransmittable on wire pings are
8590 // sent with aggressive timeout.
8591 for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) {
8592 // Receive an ACK of the previous packet. This should set the ping alarm
8593 // with the initial retransmittable-on-wire timeout.
8594 clock_.AdvanceTime(short_delay);
8595 QuicPacketNumber ack_num = creator_->packet_number();
8596 QuicAckFrame frame = InitAckFrame(
8597 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8598 ProcessAckPacket(&frame);
8599 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8600 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8601 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8602 // Simulate the alarm firing and check that a PING is sent.
8603 writer_->Reset();
8604 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8605 connection_.GetPingAlarm()->Fire();
8606 }
8607
8608 // Receive an ACK of the previous packet. This should set the ping alarm
8609 // but this time with the default ping timeout.
8610 QuicPacketNumber ack_num = creator_->packet_number();
8611 QuicAckFrame frame = InitAckFrame(
8612 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8613 ProcessAckPacket(&frame);
8614 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008615 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008616 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8617}
8618
8619TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8620 const StatelessResetToken kTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8621 0, 1, 0, 1, 0, 1, 0, 1};
8622 const StatelessResetToken kWrongTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8623 0, 1, 0, 1, 0, 1, 0, 2};
8624 QuicConfig config;
8625 // No token has been received.
8626 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8627
8628 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
martindukeeaf27602024-11-12 14:34:40 -08008629 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillRepeatedly(Return(false));
8630 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillRepeatedly(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04008631 // Token is different from received token.
8632 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8633 connection_.SetFromConfig(config);
8634 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8635
8636 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8637 connection_.SetFromConfig(config);
8638 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8639}
8640
8641TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8642 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8643 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8644 BlockOnNextWrite();
8645 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8646 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8647 // This causes connection to be closed because packet 1 has not been sent yet.
8648 QuicAckFrame frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07008649 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008650 ProcessAckPacket(1, &frame);
8651 EXPECT_EQ(0, connection_close_frame_count_);
8652}
8653
8654TEST_P(QuicConnectionTest, SendMessage) {
Bence Békybac04052022-04-07 15:44:29 -04008655 if (connection_.version().UsesTls()) {
8656 QuicConfig config;
8657 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8658 &config, kMaxAcceptedDatagramFrameSize);
8659 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08008660 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
8661 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04008662 connection_.SetFromConfig(config);
8663 }
8664 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
8665 quiche::QuicheMemSlice slice;
8666 {
8667 QuicConnection::ScopedPacketFlusher flusher(&connection_);
8668 connection_.SendStreamData3();
8669 // Send a message which cannot fit into current open packet, and 2 packets
8670 // get sent, one contains stream frame, and the other only contains the
8671 // message frame.
8672 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8673 slice = MemSliceFromString(absl::string_view(
8674 message.data(), connection_.GetCurrentLargestMessagePayload()));
8675 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8676 connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false));
8677 }
8678 // Fail to send a message if connection is congestion control blocked.
8679 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8680 slice = MemSliceFromString("message");
8681 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8682 connection_.SendMessage(2, absl::MakeSpan(&slice, 1), false));
8683
8684 // Always fail to send a message which cannot fit into one packet.
8685 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8686 slice = MemSliceFromString(absl::string_view(
8687 message.data(), connection_.GetCurrentLargestMessagePayload() + 1));
8688 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8689 connection_.SendMessage(3, absl::MakeSpan(&slice, 1), false));
8690}
8691
8692TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
martinduke225e91a2022-11-28 17:18:13 -08008693 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008694 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
8695 expected_largest_payload += 3;
8696 }
8697 if (connection_.version().HasLongHeaderLengths()) {
8698 expected_largest_payload -= 2;
8699 }
8700 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8701 expected_largest_payload -= 1;
8702 }
8703 if (connection_.version().UsesTls()) {
8704 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8705 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8706 QuicConfig config;
8707 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8708 &config, kMaxAcceptedDatagramFrameSize);
8709 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08008710 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
8711 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04008712 connection_.SetFromConfig(config);
8713 // Verify the value post-handshake.
8714 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8715 expected_largest_payload);
8716 } else {
8717 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8718 expected_largest_payload);
8719 }
8720}
8721
8722TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
martinduke225e91a2022-11-28 17:18:13 -08008723 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008724 if (connection_.version().HasLongHeaderLengths()) {
8725 expected_largest_payload -= 2;
8726 }
8727 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8728 expected_largest_payload -= 1;
8729 }
8730 if (connection_.version().UsesTls()) {
8731 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8732 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8733 QuicConfig config;
8734 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8735 &config, kMaxAcceptedDatagramFrameSize);
8736 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08008737 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
8738 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04008739 connection_.SetFromConfig(config);
8740 // Verify the value post-handshake.
8741 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8742 expected_largest_payload);
8743 } else {
8744 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8745 expected_largest_payload);
8746 }
8747}
8748
8749TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
fayangfc04b8a2023-05-18 09:26:25 -07008750 if (!connection_.version().UsesTls()) {
Bence Békybac04052022-04-07 15:44:29 -04008751 return;
8752 }
8753 constexpr QuicPacketLength kFrameSizeLimit = 1000;
8754 constexpr QuicPacketLength kPayloadSizeLimit =
8755 kFrameSizeLimit - kQuicFrameTypeSize;
8756 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8757 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8758 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8759 QuicConfig config;
8760 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
8761 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08008762 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
8763 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04008764 connection_.SetFromConfig(config);
8765 // Verify the value post-handshake.
8766 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
8767 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8768 kPayloadSizeLimit);
8769}
8770
8771// Test to check that the path challenge/path response logic works
8772// correctly. This test is only for version-99
8773TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) {
8774 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8775 return;
8776 }
8777 PathProbeTestInit(Perspective::IS_SERVER);
8778 QuicConnectionPeer::SetAddressValidated(&connection_);
8779 // First check if the server can send probing packet.
8780 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8781
8782 // Create and send the probe request (PATH_CHALLENGE frame).
8783 // SendConnectivityProbingPacket ends up calling
8784 // TestPacketWriter::WritePacket() which in turns receives and parses the
8785 // packet by calling framer_.ProcessPacket() -- which in turn calls
8786 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8787 // the packet in writer_->path_challenge_frames()
8788 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8789 connection_.SendConnectivityProbingPacket(writer_.get(),
8790 connection_.peer_address());
8791 // Save the random contents of the challenge for later comparison to the
8792 // response.
8793 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8794 QuicPathFrameBuffer challenge_data =
8795 writer_->path_challenge_frames().front().data_buffer;
8796
8797 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8798 // called and it will perform actions to ensure that the rest of the protocol
8799 // is performed.
8800 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8801 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8802 writer_->path_challenge_frames().front()));
8803 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8804 creator_->FlushCurrentPacket();
8805
8806 // The final check is to ensure that the random data in the response matches
8807 // the random data from the challenge.
8808 EXPECT_EQ(1u, writer_->path_response_frames().size());
8809 EXPECT_EQ(0, memcmp(&challenge_data,
8810 &(writer_->path_response_frames().front().data_buffer),
8811 sizeof(challenge_data)));
8812}
8813
8814TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnDefaulSocket) {
8815 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8816 return;
8817 }
8818 PathProbeTestInit(Perspective::IS_CLIENT);
8819 // First check if the client can send probing packet.
8820 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8821
8822 // Create and send the probe request (PATH_CHALLENGE frame).
8823 // SendConnectivityProbingPacket ends up calling
8824 // TestPacketWriter::WritePacket() which in turns receives and parses the
8825 // packet by calling framer_.ProcessPacket() -- which in turn calls
8826 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8827 // the packet in writer_->path_challenge_frames()
8828 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8829 connection_.SendConnectivityProbingPacket(writer_.get(),
8830 connection_.peer_address());
8831 // Save the random contents of the challenge for later validation against the
8832 // response.
8833 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8834 QuicPathFrameBuffer challenge_data =
8835 writer_->path_challenge_frames().front().data_buffer;
8836
8837 // Normally, QuicConnection::OnPathChallengeFrame would be
8838 // called and it will perform actions to ensure that the rest of the protocol
8839 // is performed.
8840 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8841 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8842 writer_->path_challenge_frames().front()));
8843 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8844 creator_->FlushCurrentPacket();
8845
8846 // The final check is to ensure that the random data in the response matches
8847 // the random data from the challenge.
8848 EXPECT_EQ(1u, writer_->path_response_frames().size());
8849 EXPECT_EQ(0, memcmp(&challenge_data,
8850 &(writer_->path_response_frames().front().data_buffer),
8851 sizeof(challenge_data)));
8852}
8853
8854TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnAlternativeSocket) {
danzh87605712022-04-11 14:36:39 -07008855 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -04008856 return;
8857 }
8858 PathProbeTestInit(Perspective::IS_CLIENT);
8859 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8860
8861 QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8862 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8863 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8864 .Times(AtLeast(1u))
8865 .WillOnce(Invoke([&]() {
8866 EXPECT_EQ(1u, new_writer.packets_write_attempts());
8867 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
8868 EXPECT_EQ(1u, new_writer.padding_frames().size());
8869 EXPECT_EQ(kNewSelfAddress.host(),
8870 new_writer.last_write_source_address());
8871 }));
8872 bool success = false;
8873 connection_.ValidatePath(
8874 std::make_unique<TestQuicPathValidationContext>(
8875 kNewSelfAddress, connection_.peer_address(), &new_writer),
8876 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -08008877 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
8878 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -04008879
8880 // Receiving a PATH_CHALLENGE on the alternative path. Response to this
8881 // PATH_CHALLENGE should be sent via the alternative writer.
8882 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8883 .Times(AtLeast(1u))
8884 .WillOnce(Invoke([&]() {
8885 EXPECT_EQ(2u, new_writer.packets_write_attempts());
8886 EXPECT_EQ(1u, new_writer.path_response_frames().size());
8887 EXPECT_EQ(1u, new_writer.padding_frames().size());
8888 EXPECT_EQ(kNewSelfAddress.host(),
8889 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -07008890 }))
8891 .WillRepeatedly(DoDefault());
8892 ;
Bence Békybac04052022-04-07 15:44:29 -04008893 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8894 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8895 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8896 probing_packet->encrypted_length),
8897 clock_.Now()));
8898 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8899
8900 QuicSocketAddress kNewerSelfAddress(QuicIpAddress::Loopback6(),
8901 /*port=*/34567);
8902 // Receiving a PATH_CHALLENGE on an unknown socket should be ignored.
8903 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
8904 ProcessReceivedPacket(kNewerSelfAddress, kPeerAddress, *received);
8905}
8906
8907TEST_P(QuicConnectionTest,
8908 RestartPathDegradingDetectionAfterMigrationWithProbe) {
danzh65153092023-06-16 10:59:32 -07008909 if (!version().HasIetfQuicFrames() &&
8910 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
8911 return;
8912 }
Bence Békybac04052022-04-07 15:44:29 -04008913 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8914 PathProbeTestInit(Perspective::IS_CLIENT);
8915
8916 // Send data and verify the path degrading detection is set.
8917 const char data[] = "data";
8918 size_t data_size = strlen(data);
8919 QuicStreamOffset offset = 0;
8920 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8921 offset += data_size;
8922
8923 // Verify the path degrading detection is in progress.
8924 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8925 EXPECT_FALSE(connection_.IsPathDegrading());
8926 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
8927
8928 // Simulate the firing of path degrading.
8929 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
8930 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
8931 connection_.PathDegradingTimeout();
8932 EXPECT_TRUE(connection_.IsPathDegrading());
8933 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8934
8935 if (!GetParam().version.HasIetfQuicFrames()) {
8936 // Simulate path degrading handling by sending a probe on an alternet path.
8937 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8938 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
8939 connection_.SendConnectivityProbingPacket(&probing_writer,
8940 connection_.peer_address());
8941 // Verify that path degrading detection is not reset.
8942 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8943
8944 // Simulate successful path degrading handling by receiving probe response.
8945 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
8946
8947 EXPECT_CALL(visitor_,
8948 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
8949 .Times(1);
8950 const QuicSocketAddress kNewSelfAddress =
8951 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8952
8953 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8954 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8955 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8956 probing_packet->encrypted_length),
8957 clock_.Now()));
8958 uint64_t num_probing_received =
8959 connection_.GetStats().num_connectivity_probing_received;
8960 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8961
danzh65153092023-06-16 10:59:32 -07008962 EXPECT_EQ(num_probing_received +
8963 (GetQuicReloadableFlag(quic_ignore_gquic_probing) ? 0u : 1u),
Bence Békybac04052022-04-07 15:44:29 -04008964 connection_.GetStats().num_connectivity_probing_received);
8965 EXPECT_EQ(kPeerAddress, connection_.peer_address());
8966 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8967 EXPECT_TRUE(connection_.IsPathDegrading());
8968 }
8969
8970 // Verify new path degrading detection is activated.
8971 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
8972 connection_.OnSuccessfulMigration(/*is_port_change*/ true);
8973 EXPECT_FALSE(connection_.IsPathDegrading());
8974 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8975}
8976
8977TEST_P(QuicConnectionTest, ClientsResetCwndAfterConnectionMigration) {
8978 if (!GetParam().version.HasIetfQuicFrames()) {
8979 return;
8980 }
8981 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8982 PathProbeTestInit(Perspective::IS_CLIENT);
8983 EXPECT_EQ(kSelfAddress, connection_.self_address());
8984
8985 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
8986 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
8987 rtt_stats->set_initial_rtt(default_init_rtt * 2);
8988 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
8989
fayang339f0c82022-04-30 14:20:02 -07008990 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
8991 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008992 const SendAlgorithmInterface* send_algorithm = manager_->GetSendAlgorithm();
8993
8994 // Migrate to a new address with different IP.
8995 const QuicSocketAddress kNewSelfAddress =
8996 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
8997 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8998 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
8999 &new_writer, false);
9000 EXPECT_EQ(default_init_rtt, manager_->GetRttStats()->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07009001 EXPECT_EQ(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04009002 EXPECT_NE(send_algorithm, manager_->GetSendAlgorithm());
9003}
9004
9005// Regression test for b/110259444
9006TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
9007 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9008 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9009 writer_->SetWriteBlocked();
9010
9011 ProcessPacket(1);
9012 // Verify ack alarm is set.
9013 EXPECT_TRUE(connection_.HasPendingAcks());
9014 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
9015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9016 connection_.GetAckAlarm()->Fire();
9017
9018 writer_->SetWritable();
9019 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9020 ProcessPacket(2);
9021 // Verify ack alarm is not set.
9022 EXPECT_FALSE(connection_.HasPendingAcks());
9023}
9024
9025TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
9026 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9027 writer_->set_supports_release_time(true);
9028 QuicConfig config;
9029 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08009030 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
9031 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04009032 connection_.SetFromConfig(config);
9033 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9034
9035 QuicTagVector connection_options;
9036 connection_options.push_back(kNPCO);
9037 config.SetConnectionOptionsToSend(connection_options);
9038 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08009039 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
9040 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04009041 connection_.SetFromConfig(config);
9042 // Verify pacing offload is disabled.
9043 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
9044}
9045
9046// Regression test for b/110259444
9047// Get a path response without having issued a path challenge...
9048TEST_P(QuicConnectionTest, OrphanPathResponse) {
9049 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
9050
9051 QuicPathResponseFrame frame(99, data);
9052 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
9053 // If PATH_RESPONSE was accepted (payload matches the payload saved
9054 // in QuicConnection::transmitted_connectivity_probe_payload_) then
9055 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
9056 // Since this PATH_RESPONSE does not match, current_packet_content_
9057 // must not be FIRST_FRAME_IS_PING.
9058 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
9059 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
9060}
9061
Bence Békybac04052022-04-07 15:44:29 -04009062TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
9063 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9064 return;
9065 }
9066 // Set first_sending_packet_number to be 0 to allow successfully processing
9067 // acks which ack packet number 0.
9068 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
9069 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9070
9071 ProcessPacket(0);
9072 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
9073 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
9074
9075 ProcessPacket(1);
9076 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
9077 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
9078
9079 ProcessPacket(2);
9080 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
9081 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
9082}
9083
9084TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
9085 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9086 return;
9087 }
Bence Békybac04052022-04-07 15:44:29 -04009088 connection_.SendCryptoStreamData();
9089 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9090 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07009091 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04009092 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9093 QuicAckFrame frame1 = InitAckFrame(1);
9094 // Received ACK for packet 1.
9095 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9096
9097 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9098 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9099 NO_FIN);
9100 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9101 NO_FIN);
9102 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9103 8, NO_FIN);
9104 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9105 12, FIN);
9106 // Received ACK for packets 2, 4, 5.
9107 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07009108 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04009109 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9110 QuicAckFrame frame2 =
9111 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9112 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9113 // Make sure although the same packet number is used, but they are in
9114 // different packet number spaces.
9115 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9116}
9117
9118TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9119 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9120 return;
9121 }
Bence Békybac04052022-04-07 15:44:29 -04009122 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9123 std::make_unique<TaggingEncrypter>(0x01));
9124
9125 connection_.SendCryptoStreamData();
9126 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9127 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07009128 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04009129 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9130 QuicAckFrame frame1 = InitAckFrame(1);
9131 // Received ACK for packet 1.
9132 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9133
9134 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9135 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9136 NO_FIN);
9137 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9138 NO_FIN);
9139
9140 // Received ACK for packets 2 and 3 in wrong packet number space.
9141 QuicAckFrame invalid_ack =
9142 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
9143 EXPECT_CALL(visitor_,
9144 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9145 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9146 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
9147 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
9148}
9149
9150TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9151 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9152 return;
9153 }
9154 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9155 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9156 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9157 }
9158 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009159 // Receives packet 1000 in initial data.
9160 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9161 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009162 peer_framer_.SetEncrypter(
9163 ENCRYPTION_FORWARD_SECURE,
9164 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
9165 SetDecrypter(
9166 ENCRYPTION_FORWARD_SECURE,
9167 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009168 // Receives packet 1000 in application data.
9169 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
9170 EXPECT_TRUE(connection_.HasPendingAcks());
9171 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9172 0, NO_FIN);
9173 // Verify application data ACK gets bundled with outgoing data.
9174 EXPECT_EQ(2u, writer_->frame_count());
9175 // Make sure ACK alarm is still set because initial data is not ACKed.
9176 EXPECT_TRUE(connection_.HasPendingAcks());
9177 // Receive packet 1001 in application data.
9178 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_FORWARD_SECURE);
9179 clock_.AdvanceTime(DefaultRetransmissionTime());
9180 // Simulates ACK alarm fires and verify two ACKs are flushed.
9181 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
martinduke9e0811c2022-12-08 20:35:57 -08009182 connection_.SetEncrypter(
9183 ENCRYPTION_FORWARD_SECURE,
9184 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009185 connection_.GetAckAlarm()->Fire();
9186 EXPECT_FALSE(connection_.HasPendingAcks());
9187 // Receives more packets in application data.
9188 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_FORWARD_SECURE);
9189 EXPECT_TRUE(connection_.HasPendingAcks());
9190
9191 // Verify zero rtt and forward secure packets get acked in the same packet.
9192 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9193 ProcessDataPacket(1003);
9194 EXPECT_FALSE(connection_.HasPendingAcks());
9195}
9196
9197TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9198 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9199 return;
9200 }
9201 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9202 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9203 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9204 }
9205 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009206 // Receives packet 1000 in initial data.
9207 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9208 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009209 peer_framer_.SetEncrypter(
9210 ENCRYPTION_ZERO_RTT,
9211 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009212 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08009213 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009214 // Receives packet 1000 in application data.
9215 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9216 EXPECT_TRUE(connection_.HasPendingAcks());
9217
9218 writer_->SetWriteBlocked();
9219 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9220 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9221 // blocked.
9222 clock_.AdvanceTime(DefaultDelayedAckTime());
9223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9224 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9225 std::make_unique<TaggingEncrypter>(0x02));
9226 connection_.GetAckAlarm()->Fire();
9227 // Verify ACK alarm is not set.
9228 EXPECT_FALSE(connection_.HasPendingAcks());
9229
9230 writer_->SetWritable();
9231 // Verify 2 ACKs are sent when connection gets unblocked.
9232 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9233 connection_.OnCanWrite();
9234 EXPECT_FALSE(connection_.HasPendingAcks());
9235}
9236
9237// Make sure a packet received with the right client connection ID is processed.
9238TEST_P(QuicConnectionTest, ValidClientConnectionId) {
9239 if (!framer_.version().SupportsClientConnectionIds()) {
9240 return;
9241 }
9242 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9243 SetClientConnectionId(TestConnectionId(0x33));
9244 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9245 header.destination_connection_id = TestConnectionId(0x33);
9246 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9247 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9248 QuicFrames frames;
9249 QuicPingFrame ping_frame;
9250 QuicPaddingFrame padding_frame;
9251 frames.push_back(QuicFrame(ping_frame));
9252 frames.push_back(QuicFrame(padding_frame));
9253 std::unique_ptr<QuicPacket> packet =
9254 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9255 char buffer[kMaxOutgoingPacketSize];
9256 size_t encrypted_length = peer_framer_.EncryptPayload(
9257 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9258 kMaxOutgoingPacketSize);
9259 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9260 false);
9261 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9262 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9263 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9264}
9265
9266// Make sure a packet received with a different client connection ID is dropped.
9267TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
9268 if (!framer_.version().SupportsClientConnectionIds()) {
9269 return;
9270 }
9271 SetClientConnectionId(TestConnectionId(0x33));
9272 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9273 header.destination_connection_id = TestConnectionId(0xbad);
9274 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9275 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9276 QuicFrames frames;
9277 QuicPingFrame ping_frame;
9278 QuicPaddingFrame padding_frame;
9279 frames.push_back(QuicFrame(ping_frame));
9280 frames.push_back(QuicFrame(padding_frame));
9281 std::unique_ptr<QuicPacket> packet =
9282 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9283 char buffer[kMaxOutgoingPacketSize];
9284 size_t encrypted_length = peer_framer_.EncryptPayload(
9285 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9286 kMaxOutgoingPacketSize);
9287 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9288 false);
9289 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9290 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9291 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9292}
9293
9294// Make sure the first packet received with a different client connection ID on
9295// the server is processed and it changes the client connection ID.
9296TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
9297 if (!framer_.version().SupportsClientConnectionIds()) {
9298 return;
9299 }
9300 set_perspective(Perspective::IS_SERVER);
9301 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9302 header.source_connection_id = TestConnectionId(0x33);
9303 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9304 QuicFrames frames;
9305 QuicPingFrame ping_frame;
9306 QuicPaddingFrame padding_frame;
9307 frames.push_back(QuicFrame(ping_frame));
9308 frames.push_back(QuicFrame(padding_frame));
9309 std::unique_ptr<QuicPacket> packet =
9310 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9311 char buffer[kMaxOutgoingPacketSize];
9312 size_t encrypted_length =
9313 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9314 *packet, buffer, kMaxOutgoingPacketSize);
9315 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9316 false);
9317 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9318 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9319 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9320 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9321}
9322void QuicConnectionTest::TestReplaceConnectionIdFromInitial() {
9323 if (!framer_.version().AllowsVariableLengthConnectionIds()) {
9324 return;
9325 }
9326 // We start with a known connection ID.
9327 EXPECT_TRUE(connection_.connected());
9328 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9329 EXPECT_NE(TestConnectionId(0x33), connection_.connection_id());
9330 // Receiving an initial can replace the connection ID once.
9331 {
9332 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9333 header.source_connection_id = TestConnectionId(0x33);
9334 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9335 QuicFrames frames;
9336 QuicPingFrame ping_frame;
9337 QuicPaddingFrame padding_frame;
9338 frames.push_back(QuicFrame(ping_frame));
9339 frames.push_back(QuicFrame(padding_frame));
9340 std::unique_ptr<QuicPacket> packet =
9341 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9342 char buffer[kMaxOutgoingPacketSize];
9343 size_t encrypted_length =
9344 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9345 *packet, buffer, kMaxOutgoingPacketSize);
9346 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9347 false);
9348 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9349 }
9350 EXPECT_TRUE(connection_.connected());
9351 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9352 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9353 // Trying to replace the connection ID a second time drops the packet.
9354 {
9355 QuicPacketHeader header = ConstructPacketHeader(2, ENCRYPTION_INITIAL);
9356 header.source_connection_id = TestConnectionId(0x66);
9357 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9358 QuicFrames frames;
9359 QuicPingFrame ping_frame;
9360 QuicPaddingFrame padding_frame;
9361 frames.push_back(QuicFrame(ping_frame));
9362 frames.push_back(QuicFrame(padding_frame));
9363 std::unique_ptr<QuicPacket> packet =
9364 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9365 char buffer[kMaxOutgoingPacketSize];
9366 size_t encrypted_length =
9367 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9368 *packet, buffer, kMaxOutgoingPacketSize);
9369 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9370 false);
9371 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9372 }
9373 EXPECT_TRUE(connection_.connected());
9374 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9375 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9376}
9377
9378TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromInitial) {
9379 TestReplaceConnectionIdFromInitial();
9380}
9381
9382TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromRetryAndInitial) {
9383 // First make the connection process a RETRY and replace the server connection
9384 // ID a first time.
9385 TestClientRetryHandling(/*invalid_retry_tag=*/false,
9386 /*missing_original_id_in_config=*/false,
9387 /*wrong_original_id_in_config=*/false,
9388 /*missing_retry_id_in_config=*/false,
9389 /*wrong_retry_id_in_config=*/false);
9390 // Reset the test framer to use the right connection ID.
9391 peer_framer_.SetInitialObfuscators(connection_.connection_id());
9392 // Now process an INITIAL and replace the server connection ID a second time.
9393 TestReplaceConnectionIdFromInitial();
9394}
9395
9396// Regression test for b/134416344.
9397TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9398 // This test mimics a scenario where a connection processes 2 packets and the
9399 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9400 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9401 // because connection is disconnected.
9402 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9403 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9404 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
9405 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
9406 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
9407 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9408 NO_IETF_QUIC_ERROR, "",
9409 /*transport_close_frame_type=*/0));
9410
9411 // Received 2 packets.
9412 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9413 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9414 } else {
9415 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9416 }
9417 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
9418 ENCRYPTION_INITIAL);
9419 EXPECT_TRUE(connection_.HasPendingAcks());
9420 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
9421 kSelfAddress, kPeerAddress,
9422 ENCRYPTION_INITIAL);
9423 // Verify ack alarm is not set.
9424 EXPECT_FALSE(connection_.HasPendingAcks());
9425}
9426
9427// Verify that a packet containing three coalesced packets is parsed correctly.
9428TEST_P(QuicConnectionTest, CoalescedPacket) {
9429 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9430 // Coalesced packets can only be encoded using long header lengths.
9431 return;
9432 }
9433 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9434 EXPECT_TRUE(connection_.connected());
9435 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9436 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9437 } else {
9438 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9439 }
9440
9441 uint64_t packet_numbers[3] = {1, 2, 3};
9442 EncryptionLevel encryption_levels[3] = {
9443 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9444 char buffer[kMaxOutgoingPacketSize] = {};
9445 size_t total_encrypted_length = 0;
9446 for (int i = 0; i < 3; i++) {
9447 QuicPacketHeader header =
9448 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9449 QuicFrames frames;
9450 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9451 frames.push_back(QuicFrame(&crypto_frame_));
9452 } else {
9453 frames.push_back(QuicFrame(frame1_));
9454 }
9455 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9456 peer_creator_.set_encryption_level(encryption_levels[i]);
9457 size_t encrypted_length = peer_framer_.EncryptPayload(
9458 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9459 buffer + total_encrypted_length,
9460 sizeof(buffer) - total_encrypted_length);
9461 EXPECT_GT(encrypted_length, 0u);
9462 total_encrypted_length += encrypted_length;
9463 }
9464 connection_.ProcessUdpPacket(
9465 kSelfAddress, kPeerAddress,
9466 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9467 if (connection_.GetSendAlarm()->IsSet()) {
9468 connection_.GetSendAlarm()->Fire();
9469 }
9470
9471 EXPECT_TRUE(connection_.connected());
9472}
9473
9474// Regression test for crbug.com/992831.
9475TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9476 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9477 // Coalesced packets can only be encoded using long header lengths.
9478 return;
9479 }
9480 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9481 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9482 return;
9483 }
9484 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9485 EXPECT_TRUE(connection_.connected());
9486 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9487 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9488 .Times(3)
9489 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9490 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009491 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009492 });
9493 } else {
9494 EXPECT_CALL(visitor_, OnStreamFrame(_))
9495 .Times(3)
9496 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9497 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009498 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009499 });
9500 }
9501
9502 uint64_t packet_numbers[3] = {1, 2, 3};
9503 EncryptionLevel encryption_levels[3] = {
9504 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9505 char buffer[kMaxOutgoingPacketSize] = {};
9506 size_t total_encrypted_length = 0;
9507 for (int i = 0; i < 3; i++) {
9508 QuicPacketHeader header =
9509 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9510 QuicFrames frames;
9511 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9512 frames.push_back(QuicFrame(&crypto_frame_));
9513 } else {
9514 frames.push_back(QuicFrame(frame1_));
9515 }
9516 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9517 peer_creator_.set_encryption_level(encryption_levels[i]);
9518 size_t encrypted_length = peer_framer_.EncryptPayload(
9519 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9520 buffer + total_encrypted_length,
9521 sizeof(buffer) - total_encrypted_length);
9522 EXPECT_GT(encrypted_length, 0u);
9523 total_encrypted_length += encrypted_length;
9524 }
9525 connection_.ProcessUdpPacket(
9526 kSelfAddress, kPeerAddress,
9527 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9528 if (connection_.GetSendAlarm()->IsSet()) {
9529 connection_.GetSendAlarm()->Fire();
9530 }
9531
9532 EXPECT_TRUE(connection_.connected());
9533
9534 SendAckPacketToPeer();
9535}
9536
9537// Regresstion test for b/138962304.
9538TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
9539 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9540
9541 QuicStreamId stream_id = 2;
9542 QuicPacketNumber last_data_packet;
9543 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9544 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9545
9546 // Writer gets blocked.
9547 writer_->SetWriteBlocked();
9548
9549 // Cancel the stream.
9550 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9551 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9552 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9553 .WillRepeatedly(
9554 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
9555 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9556
9557 // Retransmission timer fires in RTO mode.
9558 connection_.GetRetransmissionAlarm()->Fire();
9559 // Verify no packets get flushed when writer is blocked.
9560 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9561}
9562
9563// Regresstion test for b/138962304.
fayang339f0c82022-04-30 14:20:02 -07009564TEST_P(QuicConnectionTest, PtoAndWriteBlocked) {
Bence Békybac04052022-04-07 15:44:29 -04009565 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
Bence Békybac04052022-04-07 15:44:29 -04009566
9567 QuicStreamId stream_id = 2;
9568 QuicPacketNumber last_data_packet;
9569 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9570 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9571 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9572
9573 // Writer gets blocked.
9574 writer_->SetWriteBlocked();
9575
9576 // Cancel stream 2.
9577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9578 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9579 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9580
9581 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9582 // Retransmission timer fires in TLP mode.
9583 connection_.GetRetransmissionAlarm()->Fire();
9584 // Verify one packets is forced flushed when writer is blocked.
9585 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9586}
9587
Bence Békybac04052022-04-07 15:44:29 -04009588TEST_P(QuicConnectionTest, ProbeTimeout) {
9589 QuicConfig config;
9590 QuicTagVector connection_options;
9591 connection_options.push_back(k2PTO);
9592 config.SetConnectionOptionsToSend(connection_options);
9593 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08009594 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
9595 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04009596 connection_.SetFromConfig(config);
9597 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9598
9599 QuicStreamId stream_id = 2;
9600 QuicPacketNumber last_packet;
9601 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9602 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9603 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9604
9605 // Reset stream.
9606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9607 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9608
9609 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9610 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9611 connection_.GetRetransmissionAlarm()->Fire();
9612 EXPECT_EQ(0u, writer_->stream_frames().size());
9613 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9614 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9615}
9616
9617TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
9618 QuicConfig config;
9619 QuicTagVector connection_options;
9620 connection_options.push_back(k1PTO);
9621 connection_options.push_back(k6PTO);
9622 config.SetConnectionOptionsToSend(connection_options);
9623 QuicConfigPeer::SetNegotiated(&config, true);
9624 if (connection_.version().UsesTls()) {
9625 QuicConfigPeer::SetReceivedOriginalConnectionId(
9626 &config, connection_.connection_id());
9627 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9628 &config, connection_.connection_id());
9629 }
9630 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08009631 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
9632 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04009633 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009634 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9635 GetQuicReloadableFlag(
9636 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009637 EXPECT_CALL(visitor_, GetHandshakeState())
9638 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9639 }
9640 connection_.OnHandshakeComplete();
9641 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9642
9643 // Send stream data.
9644 SendStreamDataToPeer(
9645 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9646 0, FIN, nullptr);
9647
9648 // Fire the retransmission alarm 5 times.
9649 for (int i = 0; i < 5; ++i) {
9650 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9651 connection_.GetRetransmissionAlarm()->Fire();
9652 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9653 EXPECT_TRUE(connection_.connected());
9654 }
9655 EXPECT_CALL(visitor_, OnPathDegrading());
9656 connection_.PathDegradingTimeout();
9657
Bence Békybac04052022-04-07 15:44:29 -04009658 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9659 // Closes connection on 6th PTO.
9660 // May send multiple connecction close packets with multiple PN spaces.
9661 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9662 EXPECT_CALL(visitor_,
9663 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9664 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9665 connection_.GetBlackholeDetectorAlarm()->Fire();
9666 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9667 EXPECT_FALSE(connection_.connected());
9668 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9669}
9670
9671TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
9672 QuicConfig config;
9673 QuicTagVector connection_options;
9674 connection_options.push_back(k2PTO);
9675 connection_options.push_back(k7PTO);
9676 config.SetConnectionOptionsToSend(connection_options);
9677 QuicConfigPeer::SetNegotiated(&config, true);
9678 if (connection_.version().UsesTls()) {
9679 QuicConfigPeer::SetReceivedOriginalConnectionId(
9680 &config, connection_.connection_id());
9681 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9682 &config, connection_.connection_id());
9683 }
9684 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08009685 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
9686 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04009687 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009688 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9689 GetQuicReloadableFlag(
9690 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009691 EXPECT_CALL(visitor_, GetHandshakeState())
9692 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9693 }
9694 connection_.OnHandshakeComplete();
9695 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9696
9697 // Send stream data.
9698 SendStreamDataToPeer(
9699 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9700 0, FIN, nullptr);
9701
9702 // Fire the retransmission alarm 6 times.
9703 for (int i = 0; i < 6; ++i) {
9704 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9705 connection_.GetRetransmissionAlarm()->Fire();
9706 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9707 EXPECT_TRUE(connection_.connected());
9708 }
9709 EXPECT_CALL(visitor_, OnPathDegrading());
9710 connection_.PathDegradingTimeout();
9711
Bence Békybac04052022-04-07 15:44:29 -04009712 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9713 // Closes connection on 7th PTO.
9714 EXPECT_CALL(visitor_,
9715 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9716 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9717 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9718 connection_.GetBlackholeDetectorAlarm()->Fire();
9719 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9720 EXPECT_FALSE(connection_.connected());
9721 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9722}
9723
9724TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
9725 QuicConfig config;
9726 QuicTagVector connection_options;
9727 connection_options.push_back(k2PTO);
9728 connection_options.push_back(k8PTO);
9729 QuicConfigPeer::SetNegotiated(&config, true);
9730 if (connection_.version().UsesTls()) {
9731 QuicConfigPeer::SetReceivedOriginalConnectionId(
9732 &config, connection_.connection_id());
9733 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9734 &config, connection_.connection_id());
9735 }
9736 config.SetConnectionOptionsToSend(connection_options);
9737 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08009738 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
9739 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04009740 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009741 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9742 GetQuicReloadableFlag(
9743 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009744 EXPECT_CALL(visitor_, GetHandshakeState())
9745 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9746 }
9747 connection_.OnHandshakeComplete();
9748 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9749
9750 // Send stream data.
9751 SendStreamDataToPeer(
9752 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9753 0, FIN, nullptr);
9754
9755 // Fire the retransmission alarm 7 times.
9756 for (int i = 0; i < 7; ++i) {
9757 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9758 connection_.GetRetransmissionAlarm()->Fire();
9759 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9760 EXPECT_TRUE(connection_.connected());
9761 }
9762 EXPECT_CALL(visitor_, OnPathDegrading());
9763 connection_.PathDegradingTimeout();
9764
Bence Békybac04052022-04-07 15:44:29 -04009765 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9766 // Closes connection on 8th PTO.
9767 EXPECT_CALL(visitor_,
9768 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9769 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9770 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9771 connection_.GetBlackholeDetectorAlarm()->Fire();
9772 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9773 EXPECT_FALSE(connection_.connected());
9774 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9775}
9776
9777TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9778 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9779 return;
9780 }
9781 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9782 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9783
9784 // Send CHLO.
9785 connection_.SendCryptoStreamData();
9786 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9787
9788 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07009789 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04009790 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9791 QuicAckFrame frame1 = InitAckFrame(1);
9792 // Received ACK for packet 1.
9793 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9794
9795 // Verify retransmission alarm is still set because handshake is not
9796 // confirmed although there is nothing in flight.
9797 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9798 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9799 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9800
9801 // PTO fires, verify a PING packet gets sent because there is no data to send.
9802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9803 connection_.GetRetransmissionAlarm()->Fire();
9804 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9805 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
9806 EXPECT_EQ(1u, writer_->ping_frames().size());
9807}
9808
9809TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009810 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009811 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009812 return;
9813 }
9814 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9815
9816 set_perspective(Perspective::IS_SERVER);
9817 // Verify no data can be sent at the beginning because bytes received is 0.
9818 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9819 connection_.SendCryptoDataWithString("foo", 0);
9820 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9821 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9822 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9823
9824 // Receives packet 1.
9825 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009826 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009827 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9828
9829 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -07009830 GetQuicFlag(quic_anti_amplification_factor);
Bence Békybac04052022-04-07 15:44:29 -04009831 // Verify now packets can be sent.
9832 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9833 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9834 connection_.SendCryptoDataWithString("foo", i * 3);
9835 // Verify retransmission alarm is not set if throttled by anti-amplification
9836 // limit.
9837 EXPECT_EQ(i != anti_amplification_factor - 1,
9838 connection_.GetRetransmissionAlarm()->IsSet());
9839 }
9840 // Verify server is throttled by anti-amplification limit.
9841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9842 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9843
9844 // Receives packet 2.
9845 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009846 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009847 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9848 // Verify more packets can be sent.
9849 for (size_t i = anti_amplification_factor + 1;
9850 i < anti_amplification_factor * 2; ++i) {
9851 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9852 connection_.SendCryptoDataWithString("foo", i * 3);
9853 }
9854 // Verify server is throttled by anti-amplification limit.
9855 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9856 connection_.SendCryptoDataWithString("foo",
9857 2 * anti_amplification_factor * 3);
9858
9859 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009860 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009861 ProcessPacket(3);
9862 // Verify anti-amplification limit is gone after address validation.
9863 for (size_t i = 0; i < 100; ++i) {
9864 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9865 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9866 }
9867}
9868
9869TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009870 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009871 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009872 return;
9873 }
9874 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9875
9876 set_perspective(Perspective::IS_SERVER);
9877 QuicConfig config;
9878 QuicTagVector connection_options;
9879 connection_options.push_back(k3AFF);
9880 config.SetInitialReceivedConnectionOptions(connection_options);
9881 if (connection_.version().UsesTls()) {
9882 QuicConfigPeer::SetReceivedOriginalConnectionId(
9883 &config, connection_.connection_id());
9884 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9885 QuicConnectionId());
9886 }
9887 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08009888 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
9889 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04009890 connection_.SetFromConfig(config);
9891
9892 // Verify no data can be sent at the beginning because bytes received is 0.
9893 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9894 connection_.SendCryptoDataWithString("foo", 0);
9895 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9896 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9897 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9898
9899 // Receives packet 1.
9900 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009901 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009902 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9903
9904 const size_t anti_amplification_factor = 3;
9905 // Verify now packets can be sent.
9906 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9907 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9908 connection_.SendCryptoDataWithString("foo", i * 3);
9909 // Verify retransmission alarm is not set if throttled by anti-amplification
9910 // limit.
9911 EXPECT_EQ(i != anti_amplification_factor - 1,
9912 connection_.GetRetransmissionAlarm()->IsSet());
9913 }
9914 // Verify server is throttled by anti-amplification limit.
9915 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9916 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9917
9918 // Receives packet 2.
9919 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009920 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009921 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9922 // Verify more packets can be sent.
9923 for (size_t i = anti_amplification_factor + 1;
9924 i < anti_amplification_factor * 2; ++i) {
9925 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9926 connection_.SendCryptoDataWithString("foo", i * 3);
9927 }
9928 // Verify server is throttled by anti-amplification limit.
9929 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9930 connection_.SendCryptoDataWithString("foo",
9931 2 * anti_amplification_factor * 3);
9932
9933 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009934 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009935 ProcessPacket(3);
9936 // Verify anti-amplification limit is gone after address validation.
9937 for (size_t i = 0; i < 100; ++i) {
9938 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9939 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9940 }
9941}
9942
9943TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009944 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009945 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009946 return;
9947 }
9948 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9949
9950 set_perspective(Perspective::IS_SERVER);
9951 QuicConfig config;
9952 QuicTagVector connection_options;
9953 connection_options.push_back(k10AF);
9954 config.SetInitialReceivedConnectionOptions(connection_options);
9955 if (connection_.version().UsesTls()) {
9956 QuicConfigPeer::SetReceivedOriginalConnectionId(
9957 &config, connection_.connection_id());
9958 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9959 QuicConnectionId());
9960 }
9961 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -08009962 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
9963 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -04009964 connection_.SetFromConfig(config);
9965
9966 // Verify no data can be sent at the beginning because bytes received is 0.
9967 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9968 connection_.SendCryptoDataWithString("foo", 0);
9969 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9970 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9971 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9972
9973 // Receives packet 1.
9974 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009975 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009976 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9977
9978 const size_t anti_amplification_factor = 10;
9979 // Verify now packets can be sent.
9980 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9981 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9982 connection_.SendCryptoDataWithString("foo", i * 3);
9983 // Verify retransmission alarm is not set if throttled by anti-amplification
9984 // limit.
9985 EXPECT_EQ(i != anti_amplification_factor - 1,
9986 connection_.GetRetransmissionAlarm()->IsSet());
9987 }
9988 // Verify server is throttled by anti-amplification limit.
9989 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9990 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9991
9992 // Receives packet 2.
9993 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009994 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009995 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9996 // Verify more packets can be sent.
9997 for (size_t i = anti_amplification_factor + 1;
9998 i < anti_amplification_factor * 2; ++i) {
9999 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10000 connection_.SendCryptoDataWithString("foo", i * 3);
10001 }
10002 // Verify server is throttled by anti-amplification limit.
10003 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10004 connection_.SendCryptoDataWithString("foo",
10005 2 * anti_amplification_factor * 3);
10006
10007 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -070010008 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -040010009 ProcessPacket(3);
10010 // Verify anti-amplification limit is gone after address validation.
10011 for (size_t i = 0; i < 100; ++i) {
10012 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10013 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
10014 }
10015}
10016
10017TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
10018 if (!connection_.version().SupportsAntiAmplificationLimit()) {
10019 return;
10020 }
10021 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10022 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10023 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040010024 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10025 // Receives packet 1.
10026 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080010027 connection_.SetEncrypter(
10028 ENCRYPTION_HANDSHAKE,
10029 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010030 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10031 EXPECT_TRUE(connection_.HasPendingAcks());
10032 // Send response in different encryption level and cause amplification factor
10033 // throttled.
10034 size_t i = 0;
10035 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
10036 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
10037 ENCRYPTION_HANDSHAKE);
10038 ++i;
10039 }
10040 // Verify ACK is still pending.
10041 EXPECT_TRUE(connection_.HasPendingAcks());
10042
10043 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
10044 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
10045 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10046 connection_.GetAckAlarm()->Fire();
10047 // Verify ACK alarm is cancelled.
10048 EXPECT_FALSE(connection_.HasPendingAcks());
10049
10050 // Receives packet 2 and verify ACK gets flushed.
10051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10052 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10053 EXPECT_FALSE(writer_->ack_frames().empty());
10054}
10055
10056TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
10057 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10058 // Test relevent only for IETF QUIC.
10059 return;
10060 }
10061 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
10062 // Use the (unknown) frame type of 9999 to avoid triggering any logic
10063 // which might be associated with the processing of a known frame type.
10064 const uint64_t kTransportCloseFrameType = 9999u;
10065 QuicFramerPeer::set_current_received_frame_type(
10066 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
10067 // Do a transport connection close
10068 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10069 connection_.CloseConnection(
10070 kQuicErrorCode, "Some random error message",
10071 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10072 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
10073 writer_->connection_close_frames();
10074 ASSERT_EQ(1u, connection_close_frames.size());
10075 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
10076 connection_close_frames[0].close_type);
10077 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
10078 EXPECT_EQ(kTransportCloseFrameType,
10079 connection_close_frames[0].transport_close_frame_type);
10080}
10081
Bence Békybac04052022-04-07 15:44:29 -040010082TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
10083 QuicConfig config;
10084 QuicTagVector connection_options;
10085 connection_options.push_back(k1PTO);
10086 connection_options.push_back(kPTOS);
10087 config.SetConnectionOptionsToSend(connection_options);
10088 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080010089 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
10090 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040010091 connection_.SetFromConfig(config);
10092 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10093
10094 QuicStreamId stream_id = 2;
10095 QuicPacketNumber last_packet;
10096 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10097 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10098 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10099 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10100
10101 // Fire PTO and verify the PTO retransmission skips one packet number.
10102 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10103 connection_.GetRetransmissionAlarm()->Fire();
10104 EXPECT_EQ(1u, writer_->stream_frames().size());
10105 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
10106 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10107}
10108
rch92b45f72024-10-16 11:04:51 -070010109TEST_P(QuicConnectionTest, PtoChangesFlowLabel) {
10110 QuicConfig config;
10111 QuicTagVector connection_options;
10112 connection_options.push_back(k1PTO);
10113 connection_options.push_back(kPTOS);
10114 config.SetConnectionOptionsToSend(connection_options);
10115 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080010116 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
10117 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
rch92b45f72024-10-16 11:04:51 -070010118 connection_.SetFromConfig(config);
10119 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
rche8ff0132024-10-17 11:53:32 -070010120 EXPECT_EQ(0, connection_.outgoing_flow_label());
rch92b45f72024-10-16 11:04:51 -070010121 connection_.EnableBlackholeAvoidanceViaFlowLabel();
rche8ff0132024-10-17 11:53:32 -070010122 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
10123 const uint32_t flow_label = connection_.outgoing_flow_label();
10124 EXPECT_NE(0, flow_label);
rch92b45f72024-10-16 11:04:51 -070010125
10126 QuicStreamId stream_id = 2;
10127 QuicPacketNumber last_packet;
10128 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10129 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10130 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10131 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10132
10133 // Fire PTO and verify the flow label has changed.
10134 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10135 connection_.GetRetransmissionAlarm()->Fire();
rche8ff0132024-10-17 11:53:32 -070010136 EXPECT_NE(flow_label, connection_.outgoing_flow_label());
rchd4d2f9b2024-10-29 13:47:23 -070010137 EXPECT_EQ(1, connection_.GetStats().num_flow_label_changes);
10138
10139 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterFlowLabelChange());
10140 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
10141 QuicAckFrame frame = InitAckFrame(last_packet);
10142 ProcessAckPacket(1, &frame);
10143 EXPECT_EQ(
10144 1, connection_.GetStats().num_forward_progress_after_flow_label_change);
rch92b45f72024-10-16 11:04:51 -070010145}
10146
10147TEST_P(QuicConnectionTest, NewReceiveNewFlowLabelWithGapChangesFlowLabel) {
10148 QuicConfig config;
10149 QuicTagVector connection_options;
10150 connection_options.push_back(k1PTO);
10151 connection_options.push_back(kPTOS);
10152 config.SetConnectionOptionsToSend(connection_options);
10153 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080010154 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
10155 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
rch92b45f72024-10-16 11:04:51 -070010156 connection_.SetFromConfig(config);
rche8ff0132024-10-17 11:53:32 -070010157 EXPECT_EQ(0, connection_.outgoing_flow_label());
rch92b45f72024-10-16 11:04:51 -070010158 connection_.EnableBlackholeAvoidanceViaFlowLabel();
rche8ff0132024-10-17 11:53:32 -070010159 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
10160 const uint32_t flow_label = connection_.outgoing_flow_label();
10161 EXPECT_NE(0, flow_label);
rch92b45f72024-10-16 11:04:51 -070010162 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10163
10164 // Receive the first packet to initialize the flow label.
10165 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL, 0);
rche8ff0132024-10-17 11:53:32 -070010166 EXPECT_EQ(flow_label, connection_.outgoing_flow_label());
rch92b45f72024-10-16 11:04:51 -070010167
10168 // Receive the second packet with the same flow label
10169 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_INITIAL, flow_label);
rche8ff0132024-10-17 11:53:32 -070010170 EXPECT_EQ(flow_label, connection_.outgoing_flow_label());
rch92b45f72024-10-16 11:04:51 -070010171
10172 // Receive a packet with gap and a new flow label and verify the outgoing
10173 // flow label has changed.
rche8ff0132024-10-17 11:53:32 -070010174 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
rch92b45f72024-10-16 11:04:51 -070010175 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL,
10176 flow_label + 1);
10177 EXPECT_NE(flow_label, connection_.outgoing_flow_label());
10178}
10179
10180TEST_P(QuicConnectionTest,
10181 NewReceiveNewFlowLabelWithNoGapDoesNotChangeFlowLabel) {
10182 QuicConfig config;
10183 QuicTagVector connection_options;
10184 connection_options.push_back(k1PTO);
10185 connection_options.push_back(kPTOS);
10186 config.SetConnectionOptionsToSend(connection_options);
10187 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080010188 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
10189 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
rch92b45f72024-10-16 11:04:51 -070010190 connection_.SetFromConfig(config);
rche8ff0132024-10-17 11:53:32 -070010191 EXPECT_EQ(0, connection_.outgoing_flow_label());
rch92b45f72024-10-16 11:04:51 -070010192 connection_.EnableBlackholeAvoidanceViaFlowLabel();
rche8ff0132024-10-17 11:53:32 -070010193 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
10194 const uint32_t flow_label = connection_.outgoing_flow_label();
10195 EXPECT_NE(0, flow_label);
rch92b45f72024-10-16 11:04:51 -070010196 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10197
10198 // Receive the first packet to initialize the flow label.
10199 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL, 0);
rche8ff0132024-10-17 11:53:32 -070010200 EXPECT_EQ(flow_label, connection_.outgoing_flow_label());
rch92b45f72024-10-16 11:04:51 -070010201
10202 // Receive the second packet with the same flow label
10203 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_INITIAL, flow_label);
rche8ff0132024-10-17 11:53:32 -070010204 EXPECT_EQ(flow_label, connection_.outgoing_flow_label());
rch92b45f72024-10-16 11:04:51 -070010205
10206 // Receive a packet with no gap and a new flow label and verify the outgoing
10207 // flow label has not changed.
10208 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL, flow_label);
10209 EXPECT_EQ(flow_label, connection_.outgoing_flow_label());
10210}
10211
Bence Békybac04052022-04-07 15:44:29 -040010212TEST_P(QuicConnectionTest, SendCoalescedPackets) {
10213 if (!connection_.version().CanSendCoalescedPackets()) {
10214 return;
10215 }
10216 MockQuicConnectionDebugVisitor debug_visitor;
10217 connection_.set_debug_visitor(&debug_visitor);
wub92727922023-07-13 08:47:39 -070010218 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -040010219 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
10220 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10221 {
10222 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040010223 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10224 connection_.SendCryptoDataWithString("foo", 0);
10225 // Verify this packet is on hold.
10226 EXPECT_EQ(0u, writer_->packets_write_attempts());
10227
10228 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10229 std::make_unique<TaggingEncrypter>(0x02));
10230 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10231 connection_.SendCryptoDataWithString("bar", 3);
10232 EXPECT_EQ(0u, writer_->packets_write_attempts());
10233
10234 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10235 std::make_unique<TaggingEncrypter>(0x03));
10236 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10237 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10238 }
10239 // Verify all 3 packets are coalesced in the same UDP datagram.
10240 EXPECT_EQ(1u, writer_->packets_write_attempts());
10241 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10242 // Verify the packet is padded to full.
10243 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10244
10245 // Verify packet process.
dschinazif16e5a92024-12-06 15:40:18 -080010246 EXPECT_LE(1u, writer_->crypto_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040010247 EXPECT_EQ(0u, writer_->stream_frames().size());
10248 // Verify there is coalesced packet.
10249 EXPECT_NE(nullptr, writer_->coalesced_packet());
10250}
10251
10252TEST_P(QuicConnectionTest, FailToCoalescePacket) {
10253 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
10254 if (!IsDefaultTestConfiguration() ||
fayang161ce6e2022-07-01 18:02:11 -070010255 !connection_.version().CanSendCoalescedPackets() ||
birenroyef686222022-09-12 11:34:34 -070010256 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040010257 return;
10258 }
10259
10260 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040010261
Bence Békybac04052022-04-07 15:44:29 -040010262 auto test_body = [&] {
vasilvvac2e30d2022-06-02 14:26:59 -070010263 EXPECT_CALL(visitor_,
10264 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10265 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
Bence Békybac04052022-04-07 15:44:29 -040010266
vasilvvac2e30d2022-06-02 14:26:59 -070010267 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -040010268
vasilvvac2e30d2022-06-02 14:26:59 -070010269 {
10270 QuicConnection::ScopedPacketFlusher flusher(&connection_);
vasilvvac2e30d2022-06-02 14:26:59 -070010271 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10272 connection_.SendCryptoDataWithString("foo", 0);
10273 // Verify this packet is on hold.
10274 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -040010275
vasilvvac2e30d2022-06-02 14:26:59 -070010276 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10277 std::make_unique<TaggingEncrypter>(0x02));
10278 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10279 connection_.SendCryptoDataWithString("bar", 3);
10280 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -040010281
vasilvvac2e30d2022-06-02 14:26:59 -070010282 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10283 std::make_unique<TaggingEncrypter>(0x03));
10284 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10285 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
Bence Békybac04052022-04-07 15:44:29 -040010286
vasilvvac2e30d2022-06-02 14:26:59 -070010287 creator_->Flush();
10288
10289 auto& coalesced_packet =
10290 QuicConnectionPeer::GetCoalescedPacket(&connection_);
10291 QuicPacketLength coalesced_packet_max_length =
10292 coalesced_packet.max_packet_length();
10293 QuicCoalescedPacketPeer::SetMaxPacketLength(coalesced_packet,
10294 coalesced_packet.length());
10295
10296 // Make the coalescer's FORWARD_SECURE packet longer.
10297 *QuicCoalescedPacketPeer::GetMutableEncryptedBuffer(
10298 coalesced_packet, ENCRYPTION_FORWARD_SECURE) += "!!! TEST !!!";
10299
10300 QUIC_LOG(INFO) << "Reduced coalesced_packet_max_length from "
10301 << coalesced_packet_max_length << " to "
10302 << coalesced_packet.max_packet_length()
10303 << ", coalesced_packet.length:"
10304 << coalesced_packet.length()
10305 << ", coalesced_packet.packet_lengths:"
10306 << absl::StrJoin(coalesced_packet.packet_lengths(), ":");
10307 }
10308
10309 EXPECT_FALSE(connection_.connected());
10310 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10311 IsError(QUIC_FAILED_TO_SERIALIZE_PACKET));
10312 EXPECT_EQ(saved_connection_close_frame_.error_details,
10313 "Failed to serialize coalesced packet.");
Bence Békybac04052022-04-07 15:44:29 -040010314 };
10315
10316 EXPECT_QUIC_BUG(test_body(), "SerializeCoalescedPacket failed.");
Bence Békybac04052022-04-07 15:44:29 -040010317}
10318
Bence Békybac04052022-04-07 15:44:29 -040010319TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10320 if (!connection_.version().UsesTls()) {
10321 return;
10322 }
10323 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10324 QuicFrames frames;
10325 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10326 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10327 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10328}
10329
10330TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10331 if (!connection_.version().UsesTls()) {
10332 return;
10333 }
10334 set_perspective(Perspective::IS_SERVER);
10335 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10336 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
10337 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
10338 }
10339 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10340 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10341 QuicFrames frames;
10342 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10343 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10344 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10345 EXPECT_EQ(1, connection_close_frame_count_);
10346 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10347 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10348}
10349
10350TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10351 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10352 return;
10353 }
Bence Békybac04052022-04-07 15:44:29 -040010354 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010355 connection_.SetEncrypter(
10356 ENCRYPTION_HANDSHAKE,
10357 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010358 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10359 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10360 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080010361 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010362
10363 // Send application data.
10364 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10365 0, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010366 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010367 QuicTime retransmission_time =
10368 connection_.GetRetransmissionAlarm()->deadline();
10369 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10370
10371 // Retransmit handshake data.
10372 clock_.AdvanceTime(retransmission_time - clock_.Now());
10373 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _));
10374 connection_.GetRetransmissionAlarm()->Fire();
10375 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010376 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010377
10378 // Send application data.
10379 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10380 4, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010381 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010382 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10383 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10384
10385 // Retransmit handshake data again.
10386 clock_.AdvanceTime(retransmission_time - clock_.Now());
10387 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _));
10388 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(8), _, _));
10389 connection_.GetRetransmissionAlarm()->Fire();
10390 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010391 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010392
10393 // Discard handshake key.
10394 connection_.OnHandshakeComplete();
10395 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10396 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10397
10398 // Retransmit application data.
10399 clock_.AdvanceTime(retransmission_time - clock_.Now());
10400 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(11), _, _));
10401 connection_.GetRetransmissionAlarm()->Fire();
martinduke9e0811c2022-12-08 20:35:57 -080010402 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010403}
10404
10405void QuicConnectionTest::TestClientRetryHandling(
10406 bool invalid_retry_tag, bool missing_original_id_in_config,
10407 bool wrong_original_id_in_config, bool missing_retry_id_in_config,
10408 bool wrong_retry_id_in_config) {
10409 if (invalid_retry_tag) {
10410 ASSERT_FALSE(missing_original_id_in_config);
10411 ASSERT_FALSE(wrong_original_id_in_config);
10412 ASSERT_FALSE(missing_retry_id_in_config);
10413 ASSERT_FALSE(wrong_retry_id_in_config);
10414 } else {
10415 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10416 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
10417 }
10418 if (!version().UsesTls()) {
10419 return;
10420 }
10421
10422 // These values come from draft-ietf-quic-v2 Appendix A.4.
10423 uint8_t retry_packet_rfcv2[] = {
martindukea2cb68a2022-12-12 17:24:39 -080010424 0xcf, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10425 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xc8, 0x64, 0x6c, 0xe8,
10426 0xbf, 0xe3, 0x39, 0x52, 0xd9, 0x55, 0x54, 0x36, 0x65, 0xdc, 0xc7, 0xb6};
Bence Békybac04052022-04-07 15:44:29 -040010427 // These values come from RFC9001 Appendix A.4.
10428 uint8_t retry_packet_rfcv1[] = {
10429 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10430 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba,
10431 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba};
10432 uint8_t retry_packet29[] = {
10433 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10434 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10435 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
10436
10437 uint8_t* retry_packet;
10438 size_t retry_packet_length;
martinduke88918ac2023-06-02 10:44:08 -070010439 if (version() == ParsedQuicVersion::RFCv2()) {
Bence Békybac04052022-04-07 15:44:29 -040010440 retry_packet = retry_packet_rfcv2;
10441 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv2);
10442 } else if (version() == ParsedQuicVersion::RFCv1()) {
10443 retry_packet = retry_packet_rfcv1;
10444 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv1);
10445 } else if (version() == ParsedQuicVersion::Draft29()) {
10446 retry_packet = retry_packet29;
10447 retry_packet_length = ABSL_ARRAYSIZE(retry_packet29);
10448 } else {
10449 // TODO(dschinazi) generate retry packets for all versions once we have
10450 // server-side support for generating these programmatically.
10451 return;
10452 }
10453
10454 uint8_t original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10455 0x3e, 0x51, 0x57, 0x08};
10456 uint8_t new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10457 0x2a, 0x42, 0x62, 0xb5};
10458 uint8_t retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10459
10460 QuicConnectionId original_connection_id(
10461 reinterpret_cast<char*>(original_connection_id_bytes),
10462 ABSL_ARRAYSIZE(original_connection_id_bytes));
10463 QuicConnectionId new_connection_id(
10464 reinterpret_cast<char*>(new_connection_id_bytes),
10465 ABSL_ARRAYSIZE(new_connection_id_bytes));
10466
10467 std::string retry_token(reinterpret_cast<char*>(retry_token_bytes),
10468 ABSL_ARRAYSIZE(retry_token_bytes));
10469
10470 if (invalid_retry_tag) {
10471 // Flip the last bit of the retry packet to prevent the integrity tag
10472 // from validating correctly.
10473 retry_packet[retry_packet_length - 1] ^= 1;
10474 }
10475
10476 QuicConnectionId config_original_connection_id = original_connection_id;
10477 if (wrong_original_id_in_config) {
10478 // Flip the first bit of the connection ID.
10479 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10480 config_original_connection_id.mutable_data()[0] ^= 0x80;
10481 }
10482 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10483 if (wrong_retry_id_in_config) {
10484 // Flip the first bit of the connection ID.
10485 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10486 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10487 }
10488
10489 // Make sure the connection uses the connection ID from the test vectors,
10490 QuicConnectionPeer::SetServerConnectionId(&connection_,
10491 original_connection_id);
10492 // Make sure our fake framer has the new post-retry INITIAL keys so that any
10493 // retransmission triggered by retry can be decrypted.
10494 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10495
10496 // Process the RETRY packet.
10497 connection_.ProcessUdpPacket(
10498 kSelfAddress, kPeerAddress,
10499 QuicReceivedPacket(reinterpret_cast<char*>(retry_packet),
10500 retry_packet_length, clock_.Now()));
10501
10502 if (invalid_retry_tag) {
10503 // Make sure we refuse to process a RETRY with invalid tag.
10504 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10505 EXPECT_EQ(connection_.connection_id(), original_connection_id);
10506 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
10507 QuicConnectionPeer::GetPacketCreator(&connection_))
10508 .empty());
10509 return;
10510 }
10511
10512 // Make sure we correctly parsed the RETRY.
10513 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10514 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10515 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10516 QuicConnectionPeer::GetPacketCreator(&connection_)),
10517 retry_token);
10518
10519 // Test validating the original_connection_id from the config.
10520 QuicConfig received_config;
10521 QuicConfigPeer::SetNegotiated(&received_config, true);
10522 if (connection_.version().UsesTls()) {
10523 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10524 &received_config, connection_.connection_id());
10525 if (!missing_retry_id_in_config) {
10526 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10527 &received_config, config_retry_source_connection_id);
10528 }
10529 }
10530 if (!missing_original_id_in_config) {
10531 QuicConfigPeer::SetReceivedOriginalConnectionId(
10532 &received_config, config_original_connection_id);
10533 }
10534
10535 if (missing_original_id_in_config || wrong_original_id_in_config ||
10536 missing_retry_id_in_config || wrong_retry_id_in_config) {
10537 EXPECT_CALL(visitor_,
10538 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10539 .Times(1);
10540 } else {
10541 EXPECT_CALL(visitor_,
10542 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10543 .Times(0);
10544 }
10545 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
martindukeeaf27602024-11-12 14:34:40 -080010546 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillRepeatedly(Return(false));
10547 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillRepeatedly(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040010548 connection_.SetFromConfig(received_config);
10549 if (missing_original_id_in_config || wrong_original_id_in_config ||
10550 missing_retry_id_in_config || wrong_retry_id_in_config) {
10551 ASSERT_FALSE(connection_.connected());
10552 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10553 } else {
10554 EXPECT_TRUE(connection_.connected());
10555 }
10556}
10557
fayangc0123f72024-09-22 16:03:58 -070010558TEST_P(QuicConnectionTest, FixTimeoutsClient) {
10559 if (!connection_.version().UsesTls()) {
10560 return;
10561 }
10562 set_perspective(Perspective::IS_CLIENT);
10563 if (GetQuicReloadableFlag(quic_fix_timeouts)) {
10564 EXPECT_CALL(visitor_, GetHandshakeState())
10565 .WillRepeatedly(Return(HANDSHAKE_START));
10566 }
10567 QuicConfig config;
10568 QuicTagVector connection_options;
10569 connection_options.push_back(kFTOE);
10570 config.SetConnectionOptionsToSend(connection_options);
10571 QuicConfigPeer::SetNegotiated(&config, true);
10572 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
10573 connection_.connection_id());
10574 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10575 &config, connection_.connection_id());
10576
10577 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
martindukeeaf27602024-11-12 14:34:40 -080010578 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
10579 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
fayangc0123f72024-09-22 16:03:58 -070010580 connection_.SetFromConfig(config);
10581 QuicIdleNetworkDetector& idle_network_detector =
10582 QuicConnectionPeer::GetIdleNetworkDetector(&connection_);
10583 if (GetQuicReloadableFlag(quic_fix_timeouts)) {
10584 // Handshake timeout has not been removed yet.
10585 EXPECT_NE(idle_network_detector.handshake_timeout(),
10586 QuicTime::Delta::Infinite());
10587 } else {
10588 // Handshake timeout has been set to infinite.
10589 EXPECT_EQ(idle_network_detector.handshake_timeout(),
10590 QuicTime::Delta::Infinite());
10591 }
10592}
10593
10594TEST_P(QuicConnectionTest, FixTimeoutsServer) {
10595 if (!connection_.version().UsesTls()) {
10596 return;
10597 }
10598 set_perspective(Perspective::IS_SERVER);
10599 if (GetQuicReloadableFlag(quic_fix_timeouts)) {
10600 EXPECT_CALL(visitor_, GetHandshakeState())
10601 .WillRepeatedly(Return(HANDSHAKE_START));
10602 }
10603 QuicConfig config;
10604 quic::QuicTagVector initial_received_options;
10605 initial_received_options.push_back(quic::kFTOE);
10606 ASSERT_TRUE(
10607 config.SetInitialReceivedConnectionOptions(initial_received_options));
10608 QuicConfigPeer::SetNegotiated(&config, true);
10609 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
10610 connection_.connection_id());
10611 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
10612 QuicConnectionId());
10613
10614 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
martindukeeaf27602024-11-12 14:34:40 -080010615 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
10616 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
fayangc0123f72024-09-22 16:03:58 -070010617 connection_.SetFromConfig(config);
10618 QuicIdleNetworkDetector& idle_network_detector =
10619 QuicConnectionPeer::GetIdleNetworkDetector(&connection_);
10620 if (GetQuicReloadableFlag(quic_fix_timeouts)) {
10621 // Handshake timeout has not been removed yet.
10622 EXPECT_NE(idle_network_detector.handshake_timeout(),
10623 QuicTime::Delta::Infinite());
10624 } else {
10625 // Handshake timeout has been set to infinite.
10626 EXPECT_EQ(idle_network_detector.handshake_timeout(),
10627 QuicTime::Delta::Infinite());
10628 }
10629}
10630
Bence Békybac04052022-04-07 15:44:29 -040010631TEST_P(QuicConnectionTest, ClientParsesRetry) {
10632 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10633 /*missing_original_id_in_config=*/false,
10634 /*wrong_original_id_in_config=*/false,
10635 /*missing_retry_id_in_config=*/false,
10636 /*wrong_retry_id_in_config=*/false);
10637}
10638
10639TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
10640 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10641 /*missing_original_id_in_config=*/false,
10642 /*wrong_original_id_in_config=*/false,
10643 /*missing_retry_id_in_config=*/false,
10644 /*wrong_retry_id_in_config=*/false);
10645}
10646
10647TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
10648 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10649 /*missing_original_id_in_config=*/true,
10650 /*wrong_original_id_in_config=*/false,
10651 /*missing_retry_id_in_config=*/false,
10652 /*wrong_retry_id_in_config=*/false);
10653}
10654
10655TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
10656 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10657 /*missing_original_id_in_config=*/false,
10658 /*wrong_original_id_in_config=*/true,
10659 /*missing_retry_id_in_config=*/false,
10660 /*wrong_retry_id_in_config=*/false);
10661}
10662
10663TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10664 if (!connection_.version().UsesTls()) {
10665 // Versions that do not authenticate connection IDs never send the
10666 // retry_source_connection_id transport parameter.
10667 return;
10668 }
10669 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10670 /*missing_original_id_in_config=*/false,
10671 /*wrong_original_id_in_config=*/false,
10672 /*missing_retry_id_in_config=*/true,
10673 /*wrong_retry_id_in_config=*/false);
10674}
10675
10676TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10677 if (!connection_.version().UsesTls()) {
10678 // Versions that do not authenticate connection IDs never send the
10679 // retry_source_connection_id transport parameter.
10680 return;
10681 }
10682 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10683 /*missing_original_id_in_config=*/false,
10684 /*wrong_original_id_in_config=*/false,
10685 /*missing_retry_id_in_config=*/false,
10686 /*wrong_retry_id_in_config=*/true);
10687}
10688
10689TEST_P(QuicConnectionTest, ClientRetransmitsInitialPacketsOnRetry) {
10690 if (!connection_.version().HasIetfQuicFrames()) {
10691 // TestClientRetryHandling() currently only supports IETF draft versions.
10692 return;
10693 }
10694 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10695
10696 connection_.SendCryptoStreamData();
10697
10698 EXPECT_EQ(1u, writer_->packets_write_attempts());
10699 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10700 /*missing_original_id_in_config=*/false,
10701 /*wrong_original_id_in_config=*/false,
10702 /*missing_retry_id_in_config=*/false,
10703 /*wrong_retry_id_in_config=*/false);
10704
10705 // Verify that initial data is retransmitted immediately after receiving
10706 // RETRY.
10707 if (GetParam().ack_response == AckResponse::kImmediate) {
10708 EXPECT_EQ(2u, writer_->packets_write_attempts());
dschinazif16e5a92024-12-06 15:40:18 -080010709 EXPECT_LE(1u, writer_->framer()->crypto_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040010710 }
10711}
10712
10713TEST_P(QuicConnectionTest, NoInitialPacketsRetransmissionOnInvalidRetry) {
10714 if (!connection_.version().HasIetfQuicFrames()) {
10715 return;
10716 }
10717 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10718
10719 connection_.SendCryptoStreamData();
10720
10721 EXPECT_EQ(1u, writer_->packets_write_attempts());
10722 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10723 /*missing_original_id_in_config=*/false,
10724 /*wrong_original_id_in_config=*/false,
10725 /*missing_retry_id_in_config=*/false,
10726 /*wrong_retry_id_in_config=*/false);
10727
10728 EXPECT_EQ(1u, writer_->packets_write_attempts());
10729}
10730
10731TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
10732 if (!connection_.version().UsesTls()) {
10733 // QUIC+TLS is required to transmit connection ID transport parameters.
10734 return;
10735 }
10736 if (connection_.version().UsesTls()) {
10737 // Versions that authenticate connection IDs always send the
10738 // original_destination_connection_id transport parameter.
10739 return;
10740 }
10741 // Make sure that receiving the original_destination_connection_id transport
10742 // parameter fails the handshake when no RETRY packet was received before it.
10743 QuicConfig received_config;
10744 QuicConfigPeer::SetNegotiated(&received_config, true);
10745 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10746 TestConnectionId(0x12345));
10747 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
martindukeeaf27602024-11-12 14:34:40 -080010748 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillRepeatedly(Return(false));
10749 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillRepeatedly(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040010750 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10751 .Times(1);
10752 connection_.SetFromConfig(received_config);
10753 EXPECT_FALSE(connection_.connected());
10754 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10755}
10756
10757TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10758 if (!connection_.version().UsesTls()) {
10759 // Versions that do not authenticate connection IDs never send the
10760 // retry_source_connection_id transport parameter.
10761 return;
10762 }
10763 // Make sure that receiving the retry_source_connection_id transport parameter
10764 // fails the handshake when no RETRY packet was received before it.
10765 QuicConfig received_config;
10766 QuicConfigPeer::SetNegotiated(&received_config, true);
10767 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10768 TestConnectionId(0x12345));
10769 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
martindukeeaf27602024-11-12 14:34:40 -080010770 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillRepeatedly(Return(false));
10771 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillRepeatedly(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040010772 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10773 .Times(1);
10774 connection_.SetFromConfig(received_config);
10775 EXPECT_FALSE(connection_.connected());
10776 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10777}
10778
10779// Regression test for http://crbug/1047977
10780TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10781 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10782 return;
10783 }
10784 // Received frame causes connection close.
10785 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10786 .WillOnce(InvokeWithoutArgs([this]() {
10787 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10788 connection_.CloseConnection(
10789 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10790 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10791 return true;
10792 }));
10793 QuicFrames frames;
10794 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10795 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10796 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10797}
10798
10799TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10800 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10801 return;
10802 }
10803 // Received frame causes connection close.
10804 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10805 .WillOnce(InvokeWithoutArgs([this]() {
10806 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10807 connection_.CloseConnection(
10808 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10809 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10810 return true;
10811 }));
10812 QuicFrames frames;
10813 frames.push_back(
10814 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10815 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10816 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10817}
10818
10819TEST_P(QuicConnectionTest,
10820 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10821 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10822 return;
10823 }
10824 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10825 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10826 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10827 // Receives packet 1000 in initial data.
10828 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10829 // Receives packet 2000 in application data.
10830 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10831 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10832 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10833 connection_.CloseConnection(
10834 kQuicErrorCode, "Some random error message",
10835 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10836
10837 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10838
10839 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10840 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10841 // Verify ack is bundled.
10842 EXPECT_EQ(1u, writer_->ack_frames().size());
10843
10844 if (!connection_.version().CanSendCoalescedPackets()) {
10845 // Each connection close packet should be sent in distinct UDP packets.
10846 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10847 writer_->connection_close_packets());
10848 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10849 writer_->packets_write_attempts());
10850 return;
10851 }
10852
10853 // A single UDP packet should be sent with multiple connection close packets
10854 // coalesced together.
10855 EXPECT_EQ(1u, writer_->packets_write_attempts());
10856
10857 // Only the first packet has been processed yet.
10858 EXPECT_EQ(1u, writer_->connection_close_packets());
10859
10860 // ProcessPacket resets the visitor and frees the coalesced packet.
10861 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10862 auto packet = writer_->coalesced_packet()->Clone();
10863 writer_->framer()->ProcessPacket(*packet);
10864 EXPECT_EQ(1u, writer_->connection_close_packets());
10865 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10866 // Verify ack is bundled.
10867 EXPECT_EQ(1u, writer_->ack_frames().size());
10868 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10869}
10870
10871// Regression test for b/151220135.
10872TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
Bence Békybac04052022-04-07 15:44:29 -040010873 QuicConfig config;
10874 QuicTagVector connection_options;
10875 connection_options.push_back(kPTOS);
10876 connection_options.push_back(k1PTO);
10877 config.SetConnectionOptionsToSend(connection_options);
10878 if (connection_.version().UsesTls()) {
10879 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10880 &config, kMaxAcceptedDatagramFrameSize);
10881 }
10882 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080010883 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
10884 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040010885 connection_.SetFromConfig(config);
10886 connection_.OnHandshakeComplete();
10887 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10888
10889 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10890 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10891
10892 // PTO fires, verify a PING packet gets sent because there is no data to
10893 // send.
10894 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10895 connection_.GetRetransmissionAlarm()->Fire();
10896 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10897 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10898 EXPECT_EQ(1u, writer_->ping_frames().size());
10899}
10900
10901// Regression test for b/155757133
10902TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10903 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10904 return;
10905 }
10906 const size_t kMinRttMs = 40;
10907 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10908 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10909 QuicTime::Delta::Zero(), QuicTime::Zero());
10910 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -070010911 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040010912 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10913 // Discard INITIAL key.
10914 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10915 connection_.NeuterUnencryptedPackets();
10916 EXPECT_CALL(visitor_, GetHandshakeState())
10917 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10918
10919 ProcessPacket(2);
10920 ProcessPacket(3);
10921 ProcessPacket(4);
10922 // Process a packet containing stream frame followed by ACK of packets 1.
10923 QuicFrames frames;
10924 frames.push_back(QuicFrame(QuicStreamFrame(
10925 QuicUtils::GetFirstBidirectionalStreamId(
10926 connection_.version().transport_version, Perspective::IS_CLIENT),
10927 false, 0u, absl::string_view())));
10928 QuicAckFrame ack_frame = InitAckFrame(1);
10929 frames.push_back(QuicFrame(&ack_frame));
10930 // Receiving stream frame causes something to send.
10931 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10932 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
10933 // Verify now the queued ACK contains packet number 2.
10934 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10935 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10936 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10937 }));
10938 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10939 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10940}
10941
martinduke9e0811c2022-12-08 20:35:57 -080010942TEST_P(QuicConnectionTest, DoNotExtendIdleTimeOnUndecryptablePackets) {
Bence Békybac04052022-04-07 15:44:29 -040010943 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080010944 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
10945 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040010946 QuicConfig config;
10947 connection_.SetFromConfig(config);
10948 // Subtract a second from the idle timeout on the client side.
10949 QuicTime initial_deadline =
10950 clock_.ApproximateNow() +
10951 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10952 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10953
10954 // Received an undecryptable packet.
10955 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080010956 peer_framer_.SetEncrypter(
10957 ENCRYPTION_FORWARD_SECURE,
10958 std::make_unique<quic::NullEncrypter>(Perspective::IS_CLIENT));
Bence Békybac04052022-04-07 15:44:29 -040010959 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10960 // Verify deadline does not get extended.
10961 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10962 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10963 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10964 clock_.AdvanceTime(delay);
10965 connection_.GetTimeoutAlarm()->Fire();
10966 // Verify connection gets closed.
10967 EXPECT_FALSE(connection_.connected());
10968}
10969
10970TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10971 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10972 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10973
10974 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10975 notifier_.WriteOrBufferWindowUpate(0, 0);
10976 }));
10977 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10978 ProcessDataPacket(1);
10979 // Verify ACK is bundled with WINDOW_UPDATE.
10980 EXPECT_FALSE(writer_->ack_frames().empty());
10981 EXPECT_FALSE(connection_.HasPendingAcks());
10982}
10983
10984TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10985 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10986 return;
10987 }
10988 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10989 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10990 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10991 }
10992 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010993 // Receives packet 1000 in initial data.
10994 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10995 EXPECT_TRUE(connection_.HasPendingAcks());
10996
martinduke9e0811c2022-12-08 20:35:57 -080010997 peer_framer_.SetEncrypter(
10998 ENCRYPTION_ZERO_RTT,
10999 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040011000 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080011001 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040011002 // Receives packet 1000 in application data.
11003 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
11004 EXPECT_TRUE(connection_.HasPendingAcks());
11005 // Verify ACK deadline does not change.
11006 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
11007 connection_.GetAckAlarm()->deadline());
11008
11009 // Ack alarm fires early.
11010 // Verify the earliest ACK is flushed.
11011 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11012 connection_.GetAckAlarm()->Fire();
11013 EXPECT_TRUE(connection_.HasPendingAcks());
11014 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
11015 connection_.GetAckAlarm()->deadline());
11016}
11017
11018TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
11019 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11020 return;
11021 }
11022 QuicConfig config;
11023 QuicTagVector connection_options;
11024 connection_options.push_back(kCBHD);
11025 config.SetConnectionOptionsToSend(connection_options);
11026 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011027 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11028 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011029 connection_.SetFromConfig(config);
11030 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080011031 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
11032 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -040011033 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11034 // Send stream data.
11035 SendStreamDataToPeer(
11036 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11037 0, FIN, nullptr);
11038 // Verify blackhole detection is in progress.
11039 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11040}
11041
11042TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
11043 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11044 return;
11045 }
11046 set_perspective(Perspective::IS_SERVER);
11047 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11048 if (version().SupportsAntiAmplificationLimit()) {
11049 QuicConnectionPeer::SetAddressValidated(&connection_);
11050 }
11051 QuicConfig config;
11052 QuicTagVector connection_options;
11053 connection_options.push_back(kCBHD);
11054 config.SetInitialReceivedConnectionOptions(connection_options);
11055 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011056 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11057 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011058 connection_.SetFromConfig(config);
11059 EXPECT_CALL(visitor_, GetHandshakeState())
11060 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11061 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11062 // Send stream data.
11063 SendStreamDataToPeer(
11064 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11065 0, FIN, nullptr);
11066 // Verify blackhole detection is disabled.
11067 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
11068}
11069
Bence Békybac04052022-04-07 15:44:29 -040011070// Regresstion test for b/158491591.
11071TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
11072 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11073 return;
11074 }
Bence Békybac04052022-04-07 15:44:29 -040011075 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080011076 connection_.SetEncrypter(
11077 ENCRYPTION_HANDSHAKE,
11078 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011079 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11080 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11081 QuicConfig config;
11082 QuicTagVector connection_options;
11083 connection_options.push_back(k5RTO);
11084 config.SetConnectionOptionsToSend(connection_options);
11085 QuicConfigPeer::SetNegotiated(&config, true);
fayang59e518a2022-11-29 11:16:45 -080011086 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
11087 GetQuicReloadableFlag(
11088 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040011089 EXPECT_CALL(visitor_, GetHandshakeState())
11090 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11091 }
11092 if (connection_.version().UsesTls()) {
11093 QuicConfigPeer::SetReceivedOriginalConnectionId(
11094 &config, connection_.connection_id());
11095 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11096 &config, connection_.connection_id());
11097 }
11098 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011099 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11100 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011101 connection_.SetFromConfig(config);
11102
11103 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
fayang59e518a2022-11-29 11:16:45 -080011104 if (GetQuicReloadableFlag(
11105 quic_no_path_degrading_before_handshake_confirmed)) {
11106 // No blackhole detection before handshake confirmed.
11107 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11108 } else {
11109 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11110 }
Bence Békybac04052022-04-07 15:44:29 -040011111 // Discard handshake keys.
fayang59e518a2022-11-29 11:16:45 -080011112 EXPECT_CALL(visitor_, GetHandshakeState())
11113 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040011114 connection_.OnHandshakeComplete();
fayang59e518a2022-11-29 11:16:45 -080011115 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
11116 GetQuicReloadableFlag(
11117 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040011118 // Verify blackhole detection stops.
11119 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11120 } else {
11121 // Problematic: although there is nothing in flight, blackhole detection is
11122 // still in progress.
11123 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11124 }
11125}
11126
11127TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
11128 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11129 return;
11130 }
11131 // SetFromConfig is always called after construction from InitializeSession.
11132 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11133 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011134 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11135 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011136 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
11137 QuicConfig config;
11138 connection_.SetFromConfig(config);
11139 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11140 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040011141
martinduke9e0811c2022-12-08 20:35:57 -080011142 peer_framer_.SetEncrypter(
11143 ENCRYPTION_HANDSHAKE,
11144 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
11145 peer_framer_.SetEncrypter(
11146 ENCRYPTION_FORWARD_SECURE,
11147 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040011148
11149 for (uint64_t i = 1; i <= 3; ++i) {
11150 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11151 }
11152 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
11153 for (uint64_t j = 5; j <= 7; ++j) {
11154 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11155 }
11156 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11157 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11158 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080011159 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011160 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080011161 connection_.SetEncrypter(
11162 ENCRYPTION_HANDSHAKE,
11163 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011164 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11165 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
11166 if (!VersionHasIetfQuicFrames(version().transport_version)) {
11167 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
11168 }
11169 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11170 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11171
martinduke9e0811c2022-12-08 20:35:57 -080011172 SetDecrypter(
11173 ENCRYPTION_FORWARD_SECURE,
11174 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040011175 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11176 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080011177 connection_.SetEncrypter(
11178 ENCRYPTION_FORWARD_SECURE,
11179 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040011180 // Verify the 1-RTT packet gets processed.
11181 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11182 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
11183 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11184}
11185
11186TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
11187 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11188 return;
11189 }
11190 set_perspective(Perspective::IS_SERVER);
11191 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11192 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11193 }
11194 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040011195 // Receives packet 1000 in initial data.
11196 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11197 EXPECT_TRUE(connection_.HasPendingAcks());
11198
Bence Békybac04052022-04-07 15:44:29 -040011199 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11200 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11201 QuicTime expected_pto_time =
11202 connection_.sent_packet_manager().GetRetransmissionTime();
11203
11204 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11205 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11206 std::make_unique<TaggingEncrypter>(0x02));
11207 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11208 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11209 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11210 // Verify PTO time does not change.
11211 EXPECT_EQ(expected_pto_time,
11212 connection_.sent_packet_manager().GetRetransmissionTime());
11213
11214 // Receives packet 1001 in initial data.
11215 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
11216 EXPECT_TRUE(connection_.HasPendingAcks());
11217 // Receives packet 1002 in initial data.
11218 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
11219 EXPECT_FALSE(writer_->ack_frames().empty());
11220 // Verify CRYPTO frame is bundled with INITIAL ACK.
11221 EXPECT_FALSE(writer_->crypto_frames().empty());
11222 // Verify PTO time changes.
11223 EXPECT_NE(expected_pto_time,
11224 connection_.sent_packet_manager().GetRetransmissionTime());
11225}
11226
11227TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
11228 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11229 return;
11230 }
11231 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
11232 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11233 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11234 }
11235 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
martinduke9e0811c2022-12-08 20:35:57 -080011236 connection_.SetEncrypter(
11237 ENCRYPTION_HANDSHAKE,
11238 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011239 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11240 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080011241 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
11242 peer_framer_.SetEncrypter(
11243 ENCRYPTION_HANDSHAKE,
11244 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011245 // Receives packet 1000 in handshake data.
11246 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
11247 EXPECT_TRUE(connection_.HasPendingAcks());
11248 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11249 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11250
11251 // Receives packet 1001 in handshake data.
11252 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
11253 EXPECT_TRUE(connection_.HasPendingAcks());
11254 // Receives packet 1002 in handshake data.
11255 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
11256 EXPECT_FALSE(writer_->ack_frames().empty());
11257 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
11258 EXPECT_FALSE(writer_->crypto_frames().empty());
11259}
11260
11261// Regresstion test for b/156232673.
11262TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
11263 if (!connection_.version().CanSendCoalescedPackets()) {
11264 return;
11265 }
11266 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11267 {
11268 QuicConnection::ScopedPacketFlusher flusher(&connection_);
martinduke9e0811c2022-12-08 20:35:57 -080011269 connection_.SetEncrypter(
11270 ENCRYPTION_HANDSHAKE,
11271 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
11272 connection_.SetEncrypter(
11273 ENCRYPTION_FORWARD_SECURE,
11274 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040011275 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11276 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
11277 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11278 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
11279 // Verify soft max packet length gets resumed and handshake packet gets
11280 // successfully sent.
11281 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
11282 }
11283}
11284
11285// Regression test for b/160790422.
11286TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
11287 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11288 return;
11289 }
11290 set_perspective(Perspective::IS_SERVER);
11291 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11292 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11293 }
11294 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040011295 // Receives packet 1000 in initial data.
11296 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11297 EXPECT_TRUE(connection_.HasPendingAcks());
11298
Bence Békybac04052022-04-07 15:44:29 -040011299 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11300 // Send INITIAL 1.
11301 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11302 QuicTime expected_pto_time =
11303 connection_.sent_packet_manager().GetRetransmissionTime();
11304
11305 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martinduke9e0811c2022-12-08 20:35:57 -080011306 connection_.SetEncrypter(
11307 ENCRYPTION_HANDSHAKE,
11308 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011309 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11310 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11311 // Send HANDSHAKE 2 and 3.
11312 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11313 connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
11314 // Verify PTO time does not change.
11315 EXPECT_EQ(expected_pto_time,
11316 connection_.sent_packet_manager().GetRetransmissionTime());
11317
11318 // Receives ACK for HANDSHAKE 2.
11319 QuicFrames frames;
11320 auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
11321 frames.push_back(QuicFrame(&ack_frame));
martindukeba002452023-03-21 08:10:46 -070011322 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040011323 ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
11324 // Discard INITIAL key.
11325 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11326 connection_.NeuterUnencryptedPackets();
11327 // Receives PING from peer.
11328 frames.clear();
11329 frames.push_back(QuicFrame(QuicPingFrame()));
11330 frames.push_back(QuicFrame(QuicPaddingFrame(3)));
11331 ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
11332 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
11333 connection_.GetAckAlarm()->deadline());
11334 // Fire ACK alarm.
11335 clock_.AdvanceTime(kAlarmGranularity);
11336 connection_.GetAckAlarm()->Fire();
11337 EXPECT_FALSE(writer_->ack_frames().empty());
11338 // Verify handshake data gets retransmitted early.
11339 EXPECT_FALSE(writer_->crypto_frames().empty());
11340}
11341
11342// Regression test for b/161228202
11343TEST_P(QuicConnectionTest, InflatedRttSample) {
11344 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11345 return;
11346 }
11347 // 30ms RTT.
11348 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
11349 set_perspective(Perspective::IS_SERVER);
11350 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
Bence Békybac04052022-04-07 15:44:29 -040011351 // Receives packet 1000 in initial data.
11352 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11353 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11354 }
11355 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11356 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11357 EXPECT_TRUE(connection_.HasPendingAcks());
11358
Bence Békybac04052022-04-07 15:44:29 -040011359 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11360 // Send INITIAL 1.
11361 std::string initial_crypto_data(512, 'a');
11362 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11363 ENCRYPTION_INITIAL);
11364 ASSERT_TRUE(connection_.sent_packet_manager()
11365 .GetRetransmissionTime()
11366 .IsInitialized());
11367 QuicTime::Delta pto_timeout =
11368 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11369 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011370 connection_.SetEncrypter(
11371 ENCRYPTION_HANDSHAKE,
11372 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011373 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11374 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11375 std::string handshake_crypto_data(1024, 'a');
11376 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11377 ENCRYPTION_HANDSHAKE);
11378
11379 // INITIAL 1 gets lost and PTO fires.
11380 clock_.AdvanceTime(pto_timeout);
11381 connection_.GetRetransmissionAlarm()->Fire();
11382
11383 clock_.AdvanceTime(kTestRTT);
11384 // Assume retransmitted INITIAL gets received.
11385 QuicFrames frames;
11386 auto ack_frame = InitAckFrame({{QuicPacketNumber(4), QuicPacketNumber(5)}});
11387 frames.push_back(QuicFrame(&ack_frame));
martindukeba002452023-03-21 08:10:46 -070011388 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040011389 .Times(AnyNumber());
11390 ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
11391 EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
11392 // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
11393 frames.clear();
11394 // HANDSHAKE 5 is also processed.
11395 QuicAckFrame ack_frame2 =
11396 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
11397 {QuicPacketNumber(5), QuicPacketNumber(6)}});
11398 ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
11399 frames.push_back(QuicFrame(&ack_frame2));
11400 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
11401 // Verify RTT inflation gets mitigated.
11402 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
11403}
11404
11405// Regression test for b/161228202
martinduke9e0811c2022-12-08 20:35:57 -080011406TEST_P(QuicConnectionTest, CoalescingPacketCausesInfiniteLoop) {
Bence Békybac04052022-04-07 15:44:29 -040011407 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11408 return;
11409 }
11410 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040011411 // Receives packet 1000 in initial data.
11412 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11413 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11414 }
11415 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11416
11417 // Set anti amplification factor to 2, such that RetransmitDataOfSpaceIfAny
11418 // makes no forward progress and causes infinite loop.
birenroyef686222022-09-12 11:34:34 -070011419 SetQuicFlag(quic_anti_amplification_factor, 2);
Bence Békybac04052022-04-07 15:44:29 -040011420
11421 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11422 EXPECT_TRUE(connection_.HasPendingAcks());
11423
Bence Békybac04052022-04-07 15:44:29 -040011424 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11425 // Send INITIAL 1.
11426 std::string initial_crypto_data(512, 'a');
11427 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11428 ENCRYPTION_INITIAL);
11429 ASSERT_TRUE(connection_.sent_packet_manager()
11430 .GetRetransmissionTime()
11431 .IsInitialized());
11432 QuicTime::Delta pto_timeout =
11433 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11434 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011435 connection_.SetEncrypter(
11436 ENCRYPTION_HANDSHAKE,
11437 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011438 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11439 // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
11440 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11441 std::string handshake_crypto_data(1024, 'a');
11442 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11443 ENCRYPTION_HANDSHAKE);
11444
11445 // INITIAL 1 gets lost and PTO fires.
11446 clock_.AdvanceTime(pto_timeout);
11447 connection_.GetRetransmissionAlarm()->Fire();
11448}
11449
11450TEST_P(QuicConnectionTest, ClientAckDelayForAsyncPacketProcessing) {
11451 if (!version().HasIetfQuicFrames()) {
11452 return;
11453 }
11454 // SetFromConfig is always called after construction from InitializeSession.
11455 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11456 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011457 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11458 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011459 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11460 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11461 connection_.NeuterUnencryptedPackets();
11462 }));
11463 QuicConfig config;
11464 connection_.SetFromConfig(config);
11465 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080011466 peer_framer_.SetEncrypter(
11467 ENCRYPTION_HANDSHAKE,
11468 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011469 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11470
11471 // Received undecryptable HANDSHAKE 2.
11472 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11473 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11474 // Received INITIAL 4 (which is retransmission of INITIAL 1) after 100ms.
11475 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
11476 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL);
11477 // Generate HANDSHAKE key.
11478 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080011479 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011480 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080011481 connection_.SetEncrypter(
11482 ENCRYPTION_HANDSHAKE,
11483 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011484 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11485 // Verify HANDSHAKE packet gets processed.
fayangfea655c2022-05-17 08:19:12 -070011486 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -040011487 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
fayangfea655c2022-05-17 08:19:12 -070011488 // Verify immediate ACK has been sent out when flush went out of scope.
11489 ASSERT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -040011490 ASSERT_FALSE(writer_->ack_frames().empty());
fayangfea655c2022-05-17 08:19:12 -070011491 // Verify the ack_delay_time in the sent HANDSHAKE ACK frame is 100ms.
11492 EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
Bence Békybac04052022-04-07 15:44:29 -040011493 writer_->ack_frames()[0].ack_delay_time);
11494 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
11495}
11496
11497TEST_P(QuicConnectionTest, TestingLiveness) {
11498 const size_t kMinRttMs = 40;
11499 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11500 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11501 QuicTime::Delta::Zero(), QuicTime::Zero());
11502 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011503 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11504 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011505 QuicConfig config;
11506
11507 CryptoHandshakeMessage msg;
11508 std::string error_details;
11509 QuicConfig client_config;
11510 client_config.SetInitialStreamFlowControlWindowToSend(
11511 kInitialStreamFlowControlWindowForTest);
11512 client_config.SetInitialSessionFlowControlWindowToSend(
11513 kInitialSessionFlowControlWindowForTest);
11514 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11515 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11516 const QuicErrorCode error =
11517 config.ProcessPeerHello(msg, CLIENT, &error_details);
11518 EXPECT_THAT(error, IsQuicNoError());
11519
11520 if (connection_.version().UsesTls()) {
11521 QuicConfigPeer::SetReceivedOriginalConnectionId(
11522 &config, connection_.connection_id());
11523 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11524 &config, connection_.connection_id());
11525 }
11526
11527 connection_.SetFromConfig(config);
11528 connection_.OnHandshakeComplete();
11529 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11530 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11531 EXPECT_FALSE(connection_.MaybeTestLiveness());
11532
haoyuewang7b43efb2022-04-20 16:26:03 -070011533 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040011534 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11535 // Advance time to near the idle timeout.
11536 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11538 EXPECT_TRUE(connection_.MaybeTestLiveness());
11539 // Verify idle deadline does not change.
haoyuewang7b43efb2022-04-20 16:26:03 -070011540 EXPECT_EQ(deadline, QuicConnectionPeer::GetIdleNetworkDeadline(&connection_));
Bence Békybac04052022-04-07 15:44:29 -040011541}
11542
fayang5783c332022-12-14 09:30:25 -080011543TEST_P(QuicConnectionTest, DisableLivenessTesting) {
11544 const size_t kMinRttMs = 40;
11545 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11546 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11547 QuicTime::Delta::Zero(), QuicTime::Zero());
11548 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011549 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11550 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
fayang5783c332022-12-14 09:30:25 -080011551 QuicConfig config;
11552
11553 CryptoHandshakeMessage msg;
11554 std::string error_details;
11555 QuicConfig client_config;
11556 client_config.SetInitialStreamFlowControlWindowToSend(
11557 kInitialStreamFlowControlWindowForTest);
11558 client_config.SetInitialSessionFlowControlWindowToSend(
11559 kInitialSessionFlowControlWindowForTest);
11560 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11561 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11562 const QuicErrorCode error =
11563 config.ProcessPeerHello(msg, CLIENT, &error_details);
11564 EXPECT_THAT(error, IsQuicNoError());
11565
11566 if (connection_.version().UsesTls()) {
11567 QuicConfigPeer::SetReceivedOriginalConnectionId(
11568 &config, connection_.connection_id());
11569 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11570 &config, connection_.connection_id());
11571 }
11572
11573 connection_.SetFromConfig(config);
11574 connection_.OnHandshakeComplete();
11575 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11576 connection_.DisableLivenessTesting();
11577 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11578 EXPECT_FALSE(connection_.MaybeTestLiveness());
11579
11580 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
11581 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11582 // Advance time to near the idle timeout.
11583 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11584 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11585 EXPECT_FALSE(connection_.MaybeTestLiveness());
11586}
11587
Bence Békybac04052022-04-07 15:44:29 -040011588TEST_P(QuicConnectionTest, SilentIdleTimeout) {
11589 set_perspective(Perspective::IS_SERVER);
11590 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11591 if (version().SupportsAntiAmplificationLimit()) {
11592 QuicConnectionPeer::SetAddressValidated(&connection_);
11593 }
11594
11595 QuicConfig config;
11596 QuicConfigPeer::SetNegotiated(&config, true);
11597 if (connection_.version().UsesTls()) {
11598 QuicConfigPeer::SetReceivedOriginalConnectionId(
11599 &config, connection_.connection_id());
11600 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
11601 QuicConnectionId());
11602 }
11603 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011604 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11605 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011606 connection_.SetFromConfig(config);
11607
11608 EXPECT_TRUE(connection_.connected());
11609 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11610
11611 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
11612 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
11613 }
11614 EXPECT_CALL(visitor_,
11615 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11616 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11617 connection_.GetTimeoutAlarm()->Fire();
11618 // Verify the connection close packets get serialized and added to
11619 // termination packets list.
11620 EXPECT_NE(nullptr,
11621 QuicConnectionPeer::GetConnectionClosePacket(&connection_));
11622}
11623
martinduke9e0811c2022-12-08 20:35:57 -080011624TEST_P(QuicConnectionTest, DoNotSendPing) {
Bence Békybac04052022-04-07 15:44:29 -040011625 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11626 connection_.OnHandshakeComplete();
11627 EXPECT_TRUE(connection_.connected());
11628 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11629 .WillRepeatedly(Return(true));
11630 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
11631 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11632
11633 SendStreamDataToPeer(
11634 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
11635 "GET /", 0, FIN, nullptr);
11636 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11637 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11638 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
11639 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11640
11641 // Now recevie an ACK and response of the previous packet, which will move the
11642 // ping alarm forward.
11643 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11644 QuicFrames frames;
11645 QuicAckFrame ack_frame = InitAckFrame(1);
11646 frames.push_back(QuicFrame(&ack_frame));
11647 frames.push_back(QuicFrame(QuicStreamFrame(
11648 GetNthClientInitiatedStreamId(0, connection_.transport_version()), true,
11649 0u, absl::string_view())));
11650 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -070011651 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040011652 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11653 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
11654 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11655 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11656 // The ping timer is set slightly less than 15 seconds in the future, because
11657 // of the 1s ping timer alarm granularity.
11658 EXPECT_EQ(
11659 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
11660 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11661
11662 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
11663 // Suppose now ShouldKeepConnectionAlive returns false.
11664 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11665 .WillRepeatedly(Return(false));
11666 // Verify PING does not get sent.
11667 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11668 connection_.GetPingAlarm()->Fire();
11669}
11670
11671// Regression test for b/159698337
11672TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) {
11673 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11674 return;
11675 }
11676 // Finish handshake.
11677 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11678 notifier_.NeuterUnencryptedData();
11679 connection_.NeuterUnencryptedPackets();
11680 connection_.OnHandshakeComplete();
11681 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080011682 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040011683
11684 std::string data(1200, 'a');
11685 // Send data packets 1 - 5.
11686 for (size_t i = 0; i < 5; ++i) {
11687 SendStreamDataToPeer(
11688 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
11689 i * 1200, i == 4 ? FIN : NO_FIN, nullptr);
11690 }
11691 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
11692
martindukeba002452023-03-21 08:10:46 -070011693 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
11694 .Times(3);
Bence Békybac04052022-04-07 15:44:29 -040011695
11696 // ACK packet 5 and 1 and 2 are detected lost.
11697 QuicAckFrame frame =
11698 InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}});
11699 LostPacketVector lost_packets;
11700 lost_packets.push_back(
11701 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
11702 lost_packets.push_back(
11703 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
11704 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11705 .Times(AnyNumber())
11706 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
awillia202240c2024-07-08 09:47:00 -070011707 Return(LossDetectionInterface::DetectionStats())))
11708 .WillRepeatedly(DoDefault());
11709 ;
Bence Békybac04052022-04-07 15:44:29 -040011710 ProcessAckPacket(1, &frame);
11711 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
vasilvve16ac6e2024-10-25 14:08:14 -070011712 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
Bence Békybac04052022-04-07 15:44:29 -040011713
11714 // ACK packet 1 - 5 and 7.
11715 QuicAckFrame frame2 =
11716 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)},
11717 {QuicPacketNumber(7), QuicPacketNumber(8)}});
11718 ProcessAckPacket(2, &frame2);
11719 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11720
11721 // ACK packet 7 again and assume packet 6 is detected lost.
11722 QuicAckFrame frame3 =
11723 InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}});
11724 lost_packets.clear();
11725 lost_packets.push_back(
11726 LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize));
11727 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11728 .Times(AnyNumber())
11729 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11730 Return(LossDetectionInterface::DetectionStats())));
11731 ProcessAckPacket(3, &frame3);
11732 // Make sure loss detection is cancelled even there is no new acked packets.
11733 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11734}
11735
11736TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) {
11737 EXPECT_TRUE(connection_.connected());
11738 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11739 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
11740 QuicTime::Delta::Zero(), QuicTime::Zero());
11741
11742 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011743 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11744 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011745 QuicConfig config;
11746 config.SetClientConnectionOptions(QuicTagVector{kFIDT});
11747 QuicConfigPeer::SetNegotiated(&config, true);
11748 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11749 EXPECT_CALL(visitor_, GetHandshakeState())
11750 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11751 }
11752 if (connection_.version().UsesTls()) {
11753 QuicConfigPeer::SetReceivedOriginalConnectionId(
11754 &config, connection_.connection_id());
11755 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11756 &config, connection_.connection_id());
11757 }
11758 connection_.SetFromConfig(config);
11759
11760 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11761 // Send a packet close to timeout.
11762 QuicTime::Delta timeout =
11763 connection_.GetTimeoutAlarm()->deadline() - clock_.Now();
11764 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1));
11765 // Send stream data.
11766 SendStreamDataToPeer(
11767 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11768 0, FIN, nullptr);
11769 // Verify this sent packet does not extend idle timeout since 1s is > PTO
11770 // delay.
11771 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11772 EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
11773 connection_.GetTimeoutAlarm()->deadline() - clock_.Now());
11774
11775 // Received an ACK 100ms later.
11776 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100));
11777 QuicAckFrame ack = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070011778 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040011779 ProcessAckPacket(1, &ack);
11780 // Verify idle timeout gets extended.
11781 EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline());
11782}
11783
11784// Regression test for b/166255274
11785TEST_P(QuicConnectionTest,
11786 ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) {
11787 if (!connection_.version().CanSendCoalescedPackets()) {
11788 return;
11789 }
Bence Békybac04052022-04-07 15:44:29 -040011790 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11791 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11792 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11793 EXPECT_TRUE(connection_.HasPendingAcks());
11794 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11795 std::make_unique<TaggingEncrypter>(0x02));
11796 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11797 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11798 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11799 connection_.NeuterUnencryptedPackets();
11800 }));
11801 {
11802 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11803 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11804 // Verify the packet is on hold.
11805 EXPECT_EQ(0u, writer_->packets_write_attempts());
11806 // Flush pending ACKs.
11807 connection_.GetAckAlarm()->Fire();
11808 }
11809 EXPECT_FALSE(connection_.packet_creator().HasPendingFrames());
11810 // The ACK frame is deleted along with initial_packet_ in coalescer. Sending
11811 // connection close would cause this (released) ACK frame be serialized (and
11812 // crashes).
11813 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11814 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
11815 EXPECT_TRUE(connection_.connected());
11816}
11817
11818TEST_P(QuicConnectionTest, PathValidationOnNewSocketSuccess) {
danzh87605712022-04-11 14:36:39 -070011819 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011820 return;
11821 }
11822 PathProbeTestInit(Perspective::IS_CLIENT);
11823 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11824 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11825 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11826 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11827 .Times(AtLeast(1u))
11828 .WillOnce(Invoke([&]() {
11829 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11830 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11831 EXPECT_EQ(1u, new_writer.padding_frames().size());
11832 EXPECT_EQ(kNewSelfAddress.host(),
11833 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070011834 }))
11835 .WillRepeatedly(DoDefault());
11836 ;
Bence Békybac04052022-04-07 15:44:29 -040011837 bool success = false;
11838 connection_.ValidatePath(
11839 std::make_unique<TestQuicPathValidationContext>(
11840 kNewSelfAddress, connection_.peer_address(), &new_writer),
11841 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011842 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11843 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011844 EXPECT_EQ(0u, writer_->packets_write_attempts());
11845
11846 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011847 frames.push_back(QuicFrame(QuicPathResponseFrame(
Bence Békybac04052022-04-07 15:44:29 -040011848 99, new_writer.path_challenge_frames().front().data_buffer)));
11849 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
11850 ENCRYPTION_FORWARD_SECURE);
11851 EXPECT_TRUE(success);
11852}
11853
danzh90315e82023-06-08 14:09:49 -070011854TEST_P(QuicConnectionTest, PathValidationOnNewSocketWriteBlocked) {
11855 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11856 return;
11857 }
11858 PathProbeTestInit(Perspective::IS_CLIENT);
11859 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11860 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11861 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11862 new_writer.SetWriteBlocked();
11863 bool success = false;
11864 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11865 connection_.ValidatePath(
11866 std::make_unique<TestQuicPathValidationContext>(
11867 kNewSelfAddress, connection_.peer_address(), &new_writer),
11868 std::make_unique<TestValidationResultDelegate>(
11869 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11870 PathValidationReason::kReasonUnknown);
11871 EXPECT_EQ(0u, new_writer.packets_write_attempts());
11872 EXPECT_TRUE(connection_.HasPendingPathValidation());
11873
11874 new_writer.SetWritable();
11875 // Retry after time out.
11876 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11877 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11878 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11879 .WillOnce(Invoke([&]() {
11880 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11881 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11882 EXPECT_EQ(1u, new_writer.padding_frames().size());
11883 EXPECT_EQ(kNewSelfAddress.host(),
11884 new_writer.last_write_source_address());
11885 }));
11886 static_cast<TestAlarmFactory::TestAlarm*>(
11887 QuicPathValidatorPeer::retry_timer(
11888 QuicConnectionPeer::path_validator(&connection_)))
11889 ->Fire();
11890 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11891
11892 QuicFrames frames;
11893 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11894 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
11895 new_writer.SetWriteBlocked();
11896 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11897 .WillRepeatedly(Invoke([&] {
11898 // Packets other than PATH_RESPONSE may be sent over the default writer.
11899 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11900 EXPECT_TRUE(new_writer.path_response_frames().empty());
11901 EXPECT_EQ(1u, writer_->packets_write_attempts());
11902 }));
11903 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
11904 connection_.peer_address(),
11905 ENCRYPTION_FORWARD_SECURE);
11906 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11907}
11908
Bence Békybac04052022-04-07 15:44:29 -040011909TEST_P(QuicConnectionTest, NewPathValidationCancelsPreviousOne) {
danzh87605712022-04-11 14:36:39 -070011910 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011911 return;
11912 }
11913 PathProbeTestInit(Perspective::IS_CLIENT);
11914 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11915 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11916 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11917 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11918 .Times(AtLeast(1u))
11919 .WillOnce(Invoke([&]() {
11920 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11921 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11922 EXPECT_EQ(1u, new_writer.padding_frames().size());
11923 EXPECT_EQ(kNewSelfAddress.host(),
11924 new_writer.last_write_source_address());
11925 }));
11926 bool success = true;
11927 connection_.ValidatePath(
11928 std::make_unique<TestQuicPathValidationContext>(
11929 kNewSelfAddress, connection_.peer_address(), &new_writer),
11930 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011931 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11932 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011933 EXPECT_EQ(0u, writer_->packets_write_attempts());
11934
11935 // Start another path validation request.
11936 const QuicSocketAddress kNewSelfAddress2(QuicIpAddress::Any4(), 12346);
11937 EXPECT_NE(kNewSelfAddress2, connection_.self_address());
11938 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
Bence Békybac04052022-04-07 15:44:29 -040011939 bool success2 = false;
11940 connection_.ValidatePath(
11941 std::make_unique<TestQuicPathValidationContext>(
11942 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
11943 std::make_unique<TestValidationResultDelegate>(
11944 &connection_, kNewSelfAddress2, connection_.peer_address(),
renjietange499db42023-01-17 15:42:33 -080011945 &success2),
11946 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011947 EXPECT_FALSE(success);
danzh7c0ef5f2023-06-08 12:10:35 -070011948 // There is no pening path validation as there is no available connection ID.
11949 EXPECT_FALSE(connection_.HasPendingPathValidation());
Bence Békybac04052022-04-07 15:44:29 -040011950}
11951
11952// Regression test for b/182571515.
11953TEST_P(QuicConnectionTest, PathValidationRetry) {
danzh87605712022-04-11 14:36:39 -070011954 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011955 return;
11956 }
11957 PathProbeTestInit(Perspective::IS_CLIENT);
11958
11959 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11960 .Times(2u)
11961 .WillRepeatedly(Invoke([&]() {
11962 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11963 EXPECT_EQ(1u, writer_->padding_frames().size());
11964 }));
11965 bool success = true;
11966 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11967 connection_.self_address(),
11968 connection_.peer_address(), writer_.get()),
11969 std::make_unique<TestValidationResultDelegate>(
11970 &connection_, connection_.self_address(),
renjietange499db42023-01-17 15:42:33 -080011971 connection_.peer_address(), &success),
11972 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011973 EXPECT_EQ(1u, writer_->packets_write_attempts());
11974 EXPECT_TRUE(connection_.HasPendingPathValidation());
11975
11976 // Retry after time out.
11977 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11978 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11979 static_cast<TestAlarmFactory::TestAlarm*>(
11980 QuicPathValidatorPeer::retry_timer(
11981 QuicConnectionPeer::path_validator(&connection_)))
11982 ->Fire();
11983 EXPECT_EQ(2u, writer_->packets_write_attempts());
11984}
11985
11986TEST_P(QuicConnectionTest, PathValidationReceivesStatelessReset) {
danzh87605712022-04-11 14:36:39 -070011987 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011988 return;
11989 }
11990 PathProbeTestInit(Perspective::IS_CLIENT);
11991 QuicConfig config;
11992 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
11993 kTestStatelessResetToken);
11994 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080011995 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
11996 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040011997 connection_.SetFromConfig(config);
11998 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11999 EXPECT_NE(kNewSelfAddress, connection_.self_address());
12000 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
12001 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12002 .Times(AtLeast(1u))
12003 .WillOnce(Invoke([&]() {
12004 EXPECT_EQ(1u, new_writer.packets_write_attempts());
12005 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
12006 EXPECT_EQ(1u, new_writer.padding_frames().size());
12007 EXPECT_EQ(kNewSelfAddress.host(),
12008 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070012009 }))
12010 .WillRepeatedly(DoDefault());
12011 ;
Bence Békybac04052022-04-07 15:44:29 -040012012 bool success = true;
12013 connection_.ValidatePath(
12014 std::make_unique<TestQuicPathValidationContext>(
12015 kNewSelfAddress, connection_.peer_address(), &new_writer),
12016 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080012017 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
12018 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040012019 EXPECT_EQ(0u, writer_->packets_write_attempts());
12020 EXPECT_TRUE(connection_.HasPendingPathValidation());
12021
12022 std::unique_ptr<QuicEncryptedPacket> packet(
12023 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
12024 /*received_packet_length=*/100,
12025 kTestStatelessResetToken));
12026 std::unique_ptr<QuicReceivedPacket> received(
12027 ConstructReceivedPacket(*packet, QuicTime::Zero()));
12028 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
12029 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
12030 EXPECT_FALSE(connection_.HasPendingPathValidation());
12031 EXPECT_FALSE(success);
12032}
12033
12034// Tests that PATH_CHALLENGE is dropped if it is sent via a blocked alternative
12035// writer.
12036TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedNewSocket) {
danzh7c0ef5f2023-06-08 12:10:35 -070012037 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040012038 return;
12039 }
12040 PathProbeTestInit(Perspective::IS_CLIENT);
12041 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
12042 EXPECT_NE(kNewSelfAddress, connection_.self_address());
12043 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
12044 new_writer.BlockOnNextWrite();
12045 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
12046 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12047 .Times(AtLeast(1))
12048 .WillOnce(Invoke([&]() {
12049 // Even though the socket is blocked, the PATH_CHALLENGE should still be
12050 // treated as sent.
12051 EXPECT_EQ(1u, new_writer.packets_write_attempts());
12052 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
12053 EXPECT_EQ(1u, new_writer.padding_frames().size());
12054 EXPECT_EQ(kNewSelfAddress.host(),
12055 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070012056 }))
12057 .WillRepeatedly(DoDefault());
12058 ;
Bence Békybac04052022-04-07 15:44:29 -040012059 bool success = false;
12060 connection_.ValidatePath(
12061 std::make_unique<TestQuicPathValidationContext>(
12062 kNewSelfAddress, connection_.peer_address(), &new_writer),
12063 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080012064 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
12065 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040012066 EXPECT_EQ(0u, writer_->packets_write_attempts());
12067
12068 new_writer.SetWritable();
12069 // Write event on the default socket shouldn't make any difference.
12070 connection_.OnCanWrite();
12071 // A NEW_CONNECTION_ID frame is received in PathProbeTestInit and OnCanWrite
12072 // will write a acking packet.
12073 EXPECT_EQ(1u, writer_->packets_write_attempts());
12074 EXPECT_EQ(1u, new_writer.packets_write_attempts());
12075}
12076
12077// Tests that PATH_CHALLENGE is dropped if it is sent via the default writer
12078// and the writer is blocked.
12079TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedDefaultSocket) {
danzh87605712022-04-11 14:36:39 -070012080 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040012081 return;
12082 }
12083 PathProbeTestInit(Perspective::IS_SERVER);
12084 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
12085 writer_->BlockOnNextWrite();
12086 // 1st time is after writer returns WRITE_STATUS_BLOCKED. 2nd time is in
12087 // ShouldGeneratePacket().
12088 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(2));
12089 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
12090 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12091 .Times(AtLeast(1u))
12092 .WillOnce(Invoke([&]() {
12093 // This packet isn't sent actually, instead it is buffered in the
12094 // connection.
12095 EXPECT_EQ(1u, writer_->packets_write_attempts());
danzh4d58dae2023-06-06 11:13:10 -070012096 EXPECT_EQ(1u, writer_->path_response_frames().size());
12097 EXPECT_EQ(0,
12098 memcmp(&path_challenge_payload,
12099 &writer_->path_response_frames().front().data_buffer,
12100 sizeof(path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040012101 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
12102 EXPECT_EQ(1u, writer_->padding_frames().size());
12103 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12104 }))
12105 .WillRepeatedly(Invoke([&]() {
12106 // Only one PATH_CHALLENGE should be sent out.
12107 EXPECT_EQ(0u, writer_->path_challenge_frames().size());
12108 }));
danzh4d58dae2023-06-06 11:13:10 -070012109 // Receiving a PATH_CHALLENGE from the new peer address should trigger address
12110 // validation.
12111 QuicFrames frames;
12112 frames.push_back(
12113 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
12114 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12115 ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040012116 EXPECT_EQ(1u, writer_->packets_write_attempts());
12117
12118 // Try again with the new socket blocked from the beginning. The 2nd
12119 // PATH_CHALLENGE shouldn't be serialized, but be dropped.
12120 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
12121 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
12122 static_cast<TestAlarmFactory::TestAlarm*>(
12123 QuicPathValidatorPeer::retry_timer(
12124 QuicConnectionPeer::path_validator(&connection_)))
12125 ->Fire();
12126
12127 // No more write attempt should be made.
12128 EXPECT_EQ(1u, writer_->packets_write_attempts());
12129
12130 writer_->SetWritable();
12131 // OnCanWrite() should actually write out the 1st PATH_CHALLENGE packet
12132 // buffered earlier, thus incrementing the write counter. It may also send
12133 // ACKs to previously received packets.
12134 connection_.OnCanWrite();
12135 EXPECT_LE(2u, writer_->packets_write_attempts());
12136}
12137
12138// Tests that write error on the alternate socket should be ignored.
12139TEST_P(QuicConnectionTest, SendPathChallengeFailOnNewSocket) {
danzh87605712022-04-11 14:36:39 -070012140 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040012141 return;
12142 }
12143 PathProbeTestInit(Perspective::IS_CLIENT);
12144 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
12145 EXPECT_NE(kNewSelfAddress, connection_.self_address());
12146 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
12147 new_writer.SetShouldWriteFail();
12148 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
12149 .Times(0);
12150 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
12151
12152 bool success = false;
12153 connection_.ValidatePath(
12154 std::make_unique<TestQuicPathValidationContext>(
12155 kNewSelfAddress, connection_.peer_address(), &new_writer),
12156 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080012157 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
12158 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040012159 EXPECT_EQ(1u, new_writer.packets_write_attempts());
12160 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
12161 EXPECT_EQ(1u, new_writer.padding_frames().size());
12162 EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address());
12163
12164 EXPECT_EQ(0u, writer_->packets_write_attempts());
12165 // Regardless of the write error, the connection should still be connected.
12166 EXPECT_TRUE(connection_.connected());
12167}
12168
12169// Tests that write error while sending PATH_CHALLANGE from the default socket
12170// should close the connection.
12171TEST_P(QuicConnectionTest, SendPathChallengeFailOnDefaultPath) {
danzh87605712022-04-11 14:36:39 -070012172 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040012173 return;
12174 }
12175 PathProbeTestInit(Perspective::IS_CLIENT);
12176
12177 writer_->SetShouldWriteFail();
12178 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
12179 .WillOnce(
12180 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
12181 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
12182 }));
12183 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
12184 {
12185 // Add a flusher to force flush, otherwise the frames will remain in the
12186 // packet creator.
12187 bool success = false;
12188 QuicConnection::ScopedPacketFlusher flusher(&connection_);
12189 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
12190 connection_.self_address(),
12191 connection_.peer_address(), writer_.get()),
12192 std::make_unique<TestValidationResultDelegate>(
12193 &connection_, connection_.self_address(),
renjietange499db42023-01-17 15:42:33 -080012194 connection_.peer_address(), &success),
12195 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040012196 }
12197 EXPECT_EQ(1u, writer_->packets_write_attempts());
12198 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
12199 EXPECT_EQ(1u, writer_->padding_frames().size());
12200 EXPECT_EQ(connection_.peer_address(), writer_->last_write_peer_address());
12201 EXPECT_FALSE(connection_.connected());
12202 // Closing connection should abandon ongoing path validation.
12203 EXPECT_FALSE(connection_.HasPendingPathValidation());
12204}
12205
12206TEST_P(QuicConnectionTest, SendPathChallengeFailOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070012207 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040012208 return;
12209 }
12210 PathProbeTestInit(Perspective::IS_CLIENT);
12211
12212 writer_->SetShouldWriteFail();
12213 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
12214 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
12215 .WillOnce(
12216 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
12217 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
12218 }));
12219 // Sending PATH_CHALLENGE to trigger a flush write which will fail and close
12220 // the connection.
12221 bool success = false;
12222 connection_.ValidatePath(
12223 std::make_unique<TestQuicPathValidationContext>(
12224 connection_.self_address(), kNewPeerAddress, writer_.get()),
12225 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080012226 &connection_, connection_.self_address(), kNewPeerAddress, &success),
12227 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040012228
12229 EXPECT_EQ(1u, writer_->packets_write_attempts());
12230 EXPECT_FALSE(connection_.HasPendingPathValidation());
12231 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
12232 EXPECT_EQ(1u, writer_->padding_frames().size());
12233 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12234 EXPECT_FALSE(connection_.connected());
12235}
12236
12237TEST_P(QuicConnectionTest,
12238 SendPathChallengeFailPacketTooBigOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070012239 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040012240 return;
12241 }
12242 PathProbeTestInit(Perspective::IS_CLIENT);
12243 // Make sure there is no outstanding ACK_FRAME to write.
12244 connection_.OnCanWrite();
12245 uint32_t num_packets_write_attempts = writer_->packets_write_attempts();
12246
12247 writer_->SetShouldWriteFail();
12248 writer_->SetWriteError(*writer_->MessageTooBigErrorCode());
12249 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
12250 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
12251 .Times(0u);
12252 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
12253 // Sending PATH_CHALLENGE to trigger a flush write which will fail with
12254 // MSG_TOO_BIG.
12255 bool success = false;
12256 connection_.ValidatePath(
12257 std::make_unique<TestQuicPathValidationContext>(
12258 connection_.self_address(), kNewPeerAddress, writer_.get()),
12259 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080012260 &connection_, connection_.self_address(), kNewPeerAddress, &success),
12261 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040012262 EXPECT_TRUE(connection_.HasPendingPathValidation());
12263 // Connection shouldn't be closed.
12264 EXPECT_TRUE(connection_.connected());
12265 EXPECT_EQ(++num_packets_write_attempts, writer_->packets_write_attempts());
12266 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
12267 EXPECT_EQ(1u, writer_->padding_frames().size());
12268 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12269}
12270
12271// Check that if there are two PATH_CHALLENGE frames in the packet, the latter
12272// one is ignored.
12273TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) {
12274 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12275 return;
12276 }
12277 PathProbeTestInit(Perspective::IS_SERVER);
12278
12279 QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7};
12280 QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15};
12281 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070012282 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer1)));
12283 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer2)));
Bence Békybac04052022-04-07 15:44:29 -040012284 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12285 /*port=*/23456);
12286
12287 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
12288
12289 // Expect 2 packets to be sent: the first are padded PATH_RESPONSE(s) to the
12290 // alternative peer address. The 2nd is a ACK-only packet to the original
12291 // peer address.
12292 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12293 .Times(2)
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012294 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012295 EXPECT_EQ(1u, writer_->path_response_frames().size());
12296 // The final check is to ensure that the random data in the response
12297 // matches the random data from the challenge.
12298 EXPECT_EQ(0,
12299 memcmp(path_frame_buffer1.data(),
12300 &(writer_->path_response_frames().front().data_buffer),
12301 sizeof(path_frame_buffer1)));
12302 EXPECT_EQ(1u, writer_->padding_frames().size());
12303 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12304 }))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012305 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012306 // The last write of ACK-only packet should still use the old peer
12307 // address.
12308 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12309 }));
12310 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12311 ENCRYPTION_FORWARD_SECURE);
12312}
12313
12314TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) {
12315 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12316 return;
12317 }
12318 PathProbeTestInit(Perspective::IS_SERVER);
12319
12320 QuicFrames frames;
12321 frames.push_back(QuicFrame(frame1_));
12322 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012323 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
fayang161ce6e2022-07-01 18:02:11 -070012324 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
Bence Békybac04052022-04-07 15:44:29 -040012325 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
12326 /*port=*/23456);
12327
12328 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
danzh4d58dae2023-06-06 11:13:10 -070012329 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040012330 EXPECT_CALL(visitor_, OnStreamFrame(_))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012331 .WillOnce(Invoke([=, this](const QuicStreamFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040012332 // Send some data on the stream. The STREAM_FRAME should be built into
12333 // one packet together with the latter PATH_RESPONSE and PATH_CHALLENGE.
12334 const std::string data{"response body"};
12335 connection_.producer()->SaveStreamData(frame.stream_id, data);
12336 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12337 NO_FIN);
12338 }));
danzh4d58dae2023-06-06 11:13:10 -070012339 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040012340 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12341 ENCRYPTION_FORWARD_SECURE);
12342
12343 // Verify that this packet contains a STREAM_FRAME and a
12344 // PATH_RESPONSE_FRAME.
12345 EXPECT_EQ(1u, writer_->stream_frames().size());
12346 EXPECT_EQ(1u, writer_->path_response_frames().size());
danzh4d58dae2023-06-06 11:13:10 -070012347 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012348 // The final check is to ensure that the random data in the response
12349 // matches the random data from the challenge.
12350 EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
12351 &(writer_->path_response_frames().front().data_buffer),
12352 sizeof(path_frame_buffer)));
danzh4d58dae2023-06-06 11:13:10 -070012353 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012354 EXPECT_EQ(1u, writer_->padding_frames().size());
12355 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
danzh4d58dae2023-06-06 11:13:10 -070012356 EXPECT_TRUE(connection_.HasPendingPathValidation());
Bence Békybac04052022-04-07 15:44:29 -040012357}
12358
12359TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) {
12360 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12361 return;
12362 }
12363 PathProbeTestInit(Perspective::IS_SERVER);
12364
12365 QuicFrames frames;
12366 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012367 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012368 // PATH_RESPONSE should be flushed out before the rest packet is parsed.
12369 frames.push_back(QuicFrame(frame1_));
12370 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
12371 /*port=*/23456);
12372 QuicByteCount received_packet_size;
12373 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12374 .Times(AtLeast(1u))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012375 .WillOnce(Invoke([=, this, &received_packet_size]() {
Bence Békybac04052022-04-07 15:44:29 -040012376 // Verify that this packet contains a PATH_RESPONSE_FRAME.
12377 EXPECT_EQ(0u, writer_->stream_frames().size());
12378 EXPECT_EQ(1u, writer_->path_response_frames().size());
12379 // The final check is to ensure that the random data in the response
12380 // matches the random data from the challenge.
12381 EXPECT_EQ(0,
12382 memcmp(path_frame_buffer.data(),
12383 &(writer_->path_response_frames().front().data_buffer),
12384 sizeof(path_frame_buffer)));
danzh4d58dae2023-06-06 11:13:10 -070012385 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012386 EXPECT_EQ(1u, writer_->padding_frames().size());
12387 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12388 received_packet_size =
12389 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_);
12390 }));
12391 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
danzh4d58dae2023-06-06 11:13:10 -070012392 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040012393 EXPECT_CALL(visitor_, OnStreamFrame(_))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012394 .WillOnce(Invoke([=, this](const QuicStreamFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040012395 // Send some data on the stream. The STREAM_FRAME should be built into a
12396 // new packet but throttled by anti-amplifciation limit.
12397 const std::string data{"response body"};
12398 connection_.producer()->SaveStreamData(frame.stream_id, data);
12399 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12400 NO_FIN);
12401 }));
12402
12403 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12404 ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040012405 EXPECT_TRUE(connection_.HasPendingPathValidation());
12406 EXPECT_EQ(0u,
12407 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
12408 EXPECT_EQ(
12409 received_packet_size,
12410 QuicConnectionPeer::BytesReceivedBeforeAddressValidation(&connection_));
12411}
12412
12413// Tests that a PATH_CHALLENGE is received in between other frames in an out of
12414// order packet.
12415TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) {
12416 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12417 return;
12418 }
12419 PathProbeTestInit(Perspective::IS_SERVER);
12420
12421 QuicFrames frames;
12422 frames.push_back(QuicFrame(frame1_));
12423 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012424 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012425 frames.push_back(QuicFrame(frame2_));
12426 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12427 /*port=*/23456);
12428
12429 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12430 EXPECT_CALL(visitor_, OnStreamFrame(_))
12431 .Times(2)
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012432 .WillRepeatedly(Invoke([=, this](const QuicStreamFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040012433 // Send some data on the stream. The STREAM_FRAME should be built into
12434 // one packet together with the latter PATH_RESPONSE.
12435 const std::string data{"response body"};
12436 connection_.producer()->SaveStreamData(frame.stream_id, data);
12437 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12438 NO_FIN);
12439 }));
12440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012441 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012442 // Verify that this packet contains a STREAM_FRAME and is sent to the
12443 // original peer address.
12444 EXPECT_EQ(1u, writer_->stream_frames().size());
12445 // No connection migration should happen because the packet is received
12446 // out of order.
12447 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12448 }))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012449 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012450 EXPECT_EQ(1u, writer_->path_response_frames().size());
12451 // The final check is to ensure that the random data in the response
12452 // matches the random data from the challenge.
12453 EXPECT_EQ(0,
12454 memcmp(path_frame_buffer.data(),
12455 &(writer_->path_response_frames().front().data_buffer),
12456 sizeof(path_frame_buffer)));
12457 EXPECT_EQ(1u, writer_->padding_frames().size());
12458 // PATH_RESPONSE should be sent in another packet to a different peer
12459 // address.
12460 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12461 }))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012462 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012463 // Verify that this packet contains a STREAM_FRAME and is sent to the
12464 // original peer address.
12465 EXPECT_EQ(1u, writer_->stream_frames().size());
12466 // No connection migration should happen because the packet is received
12467 // out of order.
12468 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12469 }));
12470 // Lower the packet number so that receiving this packet shouldn't trigger
12471 // peer migration.
12472 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12473 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12474 ENCRYPTION_FORWARD_SECURE);
12475}
12476
12477// Tests that a PATH_CHALLENGE is cached if its PATH_RESPONSE can't be sent.
danzh90315e82023-06-08 14:09:49 -070012478TEST_P(QuicConnectionTest, FailToWritePathResponseAtServer) {
Bence Békybac04052022-04-07 15:44:29 -040012479 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12480 return;
12481 }
12482 PathProbeTestInit(Perspective::IS_SERVER);
12483
12484 QuicFrames frames;
12485 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012486 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012487 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12488 /*port=*/23456);
12489
12490 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12491 // Lower the packet number so that receiving this packet shouldn't trigger
12492 // peer migration.
12493 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12494 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
12495 writer_->SetWriteBlocked();
12496 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12497 ENCRYPTION_FORWARD_SECURE);
12498}
12499
12500// Regression test for b/168101557.
12501TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) {
12502 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12503 return;
12504 }
12505 set_perspective(Perspective::IS_SERVER);
12506 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
12507 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12508 }
12509 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040012510 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12511 EXPECT_TRUE(connection_.HasPendingAcks());
12512
Bence Békybac04052022-04-07 15:44:29 -040012513 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12514 // Send INITIAL 1.
12515 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12516
martinduke9e0811c2022-12-08 20:35:57 -080012517 connection_.SetEncrypter(
12518 ENCRYPTION_HANDSHAKE,
12519 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012520 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12521 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080012522 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012523 // Send HANDSHAKE packets.
12524 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
12525 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12526
martinduke9e0811c2022-12-08 20:35:57 -080012527 connection_.SetEncrypter(
12528 ENCRYPTION_FORWARD_SECURE,
12529 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012530 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12531 // Send half RTT packet.
12532 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12533
12534 // Receives HANDSHAKE 1.
martinduke9e0811c2022-12-08 20:35:57 -080012535 peer_framer_.SetEncrypter(
12536 ENCRYPTION_HANDSHAKE,
12537 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012538 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
12539 // Discard INITIAL key.
12540 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12541 connection_.NeuterUnencryptedPackets();
12542 // Verify there is pending ACK.
12543 ASSERT_TRUE(connection_.HasPendingAcks());
12544 // Set the send alarm.
12545 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
12546
12547 // Fire ACK alarm.
12548 connection_.GetAckAlarm()->Fire();
12549 // Verify 1-RTT packet is coalesced with handshake packet.
12550 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12551 connection_.GetSendAlarm()->Fire();
12552
12553 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12554 connection_.GetRetransmissionAlarm()->Fire();
12555 // Verify a handshake packet gets PTOed and 1-RTT packet gets coalesced.
12556 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12557}
12558
12559// Regression test for b/168294218.
12560TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) {
12561 if (!connection_.version().CanSendCoalescedPackets()) {
12562 return;
12563 }
12564 SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true);
12565 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
12566 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12567 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12568 connection_.NeuterUnencryptedPackets();
12569 }));
12570 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12571
12572 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
12573 {
12574 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040012575 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
12576 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080012577 connection_.SetEncrypter(
12578 ENCRYPTION_HANDSHAKE,
12579 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012580 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12581 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
12582 // Verify this packet is on hold.
12583 EXPECT_EQ(0u, writer_->packets_write_attempts());
12584 }
12585 EXPECT_TRUE(connection_.connected());
12586}
12587
12588// Regresstion test for b/168294218
12589TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) {
12590 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12591 return;
12592 }
12593 // Not defer send in response to packet.
12594 connection_.set_defer_send_in_response_to_packets(false);
12595 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12596 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12597 connection_.NeuterUnencryptedPackets();
12598 }));
12599 EXPECT_CALL(visitor_, OnCryptoFrame(_))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012600 .WillRepeatedly(Invoke([=, this](const QuicCryptoFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040012601 if (frame.level == ENCRYPTION_HANDSHAKE) {
12602 // 0-RTT gets rejected.
12603 connection_.MarkZeroRttPacketsForRetransmission(0);
12604 // Send Crypto data.
martinduke9e0811c2022-12-08 20:35:57 -080012605 connection_.SetEncrypter(
12606 ENCRYPTION_HANDSHAKE,
12607 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012608 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12609 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080012610 connection_.SetEncrypter(
12611 ENCRYPTION_FORWARD_SECURE,
12612 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012613 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12614 // Advance INITIAL ack delay to trigger initial ACK to be sent AFTER
12615 // the retransmission of rejected 0-RTT packets while the HANDSHAKE
12616 // packet is still in the coalescer, such that the INITIAL key gets
12617 // dropped between SendAllPendingAcks and actually send the ack frame,
12618 // bummer.
12619 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12620 }
12621 }));
Bence Békybac04052022-04-07 15:44:29 -040012622 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12623 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080012624 connection_.SetEncrypter(
12625 ENCRYPTION_ZERO_RTT,
12626 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040012627 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12628 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12629
12630 QuicAckFrame frame1 = InitAckFrame(1);
12631 // Received ACK for packet 1.
martindukeba002452023-03-21 08:10:46 -070012632 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012633 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
12634 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12635
12636 // Fire retransmission alarm.
12637 connection_.GetRetransmissionAlarm()->Fire();
12638
12639 QuicFrames frames1;
12640 frames1.push_back(QuicFrame(&crypto_frame_));
12641 QuicFrames frames2;
12642 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12643 absl::string_view(data1));
12644 frames2.push_back(QuicFrame(&crypto_frame));
12645 ProcessCoalescedPacket(
12646 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
12647}
12648
12649TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) {
12650 if (!connection_.version().UsesTls()) {
12651 return;
12652 }
12653 MockQuicConnectionDebugVisitor debug_visitor;
12654 connection_.set_debug_visitor(&debug_visitor);
Bence Békybac04052022-04-07 15:44:29 -040012655 connection_.SendCryptoStreamData();
12656 // Send 0-RTT packet.
12657 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
12658 std::make_unique<TaggingEncrypter>(0x02));
12659 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12660 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12661 connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN);
12662 // Received ACK for packet 1, HANDSHAKE packet and 1-RTT ACK.
martindukeba002452023-03-21 08:10:46 -070012663 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040012664 .Times(AnyNumber());
12665 QuicFrames frames1;
12666 QuicAckFrame ack_frame1 = InitAckFrame(1);
12667 frames1.push_back(QuicFrame(&ack_frame1));
12668
12669 QuicFrames frames2;
12670 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12671 absl::string_view(data1));
12672 frames2.push_back(QuicFrame(&crypto_frame));
12673 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12674 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
12675 ProcessCoalescedPacket(
12676 {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}});
12677
12678 QuicFrames frames3;
12679 QuicAckFrame ack_frame2 =
12680 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
12681 frames3.push_back(QuicFrame(&ack_frame2));
12682 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1);
12683 ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}});
12684
12685 QuicFrames frames4;
12686 QuicAckFrame ack_frame3 =
12687 InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}});
12688 frames4.push_back(QuicFrame(&ack_frame3));
12689 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12690 ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}});
12691}
12692
12693TEST_P(QuicConnectionTest, InitiateKeyUpdate) {
12694 if (!connection_.version().UsesTls()) {
12695 return;
12696 }
12697
12698 TransportParameters params;
12699 QuicConfig config;
12700 std::string error_details;
12701 EXPECT_THAT(config.ProcessTransportParameters(
12702 params, /* is_resumption = */ false, &error_details),
12703 IsQuicNoError());
12704 QuicConfigPeer::SetNegotiated(&config, true);
12705 if (connection_.version().UsesTls()) {
12706 QuicConfigPeer::SetReceivedOriginalConnectionId(
12707 &config, connection_.connection_id());
12708 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12709 &config, connection_.connection_id());
12710 }
12711 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080012712 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
12713 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040012714 connection_.SetFromConfig(config);
12715
12716 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12717
12718 MockFramerVisitor peer_framer_visitor_;
12719 peer_framer_.set_visitor(&peer_framer_visitor_);
12720
martinduke9e0811c2022-12-08 20:35:57 -080012721 uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012722 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12723 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012724 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012725 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012726 std::make_unique<StrictTaggingDecrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012727 EXPECT_CALL(visitor_, GetHandshakeState())
12728 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12729 connection_.OnHandshakeComplete();
12730
12731 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012732 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012733
12734 // Key update should still not be allowed, since no packet has been acked
12735 // from the current key phase.
12736 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12737 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12738
12739 // Send packet 1.
12740 QuicPacketNumber last_packet;
12741 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12742 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12743
12744 // Key update should still not be allowed, even though a packet was sent in
12745 // the current key phase it hasn't been acked yet.
12746 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12747 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12748
12749 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12750 // Receive ack for packet 1.
martindukeba002452023-03-21 08:10:46 -070012751 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012752 QuicAckFrame frame1 = InitAckFrame(1);
12753 ProcessAckPacket(&frame1);
12754
12755 // OnDecryptedFirstPacketInKeyPhase is called even on the first key phase,
12756 // so discard_previous_keys_alarm_ should be set now.
12757 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12758 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12759
martinduke9e0811c2022-12-08 20:35:57 -080012760 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012761 // Key update should now be allowed.
12762 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012763 .WillOnce([&correct_tag]() {
12764 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12765 });
12766 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12767 .WillOnce([&correct_tag]() {
12768 return std::make_unique<TaggingEncrypter>(correct_tag);
12769 });
Bence Békybac04052022-04-07 15:44:29 -040012770 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12771 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12772 // discard_previous_keys_alarm_ should not be set until a packet from the new
12773 // key phase has been received. (The alarm that was set above should be
12774 // cleared if it hasn't fired before the next key update happened.)
12775 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12776 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12777
12778 // Pretend that peer accepts the key update.
12779 EXPECT_CALL(peer_framer_visitor_,
12780 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012781 .WillOnce([&correct_tag]() {
12782 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12783 });
Bence Békybac04052022-04-07 15:44:29 -040012784 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012785 .WillOnce([&correct_tag]() {
12786 return std::make_unique<TaggingEncrypter>(correct_tag);
12787 });
Bence Békybac04052022-04-07 15:44:29 -040012788 peer_framer_.SetKeyUpdateSupportForConnection(true);
12789 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12790
12791 // Another key update should not be allowed yet.
12792 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12793
12794 // Send packet 2.
12795 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12796 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12797 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12798 // Receive ack for packet 2.
martindukeba002452023-03-21 08:10:46 -070012799 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012800 QuicAckFrame frame2 = InitAckFrame(2);
12801 ProcessAckPacket(&frame2);
12802 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12803 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12804
martinduke9e0811c2022-12-08 20:35:57 -080012805 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012806 // Key update should be allowed again now that a packet has been acked from
12807 // the current key phase.
12808 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012809 .WillOnce([&correct_tag]() {
12810 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12811 });
12812 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12813 .WillOnce([&correct_tag]() {
12814 return std::make_unique<TaggingEncrypter>(correct_tag);
12815 });
Bence Békybac04052022-04-07 15:44:29 -040012816 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12817 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12818
12819 // Pretend that peer accepts the key update.
12820 EXPECT_CALL(peer_framer_visitor_,
12821 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012822 .WillOnce([&correct_tag]() {
12823 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12824 });
Bence Békybac04052022-04-07 15:44:29 -040012825 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012826 .WillOnce([&correct_tag]() {
12827 return std::make_unique<TaggingEncrypter>(correct_tag);
12828 });
Bence Békybac04052022-04-07 15:44:29 -040012829 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12830
12831 // Another key update should not be allowed yet.
12832 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12833
12834 // Send packet 3.
12835 SendStreamDataToPeer(3, "baz", 0, NO_FIN, &last_packet);
12836 EXPECT_EQ(QuicPacketNumber(3u), last_packet);
12837
12838 // Another key update should not be allowed yet.
12839 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12840 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12841
12842 // Receive ack for packet 3.
martindukeba002452023-03-21 08:10:46 -070012843 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012844 QuicAckFrame frame3 = InitAckFrame(3);
12845 ProcessAckPacket(&frame3);
12846 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12847 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12848
martinduke9e0811c2022-12-08 20:35:57 -080012849 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012850 // Key update should be allowed now.
12851 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012852 .WillOnce([&correct_tag]() {
12853 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12854 });
12855 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12856 .WillOnce([&correct_tag]() {
12857 return std::make_unique<TaggingEncrypter>(correct_tag);
12858 });
Bence Békybac04052022-04-07 15:44:29 -040012859 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12860 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12861 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12862 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12863}
12864
12865TEST_P(QuicConnectionTest, InitiateKeyUpdateApproachingConfidentialityLimit) {
12866 if (!connection_.version().UsesTls()) {
12867 return;
12868 }
12869
birenroyef686222022-09-12 11:34:34 -070012870 SetQuicFlag(quic_key_update_confidentiality_limit, 3U);
Bence Békybac04052022-04-07 15:44:29 -040012871
12872 std::string error_details;
12873 TransportParameters params;
12874 // Key update is enabled.
12875 QuicConfig config;
12876 EXPECT_THAT(config.ProcessTransportParameters(
12877 params, /* is_resumption = */ false, &error_details),
12878 IsQuicNoError());
12879 QuicConfigPeer::SetNegotiated(&config, true);
12880 if (connection_.version().UsesTls()) {
12881 QuicConfigPeer::SetReceivedOriginalConnectionId(
12882 &config, connection_.connection_id());
12883 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12884 &config, connection_.connection_id());
12885 }
12886 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080012887 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
12888 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040012889 connection_.SetFromConfig(config);
12890
12891 MockFramerVisitor peer_framer_visitor_;
12892 peer_framer_.set_visitor(&peer_framer_visitor_);
12893
martinduke9e0811c2022-12-08 20:35:57 -080012894 uint8_t current_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012895
12896 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12897 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12898 std::make_unique<TaggingEncrypter>(current_tag));
12899 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12900 std::make_unique<StrictTaggingDecrypter>(current_tag));
12901 EXPECT_CALL(visitor_, GetHandshakeState())
12902 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12903 connection_.OnHandshakeComplete();
12904
12905 peer_framer_.SetKeyUpdateSupportForConnection(true);
12906 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12907 std::make_unique<TaggingEncrypter>(current_tag));
12908
12909 const QuicConnectionStats& stats = connection_.GetStats();
12910
12911 for (int packet_num = 1; packet_num <= 8; ++packet_num) {
12912 if (packet_num == 3 || packet_num == 6) {
12913 current_tag++;
12914 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12915 .WillOnce([current_tag]() {
12916 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12917 });
12918 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12919 .WillOnce([current_tag]() {
12920 return std::make_unique<TaggingEncrypter>(current_tag);
12921 });
12922 EXPECT_CALL(visitor_,
12923 OnKeyUpdate(KeyUpdateReason::kLocalKeyUpdateLimitOverride));
12924 }
12925 // Send packet.
12926 QuicPacketNumber last_packet;
12927 SendStreamDataToPeer(packet_num, "foo", 0, NO_FIN, &last_packet);
12928 EXPECT_EQ(QuicPacketNumber(packet_num), last_packet);
12929 if (packet_num >= 6) {
12930 EXPECT_EQ(2U, stats.key_update_count);
12931 } else if (packet_num >= 3) {
12932 EXPECT_EQ(1U, stats.key_update_count);
12933 } else {
12934 EXPECT_EQ(0U, stats.key_update_count);
12935 }
12936
12937 if (packet_num == 4 || packet_num == 7) {
12938 // Pretend that peer accepts the key update.
12939 EXPECT_CALL(peer_framer_visitor_,
12940 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12941 .WillOnce([current_tag]() {
12942 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12943 });
12944 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12945 .WillOnce([current_tag]() {
12946 return std::make_unique<TaggingEncrypter>(current_tag);
12947 });
12948 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12949 }
12950 // Receive ack for packet.
martindukeba002452023-03-21 08:10:46 -070012951 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012952 QuicAckFrame frame1 = InitAckFrame(packet_num);
12953 ProcessAckPacket(&frame1);
12954 }
12955}
12956
12957TEST_P(QuicConnectionTest,
12958 CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed) {
12959 if (!connection_.version().UsesTls()) {
12960 return;
12961 }
12962
12963 // Set key update confidentiality limit to 1 packet.
birenroyef686222022-09-12 11:34:34 -070012964 SetQuicFlag(quic_key_update_confidentiality_limit, 1U);
Bence Békybac04052022-04-07 15:44:29 -040012965 // Use confidentiality limit for connection close of 3 packets.
12966 constexpr size_t kConfidentialityLimit = 3U;
12967
12968 std::string error_details;
12969 TransportParameters params;
12970 // Key update is enabled.
12971 QuicConfig config;
12972 EXPECT_THAT(config.ProcessTransportParameters(
12973 params, /* is_resumption = */ false, &error_details),
12974 IsQuicNoError());
12975 QuicConfigPeer::SetNegotiated(&config, true);
12976 if (connection_.version().UsesTls()) {
12977 QuicConfigPeer::SetReceivedOriginalConnectionId(
12978 &config, connection_.connection_id());
12979 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12980 &config, connection_.connection_id());
12981 }
12982 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080012983 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
12984 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040012985 connection_.SetFromConfig(config);
12986
12987 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12988 connection_.SetEncrypter(
12989 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012990 std::make_unique<TaggingEncrypterWithConfidentialityLimit>(
12991 ENCRYPTION_FORWARD_SECURE, kConfidentialityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012992 EXPECT_CALL(visitor_, GetHandshakeState())
12993 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12994 connection_.OnHandshakeComplete();
12995
12996 QuicPacketNumber last_packet;
12997 // Send 3 packets without receiving acks for any of them. Key update will not
12998 // be allowed, so the confidentiality limit should be reached, forcing the
12999 // connection to be closed.
13000 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
13001 EXPECT_TRUE(connection_.connected());
13002 SendStreamDataToPeer(2, "foo", 0, NO_FIN, &last_packet);
13003 EXPECT_TRUE(connection_.connected());
13004 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13005 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
13006 EXPECT_FALSE(connection_.connected());
13007 const QuicConnectionStats& stats = connection_.GetStats();
13008 EXPECT_EQ(0U, stats.key_update_count);
13009 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
13010}
13011
13012TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitDuringHandshake) {
13013 if (!connection_.version().UsesTls()) {
13014 return;
13015 }
13016
martinduke9e0811c2022-12-08 20:35:57 -080013017 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040013018 constexpr uint8_t wrong_tag = 0xFE;
13019 constexpr QuicPacketCount kIntegrityLimit = 3;
13020
13021 SetDecrypter(ENCRYPTION_HANDSHAKE,
13022 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
13023 correct_tag, kIntegrityLimit));
13024 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13025 std::make_unique<TaggingEncrypter>(correct_tag));
13026 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
13027 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13028 std::make_unique<TaggingEncrypter>(wrong_tag));
13029 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
13030 EXPECT_TRUE(connection_.connected());
13031 if (i == kIntegrityLimit) {
13032 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13033 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
13034 }
13035 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
13036 EXPECT_EQ(
13037 i, connection_.GetStats().num_failed_authentication_packets_received);
13038 }
13039 EXPECT_FALSE(connection_.connected());
13040 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
13041}
13042
13043TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAfterHandshake) {
13044 if (!connection_.version().UsesTls()) {
13045 return;
13046 }
13047
martinduke9e0811c2022-12-08 20:35:57 -080013048 constexpr uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040013049 constexpr uint8_t wrong_tag = 0xFE;
13050 constexpr QuicPacketCount kIntegrityLimit = 3;
13051
Bence Békybac04052022-04-07 15:44:29 -040013052 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
13053 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
13054 correct_tag, kIntegrityLimit));
13055 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
13056 std::make_unique<TaggingEncrypter>(correct_tag));
13057 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13058 EXPECT_CALL(visitor_, GetHandshakeState())
13059 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13060 connection_.OnHandshakeComplete();
13061 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13062 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
13063 std::make_unique<TaggingEncrypter>(wrong_tag));
13064 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
13065 EXPECT_TRUE(connection_.connected());
13066 if (i == kIntegrityLimit) {
13067 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13068 }
13069 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13070 EXPECT_EQ(
13071 i, connection_.GetStats().num_failed_authentication_packets_received);
13072 }
13073 EXPECT_FALSE(connection_.connected());
13074 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
13075}
13076
13077TEST_P(QuicConnectionTest,
13078 CloseConnectionOnIntegrityLimitAcrossEncryptionLevels) {
13079 if (!connection_.version().UsesTls()) {
13080 return;
13081 }
13082
martinduke9e0811c2022-12-08 20:35:57 -080013083 uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040013084 constexpr uint8_t wrong_tag = 0xFE;
13085 constexpr QuicPacketCount kIntegrityLimit = 4;
13086
Bence Békybac04052022-04-07 15:44:29 -040013087 SetDecrypter(ENCRYPTION_HANDSHAKE,
13088 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
13089 correct_tag, kIntegrityLimit));
13090 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13091 std::make_unique<TaggingEncrypter>(correct_tag));
13092 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
13093 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13094 std::make_unique<TaggingEncrypter>(wrong_tag));
13095 for (uint64_t i = 1; i <= 2; ++i) {
13096 EXPECT_TRUE(connection_.connected());
13097 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
13098 EXPECT_EQ(
13099 i, connection_.GetStats().num_failed_authentication_packets_received);
13100 }
13101
martinduke9e0811c2022-12-08 20:35:57 -080013102 correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040013103 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
13104 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
13105 correct_tag, kIntegrityLimit));
13106 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
13107 std::make_unique<TaggingEncrypter>(correct_tag));
13108 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13109 EXPECT_CALL(visitor_, GetHandshakeState())
13110 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13111 connection_.OnHandshakeComplete();
13112 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13113 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
13114 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
13115 std::make_unique<TaggingEncrypter>(wrong_tag));
13116 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
13117 EXPECT_TRUE(connection_.connected());
13118 if (i == kIntegrityLimit) {
13119 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13120 }
13121 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13122 EXPECT_EQ(
13123 i, connection_.GetStats().num_failed_authentication_packets_received);
13124 }
13125 EXPECT_FALSE(connection_.connected());
13126 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
13127}
13128
13129TEST_P(QuicConnectionTest, IntegrityLimitDoesNotApplyWithoutDecryptionKey) {
13130 if (!connection_.version().UsesTls()) {
13131 return;
13132 }
13133
martinduke9e0811c2022-12-08 20:35:57 -080013134 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040013135 constexpr uint8_t wrong_tag = 0xFE;
13136 constexpr QuicPacketCount kIntegrityLimit = 3;
13137
Bence Békybac04052022-04-07 15:44:29 -040013138 SetDecrypter(ENCRYPTION_HANDSHAKE,
13139 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
13140 correct_tag, kIntegrityLimit));
13141 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13142 std::make_unique<TaggingEncrypter>(correct_tag));
13143 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
13144 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
13145
13146 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
13147 std::make_unique<TaggingEncrypter>(wrong_tag));
13148 for (uint64_t i = 1; i <= kIntegrityLimit * 2; ++i) {
13149 EXPECT_TRUE(connection_.connected());
13150 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13151 EXPECT_EQ(
13152 0u, connection_.GetStats().num_failed_authentication_packets_received);
13153 }
13154 EXPECT_TRUE(connection_.connected());
13155}
13156
13157TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossKeyPhases) {
13158 if (!connection_.version().UsesTls()) {
13159 return;
13160 }
13161
13162 constexpr QuicPacketCount kIntegrityLimit = 4;
13163
13164 TransportParameters params;
13165 QuicConfig config;
13166 std::string error_details;
13167 EXPECT_THAT(config.ProcessTransportParameters(
13168 params, /* is_resumption = */ false, &error_details),
13169 IsQuicNoError());
13170 QuicConfigPeer::SetNegotiated(&config, true);
13171 if (connection_.version().UsesTls()) {
13172 QuicConfigPeer::SetReceivedOriginalConnectionId(
13173 &config, connection_.connection_id());
13174 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
13175 &config, connection_.connection_id());
13176 }
13177 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013178 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13179 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040013180 connection_.SetFromConfig(config);
13181
13182 MockFramerVisitor peer_framer_visitor_;
13183 peer_framer_.set_visitor(&peer_framer_visitor_);
13184
Bence Békybac04052022-04-07 15:44:29 -040013185 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13186 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
13187 std::make_unique<TaggingEncrypter>(0x01));
13188 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
13189 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
martinduke9e0811c2022-12-08 20:35:57 -080013190 ENCRYPTION_FORWARD_SECURE, kIntegrityLimit));
Bence Békybac04052022-04-07 15:44:29 -040013191 EXPECT_CALL(visitor_, GetHandshakeState())
13192 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13193 connection_.OnHandshakeComplete();
13194 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13195
13196 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
13197 std::make_unique<TaggingEncrypter>(0xFF));
13198 for (uint64_t i = 1; i <= 2; ++i) {
13199 EXPECT_TRUE(connection_.connected());
13200 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13201 EXPECT_EQ(
13202 i, connection_.GetStats().num_failed_authentication_packets_received);
13203 }
13204
martinduke9e0811c2022-12-08 20:35:57 -080013205 peer_framer_.SetEncrypter(
13206 ENCRYPTION_FORWARD_SECURE,
13207 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040013208 // Send packet 1.
13209 QuicPacketNumber last_packet;
13210 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
13211 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
13212 // Receive ack for packet 1.
martindukeba002452023-03-21 08:10:46 -070013213 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040013214 QuicAckFrame frame1 = InitAckFrame(1);
13215 ProcessAckPacket(&frame1);
13216 // Key update should now be allowed, initiate it.
13217 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
13218 .WillOnce([kIntegrityLimit]() {
13219 return std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
13220 0x02, kIntegrityLimit);
13221 });
13222 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
13223 return std::make_unique<TaggingEncrypter>(0x02);
13224 });
13225 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
13226 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
13227
13228 // Pretend that peer accepts the key update.
13229 EXPECT_CALL(peer_framer_visitor_,
13230 AdvanceKeysAndCreateCurrentOneRttDecrypter())
13231 .WillOnce(
13232 []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
13233 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
13234 .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); });
13235 peer_framer_.SetKeyUpdateSupportForConnection(true);
13236 peer_framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests);
13237
13238 // Send packet 2.
13239 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
13240 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
13241 // Receive ack for packet 2.
martindukeba002452023-03-21 08:10:46 -070013242 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040013243 QuicAckFrame frame2 = InitAckFrame(2);
13244 ProcessAckPacket(&frame2);
13245
13246 EXPECT_EQ(2u,
13247 connection_.GetStats().num_failed_authentication_packets_received);
13248
13249 // Do two more undecryptable packets. Integrity limit should be reached.
13250 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
13251 std::make_unique<TaggingEncrypter>(0xFF));
13252 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
13253 EXPECT_TRUE(connection_.connected());
13254 if (i == kIntegrityLimit) {
13255 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13256 }
13257 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13258 EXPECT_EQ(
13259 i, connection_.GetStats().num_failed_authentication_packets_received);
13260 }
13261 EXPECT_FALSE(connection_.connected());
13262 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
13263}
13264
13265TEST_P(QuicConnectionTest, SendAckFrequencyFrame) {
13266 if (!version().HasIetfQuicFrames()) {
13267 return;
13268 }
13269 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13270 set_perspective(Perspective::IS_SERVER);
martindukeba002452023-03-21 08:10:46 -070013271 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040013272 .Times(AnyNumber());
13273 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
13274
13275 QuicConfig config;
13276 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13277 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013278 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13279 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040013280 connection_.SetFromConfig(config);
13281 QuicConnectionPeer::SetAddressValidated(&connection_);
13282 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13283 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
13284
13285 connection_.OnHandshakeComplete();
13286
13287 writer_->SetWritable();
13288 QuicPacketCreatorPeer::SetPacketNumber(creator_, 99);
13289 // Send packet 100
13290 SendStreamDataToPeer(/*id=*/1, "foo", /*offset=*/0, NO_FIN, nullptr);
13291
13292 QuicAckFrequencyFrame captured_frame;
13293 EXPECT_CALL(visitor_, SendAckFrequency(_))
13294 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
13295 captured_frame = frame;
13296 }));
13297 // Send packet 101.
13298 SendStreamDataToPeer(/*id=*/1, "bar", /*offset=*/3, NO_FIN, nullptr);
13299
13300 EXPECT_EQ(captured_frame.packet_tolerance, 10u);
13301 EXPECT_EQ(captured_frame.max_ack_delay,
wub349df3d2024-04-26 11:37:32 -070013302 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040013303
13304 // Sending packet 102 does not trigger sending another AckFrequencyFrame.
13305 SendStreamDataToPeer(/*id=*/1, "baz", /*offset=*/6, NO_FIN, nullptr);
13306}
13307
13308TEST_P(QuicConnectionTest, SendAckFrequencyFrameUponHandshakeCompletion) {
13309 if (!version().HasIetfQuicFrames()) {
13310 return;
13311 }
13312 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13313 set_perspective(Perspective::IS_SERVER);
martindukeba002452023-03-21 08:10:46 -070013314 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040013315 .Times(AnyNumber());
13316 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
13317
13318 QuicConfig config;
13319 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13320 QuicTagVector quic_tag_vector;
13321 // Enable sending AckFrequency upon handshake completion.
13322 quic_tag_vector.push_back(kAFF2);
13323 QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector);
13324 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013325 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13326 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040013327 connection_.SetFromConfig(config);
13328 QuicConnectionPeer::SetAddressValidated(&connection_);
13329 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13330 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
13331
13332 QuicAckFrequencyFrame captured_frame;
13333 EXPECT_CALL(visitor_, SendAckFrequency(_))
13334 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
13335 captured_frame = frame;
13336 }));
13337
13338 connection_.OnHandshakeComplete();
13339
13340 EXPECT_EQ(captured_frame.packet_tolerance, 2u);
13341 EXPECT_EQ(captured_frame.max_ack_delay,
wub349df3d2024-04-26 11:37:32 -070013342 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040013343}
13344
13345TEST_P(QuicConnectionTest, FastRecoveryOfLostServerHello) {
13346 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
13347 return;
13348 }
13349 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013350 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13351 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040013352 QuicConfig config;
13353 connection_.SetFromConfig(config);
13354
Bence Békybac04052022-04-07 15:44:29 -040013355 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13356 connection_.SendCryptoStreamData();
13357 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13358
13359 // Assume ServerHello gets lost.
13360 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13361 std::make_unique<TaggingEncrypter>(0x02));
13362 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13363 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
13364 // Shorten PTO for fast recovery from lost ServerHello.
13365 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
13366 connection_.GetRetransmissionAlarm()->deadline());
13367}
13368
13369TEST_P(QuicConnectionTest, ServerHelloGetsReordered) {
13370 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
13371 return;
13372 }
13373 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013374 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13375 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040013376 QuicConfig config;
13377 connection_.SetFromConfig(config);
13378 EXPECT_CALL(visitor_, OnCryptoFrame(_))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070013379 .WillRepeatedly(Invoke([=, this](const QuicCryptoFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040013380 if (frame.level == ENCRYPTION_INITIAL) {
13381 // Install handshake read keys.
martinduke9e0811c2022-12-08 20:35:57 -080013382 SetDecrypter(
13383 ENCRYPTION_HANDSHAKE,
13384 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
13385 connection_.SetEncrypter(
13386 ENCRYPTION_HANDSHAKE,
13387 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040013388 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
13389 }
13390 }));
13391
Bence Békybac04052022-04-07 15:44:29 -040013392 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13393 connection_.SendCryptoStreamData();
13394 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13395
13396 // Assume ServerHello gets reordered.
13397 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13398 std::make_unique<TaggingEncrypter>(0x02));
13399 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13400 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
13401 // Verify fast recovery is not enabled.
13402 EXPECT_EQ(connection_.sent_packet_manager().GetRetransmissionTime(),
13403 connection_.GetRetransmissionAlarm()->deadline());
13404}
13405
13406TEST_P(QuicConnectionTest, MigratePath) {
danzh7c0ef5f2023-06-08 12:10:35 -070013407 connection_.CreateConnectionIdManager();
13408 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13409 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -040013410 EXPECT_CALL(visitor_, GetHandshakeState())
13411 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13412 EXPECT_CALL(visitor_, OnPathDegrading());
13413 connection_.OnPathDegradingDetected();
13414 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13415 EXPECT_NE(kNewSelfAddress, connection_.self_address());
13416
13417 // Buffer a packet.
13418 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
13419 writer_->SetWriteBlocked();
13420 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
13421 EXPECT_EQ(1u, connection_.NumQueuedPackets());
13422
danzh7c0ef5f2023-06-08 12:10:35 -070013423 if (version().HasIetfQuicFrames()) {
13424 QuicNewConnectionIdFrame frame;
13425 frame.connection_id = TestConnectionId(1234);
13426 ASSERT_NE(frame.connection_id, connection_.connection_id());
13427 frame.stateless_reset_token =
13428 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13429 frame.retire_prior_to = 0u;
13430 frame.sequence_number = 1u;
13431 connection_.OnNewConnectionIdFrame(frame);
13432 }
13433
Bence Békybac04052022-04-07 15:44:29 -040013434 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13435 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
danzh7c0ef5f2023-06-08 12:10:35 -070013436 EXPECT_TRUE(connection_.MigratePath(kNewSelfAddress,
13437 connection_.peer_address(), &new_writer,
13438 /*owns_writer=*/false));
Bence Békybac04052022-04-07 15:44:29 -040013439
13440 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13441 EXPECT_EQ(&new_writer, QuicConnectionPeer::GetWriter(&connection_));
13442 EXPECT_FALSE(connection_.IsPathDegrading());
13443 // Buffered packet on the old path should be discarded.
danzh7c0ef5f2023-06-08 12:10:35 -070013444 if (version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040013445 EXPECT_EQ(0u, connection_.NumQueuedPackets());
13446 } else {
13447 EXPECT_EQ(1u, connection_.NumQueuedPackets());
13448 }
13449}
13450
13451TEST_P(QuicConnectionTest, MigrateToNewPathDuringProbing) {
danzh87605712022-04-11 14:36:39 -070013452 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040013453 return;
13454 }
13455 PathProbeTestInit(Perspective::IS_CLIENT);
13456 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13457 EXPECT_NE(kNewSelfAddress, connection_.self_address());
13458 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13460 bool success = false;
13461 connection_.ValidatePath(
13462 std::make_unique<TestQuicPathValidationContext>(
13463 kNewSelfAddress, connection_.peer_address(), &new_writer),
13464 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080013465 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
13466 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040013467 EXPECT_TRUE(connection_.HasPendingPathValidation());
13468 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13469 &connection_, kNewSelfAddress, connection_.peer_address()));
13470
13471 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
13472 &new_writer, /*owns_writer=*/false);
13473 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13474 EXPECT_TRUE(connection_.HasPendingPathValidation());
13475 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13476 &connection_, kNewSelfAddress, connection_.peer_address()));
13477}
13478
renjietang89540a62022-12-01 14:46:26 -080013479TEST_P(QuicConnectionTest, MultiPortConnection) {
renjietangfca5c772022-08-25 13:48:21 -070013480 set_perspective(Perspective::IS_CLIENT);
13481 QuicConfig config;
renjietang89540a62022-12-01 14:46:26 -080013482 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
renjietangfca5c772022-08-25 13:48:21 -070013483 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013484 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13485 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
renjietangfca5c772022-08-25 13:48:21 -070013486 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013487 if (!version().HasIetfQuicFrames()) {
renjietangfca5c772022-08-25 13:48:21 -070013488 return;
13489 }
13490 connection_.CreateConnectionIdManager();
13491 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13492 connection_.OnHandshakeComplete();
13493
renjietang864fbda2022-09-08 10:50:07 -070013494 EXPECT_CALL(visitor_, OnPathDegrading());
13495 connection_.OnPathDegradingDetected();
13496
renjietangfca5c772022-08-25 13:48:21 -070013497 auto self_address = connection_.self_address();
13498 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13499 self_address.port() + 1);
13500 EXPECT_NE(kNewSelfAddress, self_address);
13501 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13502
renjietang89540a62022-12-01 14:46:26 -080013503 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
renjietangfca5c772022-08-25 13:48:21 -070013504 QuicNewConnectionIdFrame frame;
13505 frame.connection_id = TestConnectionId(1234);
13506 ASSERT_NE(frame.connection_id, connection_.connection_id());
13507 frame.stateless_reset_token =
13508 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13509 frame.retire_prior_to = 0u;
13510 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013511 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013512 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13513 observer->OnMultiPortPathContextAvailable(
13514 std::move(std::make_unique<TestQuicPathValidationContext>(
13515 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013516 }));
renjietangfca5c772022-08-25 13:48:21 -070013517 connection_.OnNewConnectionIdFrame(frame);
13518 EXPECT_TRUE(connection_.HasPendingPathValidation());
13519 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13520 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013521 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13522 EXPECT_FALSE(alt_path->validated);
renjietange499db42023-01-17 15:42:33 -080013523 EXPECT_EQ(PathValidationReason::kMultiPort,
13524 QuicConnectionPeer::path_validator(&connection_)
13525 ->GetPathValidationReason());
13526
13527 // Suppose the server retransmits the NEW_CID frame, the client will receive
13528 // the same frame again. It should be ignored.
13529 // Regression test of crbug.com/1406762
13530 connection_.OnNewConnectionIdFrame(frame);
renjietangfca5c772022-08-25 13:48:21 -070013531
renjietang864fbda2022-09-08 10:50:07 -070013532 // 30ms RTT.
13533 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13534 // Fake a response delay.
13535 clock_.AdvanceTime(kTestRTT);
13536
renjietangfca5c772022-08-25 13:48:21 -070013537 QuicFrames frames;
13538 frames.push_back(QuicFrame(QuicPathResponseFrame(
renjietang89540a62022-12-01 14:46:26 -080013539 99, new_writer.path_challenge_frames().back().data_buffer)));
renjietangfca5c772022-08-25 13:48:21 -070013540 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13541 ENCRYPTION_FORWARD_SECURE);
13542 // No migration should happen and the alternative path should still be alive.
13543 EXPECT_FALSE(connection_.HasPendingPathValidation());
13544 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13545 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013546 EXPECT_TRUE(alt_path->validated);
renjietang864fbda2022-09-08 10:50:07 -070013547 auto stats = connection_.multi_port_stats();
renjietang201bfa52023-04-24 18:12:27 -070013548 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietangbb4f6842024-02-12 14:25:06 -080013549 EXPECT_EQ(1, stats->num_successful_probes);
13550 EXPECT_EQ(1, stats->num_client_probing_attempts);
martinduke525723b2024-09-12 13:25:06 -070013551 EXPECT_EQ(1, connection_.GetStats().num_client_probing_attempts);
renjietang864fbda2022-09-08 10:50:07 -070013552 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13553 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13554 EXPECT_EQ(kTestRTT,
13555 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13556
renjietang785c7cb2023-08-21 09:10:25 -070013557 // Receiving the retransmitted NEW_CID frame now should still have no effect.
renjietang39a1add2023-10-26 12:51:57 -070013558 EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0);
13559 connection_.OnNewConnectionIdFrame(frame);
renjietang785c7cb2023-08-21 09:10:25 -070013560
renjietang89540a62022-12-01 14:46:26 -080013561 // When there's no active request, the probing shouldn't happen. But the
13562 // probing context should be saved.
13563 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
13564 connection_.GetMultiPortProbingAlarm()->Fire();
13565 EXPECT_FALSE(connection_.HasPendingPathValidation());
13566 EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13567
13568 // Simulate the situation where a new request stream is created.
13569 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13570 .WillRepeatedly(Return(true));
13571 random_generator_.ChangeValue();
13572 connection_.MaybeProbeMultiPortPath();
13573 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13574 &connection_, kNewSelfAddress, connection_.peer_address()));
13575 EXPECT_TRUE(alt_path->validated);
13576 // Fake a response delay.
13577 clock_.AdvanceTime(kTestRTT);
13578 QuicFrames frames2;
13579 frames2.push_back(QuicFrame(QuicPathResponseFrame(
13580 99, new_writer.path_challenge_frames().back().data_buffer)));
13581 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress, kPeerAddress,
13582 ENCRYPTION_FORWARD_SECURE);
13583 // No migration should happen and the alternative path should still be alive.
13584 EXPECT_FALSE(connection_.HasPendingPathValidation());
13585 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13586 &connection_, kNewSelfAddress, connection_.peer_address()));
13587 EXPECT_TRUE(alt_path->validated);
renjietang201bfa52023-04-24 18:12:27 -070013588 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013589 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13590 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13591 EXPECT_EQ(kTestRTT,
13592 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13593
renjietang546e3962023-09-01 10:51:19 -070013594 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
13595 QuicConnectionPeer::OnForwardProgressMade(&connection_);
13596
renjietang89540a62022-12-01 14:46:26 -080013597 EXPECT_TRUE(connection_.GetMultiPortProbingAlarm()->IsSet());
13598 // Since there's already a scheduled probing alarm, manual calls won't have
13599 // any effect.
13600 connection_.MaybeProbeMultiPortPath();
13601 EXPECT_FALSE(connection_.HasPendingPathValidation());
13602
renjietang546e3962023-09-01 10:51:19 -070013603 // Since kMPQM is not set, migration shouldn't happen
13604 EXPECT_CALL(visitor_, OnPathDegrading());
13605 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0);
13606 connection_.OnPathDegradingDetected();
13607 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13608 &connection_, kNewSelfAddress, connection_.peer_address()));
13609
renjietang89540a62022-12-01 14:46:26 -080013610 // Simulate the case where the path validation fails after retries.
renjietangfca5c772022-08-25 13:48:21 -070013611 connection_.GetMultiPortProbingAlarm()->Fire();
13612 EXPECT_TRUE(connection_.HasPendingPathValidation());
13613 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13614 &connection_, kNewSelfAddress, connection_.peer_address()));
13615 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13616 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13617 static_cast<TestAlarmFactory::TestAlarm*>(
13618 QuicPathValidatorPeer::retry_timer(
13619 QuicConnectionPeer::path_validator(&connection_)))
13620 ->Fire();
13621 }
13622
13623 EXPECT_FALSE(connection_.HasPendingPathValidation());
13624 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13625 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang546e3962023-09-01 10:51:19 -070013626 EXPECT_EQ(2, connection_.GetStats().num_path_degrading);
renjietang864fbda2022-09-08 10:50:07 -070013627 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13628 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_not_degrading);
martinduke525723b2024-09-12 13:25:06 -070013629 EXPECT_EQ(0, connection_.GetStats().num_stateless_resets_on_alternate_path);
renjietangfca5c772022-08-25 13:48:21 -070013630}
13631
renjietang89540a62022-12-01 14:46:26 -080013632TEST_P(QuicConnectionTest, TooManyMultiPortPathCreations) {
13633 set_perspective(Perspective::IS_CLIENT);
13634 QuicConfig config;
renjietang89540a62022-12-01 14:46:26 -080013635 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13636 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013637 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13638 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
renjietang89540a62022-12-01 14:46:26 -080013639 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013640 if (!version().HasIetfQuicFrames()) {
renjietang89540a62022-12-01 14:46:26 -080013641 return;
13642 }
13643 connection_.CreateConnectionIdManager();
13644 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13645 connection_.OnHandshakeComplete();
13646
13647 EXPECT_CALL(visitor_, OnPathDegrading());
13648 connection_.OnPathDegradingDetected();
13649
13650 auto self_address = connection_.self_address();
13651 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13652 self_address.port() + 1);
13653 EXPECT_NE(kNewSelfAddress, self_address);
13654 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13655
13656 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13657 .WillRepeatedly(Return(true));
13658
QUICHE teame2a24ee2024-01-09 06:34:35 -080013659 {
13660 QuicNewConnectionIdFrame frame;
13661 frame.connection_id = TestConnectionId(1234);
13662 ASSERT_NE(frame.connection_id, connection_.connection_id());
13663 frame.stateless_reset_token =
13664 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13665 frame.retire_prior_to = 0u;
13666 frame.sequence_number = 1u;
13667 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13668 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13669 observer->OnMultiPortPathContextAvailable(
13670 std::move(std::make_unique<TestQuicPathValidationContext>(
13671 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13672 }));
13673 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13674 }
renjietang89540a62022-12-01 14:46:26 -080013675 EXPECT_TRUE(connection_.HasPendingPathValidation());
13676 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13677 &connection_, kNewSelfAddress, connection_.peer_address()));
13678 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13679 EXPECT_FALSE(alt_path->validated);
13680
13681 EXPECT_TRUE(connection_.HasPendingPathValidation());
13682 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13683 &connection_, kNewSelfAddress, connection_.peer_address()));
13684 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13685 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13686 static_cast<TestAlarmFactory::TestAlarm*>(
13687 QuicPathValidatorPeer::retry_timer(
13688 QuicConnectionPeer::path_validator(&connection_)))
13689 ->Fire();
13690 }
13691
13692 auto stats = connection_.multi_port_stats();
13693 EXPECT_FALSE(connection_.HasPendingPathValidation());
13694 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13695 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang201bfa52023-04-24 18:12:27 -070013696 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013697 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13698
13699 uint64_t connection_id = 1235;
13700 for (size_t i = 0; i < kMaxNumMultiPortPaths - 1; ++i) {
13701 QuicNewConnectionIdFrame frame;
13702 frame.connection_id = TestConnectionId(connection_id + i);
13703 ASSERT_NE(frame.connection_id, connection_.connection_id());
13704 frame.stateless_reset_token =
13705 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13706 frame.retire_prior_to = 0u;
13707 frame.sequence_number = i + 2;
QUICHE team107316f2023-05-03 09:04:11 -070013708 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013709 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13710 observer->OnMultiPortPathContextAvailable(
13711 std::move(std::make_unique<TestQuicPathValidationContext>(
13712 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013713 }));
renjietang89540a62022-12-01 14:46:26 -080013714 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13715 EXPECT_TRUE(connection_.HasPendingPathValidation());
13716 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13717 &connection_, kNewSelfAddress, connection_.peer_address()));
13718 EXPECT_FALSE(alt_path->validated);
13719
13720 for (size_t j = 0; j < QuicPathValidator::kMaxRetryTimes + 1; ++j) {
13721 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13722 static_cast<TestAlarmFactory::TestAlarm*>(
13723 QuicPathValidatorPeer::retry_timer(
13724 QuicConnectionPeer::path_validator(&connection_)))
13725 ->Fire();
13726 }
13727
13728 EXPECT_FALSE(connection_.HasPendingPathValidation());
13729 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13730 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang201bfa52023-04-24 18:12:27 -070013731 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013732 EXPECT_EQ(i + 2, stats->num_multi_port_probe_failures_when_path_degrading);
13733 }
13734
13735 // The 6th attemp should fail.
13736 QuicNewConnectionIdFrame frame2;
13737 frame2.connection_id = TestConnectionId(1239);
13738 ASSERT_NE(frame2.connection_id, connection_.connection_id());
13739 frame2.stateless_reset_token =
13740 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
13741 frame2.retire_prior_to = 0u;
13742 frame2.sequence_number = 6u;
13743 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame2));
13744 EXPECT_FALSE(connection_.HasPendingPathValidation());
13745 EXPECT_EQ(kMaxNumMultiPortPaths,
13746 stats->num_multi_port_probe_failures_when_path_degrading);
13747}
13748
renjietang4ca6b842023-06-05 08:00:57 -070013749TEST_P(QuicConnectionTest, MultiPortPathReceivesStatelessReset) {
13750 set_perspective(Perspective::IS_CLIENT);
13751 QuicConfig config;
13752 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
13753 kTestStatelessResetToken);
13754 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13755 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013756 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13757 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
renjietang4ca6b842023-06-05 08:00:57 -070013758 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013759 if (!version().HasIetfQuicFrames()) {
renjietang4ca6b842023-06-05 08:00:57 -070013760 return;
13761 }
13762 connection_.CreateConnectionIdManager();
13763 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13764 connection_.OnHandshakeComplete();
13765
13766 EXPECT_CALL(visitor_, OnPathDegrading());
13767 connection_.OnPathDegradingDetected();
13768
13769 auto self_address = connection_.self_address();
13770 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13771 self_address.port() + 1);
13772 EXPECT_NE(kNewSelfAddress, self_address);
13773 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13774
13775 QuicNewConnectionIdFrame frame;
13776 frame.connection_id = TestConnectionId(1234);
13777 ASSERT_NE(frame.connection_id, connection_.connection_id());
13778 frame.stateless_reset_token =
13779 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13780 frame.retire_prior_to = 0u;
13781 frame.sequence_number = 1u;
13782 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13783 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13784 observer->OnMultiPortPathContextAvailable(
13785 std::move(std::make_unique<TestQuicPathValidationContext>(
13786 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13787 }));
13788 connection_.OnNewConnectionIdFrame(frame);
13789 EXPECT_TRUE(connection_.HasPendingPathValidation());
13790 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13791 &connection_, kNewSelfAddress, connection_.peer_address()));
13792 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13793 EXPECT_FALSE(alt_path->validated);
13794 EXPECT_EQ(PathValidationReason::kMultiPort,
13795 QuicConnectionPeer::path_validator(&connection_)
13796 ->GetPathValidationReason());
13797
13798 std::unique_ptr<QuicEncryptedPacket> packet(
13799 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
13800 /*received_packet_length=*/100,
13801 kTestStatelessResetToken));
13802 std::unique_ptr<QuicReceivedPacket> received(
13803 ConstructReceivedPacket(*packet, QuicTime::Zero()));
13804 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
13805 .Times(0);
13806 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
martinduke525723b2024-09-12 13:25:06 -070013807 EXPECT_EQ(connection_.GetStats().num_client_probing_attempts, 1);
13808 EXPECT_EQ(connection_.GetStats().num_stateless_resets_on_alternate_path, 1);
renjietang4ca6b842023-06-05 08:00:57 -070013809}
13810
renjietangc60dcb72023-06-06 13:00:51 -070013811// Test that if the client's active migration is disabled, multi-port will not
13812// be attempted.
13813TEST_P(QuicConnectionTest, MultiPortPathRespectsActiveMigrationConfig) {
danzh7c0ef5f2023-06-08 12:10:35 -070013814 if (!version().HasIetfQuicFrames()) {
13815 return;
13816 }
renjietangc60dcb72023-06-06 13:00:51 -070013817 set_perspective(Perspective::IS_CLIENT);
13818 QuicConfig config;
13819 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
13820 kTestStatelessResetToken);
13821 QuicConfigPeer::SetReceivedDisableConnectionMigration(&config);
13822 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13823 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013824 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13825 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
renjietangc60dcb72023-06-06 13:00:51 -070013826 connection_.SetFromConfig(config);
renjietangc60dcb72023-06-06 13:00:51 -070013827 connection_.CreateConnectionIdManager();
13828 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13829 connection_.OnHandshakeComplete();
13830
13831 EXPECT_CALL(visitor_, OnPathDegrading());
13832 connection_.OnPathDegradingDetected();
13833
13834 QuicNewConnectionIdFrame frame;
13835 frame.connection_id = TestConnectionId(1234);
13836 ASSERT_NE(frame.connection_id, connection_.connection_id());
13837 frame.stateless_reset_token =
13838 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13839 frame.retire_prior_to = 0u;
13840 frame.sequence_number = 1u;
13841 EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0);
13842 connection_.OnNewConnectionIdFrame(frame);
13843 EXPECT_FALSE(connection_.HasPendingPathValidation());
13844}
13845
renjietang5ba0e1b2023-03-14 13:08:03 -070013846// Verify that when multi-port is enabled and path degrading is triggered, if
13847// the alt-path is not ready, nothing happens.
13848TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsNotReady) {
13849 set_perspective(Perspective::IS_CLIENT);
13850 QuicConfig config;
renjietang5ba0e1b2023-03-14 13:08:03 -070013851 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13852 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013853 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13854 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
renjietang5ba0e1b2023-03-14 13:08:03 -070013855 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013856 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070013857 return;
13858 }
13859 connection_.CreateConnectionIdManager();
13860 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13861 connection_.OnHandshakeComplete();
13862
13863 auto self_address = connection_.self_address();
13864 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13865 self_address.port() + 1);
13866 EXPECT_NE(kNewSelfAddress, self_address);
13867 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13868
13869 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13870 .WillRepeatedly(Return(true));
13871
13872 QuicNewConnectionIdFrame frame;
13873 frame.connection_id = TestConnectionId(1234);
13874 ASSERT_NE(frame.connection_id, connection_.connection_id());
13875 frame.stateless_reset_token =
13876 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13877 frame.retire_prior_to = 0u;
13878 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013879 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013880 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13881 observer->OnMultiPortPathContextAvailable(
13882 std::move(std::make_unique<TestQuicPathValidationContext>(
13883 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013884 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070013885 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13886 EXPECT_TRUE(connection_.HasPendingPathValidation());
13887 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13888 &connection_, kNewSelfAddress, connection_.peer_address()));
13889 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13890 EXPECT_FALSE(alt_path->validated);
13891
13892 // The alt path is not ready, path degrading doesn't do anything.
13893 EXPECT_CALL(visitor_, OnPathDegrading());
13894 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0);
13895 connection_.OnPathDegradingDetected();
13896
13897 // 30ms RTT.
13898 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13899 // Fake a response delay.
13900 clock_.AdvanceTime(kTestRTT);
13901
13902 // Even if the alt path is validated after path degrading, nothing should
13903 // happen.
13904 QuicFrames frames;
13905 frames.push_back(QuicFrame(QuicPathResponseFrame(
13906 99, new_writer.path_challenge_frames().back().data_buffer)));
13907 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13908 ENCRYPTION_FORWARD_SECURE);
13909 // No migration should happen and the alternative path should still be alive.
13910 EXPECT_FALSE(connection_.HasPendingPathValidation());
13911 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13912 &connection_, kNewSelfAddress, connection_.peer_address()));
13913 EXPECT_TRUE(alt_path->validated);
13914}
13915
13916// Verify that when multi-port is enabled and path degrading is triggered, if
13917// the alt-path is ready and not probing, it should be migrated.
13918TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndNotProbing) {
13919 EXPECT_CALL(visitor_, GetHandshakeState())
13920 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13921 set_perspective(Perspective::IS_CLIENT);
13922 QuicConfig config;
renjietang546e3962023-09-01 10:51:19 -070013923 config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
renjietang5ba0e1b2023-03-14 13:08:03 -070013924 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080013925 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
13926 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
renjietang5ba0e1b2023-03-14 13:08:03 -070013927 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013928 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070013929 return;
13930 }
13931 connection_.CreateConnectionIdManager();
13932 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13933 connection_.OnHandshakeComplete();
13934
13935 auto self_address = connection_.self_address();
13936 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13937 self_address.port() + 1);
13938 EXPECT_NE(kNewSelfAddress, self_address);
13939 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13940
13941 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13942 .WillRepeatedly(Return(true));
13943
13944 QuicNewConnectionIdFrame frame;
13945 frame.connection_id = TestConnectionId(1234);
13946 ASSERT_NE(frame.connection_id, connection_.connection_id());
13947 frame.stateless_reset_token =
13948 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13949 frame.retire_prior_to = 0u;
13950 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013951 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013952 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13953 observer->OnMultiPortPathContextAvailable(
13954 std::move(std::make_unique<TestQuicPathValidationContext>(
13955 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013956 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070013957 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13958 EXPECT_TRUE(connection_.HasPendingPathValidation());
13959 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13960 &connection_, kNewSelfAddress, connection_.peer_address()));
13961 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13962 EXPECT_FALSE(alt_path->validated);
13963
13964 // 30ms RTT.
13965 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13966 // Fake a response delay.
13967 clock_.AdvanceTime(kTestRTT);
13968
13969 // Even if the alt path is validated after path degrading, nothing should
13970 // happen.
13971 QuicFrames frames;
13972 frames.push_back(QuicFrame(QuicPathResponseFrame(
13973 99, new_writer.path_challenge_frames().back().data_buffer)));
13974 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13975 ENCRYPTION_FORWARD_SECURE);
13976 // No migration should happen and the alternative path should still be alive.
13977 EXPECT_FALSE(connection_.HasPendingPathValidation());
13978 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13979 &connection_, kNewSelfAddress, connection_.peer_address()));
13980 EXPECT_TRUE(alt_path->validated);
13981
13982 // Trigger path degrading and the connection should attempt to migrate.
13983 EXPECT_CALL(visitor_, OnPathDegrading());
13984 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0);
13985 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_))
13986 .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) {
13987 EXPECT_EQ(context->self_address(), kNewSelfAddress);
13988 connection_.MigratePath(context->self_address(),
13989 context->peer_address(), context->WriterToUse(),
13990 /*owns_writer=*/false);
13991 }));
13992 connection_.OnPathDegradingDetected();
13993}
13994
13995// Verify that when multi-port is enabled and path degrading is triggered, if
13996// the alt-path is probing, the probing should be cancelled and the path should
13997// be migrated.
13998TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndProbing) {
13999 EXPECT_CALL(visitor_, GetHandshakeState())
14000 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
14001 set_perspective(Perspective::IS_CLIENT);
14002 QuicConfig config;
renjietang546e3962023-09-01 10:51:19 -070014003 config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
renjietang5ba0e1b2023-03-14 13:08:03 -070014004 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080014005 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
14006 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
renjietang5ba0e1b2023-03-14 13:08:03 -070014007 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070014008 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070014009 return;
14010 }
14011 connection_.CreateConnectionIdManager();
14012 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14013 connection_.OnHandshakeComplete();
14014
14015 auto self_address = connection_.self_address();
14016 const QuicSocketAddress kNewSelfAddress(self_address.host(),
14017 self_address.port() + 1);
14018 EXPECT_NE(kNewSelfAddress, self_address);
14019 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14020
14021 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
14022 .WillRepeatedly(Return(true));
14023
14024 QuicNewConnectionIdFrame frame;
14025 frame.connection_id = TestConnectionId(1234);
14026 ASSERT_NE(frame.connection_id, connection_.connection_id());
14027 frame.stateless_reset_token =
14028 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14029 frame.retire_prior_to = 0u;
14030 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070014031 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070014032 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
14033 observer->OnMultiPortPathContextAvailable(
14034 std::move(std::make_unique<TestQuicPathValidationContext>(
14035 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070014036 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070014037 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14038 EXPECT_TRUE(connection_.HasPendingPathValidation());
14039 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
14040 &connection_, kNewSelfAddress, connection_.peer_address()));
14041 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
14042 EXPECT_FALSE(alt_path->validated);
14043
14044 // 30ms RTT.
14045 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
14046 // Fake a response delay.
14047 clock_.AdvanceTime(kTestRTT);
14048
14049 // Even if the alt path is validated after path degrading, nothing should
14050 // happen.
14051 QuicFrames frames;
14052 frames.push_back(QuicFrame(QuicPathResponseFrame(
14053 99, new_writer.path_challenge_frames().back().data_buffer)));
14054 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
14055 ENCRYPTION_FORWARD_SECURE);
14056 // No migration should happen and the alternative path should still be alive.
14057 EXPECT_FALSE(connection_.HasPendingPathValidation());
14058 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
14059 &connection_, kNewSelfAddress, connection_.peer_address()));
14060 EXPECT_TRUE(alt_path->validated);
14061
14062 random_generator_.ChangeValue();
14063 connection_.GetMultiPortProbingAlarm()->Fire();
14064 EXPECT_TRUE(connection_.HasPendingPathValidation());
14065 EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
14066
14067 // Trigger path degrading and the connection should attempt to migrate.
14068 EXPECT_CALL(visitor_, OnPathDegrading());
14069 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0);
14070 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_))
14071 .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) {
14072 EXPECT_EQ(context->self_address(), kNewSelfAddress);
14073 connection_.MigratePath(context->self_address(),
14074 context->peer_address(), context->WriterToUse(),
14075 /*owns_writer=*/false);
14076 }));
14077 connection_.OnPathDegradingDetected();
14078 EXPECT_FALSE(connection_.HasPendingPathValidation());
14079 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
14080 EXPECT_FALSE(QuicPathValidatorPeer::retry_timer(path_validator)->IsSet());
14081}
14082
Bence Békybac04052022-04-07 15:44:29 -040014083TEST_P(QuicConnectionTest, SingleAckInPacket) {
14084 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
14085 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
14086 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14087 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
14088 connection_.NeuterUnencryptedPackets();
14089 connection_.OnHandshakeComplete();
14090 EXPECT_CALL(visitor_, GetHandshakeState())
14091 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
14092
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014093 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040014094 connection_.SendStreamData3();
14095 connection_.CloseConnection(
14096 QUIC_INTERNAL_ERROR, "error",
14097 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
14098 }));
14099 QuicFrames frames;
14100 frames.push_back(QuicFrame(frame1_));
14101 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
14102 ENCRYPTION_FORWARD_SECURE);
14103 ASSERT_FALSE(writer_->ack_frames().empty());
14104 EXPECT_EQ(1u, writer_->ack_frames().size());
14105}
14106
14107TEST_P(QuicConnectionTest,
14108 ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey) {
14109 if (!connection_.version().UsesTls()) {
14110 return;
14111 }
14112
14113 set_perspective(Perspective::IS_SERVER);
14114 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080014115 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040014116
14117 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
14118 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
14119
14120 // Finish handshake.
14121 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14122 notifier_.NeuterUnencryptedData();
14123 connection_.NeuterUnencryptedPackets();
14124 connection_.OnHandshakeComplete();
14125 EXPECT_CALL(visitor_, GetHandshakeState())
14126 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
14127
14128 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
14129 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14130 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
14131
14132 // 0-RTT packet received out of order should be decoded since the decrypter
14133 // is temporarily retained.
14134 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
14135 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
14136 EXPECT_EQ(
14137 0u,
14138 connection_.GetStats()
14139 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
14140
14141 // Simulate the timeout for discarding 0-RTT keys passing.
14142 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
14143
14144 // Another 0-RTT packet received now should not be decoded.
14145 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
14146 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
14147 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
14148 EXPECT_EQ(
14149 1u,
14150 connection_.GetStats()
14151 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
14152
14153 // The |discard_zero_rtt_decryption_keys_alarm_| should only be set on the
14154 // first 1-RTT packet received.
14155 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
14156 ProcessDataPacketAtLevel(5, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14157 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
14158}
14159
14160TEST_P(QuicConnectionTest, NewTokenFrameInstigateAcks) {
14161 if (!version().HasIetfQuicFrames()) {
14162 return;
14163 }
14164 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
14165
14166 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
14167 EXPECT_CALL(visitor_, OnNewTokenReceived(_));
14168 ProcessFramePacket(QuicFrame(new_token));
14169
14170 // Ensure that this has caused the ACK alarm to be set.
14171 EXPECT_TRUE(connection_.HasPendingAcks());
14172}
14173
14174TEST_P(QuicConnectionTest, ServerClosesConnectionOnNewTokenFrame) {
14175 if (!version().HasIetfQuicFrames()) {
14176 return;
14177 }
14178 set_perspective(Perspective::IS_SERVER);
14179 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
14180 EXPECT_CALL(visitor_, OnNewTokenReceived(_)).Times(0);
14181 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
14182 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14183 ProcessFramePacket(QuicFrame(new_token));
14184 EXPECT_FALSE(connection_.connected());
14185}
14186
14187TEST_P(QuicConnectionTest, OverrideRetryTokenWithRetryPacket) {
14188 if (!version().HasIetfQuicFrames()) {
14189 return;
14190 }
14191 std::string address_token = "TestAddressToken";
14192 connection_.SetSourceAddressTokenToSend(address_token);
14193 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
14194 QuicConnectionPeer::GetPacketCreator(&connection_)),
14195 address_token);
14196 // Passes valid retry and verify token gets overridden.
14197 TestClientRetryHandling(/*invalid_retry_tag=*/false,
14198 /*missing_original_id_in_config=*/false,
14199 /*wrong_original_id_in_config=*/false,
14200 /*missing_retry_id_in_config=*/false,
14201 /*wrong_retry_id_in_config=*/false);
14202}
14203
14204TEST_P(QuicConnectionTest, DonotOverrideRetryTokenWithAddressToken) {
14205 if (!version().HasIetfQuicFrames()) {
14206 return;
14207 }
14208 // Passes valid retry and verify token gets overridden.
14209 TestClientRetryHandling(/*invalid_retry_tag=*/false,
14210 /*missing_original_id_in_config=*/false,
14211 /*wrong_original_id_in_config=*/false,
14212 /*missing_retry_id_in_config=*/false,
14213 /*wrong_retry_id_in_config=*/false);
14214 std::string retry_token = QuicPacketCreatorPeer::GetRetryToken(
14215 QuicConnectionPeer::GetPacketCreator(&connection_));
14216
14217 std::string address_token = "TestAddressToken";
14218 connection_.SetSourceAddressTokenToSend(address_token);
14219 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
14220 QuicConnectionPeer::GetPacketCreator(&connection_)),
14221 retry_token);
14222}
14223
14224TEST_P(QuicConnectionTest,
14225 ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt) {
14226 if (!connection_.version().UsesTls()) {
14227 return;
14228 }
14229
14230 // The code that checks for this error piggybacks on some book-keeping state
14231 // kept for key update, so enable key update for the test.
14232 std::string error_details;
14233 TransportParameters params;
14234 QuicConfig config;
14235 EXPECT_THAT(config.ProcessTransportParameters(
14236 params, /* is_resumption = */ false, &error_details),
14237 IsQuicNoError());
14238 QuicConfigPeer::SetNegotiated(&config, true);
14239 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
14240 connection_.connection_id());
14241 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
14242 &config, connection_.connection_id());
14243 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080014244 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
14245 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040014246 connection_.SetFromConfig(config);
14247
14248 set_perspective(Perspective::IS_SERVER);
14249 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080014250 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040014251
14252 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
14253 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
14254
14255 // Finish handshake.
14256 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14257 notifier_.NeuterUnencryptedData();
14258 connection_.NeuterUnencryptedPackets();
14259 connection_.OnHandshakeComplete();
14260 EXPECT_CALL(visitor_, GetHandshakeState())
14261 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
14262
14263 // Decrypt a 1-RTT packet.
14264 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
14265 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14266 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
14267
14268 // 0-RTT packet with higher packet number than a 1-RTT packet is invalid and
14269 // should cause the connection to be closed.
14270 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14271 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
14272 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
14273 EXPECT_FALSE(connection_.connected());
14274 TestConnectionCloseQuicErrorCode(
14275 QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
14276}
14277
14278// Regression test for b/177312785
14279TEST_P(QuicConnectionTest, PeerMigrateBeforeHandshakeConfirm) {
14280 if (!VersionHasIetfQuicFrames(version().transport_version)) {
14281 return;
14282 }
14283 set_perspective(Perspective::IS_SERVER);
14284 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
14285 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
14286 EXPECT_CALL(visitor_, GetHandshakeState())
14287 .WillRepeatedly(Return(HANDSHAKE_START));
14288
14289 // Clear direct_peer_address.
14290 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
14291 // Clear effective_peer_address, it is the same as direct_peer_address for
14292 // this test.
14293 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
14294 QuicSocketAddress());
14295 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
14296
14297 const QuicSocketAddress kNewPeerAddress =
14298 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
14299 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
14300 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
14301 ENCRYPTION_INITIAL);
14302 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14303 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14304
14305 // Process another packet with a different peer address on server side will
14306 // close connection.
14307 QuicAckFrame frame = InitAckFrame(1);
14308 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14309 EXPECT_CALL(visitor_,
14310 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
14311 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
14312
martindukeba002452023-03-21 08:10:46 -070014313 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
14314 .Times(0);
Bence Békybac04052022-04-07 15:44:29 -040014315 ProcessFramePacketWithAddresses(QuicFrame(&frame), kSelfAddress,
14316 kNewPeerAddress, ENCRYPTION_INITIAL);
14317 EXPECT_FALSE(connection_.connected());
14318}
14319
14320// Regresstion test for b/175685916
14321TEST_P(QuicConnectionTest, TryToFlushAckWithAckQueued) {
14322 if (!version().HasIetfQuicFrames()) {
14323 return;
14324 }
14325 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
14326 set_perspective(Perspective::IS_SERVER);
14327
14328 QuicConfig config;
14329 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
14330 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080014331 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
14332 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040014333 connection_.SetFromConfig(config);
14334 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14335 connection_.OnHandshakeComplete();
14336 QuicPacketCreatorPeer::SetPacketNumber(creator_, 200);
14337
14338 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
14339 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14340 // Sending ACK_FREQUENCY bundles ACK. QuicConnectionPeer::SendPing
14341 // will try to bundle ACK but there is no pending ACK.
14342 EXPECT_CALL(visitor_, SendAckFrequency(_))
14343 .WillOnce(Invoke(&notifier_,
14344 &SimpleSessionNotifier::WriteOrBufferAckFrequency));
14345 QuicConnectionPeer::SendPing(&connection_);
14346}
14347
14348TEST_P(QuicConnectionTest, PathChallengeBeforePeerIpAddressChangeAtServer) {
14349 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070014350 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014351 return;
14352 }
14353 PathProbeTestInit(Perspective::IS_SERVER);
14354 SetClientConnectionId(TestConnectionId(1));
14355 connection_.CreateConnectionIdManager();
14356
14357 QuicConnectionId server_cid0 = connection_.connection_id();
14358 QuicConnectionId client_cid0 = connection_.client_connection_id();
14359 QuicConnectionId client_cid1 = TestConnectionId(2);
14360 QuicConnectionId server_cid1;
14361 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014362 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014363 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14364 .WillOnce(Return(TestConnectionId(456)));
14365 }
haoyuewangada6b822022-06-23 13:41:18 -070014366 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14367 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14368 server_cid1 = cid;
14369 return true;
14370 }));
Bence Békybac04052022-04-07 15:44:29 -040014371 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14372 connection_.MaybeSendConnectionIdToClient();
14373 // Receives new client CID from client.
14374 QuicNewConnectionIdFrame new_cid_frame;
14375 new_cid_frame.connection_id = client_cid1;
14376 new_cid_frame.sequence_number = 1u;
14377 new_cid_frame.retire_prior_to = 0u;
14378 connection_.OnNewConnectionIdFrame(new_cid_frame);
14379 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14380 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14381 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14382
14383 peer_creator_.SetServerConnectionId(server_cid1);
14384 const QuicSocketAddress kNewPeerAddress =
14385 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
14386 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14387 QuicFrames frames1;
14388 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014389 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014390 QuicPathFrameBuffer payload;
14391 EXPECT_CALL(*send_algorithm_,
14392 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14393 .Times(AtLeast(1))
14394 .WillOnce(Invoke([&]() {
14395 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14396 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14397 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14398 EXPECT_FALSE(writer_->path_response_frames().empty());
14399 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14400 payload = writer_->path_challenge_frames().front().data_buffer;
awillia202240c2024-07-08 09:47:00 -070014401 }))
14402 .WillRepeatedly(DoDefault());
14403 ;
Bence Békybac04052022-04-07 15:44:29 -040014404 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14405 ENCRYPTION_FORWARD_SECURE);
14406 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14407 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14408 EXPECT_TRUE(connection_.HasPendingPathValidation());
14409 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14410 const auto* alternative_path =
14411 QuicConnectionPeer::GetAlternativePath(&connection_);
14412 EXPECT_EQ(default_path->client_connection_id, client_cid0);
14413 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14414 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14415 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14416 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14417 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14418
14419 // Process another packet with a different peer address on server side will
14420 // start connection migration.
14421 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014422 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040014423 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14424 }));
14425 // IETF QUIC send algorithm should be changed to a different object, so no
14426 // OnPacketSent() called on the old send algorithm.
14427 EXPECT_CALL(*send_algorithm_,
14428 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14429 .Times(0);
14430 QuicFrames frames2;
14431 frames2.push_back(QuicFrame(frame2_));
14432 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14433 ENCRYPTION_FORWARD_SECURE);
14434 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14435 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14436 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
14437 connection_.active_effective_peer_migration_type());
14438 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14439 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
14440 send_algorithm_);
14441 // Switch to use the mock send algorithm.
14442 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14443 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14444 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14445 .WillRepeatedly(Return(kDefaultTCPMSS));
14446 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14447 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14448 .Times(AnyNumber())
14449 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14450 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14451 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14452 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14453 connection_.SetSendAlgorithm(send_algorithm_);
14454 EXPECT_EQ(default_path->client_connection_id, client_cid1);
14455 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14456 // The previous default path is kept as alternative path before reverse path
14457 // validation finishes.
14458 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
14459 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
14460 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
14461 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
14462
14463 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14464 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14465 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
14466 connection_.active_effective_peer_migration_type());
14467 EXPECT_EQ(1u, connection_.GetStats()
14468 .num_peer_migration_to_proactively_validated_address);
14469
14470 // The PATH_CHALLENGE and PATH_RESPONSE is expanded upto the max packet size
14471 // which may exceeds the anti-amplification limit. Verify server is throttled
14472 // by anti-amplification limit.
14473 connection_.SendCryptoDataWithString("foo", 0);
14474 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
14475
14476 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
14477 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070014478 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040014479 EXPECT_CALL(visitor_, MaybeSendAddressToken());
14480 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14481 .Times(testing::AtLeast(1u));
14482 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
14483 ENCRYPTION_FORWARD_SECURE);
14484 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
14485 // Verify that alternative_path_ is cleared and the peer CID is retired.
14486 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14487 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14488 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14489 auto* retire_peer_issued_cid_alarm =
14490 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14491 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14492 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14493 retire_peer_issued_cid_alarm->Fire();
14494
14495 // Verify the anti-amplification limit is lifted by sending a packet larger
14496 // than the anti-amplification limit.
14497 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
14498 EXPECT_CALL(*send_algorithm_, PacingRate(_))
14499 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14500 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
14501 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -070014502 EXPECT_EQ(1u, connection_.num_unlinkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -040014503}
14504
14505TEST_P(QuicConnectionTest,
14506 PathValidationSucceedsBeforePeerIpAddressChangeAtServer) {
14507 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070014508 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014509 return;
14510 }
14511 PathProbeTestInit(Perspective::IS_SERVER);
14512 connection_.CreateConnectionIdManager();
14513
14514 QuicConnectionId server_cid0 = connection_.connection_id();
14515 QuicConnectionId server_cid1;
14516 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014517 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014518 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14519 .WillOnce(Return(TestConnectionId(456)));
14520 }
haoyuewangada6b822022-06-23 13:41:18 -070014521 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14522 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14523 server_cid1 = cid;
14524 return true;
14525 }));
Bence Békybac04052022-04-07 15:44:29 -040014526 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14527 connection_.MaybeSendConnectionIdToClient();
14528 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14529 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14530
14531 // Receive probing packet with new peer address.
14532 peer_creator_.SetServerConnectionId(server_cid1);
14533 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14534 /*port=*/23456);
14535 QuicPathFrameBuffer payload;
14536 EXPECT_CALL(*send_algorithm_,
14537 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14538 .WillOnce(Invoke([&]() {
14539 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14540 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14541 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14542 EXPECT_FALSE(writer_->path_response_frames().empty());
14543 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14544 payload = writer_->path_challenge_frames().front().data_buffer;
14545 }))
14546 .WillRepeatedly(Invoke([&]() {
14547 // Only start reverse path validation once.
14548 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14549 }));
14550 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14551 QuicFrames frames1;
14552 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014553 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014554 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14555 ENCRYPTION_FORWARD_SECURE);
14556 EXPECT_TRUE(connection_.HasPendingPathValidation());
14557 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14558 const auto* alternative_path =
14559 QuicConnectionPeer::GetAlternativePath(&connection_);
14560 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14561 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14562 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14563
14564 // Receive PATH_RESPONSE should mark the new peer address validated.
14565 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070014566 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040014567 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
14568 ENCRYPTION_FORWARD_SECURE);
14569
14570 // Process another packet with a newer peer address with the same port will
14571 // start connection migration.
14572 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14573 // IETF QUIC send algorithm should be changed to a different object, so no
14574 // OnPacketSent() called on the old send algorithm.
14575 EXPECT_CALL(*send_algorithm_,
14576 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14577 .Times(0);
14578 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14579 /*port=*/34567);
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014580 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040014581 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
14582 }));
14583 EXPECT_CALL(visitor_, MaybeSendAddressToken());
14584 QuicFrames frames2;
14585 frames2.push_back(QuicFrame(frame2_));
14586 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewerPeerAddress,
14587 ENCRYPTION_FORWARD_SECURE);
14588 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
14589 EXPECT_EQ(kNewerPeerAddress, connection_.effective_peer_address());
14590 // Since the newer address has the same IP as the previously validated probing
14591 // address. The peer migration becomes validated immediately.
14592 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
14593 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14594 EXPECT_EQ(1u, connection_.GetStats()
14595 .num_peer_migration_to_proactively_validated_address);
14596 EXPECT_FALSE(connection_.HasPendingPathValidation());
14597 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
14598 send_algorithm_);
14599
14600 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14601 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
14602 // Verify that alternative_path_ is cleared.
14603 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14604 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14605
14606 // Switch to use the mock send algorithm.
14607 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14608 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14609 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14610 .WillRepeatedly(Return(kDefaultTCPMSS));
14611 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14612 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14613 .Times(AnyNumber())
14614 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14615 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14616 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14617 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14618 connection_.SetSendAlgorithm(send_algorithm_);
14619
14620 // Verify the server is not throttled by the anti-amplification limit by
14621 // sending a packet larger than the anti-amplification limit.
14622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
14623 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
14624 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
14625}
14626
danzhb37451f2022-04-19 08:18:54 -070014627// Regression test of b/228645208.
14628TEST_P(QuicConnectionTest, NoNonProbingFrameOnAlternativePath) {
danzh7c0ef5f2023-06-08 12:10:35 -070014629 if (!version().HasIetfQuicFrames()) {
danzhb37451f2022-04-19 08:18:54 -070014630 return;
14631 }
14632
14633 PathProbeTestInit(Perspective::IS_SERVER);
14634 SetClientConnectionId(TestConnectionId(1));
14635 connection_.CreateConnectionIdManager();
14636
14637 QuicConnectionId server_cid0 = connection_.connection_id();
14638 QuicConnectionId client_cid0 = connection_.client_connection_id();
14639 QuicConnectionId client_cid1 = TestConnectionId(2);
14640 QuicConnectionId server_cid1;
14641 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014642 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014643 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14644 .WillOnce(Return(TestConnectionId(456)));
14645 }
haoyuewangada6b822022-06-23 13:41:18 -070014646 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14647 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14648 server_cid1 = cid;
14649 return true;
14650 }));
danzhb37451f2022-04-19 08:18:54 -070014651 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14652 connection_.MaybeSendConnectionIdToClient();
14653 // Receives new client CID from client.
14654 QuicNewConnectionIdFrame new_cid_frame;
14655 new_cid_frame.connection_id = client_cid1;
14656 new_cid_frame.sequence_number = 1u;
14657 new_cid_frame.retire_prior_to = 0u;
14658 connection_.OnNewConnectionIdFrame(new_cid_frame);
14659 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14660 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14661 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14662
14663 peer_creator_.SetServerConnectionId(server_cid1);
14664 const QuicSocketAddress kNewPeerAddress =
14665 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
14666 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14667 QuicFrames frames1;
14668 frames1.push_back(
14669 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
danzhb37451f2022-04-19 08:18:54 -070014670 EXPECT_CALL(*send_algorithm_,
14671 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14672 .Times(AtLeast(1))
14673 .WillOnce(Invoke([&]() {
14674 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14675 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14676 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14677 EXPECT_FALSE(writer_->path_response_frames().empty());
14678 EXPECT_FALSE(writer_->path_challenge_frames().empty());
awillia202240c2024-07-08 09:47:00 -070014679 }))
14680 .WillRepeatedly(DoDefault());
danzhb37451f2022-04-19 08:18:54 -070014681 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14682 ENCRYPTION_FORWARD_SECURE);
14683 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14684 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14685 EXPECT_TRUE(connection_.HasPendingPathValidation());
14686 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14687 const auto* alternative_path =
14688 QuicConnectionPeer::GetAlternativePath(&connection_);
14689 EXPECT_EQ(default_path->client_connection_id, client_cid0);
14690 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14691 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14692 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14693 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14694 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14695
14696 // Process non-probing packets on the default path.
14697 peer_creator_.SetServerConnectionId(server_cid0);
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014698 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillRepeatedly(Invoke([=, this]() {
danzhb37451f2022-04-19 08:18:54 -070014699 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14700 }));
14701 // Receives packets 3 - 39 to send 19 ACK-only packets, which will force the
14702 // connection to reach |kMaxConsecutiveNonRetransmittablePackets| while
14703 // sending the next ACK.
14704 for (size_t i = 3; i <= 39; ++i) {
14705 ProcessDataPacket(i);
14706 }
14707 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14708 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14709
14710 EXPECT_TRUE(connection_.HasPendingAcks());
14711 QuicTime ack_time = connection_.GetAckAlarm()->deadline();
14712 QuicTime path_validation_retry_time =
14713 connection_.GetRetryTimeout(kNewPeerAddress, writer_.get());
14714 // Advance time to simultaneously fire path validation retry and ACK alarms.
14715 clock_.AdvanceTime(std::max(ack_time, path_validation_retry_time) -
14716 clock_.ApproximateNow());
14717
14718 // The 20th ACK should bundle with a WINDOW_UPDATE frame.
14719 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
14720 .WillOnce(Invoke([this]() {
14721 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
14722 }));
martindukee6444ef2022-09-23 12:32:23 -070014723 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14724 .WillOnce(Invoke([&]() {
14725 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14726 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14727 // Retry path validation shouldn't bundle ACK.
14728 EXPECT_TRUE(writer_->ack_frames().empty());
14729 }))
14730 .WillOnce(Invoke([&]() {
14731 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
14732 EXPECT_FALSE(writer_->ack_frames().empty());
14733 EXPECT_FALSE(writer_->window_update_frames().empty());
14734 }));
14735 static_cast<TestAlarmFactory::TestAlarm*>(
14736 QuicPathValidatorPeer::retry_timer(
14737 QuicConnectionPeer::path_validator(&connection_)))
14738 ->Fire();
danzhb37451f2022-04-19 08:18:54 -070014739}
14740
haoyuewangada6b822022-06-23 13:41:18 -070014741TEST_P(QuicConnectionTest, DoNotIssueNewCidIfVisitorSaysNo) {
14742 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070014743 if (!version().HasIetfQuicFrames()) {
haoyuewangada6b822022-06-23 13:41:18 -070014744 return;
14745 }
14746
14747 connection_.CreateConnectionIdManager();
14748
14749 QuicConnectionId server_cid0 = connection_.connection_id();
14750 QuicConnectionId client_cid1 = TestConnectionId(2);
14751 QuicConnectionId server_cid1;
14752 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014753 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014754 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14755 .WillOnce(Return(TestConnectionId(456)));
14756 }
haoyuewangada6b822022-06-23 13:41:18 -070014757 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(false));
haoyuewangc0d96f52023-06-08 11:24:28 -070014758 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(0);
haoyuewangada6b822022-06-23 13:41:18 -070014759 connection_.MaybeSendConnectionIdToClient();
14760}
14761
Bence Békybac04052022-04-07 15:44:29 -040014762TEST_P(QuicConnectionTest,
14763 ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer) {
14764 PathProbeTestInit(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -070014765 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014766 return;
14767 }
14768
14769 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14770 /*port=*/23456);
14771
14772 // Process a packet with a new peer address will start connection migration.
14773 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14774 // IETF QUIC send algorithm should be changed to a different object, so no
14775 // OnPacketSent() called on the old send algorithm.
14776 EXPECT_CALL(*send_algorithm_,
14777 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14778 .Times(0);
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014779 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040014780 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14781 }));
14782 QuicFrames frames2;
14783 frames2.push_back(QuicFrame(frame2_));
14784 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14785 ENCRYPTION_FORWARD_SECURE);
14786 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14787 EXPECT_TRUE(connection_.HasPendingPathValidation());
14788
14789 // Switch to use the mock send algorithm.
14790 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14791 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14792 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14793 .WillRepeatedly(Return(kDefaultTCPMSS));
14794 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14795 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14796 .Times(AnyNumber())
14797 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14798 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14799 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14800 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14801 connection_.SetSendAlgorithm(send_algorithm_);
14802
14803 // Receive probing packet with a newer peer address shouldn't override the
14804 // on-going path validation.
14805 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14806 /*port=*/34567);
14807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14808 .WillOnce(Invoke([&]() {
14809 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14810 EXPECT_FALSE(writer_->path_response_frames().empty());
14811 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14812 }));
14813 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14814 QuicFrames frames1;
14815 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014816 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014817 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewerPeerAddress,
14818 ENCRYPTION_FORWARD_SECURE);
14819 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14820 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14821 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14822 EXPECT_TRUE(connection_.HasPendingPathValidation());
14823}
14824
14825TEST_P(QuicConnectionTest,
14826 PathValidationFailedOnClientDueToLackOfServerConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070014827 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014828 return;
14829 }
14830 PathProbeTestInit(Perspective::IS_CLIENT,
14831 /*receive_new_server_connection_id=*/false);
14832
14833 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14834 /*port=*/34567);
14835
14836 bool success;
14837 connection_.ValidatePath(
14838 std::make_unique<TestQuicPathValidationContext>(
14839 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14840 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014841 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
14842 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014843
14844 EXPECT_FALSE(success);
14845}
14846
14847TEST_P(QuicConnectionTest,
14848 PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime) {
danzh7c0ef5f2023-06-08 12:10:35 -070014849 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014850 return;
14851 }
14852 PathProbeTestInit(Perspective::IS_CLIENT,
14853 /*receive_new_server_connection_id=*/false);
14854 SetClientConnectionId(TestConnectionId(1));
14855
14856 // Make sure server connection ID is available for the 1st validation.
14857 QuicConnectionId server_cid0 = connection_.connection_id();
14858 QuicConnectionId server_cid1 = TestConnectionId(2);
14859 QuicConnectionId server_cid2 = TestConnectionId(4);
14860 QuicConnectionId client_cid1;
14861 QuicNewConnectionIdFrame frame1;
14862 frame1.connection_id = server_cid1;
14863 frame1.sequence_number = 1u;
14864 frame1.retire_prior_to = 0u;
14865 frame1.stateless_reset_token =
14866 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14867 connection_.OnNewConnectionIdFrame(frame1);
14868 const auto* packet_creator =
14869 QuicConnectionPeer::GetPacketCreator(&connection_);
14870 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid0);
14871
14872 // Client will issue a new client connection ID to server.
martinduke08e3ff82022-10-18 09:06:26 -070014873 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14874 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014875 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14876 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14877 client_cid1 = frame.connection_id;
14878 }));
14879
14880 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14881 ASSERT_NE(kSelfAddress1, connection_.self_address());
14882 bool success1;
14883 connection_.ValidatePath(
14884 std::make_unique<TestQuicPathValidationContext>(
14885 kSelfAddress1, connection_.peer_address(), writer_.get()),
14886 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014887 &connection_, kSelfAddress1, connection_.peer_address(), &success1),
14888 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014889
14890 // Migrate upon 1st validation success.
14891 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14892 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14893 &new_writer, /*owns_writer=*/false));
14894 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14895 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14896 EXPECT_EQ(default_path->client_connection_id, client_cid1);
14897 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14898 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14899 const auto* alternative_path =
14900 QuicConnectionPeer::GetAlternativePath(&connection_);
14901 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14902 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14903 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14904 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid1);
14905
14906 // Client will retire server connection ID on old default_path.
14907 auto* retire_peer_issued_cid_alarm =
14908 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14909 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14910 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14911 retire_peer_issued_cid_alarm->Fire();
14912
14913 // Another server connection ID is available to client.
14914 QuicNewConnectionIdFrame frame2;
14915 frame2.connection_id = server_cid2;
14916 frame2.sequence_number = 2u;
14917 frame2.retire_prior_to = 1u;
14918 frame2.stateless_reset_token =
14919 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14920 connection_.OnNewConnectionIdFrame(frame2);
14921
14922 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14923 /*port=*/45678);
14924 bool success2;
14925 connection_.ValidatePath(
14926 std::make_unique<TestQuicPathValidationContext>(
14927 kSelfAddress2, connection_.peer_address(), writer_.get()),
14928 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014929 &connection_, kSelfAddress2, connection_.peer_address(), &success2),
14930 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014931 // Since server does not retire any client connection ID yet, 2nd validation
14932 // would fail due to lack of client connection ID.
14933 EXPECT_FALSE(success2);
14934}
14935
14936TEST_P(QuicConnectionTest, ServerConnectionIdRetiredUponPathValidationFailure) {
danzh7c0ef5f2023-06-08 12:10:35 -070014937 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014938 return;
14939 }
14940 PathProbeTestInit(Perspective::IS_CLIENT);
14941
14942 // Make sure server connection ID is available for validation.
14943 QuicNewConnectionIdFrame frame;
14944 frame.connection_id = TestConnectionId(2);
14945 frame.sequence_number = 1u;
14946 frame.retire_prior_to = 0u;
14947 frame.stateless_reset_token =
14948 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14949 connection_.OnNewConnectionIdFrame(frame);
14950
14951 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14952 /*port=*/34567);
14953 bool success;
14954 connection_.ValidatePath(
14955 std::make_unique<TestQuicPathValidationContext>(
14956 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14957 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014958 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
14959 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014960
14961 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
14962 path_validator->CancelPathValidation();
14963 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14964 EXPECT_FALSE(success);
14965 const auto* alternative_path =
14966 QuicConnectionPeer::GetAlternativePath(&connection_);
14967 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14968 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14969 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14970
14971 // Client will retire server connection ID on alternative_path.
14972 auto* retire_peer_issued_cid_alarm =
14973 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14974 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14975 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
14976 retire_peer_issued_cid_alarm->Fire();
14977}
14978
14979TEST_P(QuicConnectionTest,
14980 MigratePathDirectlyFailedDueToLackOfServerConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070014981 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014982 return;
14983 }
14984 PathProbeTestInit(Perspective::IS_CLIENT,
14985 /*receive_new_server_connection_id=*/false);
14986 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14987 ASSERT_NE(kSelfAddress1, connection_.self_address());
14988
14989 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14990 ASSERT_FALSE(connection_.MigratePath(kSelfAddress1,
14991 connection_.peer_address(), &new_writer,
14992 /*owns_writer=*/false));
14993}
14994
14995TEST_P(QuicConnectionTest,
14996 MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime) {
danzh7c0ef5f2023-06-08 12:10:35 -070014997 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014998 return;
14999 }
15000 PathProbeTestInit(Perspective::IS_CLIENT,
15001 /*receive_new_server_connection_id=*/false);
15002 SetClientConnectionId(TestConnectionId(1));
15003
15004 // Make sure server connection ID is available for the 1st migration.
15005 QuicNewConnectionIdFrame frame1;
15006 frame1.connection_id = TestConnectionId(2);
15007 frame1.sequence_number = 1u;
15008 frame1.retire_prior_to = 0u;
15009 frame1.stateless_reset_token =
15010 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
15011 connection_.OnNewConnectionIdFrame(frame1);
15012
15013 // Client will issue a new client connection ID to server.
15014 QuicConnectionId new_client_connection_id;
martinduke08e3ff82022-10-18 09:06:26 -070015015 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
15016 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040015017 EXPECT_CALL(visitor_, SendNewConnectionId(_))
15018 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
15019 new_client_connection_id = frame.connection_id;
15020 }));
15021
15022 // 1st migration is successful.
15023 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
15024 ASSERT_NE(kSelfAddress1, connection_.self_address());
15025 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
15026 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
15027 &new_writer,
15028 /*owns_writer=*/false));
15029 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
15030 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15031 EXPECT_EQ(default_path->client_connection_id, new_client_connection_id);
15032 EXPECT_EQ(default_path->server_connection_id, frame1.connection_id);
15033 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
15034
15035 // Client will retire server connection ID on old default_path.
15036 auto* retire_peer_issued_cid_alarm =
15037 connection_.GetRetirePeerIssuedConnectionIdAlarm();
15038 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
15039 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
15040 retire_peer_issued_cid_alarm->Fire();
15041
15042 // Another server connection ID is available to client.
15043 QuicNewConnectionIdFrame frame2;
15044 frame2.connection_id = TestConnectionId(4);
15045 frame2.sequence_number = 2u;
15046 frame2.retire_prior_to = 1u;
15047 frame2.stateless_reset_token =
15048 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
15049 connection_.OnNewConnectionIdFrame(frame2);
15050
15051 // Since server does not retire any client connection ID yet, 2nd migration
15052 // would fail due to lack of client connection ID.
15053 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
15054 /*port=*/45678);
15055 auto new_writer2 = std::make_unique<TestPacketWriter>(version(), &clock_,
15056 Perspective::IS_CLIENT);
15057 ASSERT_FALSE(connection_.MigratePath(
15058 kSelfAddress2, connection_.peer_address(), new_writer2.release(),
15059 /*owns_writer=*/true));
15060}
15061
15062TEST_P(QuicConnectionTest,
15063 CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID) {
15064 if (!version().HasIetfQuicFrames()) {
15065 return;
15066 }
15067 set_perspective(Perspective::IS_SERVER);
15068 ASSERT_TRUE(connection_.client_connection_id().IsEmpty());
15069
15070 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15071 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
15072 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
15073 QuicNewConnectionIdFrame frame;
15074 frame.sequence_number = 1u;
15075 frame.connection_id = TestConnectionId(1);
15076 frame.stateless_reset_token =
15077 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15078 frame.retire_prior_to = 0u;
15079
15080 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
15081
15082 EXPECT_FALSE(connection_.connected());
15083 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
15084 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
15085}
15086
15087TEST_P(QuicConnectionTest, NewConnectionIdFrameResultsInError) {
15088 if (!version().HasIetfQuicFrames()) {
15089 return;
15090 }
15091 connection_.CreateConnectionIdManager();
15092 ASSERT_FALSE(connection_.connection_id().IsEmpty());
15093
15094 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
15095 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
15096 QuicNewConnectionIdFrame frame;
15097 frame.sequence_number = 1u;
15098 frame.connection_id = connection_id_; // Reuses connection ID casuing error.
15099 frame.stateless_reset_token =
15100 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15101 frame.retire_prior_to = 0u;
15102
15103 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
15104
15105 EXPECT_FALSE(connection_.connected());
15106 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
15107 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
15108}
15109
15110TEST_P(QuicConnectionTest,
15111 ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
15112 if (!version().HasIetfQuicFrames()) {
15113 return;
15114 }
15115 connection_.CreateConnectionIdManager();
15116
15117 QuicNewConnectionIdFrame frame;
15118 frame.sequence_number = 1u;
15119 frame.connection_id = TestConnectionId(1);
15120 frame.stateless_reset_token =
15121 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15122 frame.retire_prior_to = 0u;
15123
15124 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
15125 auto* retire_peer_issued_cid_alarm =
15126 connection_.GetRetirePeerIssuedConnectionIdAlarm();
15127 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
15128
15129 frame.sequence_number = 2u;
15130 frame.connection_id = TestConnectionId(2);
15131 frame.stateless_reset_token =
15132 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15133 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
15134
15135 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
15136 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
15137 EXPECT_EQ(connection_.connection_id(), connection_id_);
15138
15139 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
15140 retire_peer_issued_cid_alarm->Fire();
15141 EXPECT_EQ(connection_.connection_id(), TestConnectionId(2));
15142 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
15143 TestConnectionId(2));
15144}
15145
15146TEST_P(QuicConnectionTest,
15147 ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
15148 if (!version().HasIetfQuicFrames()) {
15149 return;
15150 }
15151 set_perspective(Perspective::IS_SERVER);
15152 SetClientConnectionId(TestConnectionId(0));
15153
15154 QuicNewConnectionIdFrame frame;
15155 frame.sequence_number = 1u;
15156 frame.connection_id = TestConnectionId(1);
15157 frame.stateless_reset_token =
15158 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15159 frame.retire_prior_to = 0u;
15160
15161 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
15162 auto* retire_peer_issued_cid_alarm =
15163 connection_.GetRetirePeerIssuedConnectionIdAlarm();
15164 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
15165
15166 frame.sequence_number = 2u;
15167 frame.connection_id = TestConnectionId(2);
15168 frame.stateless_reset_token =
15169 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15170 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
15171
15172 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
15173 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
15174 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
15175
15176 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
15177 retire_peer_issued_cid_alarm->Fire();
15178 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
15179 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
15180 TestConnectionId(2));
15181}
15182
15183TEST_P(
15184 QuicConnectionTest,
15185 ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame) {
danzhaf2e52a2022-04-20 07:37:03 -070015186 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040015187 return;
15188 }
15189 PathProbeTestInit(Perspective::IS_SERVER);
15190 SetClientConnectionId(TestConnectionId(0));
15191
15192 // Populate alternative_path_ with probing packet.
15193 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
15194
15195 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
15196 QuicEncryptedPacket(probing_packet->encrypted_buffer,
15197 probing_packet->encrypted_length),
15198 clock_.Now()));
15199 QuicIpAddress new_host;
15200 new_host.FromString("1.1.1.1");
15201 ProcessReceivedPacket(kSelfAddress,
15202 QuicSocketAddress(new_host, /*port=*/23456), *received);
15203
15204 EXPECT_EQ(
15205 TestConnectionId(0),
15206 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
15207
15208 QuicNewConnectionIdFrame frame;
15209 frame.sequence_number = 1u;
15210 frame.connection_id = TestConnectionId(1);
15211 frame.stateless_reset_token =
15212 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15213 frame.retire_prior_to = 0u;
15214
15215 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
15216 auto* retire_peer_issued_cid_alarm =
15217 connection_.GetRetirePeerIssuedConnectionIdAlarm();
15218 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
15219
15220 frame.sequence_number = 2u;
15221 frame.connection_id = TestConnectionId(2);
15222 frame.stateless_reset_token =
15223 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15224 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
15225
15226 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
15227 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
15228 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
15229
15230 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
15231 retire_peer_issued_cid_alarm->Fire();
15232 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
15233 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
15234 TestConnectionId(2));
15235 // Clean up alternative path connection ID.
15236 EXPECT_EQ(
15237 TestConnectionId(2),
15238 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
15239}
15240
15241TEST_P(QuicConnectionTest,
15242 CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued) {
danzh7c0ef5f2023-06-08 12:10:35 -070015243 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040015244 return;
15245 }
15246 set_perspective(Perspective::IS_SERVER);
15247
15248 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15249 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
15250 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
15251 QuicRetireConnectionIdFrame frame;
15252 frame.sequence_number = 1u;
15253
15254 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
15255
15256 EXPECT_FALSE(connection_.connected());
15257 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
15258 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
15259}
15260
15261TEST_P(QuicConnectionTest, RetireConnectionIdFrameResultsInError) {
danzh7c0ef5f2023-06-08 12:10:35 -070015262 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040015263 return;
15264 }
15265 set_perspective(Perspective::IS_SERVER);
15266 connection_.CreateConnectionIdManager();
15267
martinduke08e3ff82022-10-18 09:06:26 -070015268 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070015269 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
15270 .WillOnce(Return(TestConnectionId(456)));
15271 }
danzh7c0ef5f2023-06-08 12:10:35 -070015272 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
Bence Békybac04052022-04-07 15:44:29 -040015273 EXPECT_CALL(visitor_, SendNewConnectionId(_));
15274 connection_.MaybeSendConnectionIdToClient();
15275
15276 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15277 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
15278 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
15279 QuicRetireConnectionIdFrame frame;
15280 frame.sequence_number = 2u; // The corresponding ID is never issued.
15281
15282 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
15283
15284 EXPECT_FALSE(connection_.connected());
15285 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
15286 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
15287}
15288
15289TEST_P(QuicConnectionTest,
15290 ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore) {
15291 if (!version().HasIetfQuicFrames()) {
15292 return;
15293 }
15294 set_perspective(Perspective::IS_SERVER);
15295 connection_.CreateConnectionIdManager();
15296
15297 auto* retire_self_issued_cid_alarm =
15298 connection_.GetRetireSelfIssuedConnectionIdAlarm();
15299 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
15300
15301 QuicConnectionId cid0 = connection_id_;
15302 QuicRetireConnectionIdFrame frame;
15303 frame.sequence_number = 0u;
danzh7c0ef5f2023-06-08 12:10:35 -070015304
15305 if (!connection_.connection_id().IsEmpty()) {
15306 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(cid0))
15307 .WillOnce(Return(TestConnectionId(456)));
15308 EXPECT_CALL(connection_id_generator_,
15309 GenerateNextConnectionId(TestConnectionId(456)))
15310 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040015311 }
danzh7c0ef5f2023-06-08 12:10:35 -070015312 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
15313 .Times(2)
15314 .WillRepeatedly(Return(true));
15315 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -040015316 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(frame));
15317}
15318
15319TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070015320 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040015321 return;
15322 }
15323 set_perspective(Perspective::IS_SERVER);
15324 connection_.CreateConnectionIdManager();
15325 QuicConnectionId recorded_cid;
haoyuewangada6b822022-06-23 13:41:18 -070015326 auto cid_recorder = [&recorded_cid](const QuicConnectionId& cid) -> bool {
Bence Békybac04052022-04-07 15:44:29 -040015327 recorded_cid = cid;
haoyuewangada6b822022-06-23 13:41:18 -070015328 return true;
Bence Békybac04052022-04-07 15:44:29 -040015329 };
15330 QuicConnectionId cid0 = connection_id_;
15331 QuicConnectionId cid1;
15332 QuicConnectionId cid2;
15333 EXPECT_EQ(connection_.connection_id(), cid0);
15334 EXPECT_EQ(connection_.GetOneActiveServerConnectionId(), cid0);
15335
15336 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke08e3ff82022-10-18 09:06:26 -070015337 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070015338 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
15339 .WillOnce(Return(TestConnectionId(456)));
15340 }
haoyuewangada6b822022-06-23 13:41:18 -070015341 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040015342 .WillOnce(Invoke(cid_recorder));
15343 EXPECT_CALL(visitor_, SendNewConnectionId(_));
15344 connection_.MaybeSendConnectionIdToClient();
15345 cid1 = recorded_cid;
15346
15347 auto* retire_self_issued_cid_alarm =
15348 connection_.GetRetireSelfIssuedConnectionIdAlarm();
15349 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
15350
15351 // Generate three packets with different connection IDs that will arrive out
15352 // of order (2, 1, 3) later.
15353 char buffers[3][kMaxOutgoingPacketSize];
15354 // Destination connection ID of packet1 is cid0.
15355 auto packet1 =
15356 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
15357 buffers[0], kMaxOutgoingPacketSize);
15358 peer_creator_.SetServerConnectionId(cid1);
15359 auto retire_cid_frame = std::make_unique<QuicRetireConnectionIdFrame>();
15360 retire_cid_frame->sequence_number = 0u;
15361 // Destination connection ID of packet2 is cid1.
15362 auto packet2 = ConstructPacket({QuicFrame(retire_cid_frame.release())},
15363 ENCRYPTION_FORWARD_SECURE, buffers[1],
15364 kMaxOutgoingPacketSize);
15365 // Destination connection ID of packet3 is cid1.
15366 auto packet3 =
15367 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
15368 buffers[2], kMaxOutgoingPacketSize);
15369
15370 // Packet2 with RetireConnectionId frame trigers sending NewConnectionId
15371 // immediately.
martinduke08e3ff82022-10-18 09:06:26 -070015372 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070015373 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
15374 .WillOnce(Return(TestConnectionId(456)));
15375 }
haoyuewangada6b822022-06-23 13:41:18 -070015376 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040015377 .WillOnce(Invoke(cid_recorder));
15378 EXPECT_CALL(visitor_, SendNewConnectionId(_));
15379 peer_creator_.SetServerConnectionId(cid1);
15380 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet2);
15381 cid2 = recorded_cid;
15382 // cid0 is not retired immediately.
15383 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
15384 ElementsAre(cid0, cid1, cid2));
15385 ASSERT_TRUE(retire_self_issued_cid_alarm->IsSet());
15386 EXPECT_EQ(connection_.connection_id(), cid1);
15387 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
15388 connection_.GetOneActiveServerConnectionId() == cid1 ||
15389 connection_.GetOneActiveServerConnectionId() == cid2);
15390
15391 // Packet1 updates the connection ID on the default path but not the active
15392 // connection ID.
15393 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet1);
15394 EXPECT_EQ(connection_.connection_id(), cid0);
15395 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
15396 connection_.GetOneActiveServerConnectionId() == cid1 ||
15397 connection_.GetOneActiveServerConnectionId() == cid2);
15398
15399 // cid0 is retired when the retire CID alarm fires.
15400 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(cid0));
15401 retire_self_issued_cid_alarm->Fire();
15402 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
15403 ElementsAre(cid1, cid2));
15404 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
15405 connection_.GetOneActiveServerConnectionId() == cid2);
15406
15407 // Packet3 updates the connection ID on the default path.
15408 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet3);
15409 EXPECT_EQ(connection_.connection_id(), cid1);
15410 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
15411 connection_.GetOneActiveServerConnectionId() == cid2);
15412}
15413
15414TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoAlternativePath) {
15415 if (!version().HasIetfQuicFrames()) {
15416 return;
15417 }
15418 set_perspective(Perspective::IS_SERVER);
15419 connection_.CreateConnectionIdManager();
15420 connection_.set_client_connection_id(TestConnectionId(1));
15421
15422 // Set up the state after path probing.
15423 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15424 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
15425 QuicIpAddress new_host;
15426 new_host.FromString("12.12.12.12");
15427 alternative_path->self_address = default_path->self_address;
15428 alternative_path->peer_address = QuicSocketAddress(new_host, 12345);
15429 alternative_path->server_connection_id = TestConnectionId(3);
15430 ASSERT_TRUE(alternative_path->client_connection_id.IsEmpty());
15431 ASSERT_FALSE(alternative_path->stateless_reset_token.has_value());
15432
15433 QuicNewConnectionIdFrame frame;
15434 frame.sequence_number = 1u;
15435 frame.connection_id = TestConnectionId(5);
15436 frame.stateless_reset_token =
15437 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15438 frame.retire_prior_to = 0u;
15439 // New ID is patched onto the alternative path when the needed
15440 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
15441 connection_.OnNewConnectionIdFrame(frame);
15442
15443 ASSERT_EQ(alternative_path->client_connection_id, frame.connection_id);
15444 ASSERT_EQ(alternative_path->stateless_reset_token,
15445 frame.stateless_reset_token);
15446}
15447
15448TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoDefaultPath) {
15449 if (!version().HasIetfQuicFrames()) {
15450 return;
15451 }
15452 set_perspective(Perspective::IS_SERVER);
15453 connection_.CreateConnectionIdManager();
15454 connection_.set_client_connection_id(TestConnectionId(1));
15455
15456 // Set up the state after peer migration without probing.
15457 auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15458 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
15459 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
15460 *alternative_path = std::move(*default_path);
15461 QuicIpAddress new_host;
15462 new_host.FromString("12.12.12.12");
15463 default_path->self_address = default_path->self_address;
15464 default_path->peer_address = QuicSocketAddress(new_host, 12345);
15465 default_path->server_connection_id = TestConnectionId(3);
15466 packet_creator->SetDefaultPeerAddress(default_path->peer_address);
15467 packet_creator->SetServerConnectionId(default_path->server_connection_id);
15468 packet_creator->SetClientConnectionId(default_path->client_connection_id);
15469
15470 ASSERT_FALSE(default_path->validated);
15471 ASSERT_TRUE(default_path->client_connection_id.IsEmpty());
15472 ASSERT_FALSE(default_path->stateless_reset_token.has_value());
15473
15474 QuicNewConnectionIdFrame frame;
15475 frame.sequence_number = 1u;
15476 frame.connection_id = TestConnectionId(5);
15477 frame.stateless_reset_token =
15478 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15479 frame.retire_prior_to = 0u;
15480 // New ID is patched onto the default path when the needed
15481 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
15482 connection_.OnNewConnectionIdFrame(frame);
15483
15484 ASSERT_EQ(default_path->client_connection_id, frame.connection_id);
15485 ASSERT_EQ(default_path->stateless_reset_token, frame.stateless_reset_token);
15486 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), frame.connection_id);
15487}
15488
15489TEST_P(QuicConnectionTest, ShouldGeneratePacketBlockedByMissingConnectionId) {
15490 if (!version().HasIetfQuicFrames()) {
15491 return;
15492 }
15493 set_perspective(Perspective::IS_SERVER);
15494 connection_.set_client_connection_id(TestConnectionId(1));
15495 connection_.CreateConnectionIdManager();
15496 if (version().SupportsAntiAmplificationLimit()) {
15497 QuicConnectionPeer::SetAddressValidated(&connection_);
15498 }
15499
15500 ASSERT_TRUE(
15501 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
15502
15503 QuicPacketCreator* packet_creator =
15504 QuicConnectionPeer::GetPacketCreator(&connection_);
15505 QuicIpAddress peer_host1;
15506 peer_host1.FromString("12.12.12.12");
15507 QuicSocketAddress peer_address1(peer_host1, 1235);
15508
15509 {
15510 // No connection ID is available as context is created without any.
15511 QuicPacketCreator::ScopedPeerAddressContext context(
15512 packet_creator, peer_address1, EmptyQuicConnectionId(),
danzh7c0ef5f2023-06-08 12:10:35 -070015513 EmptyQuicConnectionId());
Bence Békybac04052022-04-07 15:44:29 -040015514 ASSERT_FALSE(connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
15515 NOT_HANDSHAKE));
15516 }
15517 ASSERT_TRUE(
15518 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
15519}
15520
15521// Regression test for b/182571515
15522TEST_P(QuicConnectionTest, LostDataThenGetAcknowledged) {
15523 set_perspective(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -070015524 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -070015525 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040015526 return;
15527 }
15528
15529 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
15530 if (version().SupportsAntiAmplificationLimit()) {
15531 QuicConnectionPeer::SetAddressValidated(&connection_);
15532 }
15533 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15534 // Discard INITIAL key.
15535 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15536 connection_.NeuterUnencryptedPackets();
15537 EXPECT_CALL(visitor_, GetHandshakeState())
15538 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
15539
15540 QuicPacketNumber last_packet;
15541 // Send packets 1 to 4.
15542 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
15543 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 2
15544 SendStreamDataToPeer(3, "foo", 6, NO_FIN, &last_packet); // Packet 3
15545 SendStreamDataToPeer(3, "foo", 9, NO_FIN, &last_packet); // Packet 4
15546
15547 // Process a PING packet to set peer address.
15548 ProcessFramePacket(QuicFrame(QuicPingFrame()));
15549
15550 // Process a packet containing a STREAM_FRAME and an ACK with changed peer
15551 // address.
15552 QuicFrames frames;
15553 frames.push_back(QuicFrame(frame1_));
15554 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}});
15555 frames.push_back(QuicFrame(&ack));
15556
Bence Békybac04052022-04-07 15:44:29 -040015557 // Invoke OnCanWrite.
Bence Békybac04052022-04-07 15:44:29 -040015558 QuicIpAddress ip_address;
15559 ASSERT_TRUE(ip_address.FromString("127.0.52.223"));
vasilvvac2e30d2022-06-02 14:26:59 -070015560 EXPECT_QUIC_BUG(
15561 {
15562 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(1);
15563 EXPECT_CALL(visitor_, OnStreamFrame(_))
15564 .WillOnce(InvokeWithoutArgs(&notifier_,
15565 &SimpleSessionNotifier::OnCanWrite));
15566 ProcessFramesPacketWithAddresses(frames, kSelfAddress,
15567 QuicSocketAddress(ip_address, 1000),
15568 ENCRYPTION_FORWARD_SECURE);
15569 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
15570
15571 // Verify stream frame will not be retransmitted.
15572 EXPECT_TRUE(writer_->stream_frames().empty());
15573 },
15574 "Try to write mid packet processing");
Bence Békybac04052022-04-07 15:44:29 -040015575}
15576
15577TEST_P(QuicConnectionTest, PtoSendStreamData) {
15578 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15579 return;
15580 }
15581 set_perspective(Perspective::IS_SERVER);
15582 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
15583 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15584 }
15585 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015586 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15587 EXPECT_TRUE(connection_.HasPendingAcks());
15588
Bence Békybac04052022-04-07 15:44:29 -040015589 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15590 // Send INITIAL 1.
15591 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15592
martinduke9e0811c2022-12-08 20:35:57 -080015593 connection_.SetEncrypter(
15594 ENCRYPTION_HANDSHAKE,
15595 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015596 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15597 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015598 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015599 // Send HANDSHAKE packets.
15600 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15601 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15602
martinduke9e0811c2022-12-08 20:35:57 -080015603 connection_.SetEncrypter(
15604 ENCRYPTION_FORWARD_SECURE,
15605 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015606 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15607
15608 // Send half RTT packet with congestion control blocked.
15609 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
15610 connection_.SendStreamDataWithString(2, std::string(1500, 'a'), 0, NO_FIN);
15611
15612 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15613 connection_.GetRetransmissionAlarm()->Fire();
15614 // Verify INITIAL and HANDSHAKE get retransmitted.
martinduke9e0811c2022-12-08 20:35:57 -080015615 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015616}
15617
15618TEST_P(QuicConnectionTest, SendingZeroRttPacketsDoesNotPostponePTO) {
15619 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15620 return;
15621 }
Bence Békybac04052022-04-07 15:44:29 -040015622 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15623 // Send CHLO.
15624 connection_.SendCryptoStreamData();
15625 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15626 // Install 0-RTT keys.
15627 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15628 std::make_unique<TaggingEncrypter>(0x02));
15629 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15630
15631 // CHLO gets acknowledged after 10ms.
15632 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15633 QuicAckFrame frame1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070015634 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015635 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15636 // Verify PTO is still armed since address validation is not finished yet.
15637 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15638 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15639
15640 // Send 0-RTT packet.
15641 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15642 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15643 std::make_unique<TaggingEncrypter>(0x02));
15644 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15645 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15646 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15647 // PTO deadline should be unchanged.
15648 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15649}
15650
15651TEST_P(QuicConnectionTest, QueueingUndecryptablePacketsDoesntPostponePTO) {
15652 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15653 return;
15654 }
15655 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080015656 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
15657 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040015658 QuicConfig config;
15659 config.set_max_undecryptable_packets(3);
15660 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040015661 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15662 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15663 // Send CHLO.
15664 connection_.SendCryptoStreamData();
15665
15666 // Send 0-RTT packet.
15667 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15668 std::make_unique<TaggingEncrypter>(0x02));
15669 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15670 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15671
15672 // CHLO gets acknowledged after 10ms.
15673 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15674 QuicAckFrame frame1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070015675 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015676 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15677 // Verify PTO is still armed since address validation is not finished yet.
15678 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15679 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15680
15681 // Receive an undecryptable packets.
15682 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15683 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15684 std::make_unique<TaggingEncrypter>(0xFF));
15685 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15686 // Verify PTO deadline is sooner.
15687 EXPECT_GT(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15688 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15689
15690 // PTO fires.
15691 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15692 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15693 connection_.GetRetransmissionAlarm()->Fire();
15694 // Verify PTO is still armed since address validation is not finished yet.
15695 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15696 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15697
15698 // Verify PTO deadline does not change.
15699 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15700 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15701}
15702
15703TEST_P(QuicConnectionTest, QueueUndecryptableHandshakePackets) {
15704 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15705 return;
15706 }
15707 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080015708 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
15709 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040015710 QuicConfig config;
15711 config.set_max_undecryptable_packets(3);
15712 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040015713 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15714 connection_.RemoveDecrypter(ENCRYPTION_HANDSHAKE);
15715 // Send CHLO.
15716 connection_.SendCryptoStreamData();
15717
15718 // Send 0-RTT packet.
15719 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15720 std::make_unique<TaggingEncrypter>(0x02));
15721 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15722 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15723 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15724
15725 // Receive an undecryptable handshake packet.
15726 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15727 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15728 std::make_unique<TaggingEncrypter>(0xFF));
15729 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
15730 // Verify this handshake packet gets queued.
15731 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15732}
15733
15734TEST_P(QuicConnectionTest, PingNotSentAt0RTTLevelWhenInitialAvailable) {
15735 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15736 return;
15737 }
Bence Békybac04052022-04-07 15:44:29 -040015738 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15739 // Send CHLO.
15740 connection_.SendCryptoStreamData();
15741 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080015742 connection_.SetEncrypter(
15743 ENCRYPTION_ZERO_RTT,
15744 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015745 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15746 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15747
15748 // CHLO gets acknowledged after 10ms.
15749 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15750 QuicAckFrame frame1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070015751 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015752 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15753 // Verify PTO is still armed since address validation is not finished yet.
15754 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15755 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15756
15757 // PTO fires.
15758 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15759 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15760 connection_.GetRetransmissionAlarm()->Fire();
15761 // Verify the PING gets sent in ENCRYPTION_INITIAL.
martinduke9e0811c2022-12-08 20:35:57 -080015762 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015763}
15764
15765TEST_P(QuicConnectionTest, AckElicitingFrames) {
danzh7c0ef5f2023-06-08 12:10:35 -070015766 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040015767 return;
15768 }
martinduke15c43d02024-09-26 14:00:37 -070015769 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080015770 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
15771 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martinduke15c43d02024-09-26 14:00:37 -070015772 QuicConfig config;
15773 config.SetReliableStreamReset(true);
15774 connection_.SetFromConfig(config);
15775
martinduke08e3ff82022-10-18 09:06:26 -070015776 EXPECT_CALL(connection_id_generator_,
15777 GenerateNextConnectionId(TestConnectionId(12)))
15778 .WillOnce(Return(TestConnectionId(456)));
15779 EXPECT_CALL(connection_id_generator_,
15780 GenerateNextConnectionId(TestConnectionId(456)))
15781 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040015782 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
15783 EXPECT_CALL(visitor_, OnRstStream(_));
martinduke15c43d02024-09-26 14:00:37 -070015784 EXPECT_CALL(visitor_, OnResetStreamAt(_));
Bence Békybac04052022-04-07 15:44:29 -040015785 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
15786 EXPECT_CALL(visitor_, OnBlockedFrame(_));
15787 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
15788 EXPECT_CALL(visitor_, OnStreamFrame(_));
martindukeba002452023-03-21 08:10:46 -070015789 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015790 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_));
15791 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_));
15792 EXPECT_CALL(visitor_, OnStopSendingFrame(_));
15793 EXPECT_CALL(visitor_, OnMessageReceived(""));
15794 EXPECT_CALL(visitor_, OnNewTokenReceived(""));
15795
15796 SetClientConnectionId(TestConnectionId(12));
15797 connection_.CreateConnectionIdManager();
15798 QuicConnectionPeer::GetSelfIssuedConnectionIdManager(&connection_)
15799 ->MaybeSendNewConnectionIds();
15800 connection_.set_can_receive_ack_frequency_frame();
15801
15802 QuicAckFrame ack_frame = InitAckFrame(1);
15803 QuicRstStreamFrame rst_stream_frame;
15804 QuicWindowUpdateFrame window_update_frame;
15805 QuicPathChallengeFrame path_challenge_frame;
15806 QuicNewConnectionIdFrame new_connection_id_frame;
renjietang785c7cb2023-08-21 09:10:25 -070015807 new_connection_id_frame.sequence_number = 1u;
Bence Békybac04052022-04-07 15:44:29 -040015808 QuicRetireConnectionIdFrame retire_connection_id_frame;
15809 retire_connection_id_frame.sequence_number = 1u;
15810 QuicStopSendingFrame stop_sending_frame;
15811 QuicPathResponseFrame path_response_frame;
15812 QuicMessageFrame message_frame;
15813 QuicNewTokenFrame new_token_frame;
15814 QuicAckFrequencyFrame ack_frequency_frame;
vasilvv60a22a62024-02-05 08:26:22 -080015815 QuicResetStreamAtFrame reset_stream_at_frame;
Bence Békybac04052022-04-07 15:44:29 -040015816 QuicBlockedFrame blocked_frame;
15817 size_t packet_number = 1;
15818
15819 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
vasilvv60a22a62024-02-05 08:26:22 -080015820 QuicFramer* framer = const_cast<QuicFramer*>(&connection_.framer());
15821 framer->set_process_reset_stream_at(true);
15822 peer_framer_.set_process_reset_stream_at(true);
Bence Békybac04052022-04-07 15:44:29 -040015823
15824 for (uint8_t i = 0; i < NUM_FRAME_TYPES; ++i) {
15825 QuicFrameType frame_type = static_cast<QuicFrameType>(i);
15826 bool skipped = false;
15827 QuicFrame frame;
15828 QuicFrames frames;
15829 // Add some padding to fullfill the min size requirement of header
15830 // protection.
15831 frames.push_back(QuicFrame(QuicPaddingFrame(10)));
15832 switch (frame_type) {
15833 case PADDING_FRAME:
15834 frame = QuicFrame(QuicPaddingFrame(10));
15835 break;
15836 case MTU_DISCOVERY_FRAME:
15837 frame = QuicFrame(QuicMtuDiscoveryFrame());
15838 break;
15839 case PING_FRAME:
15840 frame = QuicFrame(QuicPingFrame());
15841 break;
15842 case MAX_STREAMS_FRAME:
15843 frame = QuicFrame(QuicMaxStreamsFrame());
15844 break;
15845 case STOP_WAITING_FRAME:
15846 // Not supported.
15847 skipped = true;
15848 break;
15849 case STREAMS_BLOCKED_FRAME:
15850 frame = QuicFrame(QuicStreamsBlockedFrame());
15851 break;
15852 case STREAM_FRAME:
15853 frame = QuicFrame(QuicStreamFrame());
15854 break;
15855 case HANDSHAKE_DONE_FRAME:
15856 frame = QuicFrame(QuicHandshakeDoneFrame());
15857 break;
15858 case ACK_FRAME:
15859 frame = QuicFrame(&ack_frame);
15860 break;
15861 case RST_STREAM_FRAME:
15862 frame = QuicFrame(&rst_stream_frame);
15863 break;
15864 case CONNECTION_CLOSE_FRAME:
15865 // Do not test connection close.
15866 skipped = true;
15867 break;
15868 case GOAWAY_FRAME:
15869 // Does not exist in IETF QUIC.
15870 skipped = true;
15871 break;
15872 case BLOCKED_FRAME:
15873 frame = QuicFrame(blocked_frame);
15874 break;
15875 case WINDOW_UPDATE_FRAME:
15876 frame = QuicFrame(window_update_frame);
15877 break;
15878 case PATH_CHALLENGE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015879 frame = QuicFrame(path_challenge_frame);
Bence Békybac04052022-04-07 15:44:29 -040015880 break;
15881 case STOP_SENDING_FRAME:
15882 frame = QuicFrame(stop_sending_frame);
15883 break;
15884 case NEW_CONNECTION_ID_FRAME:
15885 frame = QuicFrame(&new_connection_id_frame);
15886 break;
15887 case RETIRE_CONNECTION_ID_FRAME:
15888 frame = QuicFrame(&retire_connection_id_frame);
15889 break;
15890 case PATH_RESPONSE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015891 frame = QuicFrame(path_response_frame);
Bence Békybac04052022-04-07 15:44:29 -040015892 break;
15893 case MESSAGE_FRAME:
15894 frame = QuicFrame(&message_frame);
15895 break;
15896 case CRYPTO_FRAME:
15897 // CRYPTO_FRAME is ack eliciting is covered by other tests.
15898 skipped = true;
15899 break;
15900 case NEW_TOKEN_FRAME:
15901 frame = QuicFrame(&new_token_frame);
15902 break;
15903 case ACK_FREQUENCY_FRAME:
15904 frame = QuicFrame(&ack_frequency_frame);
15905 break;
vasilvv60a22a62024-02-05 08:26:22 -080015906 case RESET_STREAM_AT_FRAME:
15907 frame = QuicFrame(&reset_stream_at_frame);
15908 break;
Bence Békybac04052022-04-07 15:44:29 -040015909 case NUM_FRAME_TYPES:
15910 skipped = true;
15911 break;
15912 }
15913 if (skipped) {
15914 continue;
15915 }
15916 ASSERT_EQ(frame_type, frame.type);
15917 frames.push_back(frame);
15918 EXPECT_FALSE(connection_.HasPendingAcks());
15919 // Process frame.
15920 ProcessFramesPacketAtLevel(packet_number++, frames,
15921 ENCRYPTION_FORWARD_SECURE);
15922 if (QuicUtils::IsAckElicitingFrame(frame_type)) {
15923 ASSERT_TRUE(connection_.HasPendingAcks()) << frame;
15924 // Flush ACK.
15925 clock_.AdvanceTime(DefaultDelayedAckTime());
15926 connection_.GetAckAlarm()->Fire();
15927 }
15928 EXPECT_FALSE(connection_.HasPendingAcks());
15929 ASSERT_TRUE(connection_.connected());
15930 }
15931}
15932
15933TEST_P(QuicConnectionTest, ReceivedChloAndAck) {
15934 if (!version().HasIetfQuicFrames()) {
15935 return;
15936 }
15937 set_perspective(Perspective::IS_SERVER);
15938 QuicFrames frames;
15939 QuicAckFrame ack_frame = InitAckFrame(1);
15940 frames.push_back(MakeCryptoFrame());
15941 frames.push_back(QuicFrame(&ack_frame));
15942
15943 EXPECT_CALL(visitor_, OnCryptoFrame(_))
15944 .WillOnce(IgnoreResult(InvokeWithoutArgs(
15945 &connection_, &TestConnection::SendCryptoStreamData)));
15946 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15947 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15948 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
15949 ENCRYPTION_INITIAL);
15950}
15951
15952// Regression test for b/201643321.
15953TEST_P(QuicConnectionTest, FailedToRetransmitShlo) {
danzh4d58dae2023-06-06 11:13:10 -070015954 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -070015955 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040015956 return;
15957 }
15958 set_perspective(Perspective::IS_SERVER);
15959 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15960 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015961 // Received INITIAL 1.
15962 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15963 EXPECT_TRUE(connection_.HasPendingAcks());
15964
martinduke9e0811c2022-12-08 20:35:57 -080015965 peer_framer_.SetEncrypter(
15966 ENCRYPTION_ZERO_RTT,
15967 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015968
martinduke9e0811c2022-12-08 20:35:57 -080015969 connection_.SetEncrypter(
15970 ENCRYPTION_HANDSHAKE,
15971 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015972 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015973 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015974 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015975 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15976 connection_.SetEncrypter(
15977 ENCRYPTION_FORWARD_SECURE,
15978 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015979 // Received ENCRYPTION_ZERO_RTT 1.
15980 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15981 {
15982 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15983 // Send INITIAL 1.
15984 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15985 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15986 // Send HANDSHAKE 2.
15987 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15988 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15989 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15990 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15991 // Send half RTT data to exhaust amplification credit.
15992 connection_.SendStreamDataWithString(0, std::string(100 * 1024, 'a'), 0,
15993 NO_FIN);
15994 }
15995 // Received INITIAL 2.
15996 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
15997 ASSERT_TRUE(connection_.HasPendingAcks());
15998 // Verify ACK delay is 1ms.
15999 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
16000 connection_.GetAckAlarm()->deadline());
16001 // ACK is not throttled by amplification limit, and SHLO is bundled. Also
16002 // HANDSHAKE + 1RTT packets get coalesced.
fayange9753892022-05-17 03:57:11 -070016003 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -040016004 // ACK alarm fires.
16005 clock_.AdvanceTime(kAlarmGranularity);
16006 connection_.GetAckAlarm()->Fire();
fayange9753892022-05-17 03:57:11 -070016007 // Verify 1-RTT packet is coalesced.
martinduke9e0811c2022-12-08 20:35:57 -080016008 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040016009 // Only the first packet in the coalesced packet has been processed,
16010 // verify SHLO is bundled with INITIAL ACK.
16011 EXPECT_EQ(1u, writer_->ack_frames().size());
16012 EXPECT_EQ(1u, writer_->crypto_frames().size());
16013 // Process the coalesced HANDSHAKE packet.
16014 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16015 auto packet = writer_->coalesced_packet()->Clone();
16016 writer_->framer()->ProcessPacket(*packet);
16017 EXPECT_EQ(0u, writer_->ack_frames().size());
16018 EXPECT_EQ(1u, writer_->crypto_frames().size());
fayange9753892022-05-17 03:57:11 -070016019 // Process the coalesced 1-RTT packet.
16020 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16021 packet = writer_->coalesced_packet()->Clone();
16022 writer_->framer()->ProcessPacket(*packet);
16023 EXPECT_EQ(0u, writer_->crypto_frames().size());
16024 EXPECT_EQ(1u, writer_->stream_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040016025
16026 // Received INITIAL 3.
16027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
16028 ProcessCryptoPacketAtLevel(3, ENCRYPTION_INITIAL);
16029 EXPECT_TRUE(connection_.HasPendingAcks());
16030}
16031
16032// Regression test for b/216133388.
16033TEST_P(QuicConnectionTest, FailedToConsumeCryptoData) {
16034 if (!version().HasIetfQuicFrames()) {
16035 return;
16036 }
16037 set_perspective(Perspective::IS_SERVER);
16038 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
16039 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040016040 // Received INITIAL 1.
16041 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16042 EXPECT_TRUE(connection_.HasPendingAcks());
16043
martinduke9e0811c2022-12-08 20:35:57 -080016044 peer_framer_.SetEncrypter(
16045 ENCRYPTION_ZERO_RTT,
16046 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
16047 connection_.SetEncrypter(
16048 ENCRYPTION_HANDSHAKE,
16049 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016050 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080016051 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016052 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080016053 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
16054 connection_.SetEncrypter(
16055 ENCRYPTION_FORWARD_SECURE,
16056 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016057 // Received ENCRYPTION_ZERO_RTT 1.
16058 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
16059 {
16060 QuicConnection::ScopedPacketFlusher flusher(&connection_);
16061 // Send INITIAL 1.
16062 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16063 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
16064 // Send HANDSHAKE 2.
16065 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
16066 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
16067 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
16068 ENCRYPTION_HANDSHAKE);
16069 // Send 1-RTT 3.
16070 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16071 connection_.SendStreamDataWithString(0, std::string(40, 'a'), 0, NO_FIN);
16072 }
16073 // Received HANDSHAKE Ping, hence discard INITIAL keys.
16074 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16075 std::make_unique<TaggingEncrypter>(0x03));
16076 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
16077 connection_.NeuterUnencryptedPackets();
16078 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
16079 clock_.AdvanceTime(kAlarmGranularity);
16080 {
16081 QuicConnection::ScopedPacketFlusher flusher(&connection_);
16082 // Sending this 1-RTT data would leave the coalescer only have space to
16083 // accommodate the HANDSHAKE ACK. The crypto data cannot be bundled with the
16084 // ACK.
16085 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16086 connection_.SendStreamDataWithString(0, std::string(1395, 'a'), 40, NO_FIN);
16087 }
16088 // Verify retransmission alarm is armed.
16089 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
16090 const QuicTime retransmission_time =
16091 connection_.GetRetransmissionAlarm()->deadline();
16092 clock_.AdvanceTime(retransmission_time - clock_.Now());
16093 connection_.GetRetransmissionAlarm()->Fire();
16094
fayang43294412022-04-21 09:22:12 -070016095 // Verify the retransmission is a coalesced packet with HANDSHAKE 2 and
16096 // 1-RTT 3.
martinduke9e0811c2022-12-08 20:35:57 -080016097 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
fayang43294412022-04-21 09:22:12 -070016098 // Only the first packet in the coalesced packet has been processed.
16099 EXPECT_EQ(1u, writer_->crypto_frames().size());
16100 // Process the coalesced 1-RTT packet.
16101 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16102 auto packet = writer_->coalesced_packet()->Clone();
16103 writer_->framer()->ProcessPacket(*packet);
16104 EXPECT_EQ(1u, writer_->stream_frames().size());
16105 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
Bence Békybac04052022-04-07 15:44:29 -040016106 // Verify retransmission alarm is still armed.
16107 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
16108}
16109
16110TEST_P(QuicConnectionTest,
16111 RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing) {
16112 // An endpoint might postpone the processing of ACK when the corresponding
16113 // decryption key is not available. This test makes sure the RTT sample does
16114 // not include the queuing delay.
16115 if (!version().HasIetfQuicFrames()) {
16116 return;
16117 }
16118 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080016119 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
16120 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040016121 QuicConfig config;
16122 config.set_max_undecryptable_packets(3);
16123 connection_.SetFromConfig(config);
16124
16125 // 30ms RTT.
16126 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
16127 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
16128 rtt_stats->UpdateRtt(kTestRTT, QuicTime::Delta::Zero(), QuicTime::Zero());
Bence Békybac04052022-04-07 15:44:29 -040016129
16130 // Send 0-RTT packet.
16131 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080016132 connection_.SetEncrypter(
16133 ENCRYPTION_ZERO_RTT,
16134 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040016135 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
16136 connection_.SendStreamDataWithString(0, std::string(10, 'a'), 0, FIN);
16137
16138 // Receives 1-RTT ACK for 0-RTT packet after RTT + ack_delay.
wub349df3d2024-04-26 11:37:32 -070016139 clock_.AdvanceTime(kTestRTT + QuicTime::Delta::FromMilliseconds(
16140 GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040016141 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
martinduke9e0811c2022-12-08 20:35:57 -080016142 peer_framer_.SetEncrypter(
16143 ENCRYPTION_FORWARD_SECURE,
16144 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016145 QuicAckFrame ack_frame = InitAckFrame(1);
16146 // Peer reported ACK delay.
16147 ack_frame.ack_delay_time =
wub349df3d2024-04-26 11:37:32 -070016148 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
Bence Békybac04052022-04-07 15:44:29 -040016149 QuicFrames frames;
16150 frames.push_back(QuicFrame(&ack_frame));
16151 QuicPacketHeader header =
16152 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
16153 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
16154
16155 char buffer[kMaxOutgoingPacketSize];
16156 size_t encrypted_length = peer_framer_.EncryptPayload(
16157 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
16158 kMaxOutgoingPacketSize);
16159 connection_.ProcessUdpPacket(
16160 kSelfAddress, kPeerAddress,
16161 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
16162 if (connection_.GetSendAlarm()->IsSet()) {
16163 connection_.GetSendAlarm()->Fire();
16164 }
16165 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
16166
16167 // Assume 1-RTT decrypter is available after 10ms.
16168 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
16169 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080016170 SetDecrypter(
16171 ENCRYPTION_FORWARD_SECURE,
16172 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016173 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
16174
martindukeba002452023-03-21 08:10:46 -070016175 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040016176 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
16177 // Verify RTT sample does not include queueing delay.
16178 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
16179}
16180
16181// Regression test for b/112480134.
16182TEST_P(QuicConnectionTest, NoExtraPaddingInReserializedInitial) {
16183 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
16184 if (!IsDefaultTestConfiguration() ||
16185 !connection_.version().CanSendCoalescedPackets()) {
16186 return;
16187 }
16188
16189 set_perspective(Perspective::IS_SERVER);
16190 MockQuicConnectionDebugVisitor debug_visitor;
16191 connection_.set_debug_visitor(&debug_visitor);
16192
16193 uint64_t debug_visitor_sent_count = 0;
wub92727922023-07-13 08:47:39 -070016194 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040016195 .WillRepeatedly([&]() { debug_visitor_sent_count++; });
16196
16197 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
16198 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040016199
16200 // Received INITIAL 1.
16201 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16202
martinduke9e0811c2022-12-08 20:35:57 -080016203 peer_framer_.SetEncrypter(
16204 ENCRYPTION_ZERO_RTT,
16205 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
16206 connection_.SetEncrypter(
16207 ENCRYPTION_HANDSHAKE,
16208 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016209 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080016210 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016211 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080016212 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
16213 connection_.SetEncrypter(
16214 ENCRYPTION_FORWARD_SECURE,
16215 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016216
16217 // Received ENCRYPTION_ZERO_RTT 2.
16218 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
16219
16220 {
16221 QuicConnection::ScopedPacketFlusher flusher(&connection_);
16222 // Send INITIAL 1.
16223 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16224 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
16225 // Send HANDSHAKE 2.
16226 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
16227 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
16228 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
16229 ENCRYPTION_HANDSHAKE);
16230 // Send 1-RTT 3.
16231 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16232 connection_.SendStreamDataWithString(0, std::string(400, 'b'), 0, NO_FIN);
16233 }
16234
16235 // Arrange the stream data to be sent in response to ENCRYPTION_INITIAL 3.
16236 const std::string data4(1000, '4'); // Data to send in stream id 4
16237 const std::string data8(3000, '8'); // Data to send in stream id 8
16238 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce([&]() {
16239 connection_.producer()->SaveStreamData(4, data4);
16240 connection_.producer()->SaveStreamData(8, data8);
16241
16242 notifier_.WriteOrBufferData(4, data4.size(), FIN_AND_PADDING);
16243
16244 // This should trigger FlushCoalescedPacket.
16245 notifier_.WriteOrBufferData(8, data8.size(), FIN);
16246 });
16247
16248 QuicByteCount pending_padding_after_serialize_2nd_1rtt_packet = 0;
16249 QuicPacketCount num_1rtt_packets_serialized = 0;
16250 EXPECT_CALL(connection_, OnSerializedPacket(_))
16251 .WillRepeatedly([&](SerializedPacket packet) {
16252 if (packet.encryption_level == ENCRYPTION_FORWARD_SECURE) {
16253 num_1rtt_packets_serialized++;
16254 if (num_1rtt_packets_serialized == 2) {
16255 pending_padding_after_serialize_2nd_1rtt_packet =
16256 connection_.packet_creator().pending_padding_bytes();
16257 }
16258 }
16259 connection_.QuicConnection::OnSerializedPacket(std::move(packet));
16260 });
16261
16262 // Server receives INITIAL 3, this will serialzie FS 7 (stream 4, stream 8),
16263 // which will trigger a flush of a coalesced packet consists of INITIAL 4,
16264 // HS 5 and FS 6 (stream 4).
wub08efde42022-05-09 12:25:02 -070016265
16266 // Expect no QUIC_BUG.
16267 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
16268 EXPECT_EQ(
16269 debug_visitor_sent_count,
16270 connection_.sent_packet_manager().GetLargestSentPacket().ToUint64());
Bence Békybac04052022-04-07 15:44:29 -040016271
16272 // The error only happens if after serializing the second 1RTT packet(pkt #7),
16273 // the pending padding bytes is non zero.
16274 EXPECT_GT(pending_padding_after_serialize_2nd_1rtt_packet, 0u);
16275 EXPECT_TRUE(connection_.connected());
16276}
16277
16278TEST_P(QuicConnectionTest, ReportedAckDelayIncludesQueuingDelay) {
16279 if (!version().HasIetfQuicFrames()) {
16280 return;
16281 }
16282 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080016283 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
16284 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
Bence Békybac04052022-04-07 15:44:29 -040016285 QuicConfig config;
16286 config.set_max_undecryptable_packets(3);
16287 connection_.SetFromConfig(config);
16288
16289 // Receive 1-RTT ack-eliciting packet while keys are not available.
16290 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080016291 peer_framer_.SetEncrypter(
16292 ENCRYPTION_FORWARD_SECURE,
16293 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016294 QuicFrames frames;
16295 frames.push_back(QuicFrame(QuicPingFrame()));
16296 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
16297 QuicPacketHeader header =
16298 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
16299 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
16300
16301 char buffer[kMaxOutgoingPacketSize];
16302 size_t encrypted_length = peer_framer_.EncryptPayload(
16303 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
16304 kMaxOutgoingPacketSize);
16305 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
16306 const QuicTime packet_receipt_time = clock_.Now();
16307 connection_.ProcessUdpPacket(
16308 kSelfAddress, kPeerAddress,
16309 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
16310 if (connection_.GetSendAlarm()->IsSet()) {
16311 connection_.GetSendAlarm()->Fire();
16312 }
16313 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
16314 // 1-RTT keys become available after 10ms.
16315 const QuicTime::Delta kQueuingDelay = QuicTime::Delta::FromMilliseconds(10);
16316 clock_.AdvanceTime(kQueuingDelay);
16317 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
16318 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080016319 SetDecrypter(
16320 ENCRYPTION_FORWARD_SECURE,
16321 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016322 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
16323
16324 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
16325 ASSERT_TRUE(connection_.HasPendingAcks());
fayangfea655c2022-05-17 08:19:12 -070016326 EXPECT_EQ(packet_receipt_time + DefaultDelayedAckTime(),
16327 connection_.GetAckAlarm()->deadline());
16328 clock_.AdvanceTime(packet_receipt_time + DefaultDelayedAckTime() -
16329 clock_.Now());
Bence Békybac04052022-04-07 15:44:29 -040016330 // Fire ACK alarm.
16331 connection_.GetAckAlarm()->Fire();
16332 ASSERT_EQ(1u, writer_->ack_frames().size());
fayangfea655c2022-05-17 08:19:12 -070016333 // Verify ACK delay time does not include queuing delay.
16334 EXPECT_EQ(DefaultDelayedAckTime(), writer_->ack_frames()[0].ack_delay_time);
Bence Békybac04052022-04-07 15:44:29 -040016335}
16336
16337TEST_P(QuicConnectionTest, CoalesceOneRTTPacketWithInitialAndHandshakePackets) {
16338 if (!version().HasIetfQuicFrames()) {
16339 return;
16340 }
16341 set_perspective(Perspective::IS_SERVER);
16342 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
16343 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040016344
16345 // Received INITIAL 1.
16346 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16347
martinduke9e0811c2022-12-08 20:35:57 -080016348 peer_framer_.SetEncrypter(
16349 ENCRYPTION_ZERO_RTT,
16350 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040016351
martinduke9e0811c2022-12-08 20:35:57 -080016352 connection_.SetEncrypter(
16353 ENCRYPTION_HANDSHAKE,
16354 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016355 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080016356 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016357 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080016358 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
16359 connection_.SetEncrypter(
16360 ENCRYPTION_FORWARD_SECURE,
16361 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016362
16363 // Received ENCRYPTION_ZERO_RTT 2.
16364 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
16365
16366 {
16367 QuicConnection::ScopedPacketFlusher flusher(&connection_);
16368 // Send INITIAL 1.
16369 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16370 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
16371 // Send HANDSHAKE 2.
16372 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
16373 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
16374 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
16375 ENCRYPTION_HANDSHAKE);
16376 // Send 1-RTT data.
16377 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16378 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
16379 }
16380 // Verify coalesced packet [INITIAL 1 + HANDSHAKE 2 + part of 1-RTT data] +
16381 // rest of 1-RTT data get sent.
16382 EXPECT_EQ(2u, writer_->packets_write_attempts());
16383
16384 // Received ENCRYPTION_INITIAL 3.
16385 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
16386
16387 // Verify a coalesced packet gets sent.
16388 EXPECT_EQ(3u, writer_->packets_write_attempts());
16389
16390 // Only the first INITIAL packet has been processed yet.
16391 EXPECT_EQ(1u, writer_->ack_frames().size());
16392 EXPECT_EQ(1u, writer_->crypto_frames().size());
16393
16394 // Process HANDSHAKE packet.
16395 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16396 auto packet = writer_->coalesced_packet()->Clone();
16397 writer_->framer()->ProcessPacket(*packet);
16398 EXPECT_EQ(1u, writer_->crypto_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040016399 // Process 1-RTT packet.
16400 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16401 packet = writer_->coalesced_packet()->Clone();
16402 writer_->framer()->ProcessPacket(*packet);
16403 EXPECT_EQ(1u, writer_->stream_frames().size());
16404}
16405
16406// Regression test for b/180103273
16407TEST_P(QuicConnectionTest, SendMultipleConnectionCloses) {
wub0f4f8582024-10-08 08:09:50 -070016408 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
16409 if (!IsDefaultTestConfiguration()) {
16410 return;
16411 }
Bence Békybac04052022-04-07 15:44:29 -040016412 if (!version().HasIetfQuicFrames() ||
16413 !GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
16414 return;
16415 }
16416 set_perspective(Perspective::IS_SERVER);
16417 // Finish handshake.
16418 QuicConnectionPeer::SetAddressValidated(&connection_);
16419 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16420 notifier_.NeuterUnencryptedData();
16421 connection_.NeuterUnencryptedPackets();
16422 connection_.OnHandshakeComplete();
16423 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
16424 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
16425 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080016426 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040016427
16428 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
16429 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
bnc3000cba2022-04-18 12:19:14 -070016430 // Verify that BeforeConnectionCloseSent() gets called twice,
16431 // while OnConnectionClosed() is called only once.
Bence Békybac04052022-04-07 15:44:29 -040016432 EXPECT_CALL(visitor_, BeforeConnectionCloseSent()).Times(2);
16433 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
16434 // Send connection close w/o closing connection.
16435 QuicConnectionPeer::SendConnectionClosePacket(
16436 &connection_, INTERNAL_ERROR, QUIC_INTERNAL_ERROR, "internal error");
bnc3000cba2022-04-18 12:19:14 -070016437 // Fire blackhole detection alarm. This will invoke
16438 // SendConnectionClosePacket() a second time.
wub0f4f8582024-10-08 08:09:50 -070016439 EXPECT_QUIC_BUG(connection_.GetBlackholeDetectorAlarm()->Fire(),
16440 // 1=QUIC_INTERNAL_ERROR, 85=QUIC_TOO_MANY_RTOS.
16441 "Initial error code: 1, new error code: 85");
Bence Békybac04052022-04-07 15:44:29 -040016442}
16443
16444// Regression test for b/157895910.
16445TEST_P(QuicConnectionTest, EarliestSentTimeNotInitializedWhenPtoFires) {
16446 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
16447 return;
16448 }
16449 set_perspective(Perspective::IS_SERVER);
16450 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
16451 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040016452
16453 // Received INITIAL 1.
16454 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080016455 connection_.SetEncrypter(
16456 ENCRYPTION_HANDSHAKE,
16457 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016458 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080016459 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
16460 connection_.SetEncrypter(
16461 ENCRYPTION_FORWARD_SECURE,
16462 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016463 {
16464 QuicConnection::ScopedPacketFlusher flusher(&connection_);
16465 // Send INITIAL 1.
16466 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16467 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
16468 // Send HANDSHAKE 2.
16469 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
16470 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
16471 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
16472 ENCRYPTION_HANDSHAKE);
16473 // Send half RTT data.
16474 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16475 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
16476 }
16477
16478 // Received ACKs for both INITIAL and HANDSHAKE packets.
martindukeba002452023-03-21 08:10:46 -070016479 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040016480 .Times(AnyNumber());
16481 QuicFrames frames1;
16482 QuicAckFrame ack_frame1 = InitAckFrame(1);
16483 frames1.push_back(QuicFrame(&ack_frame1));
16484
16485 QuicFrames frames2;
16486 QuicAckFrame ack_frame2 =
16487 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
16488 frames2.push_back(QuicFrame(&ack_frame2));
16489 ProcessCoalescedPacket(
16490 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
16491 // Verify PTO is not armed given the only outstanding data is half RTT data.
16492 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16493}
16494
wub47bb7282022-06-14 09:40:33 -070016495TEST_P(QuicConnectionTest, CalculateNetworkBlackholeDelay) {
16496 if (!IsDefaultTestConfiguration()) {
16497 return;
16498 }
16499
16500 const QuicTime::Delta kOneSec = QuicTime::Delta::FromSeconds(1);
16501 const QuicTime::Delta kTwoSec = QuicTime::Delta::FromSeconds(2);
16502 const QuicTime::Delta kFourSec = QuicTime::Delta::FromSeconds(4);
16503
16504 // Normal case: blackhole_delay longer than path_degrading_delay +
16505 // 2*pto_delay.
16506 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
16507 kOneSec),
16508 kFourSec);
16509
16510 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
16511 kTwoSec),
16512 QuicTime::Delta::FromSeconds(5));
16513}
16514
fayangb225e172022-06-27 17:45:38 -070016515TEST_P(QuicConnectionTest, FixBytesAccountingForBufferedCoalescedPackets) {
16516 if (!connection_.version().CanSendCoalescedPackets()) {
16517 return;
16518 }
fayangb225e172022-06-27 17:45:38 -070016519 // Write is blocked.
16520 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
16521 writer_->SetWriteBlocked();
16522 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16523 QuicConnectionPeer::SendPing(&connection_);
16524 const QuicConnectionStats& stats = connection_.GetStats();
fayang4e283832022-09-01 12:47:07 -070016525 // Verify padding is accounted.
16526 EXPECT_EQ(stats.bytes_sent, connection_.max_packet_length());
fayangb225e172022-06-27 17:45:38 -070016527}
16528
fayang161ce6e2022-07-01 18:02:11 -070016529TEST_P(QuicConnectionTest, StrictAntiAmplificationLimit) {
16530 if (!connection_.version().SupportsAntiAmplificationLimit()) {
16531 return;
16532 }
16533 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
16534 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -070016535 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16536 // Verify no data can be sent at the beginning because bytes received is 0.
16537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
16538 connection_.SendCryptoDataWithString("foo", 0);
16539 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
16540 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
16541 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16542
16543 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -070016544 GetQuicFlag(quic_anti_amplification_factor);
fayang161ce6e2022-07-01 18:02:11 -070016545 // Receives packet 1.
16546 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
16547 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16548 .Times(anti_amplification_factor);
wubc9fd4292023-08-14 13:00:21 -070016549 ForceWillingAndAbleToWriteOnceForDeferSending();
fayang161ce6e2022-07-01 18:02:11 -070016550 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16551 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16552 std::make_unique<TaggingEncrypter>(0x02));
16553 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16554 std::make_unique<TaggingEncrypter>(0x03));
16555
16556 for (size_t i = 1; i < anti_amplification_factor - 1; ++i) {
16557 connection_.SendCryptoDataWithString("foo", i * 3);
16558 }
16559 // Send an addtion packet with max_packet_size - 1.
16560 connection_.SetMaxPacketLength(connection_.max_packet_length() - 1);
16561 connection_.SendCryptoDataWithString("bar",
16562 (anti_amplification_factor - 1) * 3);
16563 EXPECT_LT(writer_->total_bytes_written(),
16564 anti_amplification_factor *
16565 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
birenroyef686222022-09-12 11:34:34 -070016566 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070016567 // 3 connection closes which will be buffered.
16568 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
16569 // Verify retransmission alarm is not set.
16570 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16571 } else {
16572 // Crypto + 3 connection closes.
16573 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
16574 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
16575 }
16576 // Try to send another packet with max_packet_size.
16577 connection_.SetMaxPacketLength(connection_.max_packet_length() + 1);
16578 connection_.SendCryptoDataWithString("bar", anti_amplification_factor * 3);
16579 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16580 // Close connection.
16581 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
16582 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
16583 connection_.CloseConnection(
16584 QUIC_INTERNAL_ERROR, "error",
16585 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
16586 EXPECT_EQ(0u, connection_.NumQueuedPackets());
birenroyef686222022-09-12 11:34:34 -070016587 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070016588 EXPECT_LT(writer_->total_bytes_written(),
16589 anti_amplification_factor *
16590 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16591 } else {
16592 EXPECT_LT(writer_->total_bytes_written(),
16593 (anti_amplification_factor + 2) *
16594 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16595 EXPECT_GT(writer_->total_bytes_written(),
16596 (anti_amplification_factor + 1) *
16597 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16598 }
16599}
16600
martinduke96840a02022-07-14 07:09:06 -070016601TEST_P(QuicConnectionTest, OriginalConnectionId) {
16602 set_perspective(Perspective::IS_SERVER);
16603 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
16604 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
16605 connection_.connection_id());
16606 QuicConnectionId original({0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
16607 connection_.SetOriginalDestinationConnectionId(original);
16608 EXPECT_EQ(original, connection_.GetOriginalDestinationConnectionId());
16609 // Send a 1-RTT packet to start the DiscardZeroRttDecryptionKeys timer.
16610 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16611 ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE);
martindukee6444ef2022-09-23 12:32:23 -070016612 if (connection_.version().UsesTls()) {
martinduke96840a02022-07-14 07:09:06 -070016613 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
16614 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(original));
16615 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
16616 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
16617 connection_.connection_id());
16618 } else {
16619 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), original);
16620 }
16621}
16622
martindukebae24052022-10-06 15:27:46 -070016623ACTION_P2(InstallKeys, conn, level) {
16624 uint8_t crypto_input = (level == ENCRYPTION_FORWARD_SECURE) ? 0x03 : 0x02;
16625 conn->SetEncrypter(level, std::make_unique<TaggingEncrypter>(crypto_input));
16626 conn->InstallDecrypter(
16627 level, std::make_unique<StrictTaggingDecrypter>(crypto_input));
16628 conn->SetDefaultEncryptionLevel(level);
martindukec2a33062022-09-30 16:04:13 -070016629}
16630
martindukebae24052022-10-06 15:27:46 -070016631TEST_P(QuicConnectionTest, ServerConnectionIdChangeWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070016632 if (!connection_.version().HasIetfQuicFrames()) {
16633 return;
16634 }
16635 // Call SetFromConfig so that the undecrypted packet buffer size is
16636 // initialized above zero.
16637 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
martindukeeaf27602024-11-12 14:34:40 -080016638 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
16639 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martindukec2a33062022-09-30 16:04:13 -070016640 QuicConfig config;
16641 connection_.SetFromConfig(config);
martindukebae24052022-10-06 15:27:46 -070016642 connection_.RemoveEncrypter(ENCRYPTION_FORWARD_SECURE);
16643 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martindukec2a33062022-09-30 16:04:13 -070016644
16645 // Send Client Initial.
16646 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16647 connection_.SendCryptoStreamData();
16648
16649 EXPECT_EQ(1u, writer_->packets_write_attempts());
martindukebae24052022-10-06 15:27:46 -070016650 // Server Handshake packet with new connection ID is buffered.
martindukec2a33062022-09-30 16:04:13 -070016651 QuicConnectionId old_id = connection_id_;
16652 connection_id_ = TestConnectionId(2);
16653 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16654 std::make_unique<TaggingEncrypter>(0x02));
16655 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
martindukec2a33062022-09-30 16:04:13 -070016656 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16657 EXPECT_EQ(connection_.connection_id(), old_id);
16658
martindukebae24052022-10-06 15:27:46 -070016659 // Server 1-RTT Packet is buffered.
16660 peer_creator_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16661 std::make_unique<TaggingEncrypter>(0x03));
16662 ProcessDataPacket(0);
16663 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 2u);
16664
martindukec2a33062022-09-30 16:04:13 -070016665 // Pretend the server Initial packet will yield the Handshake keys.
16666 EXPECT_CALL(visitor_, OnCryptoFrame(_))
16667 .Times(2)
martindukebae24052022-10-06 15:27:46 -070016668 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE))
16669 .WillOnce(InstallKeys(&connection_, ENCRYPTION_FORWARD_SECURE));
16670 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martindukec2a33062022-09-30 16:04:13 -070016671 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16672 // Two packets processed, connection ID changed.
16673 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16674 EXPECT_EQ(connection_.connection_id(), connection_id_);
16675}
16676
martindukebae24052022-10-06 15:27:46 -070016677TEST_P(QuicConnectionTest, ServerConnectionIdChangeTwiceWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070016678 if (!connection_.version().HasIetfQuicFrames()) {
16679 return;
16680 }
16681 // Call SetFromConfig so that the undecrypted packet buffer size is
16682 // initialized above zero.
16683 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
martindukeeaf27602024-11-12 14:34:40 -080016684 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
16685 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martindukec2a33062022-09-30 16:04:13 -070016686 QuicConfig config;
16687 connection_.SetFromConfig(config);
16688
16689 // Send Client Initial.
16690 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16691 connection_.SendCryptoStreamData();
16692
16693 EXPECT_EQ(1u, writer_->packets_write_attempts());
16694 // Server Handshake Packet Arrives with new connection ID.
16695 QuicConnectionId old_id = connection_id_;
16696 connection_id_ = TestConnectionId(2);
16697 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16698 std::make_unique<TaggingEncrypter>(0x02));
16699 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
16700 // Packet is buffered.
16701 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16702 EXPECT_EQ(connection_.connection_id(), old_id);
16703
16704 // Pretend the server Initial packet will yield the Handshake keys.
16705 EXPECT_CALL(visitor_, OnCryptoFrame(_))
martindukebae24052022-10-06 15:27:46 -070016706 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE));
martindukec2a33062022-09-30 16:04:13 -070016707 connection_id_ = TestConnectionId(1);
16708 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16709 // Handshake packet discarded because there's a different connection ID.
16710 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16711 EXPECT_EQ(connection_.connection_id(), connection_id_);
16712}
16713
fayangdbd6a302022-12-21 16:24:27 -080016714TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress) {
16715 // Test the scenario where the client validates server preferred address by
16716 // receiving PATH_RESPONSE from server preferred address.
16717 if (!connection_.version().HasIetfQuicFrames()) {
16718 return;
16719 }
fayanga0618a62022-12-28 19:31:24 -080016720 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016721 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016722 const QuicSocketAddress kNewSelfAddress =
16723 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16724 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016725 const StatelessResetToken kNewStatelessResetToken =
16726 QuicUtils::GenerateStatelessResetToken(TestConnectionId(17));
16727 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16728 EXPECT_CALL(visitor_, GetHandshakeState())
16729 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16730 // Kick off path validation of server preferred address on handshake
16731 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016732 EXPECT_CALL(visitor_,
16733 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16734 .WillOnce(Invoke([&]() {
16735 connection_.ValidatePath(
16736 std::make_unique<TestQuicPathValidationContext>(
16737 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16738 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016739 &connection_),
16740 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016741 }));
fayangdbd6a302022-12-21 16:24:27 -080016742 connection_.OnHandshakeComplete();
16743 EXPECT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016744 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16745 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016746 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016747 new_writer.last_packet_header().destination_connection_id);
16748 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016749
fayang37765f62022-12-27 17:49:13 -080016750 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016751 QuicPathFrameBuffer payload =
fayang37765f62022-12-27 17:49:13 -080016752 new_writer.path_challenge_frames().front().data_buffer;
fayangdbd6a302022-12-21 16:24:27 -080016753 // Send data packet while path validation is pending.
16754 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016755 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016756 // While path validation is pending, packet is sent on default path.
16757 EXPECT_EQ(TestConnectionId(),
16758 writer_->last_packet_header().destination_connection_id);
16759 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16760 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16761 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16762
danzh8fdee2e2023-01-05 15:33:02 -080016763 // Receive path response from server preferred address.
fayangdbd6a302022-12-21 16:24:27 -080016764 QuicFrames frames;
16765 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16766 // Verify send_algorithm gets reset after migration (new sent packet is not
16767 // updated to exsting send_algorithm_).
16768 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang37765f62022-12-27 17:49:13 -080016769 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
16770 kServerPreferredAddress,
16771 ENCRYPTION_FORWARD_SECURE);
fayangdbd6a302022-12-21 16:24:27 -080016772 ASSERT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016773 EXPECT_TRUE(QuicConnectionPeer::IsDefaultPath(&connection_, kNewSelfAddress,
16774 kServerPreferredAddress));
16775 ASSERT_FALSE(new_writer.stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016776 // Verify stream data is retransmitted on new path.
16777 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016778 new_writer.last_packet_header().destination_connection_id);
16779 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016780 // Verify stateless reset token gets changed.
16781 EXPECT_FALSE(
16782 connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16783 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16784
16785 auto* retire_peer_issued_cid_alarm =
16786 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16787 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16788 // Verify client retires connection ID with sequence number 0.
16789 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16790 retire_peer_issued_cid_alarm->Fire();
fayang37765f62022-12-27 17:49:13 -080016791 EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16792 EXPECT_FALSE(
16793 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016794}
16795
16796TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress2) {
16797 // Test the scenario where the client validates server preferred address by
16798 // receiving PATH_RESPONSE from original server address.
16799 if (!connection_.version().HasIetfQuicFrames()) {
16800 return;
16801 }
fayanga0618a62022-12-28 19:31:24 -080016802 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016803 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016804 const QuicSocketAddress kNewSelfAddress =
16805 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16806 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016807 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16808 EXPECT_CALL(visitor_, GetHandshakeState())
16809 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16810 // Kick off path validation of server preferred address on handshake
16811 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016812 EXPECT_CALL(visitor_,
16813 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16814 .WillOnce(Invoke([&]() {
16815 connection_.ValidatePath(
16816 std::make_unique<TestQuicPathValidationContext>(
16817 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16818 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016819 &connection_),
16820 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016821 }));
fayangdbd6a302022-12-21 16:24:27 -080016822 connection_.OnHandshakeComplete();
16823 EXPECT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016824 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016825 QuicPathFrameBuffer payload =
fayang37765f62022-12-27 17:49:13 -080016826 new_writer.path_challenge_frames().front().data_buffer;
fayangdbd6a302022-12-21 16:24:27 -080016827 // Send data packet while path validation is pending.
16828 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016829 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016830 EXPECT_EQ(TestConnectionId(),
16831 writer_->last_packet_header().destination_connection_id);
16832 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16833
danzh8fdee2e2023-01-05 15:33:02 -080016834 // Receive path response from original server address.
fayangdbd6a302022-12-21 16:24:27 -080016835 QuicFrames frames;
16836 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
fayang37765f62022-12-27 17:49:13 -080016837 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
fayangdbd6a302022-12-21 16:24:27 -080016838 ENCRYPTION_FORWARD_SECURE);
16839 ASSERT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016840 ASSERT_FALSE(new_writer.stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016841 // Verify stream data is retransmitted on new path.
16842 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016843 new_writer.last_packet_header().destination_connection_id);
16844 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016845
16846 auto* retire_peer_issued_cid_alarm =
16847 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16848 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16849 // Verify client retires connection ID with sequence number 0.
16850 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16851 retire_peer_issued_cid_alarm->Fire();
16852
16853 // Verify another packet from original server address gets processed.
16854 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16855 frames.clear();
16856 frames.push_back(QuicFrame(frame1_));
16857 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
16858 ENCRYPTION_FORWARD_SECURE);
fayang37765f62022-12-27 17:49:13 -080016859 EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16860 EXPECT_FALSE(
16861 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016862}
16863
16864TEST_P(QuicConnectionTest, ClientFailedToValidateServerPreferredAddress) {
16865 // Test the scenario where the client fails to validate server preferred
16866 // address.
16867 if (!connection_.version().HasIetfQuicFrames()) {
16868 return;
16869 }
fayanga0618a62022-12-28 19:31:24 -080016870 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016871 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016872 const QuicSocketAddress kNewSelfAddress =
16873 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16874 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016875 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16876 EXPECT_CALL(visitor_, GetHandshakeState())
16877 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16878 // Kick off path validation of server preferred address on handshake
16879 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016880 EXPECT_CALL(visitor_,
16881 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16882 .WillOnce(Invoke([&]() {
16883 connection_.ValidatePath(
16884 std::make_unique<TestQuicPathValidationContext>(
16885 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16886 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016887 &connection_),
16888 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016889 }));
fayangdbd6a302022-12-21 16:24:27 -080016890 connection_.OnHandshakeComplete();
danzh8fdee2e2023-01-05 15:33:02 -080016891 EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
fayang37765f62022-12-27 17:49:13 -080016892 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16893 &connection_, kNewSelfAddress, kServerPreferredAddress));
16894 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016895
16896 // Receive mismatched path challenge from original server address.
16897 QuicFrames frames;
16898 frames.push_back(
16899 QuicFrame(QuicPathResponseFrame(99, {0, 1, 2, 3, 4, 5, 6, 7})));
fayang37765f62022-12-27 17:49:13 -080016900 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
fayangdbd6a302022-12-21 16:24:27 -080016901 ENCRYPTION_FORWARD_SECURE);
16902 ASSERT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016903 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16904 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016905
16906 // Simluate path validation times out.
16907 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16908 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16909 static_cast<TestAlarmFactory::TestAlarm*>(
16910 QuicPathValidatorPeer::retry_timer(
16911 QuicConnectionPeer::path_validator(&connection_)))
16912 ->Fire();
16913 }
16914 EXPECT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016915 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
16916 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016917 // Verify stream data is sent on the default path.
16918 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016919 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016920 EXPECT_EQ(TestConnectionId(),
16921 writer_->last_packet_header().destination_connection_id);
16922 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16923
16924 auto* retire_peer_issued_cid_alarm =
16925 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16926 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16927 // Verify client retires connection ID with sequence number 1.
16928 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
16929 retire_peer_issued_cid_alarm->Fire();
16930 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
fayang37765f62022-12-27 17:49:13 -080016931 EXPECT_FALSE(connection_.GetStats().server_preferred_address_validated);
16932 EXPECT_TRUE(
16933 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016934}
16935
fayanga0618a62022-12-28 19:31:24 -080016936TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress) {
16937 if (!connection_.version().HasIetfQuicFrames()) {
16938 return;
16939 }
fayanga0618a62022-12-28 19:31:24 -080016940 const QuicSocketAddress kNewSelfAddress =
16941 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16942 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016943 EXPECT_CALL(visitor_,
16944 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16945 .WillOnce(Invoke([&]() {
16946 connection_.ValidatePath(
16947 std::make_unique<TestQuicPathValidationContext>(
16948 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16949 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016950 &connection_),
16951 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016952 }));
fayanga0618a62022-12-28 19:31:24 -080016953 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016954 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080016955 ServerPreferredAddressInit(config);
16956 EXPECT_TRUE(connection_.HasPendingPathValidation());
16957 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16958
16959 // Send data packet while path validation is pending.
16960 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16961 // Verify the packet is sent on both paths.
16962 EXPECT_FALSE(writer_->stream_frames().empty());
16963 EXPECT_FALSE(new_writer.stream_frames().empty());
16964
16965 // Verify packet duplication stops on handshake confirmed.
16966 EXPECT_CALL(visitor_, GetHandshakeState())
16967 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16968 connection_.OnHandshakeComplete();
16969 SendPing();
16970 EXPECT_FALSE(writer_->ping_frames().empty());
16971 EXPECT_TRUE(new_writer.ping_frames().empty());
16972}
16973
16974TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress2) {
16975 if (!connection_.version().HasIetfQuicFrames()) {
16976 return;
16977 }
fayanga0618a62022-12-28 19:31:24 -080016978 const QuicSocketAddress kNewSelfAddress =
16979 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16980 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016981 EXPECT_CALL(visitor_,
16982 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16983 .WillOnce(Invoke([&]() {
16984 connection_.ValidatePath(
16985 std::make_unique<TestQuicPathValidationContext>(
16986 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16987 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016988 &connection_),
16989 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016990 }));
fayanga0618a62022-12-28 19:31:24 -080016991 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016992 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080016993 ServerPreferredAddressInit(config);
16994 EXPECT_TRUE(connection_.HasPendingPathValidation());
16995 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16996
16997 // Send data packet while path validation is pending.
16998 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16999 // Verify the packet is sent on both paths.
17000 EXPECT_FALSE(writer_->stream_frames().empty());
17001 EXPECT_FALSE(new_writer.stream_frames().empty());
17002
17003 // Simluate path validation times out.
17004 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
17005 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
17006 static_cast<TestAlarmFactory::TestAlarm*>(
17007 QuicPathValidatorPeer::retry_timer(
17008 QuicConnectionPeer::path_validator(&connection_)))
17009 ->Fire();
17010 }
17011 EXPECT_FALSE(connection_.HasPendingPathValidation());
17012 // Verify packet duplication stops if there is no pending validation.
17013 SendPing();
17014 EXPECT_FALSE(writer_->ping_frames().empty());
17015 EXPECT_TRUE(new_writer.ping_frames().empty());
17016}
17017
17018TEST_P(QuicConnectionTest, MaxDuplicatedPacketsSentToServerPreferredAddress) {
17019 if (!connection_.version().HasIetfQuicFrames()) {
17020 return;
17021 }
fayanga0618a62022-12-28 19:31:24 -080017022 const QuicSocketAddress kNewSelfAddress =
17023 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
17024 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080017025 EXPECT_CALL(visitor_,
17026 OnServerPreferredAddressAvailable(kServerPreferredAddress))
17027 .WillOnce(Invoke([&]() {
17028 connection_.ValidatePath(
17029 std::make_unique<TestQuicPathValidationContext>(
17030 kNewSelfAddress, kServerPreferredAddress, &new_writer),
17031 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080017032 &connection_),
17033 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080017034 }));
fayanga0618a62022-12-28 19:31:24 -080017035 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080017036 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080017037 ServerPreferredAddressInit(config);
17038 EXPECT_TRUE(connection_.HasPendingPathValidation());
17039 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
17040
17041 // Send data packet while path validation is pending.
17042 size_t write_limit = writer_->packets_write_attempts();
17043 size_t new_write_limit = new_writer.packets_write_attempts();
17044 for (size_t i = 0; i < kMaxDuplicatedPacketsSentToServerPreferredAddress;
17045 ++i) {
17046 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
17047 // Verify the packet is sent on both paths.
17048 ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
17049 ASSERT_EQ(new_write_limit + 1, new_writer.packets_write_attempts());
17050 ++write_limit;
17051 ++new_write_limit;
17052 EXPECT_FALSE(writer_->stream_frames().empty());
17053 EXPECT_FALSE(new_writer.stream_frames().empty());
17054 }
17055
17056 // Verify packet duplication stops if duplication limit is hit.
17057 SendPing();
17058 ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
17059 ASSERT_EQ(new_write_limit, new_writer.packets_write_attempts());
17060 EXPECT_FALSE(writer_->ping_frames().empty());
17061 EXPECT_TRUE(new_writer.ping_frames().empty());
17062}
17063
danzh8fdee2e2023-01-05 15:33:02 -080017064TEST_P(QuicConnectionTest, MultiPortCreationAfterServerMigration) {
17065 if (!GetParam().version.HasIetfQuicFrames()) {
17066 return;
17067 }
17068 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080017069 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
danzh8fdee2e2023-01-05 15:33:02 -080017070 ServerPreferredAddressInit(config);
danzh8fdee2e2023-01-05 15:33:02 -080017071 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17072 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
17073 const QuicSocketAddress kNewSelfAddress =
17074 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
17075 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
17076 EXPECT_CALL(visitor_,
17077 OnServerPreferredAddressAvailable(kServerPreferredAddress))
17078 .WillOnce(Invoke([&]() {
17079 connection_.ValidatePath(
17080 std::make_unique<TestQuicPathValidationContext>(
17081 kNewSelfAddress, kServerPreferredAddress, &new_writer),
17082 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080017083 &connection_),
17084 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080017085 }));
17086 // The connection should start probing the preferred address after handshake
17087 // confirmed.
17088 QuicPathFrameBuffer payload;
17089 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17090 .Times(testing::AtLeast(1u))
17091 .WillOnce(Invoke([&]() {
17092 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
17093 payload = new_writer.path_challenge_frames().front().data_buffer;
17094 EXPECT_EQ(kServerPreferredAddress,
17095 new_writer.last_write_peer_address());
17096 }));
17097 EXPECT_CALL(visitor_, GetHandshakeState())
17098 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
17099 connection_.OnHandshakeComplete();
17100 EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
17101
17102 // Receiving PATH_RESPONSE should cause the connection to migrate to the
17103 // preferred address.
17104 QuicFrames frames;
17105 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
17106 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
17107 ENCRYPTION_FORWARD_SECURE);
17108 EXPECT_FALSE(connection_.IsValidatingServerPreferredAddress());
17109 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
17110 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
17111 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
17112
17113 // As the default path changed, the server issued CID 1 should be retired.
17114 auto* retire_peer_issued_cid_alarm =
17115 connection_.GetRetirePeerIssuedConnectionIdAlarm();
17116 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
17117 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
17118 retire_peer_issued_cid_alarm->Fire();
17119
17120 const QuicSocketAddress kNewSelfAddress2(kNewSelfAddress.host(),
17121 kNewSelfAddress.port() + 1);
17122 EXPECT_NE(kNewSelfAddress2, kNewSelfAddress);
17123 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
17124 QuicNewConnectionIdFrame frame;
17125 frame.connection_id = TestConnectionId(789);
17126 ASSERT_NE(frame.connection_id, connection_.connection_id());
17127 frame.stateless_reset_token =
17128 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
17129 frame.retire_prior_to = 0u;
17130 frame.sequence_number = 2u;
QUICHE team107316f2023-05-03 09:04:11 -070017131 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070017132 .WillOnce(testing::WithArgs<0>([&](auto&& observer) {
17133 observer->OnMultiPortPathContextAvailable(
17134 std::move(std::make_unique<TestQuicPathValidationContext>(
17135 kNewSelfAddress2, connection_.peer_address(), &new_writer2)));
QUICHE team107316f2023-05-03 09:04:11 -070017136 }));
danzh8fdee2e2023-01-05 15:33:02 -080017137 connection_.OnNewConnectionIdFrame(frame);
17138 EXPECT_TRUE(connection_.HasPendingPathValidation());
17139 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
17140 payload = new_writer.path_challenge_frames().front().data_buffer;
17141 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
17142 EXPECT_EQ(kNewSelfAddress2.host(), new_writer.last_write_source_address());
17143 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
17144 &connection_, kNewSelfAddress2, connection_.peer_address()));
17145 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
17146 EXPECT_FALSE(alt_path->validated);
17147 QuicFrames frames2;
17148 frames2.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
17149 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress2, kPeerAddress,
17150 ENCRYPTION_FORWARD_SECURE);
17151 EXPECT_TRUE(alt_path->validated);
17152}
17153
danzh72225ae2023-01-13 14:57:42 -080017154// Tests that after half-way server migration, the client should be able to
17155// respond to any reverse path validation from the original server address.
17156TEST_P(QuicConnectionTest, ClientReceivePathChallengeAfterServerMigration) {
17157 if (!GetParam().version.HasIetfQuicFrames()) {
17158 return;
17159 }
17160 QuicConfig config;
17161 ServerPreferredAddressInit(config);
17162 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
17163 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17164 EXPECT_CALL(visitor_,
17165 OnServerPreferredAddressAvailable(kServerPreferredAddress))
17166 .WillOnce(Invoke([&]() {
17167 connection_.AddKnownServerAddress(kServerPreferredAddress);
17168 }));
17169 EXPECT_CALL(visitor_, GetHandshakeState())
17170 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
17171 connection_.OnHandshakeComplete();
17172
17173 const QuicSocketAddress kNewSelfAddress =
17174 QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1);
17175 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
17176 auto context = std::make_unique<TestQuicPathValidationContext>(
17177 kNewSelfAddress, kServerPreferredAddress, &new_writer);
17178 // Pretend that the validation already succeeded. And start to use the server
17179 // preferred address.
17180 connection_.OnServerPreferredAddressValidated(*context, false);
17181 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
17182 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
17183 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
17184 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
17185 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
17186 send_algorithm_);
17187 // Switch to use a mock send algorithm.
17188 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
17189 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
17190 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
17191 .WillRepeatedly(Return(kDefaultTCPMSS));
17192 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
17193 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
17194 .Times(AnyNumber())
17195 .WillRepeatedly(Return(QuicBandwidth::Zero()));
17196 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
17197 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
17198 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
17199 connection_.SetSendAlgorithm(send_algorithm_);
17200
17201 // As the default path changed, the server issued CID 123 should be retired.
17202 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
17203 auto* retire_peer_issued_cid_alarm =
17204 connection_.GetRetirePeerIssuedConnectionIdAlarm();
17205 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
17206 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
17207 retire_peer_issued_cid_alarm->Fire();
17208
17209 // Receive PATH_CHALLENGE from the original server
17210 // address. The client connection responds it on the default path.
17211 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
17212 QuicFrames frames1;
17213 frames1.push_back(
17214 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
17215 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17216 .Times(AtLeast(1))
17217 .WillOnce(Invoke([&]() {
17218 ASSERT_FALSE(new_writer.path_response_frames().empty());
17219 EXPECT_EQ(
17220 0, memcmp(&path_challenge_payload,
17221 &(new_writer.path_response_frames().front().data_buffer),
17222 sizeof(path_challenge_payload)));
17223 EXPECT_EQ(kServerPreferredAddress,
17224 new_writer.last_write_peer_address());
17225 EXPECT_EQ(kNewSelfAddress.host(),
17226 new_writer.last_write_source_address());
17227 }));
17228 ProcessFramesPacketWithAddresses(frames1, kNewSelfAddress, kPeerAddress,
17229 ENCRYPTION_FORWARD_SECURE);
17230}
17231
17232// Tests that after half-way server migration, the client should be able to
17233// probe with a different socket and respond to reverse path validation.
17234TEST_P(QuicConnectionTest, ClientProbesAfterServerMigration) {
17235 if (!GetParam().version.HasIetfQuicFrames()) {
17236 return;
17237 }
17238 QuicConfig config;
17239 ServerPreferredAddressInit(config);
17240 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
17241 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17242
17243 // The connection should start probing the preferred address after handshake
17244 // confirmed.
17245 EXPECT_CALL(visitor_,
17246 OnServerPreferredAddressAvailable(kServerPreferredAddress))
17247 .WillOnce(Invoke([&]() {
17248 connection_.AddKnownServerAddress(kServerPreferredAddress);
17249 }));
17250 EXPECT_CALL(visitor_, GetHandshakeState())
17251 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
17252 connection_.OnHandshakeComplete();
17253
17254 const QuicSocketAddress kNewSelfAddress =
17255 QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1);
17256 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
17257 auto context = std::make_unique<TestQuicPathValidationContext>(
17258 kNewSelfAddress, kServerPreferredAddress, &new_writer);
17259 // Pretend that the validation already succeeded.
17260 connection_.OnServerPreferredAddressValidated(*context, false);
17261 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
17262 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
17263 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
17264 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
17265 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
17266 send_algorithm_);
17267 // Switch to use a mock send algorithm.
17268 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
17269 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
17270 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
17271 .WillRepeatedly(Return(kDefaultTCPMSS));
17272 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
17273 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
17274 .Times(AnyNumber())
17275 .WillRepeatedly(Return(QuicBandwidth::Zero()));
17276 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
17277 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
17278 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
17279 connection_.SetSendAlgorithm(send_algorithm_);
17280
17281 // Receiving data from the original server address should not change the peer
17282 // address.
17283 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17284 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kNewSelfAddress,
17285 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17286 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
17287 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
17288
17289 // As the default path changed, the server issued CID 123 should be retired.
17290 auto* retire_peer_issued_cid_alarm =
17291 connection_.GetRetirePeerIssuedConnectionIdAlarm();
17292 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
17293 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
17294 retire_peer_issued_cid_alarm->Fire();
17295
17296 // Receiving a new CID from the server.
17297 QuicNewConnectionIdFrame new_cid_frame1;
17298 new_cid_frame1.connection_id = TestConnectionId(456);
17299 ASSERT_NE(new_cid_frame1.connection_id, connection_.connection_id());
17300 new_cid_frame1.stateless_reset_token =
17301 QuicUtils::GenerateStatelessResetToken(new_cid_frame1.connection_id);
17302 new_cid_frame1.retire_prior_to = 0u;
17303 new_cid_frame1.sequence_number = 2u;
17304 connection_.OnNewConnectionIdFrame(new_cid_frame1);
17305
17306 // Probe from a new socket.
17307 const QuicSocketAddress kNewSelfAddress2 =
17308 QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort + 2);
17309 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
17310 bool success;
17311 QuicPathFrameBuffer payload;
17312 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17313 .Times(testing::AtLeast(1u))
17314 .WillOnce(Invoke([&]() {
17315 EXPECT_EQ(1u, new_writer2.path_challenge_frames().size());
17316 payload = new_writer2.path_challenge_frames().front().data_buffer;
17317 EXPECT_EQ(kServerPreferredAddress,
17318 new_writer2.last_write_peer_address());
17319 EXPECT_EQ(kNewSelfAddress2.host(),
17320 new_writer2.last_write_source_address());
17321 }));
17322 connection_.ValidatePath(
17323 std::make_unique<TestQuicPathValidationContext>(
17324 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
17325 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080017326 &connection_, kNewSelfAddress2, connection_.peer_address(), &success),
17327 PathValidationReason::kServerPreferredAddressMigration);
danzh72225ae2023-01-13 14:57:42 -080017328 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
17329 &connection_, kNewSelfAddress2, kServerPreferredAddress));
17330
17331 // Our server implementation will send PATH_CHALLENGE from the original server
17332 // address. The client connection send PATH_RESPONSE to the default peer
17333 // address.
17334 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
17335 QuicFrames frames;
17336 frames.push_back(
17337 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
17338 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
17339 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17340 .Times(AtLeast(1))
17341 .WillOnce(Invoke([&]() {
17342 EXPECT_FALSE(new_writer2.path_response_frames().empty());
17343 EXPECT_EQ(
17344 0, memcmp(&path_challenge_payload,
17345 &(new_writer2.path_response_frames().front().data_buffer),
17346 sizeof(path_challenge_payload)));
17347 EXPECT_EQ(kServerPreferredAddress,
17348 new_writer2.last_write_peer_address());
17349 EXPECT_EQ(kNewSelfAddress2.host(),
17350 new_writer2.last_write_source_address());
17351 }));
17352 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress2, kPeerAddress,
17353 ENCRYPTION_FORWARD_SECURE);
17354 EXPECT_TRUE(success);
17355}
17356
martindukefcfa32a2023-01-12 10:04:44 -080017357TEST_P(QuicConnectionTest, EcnMarksCorrectlyRecorded) {
17358 set_perspective(Perspective::IS_SERVER);
martindukefcfa32a2023-01-12 10:04:44 -080017359 QuicFrames frames;
martindukef33b1da2023-01-12 14:14:29 -080017360 frames.push_back(QuicFrame(QuicPingFrame()));
17361 frames.push_back(QuicFrame(QuicPaddingFrame(7)));
17362 QuicAckFrame ack_frame =
17363 connection_.SupportsMultiplePacketNumberSpaces()
17364 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17365 : connection_.received_packet_manager().ack_frame();
17366 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17367
17368 ProcessFramesPacketAtLevelWithEcn(1, frames, ENCRYPTION_FORWARD_SECURE,
17369 ECN_ECT0);
17370 ack_frame =
17371 connection_.SupportsMultiplePacketNumberSpaces()
17372 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17373 : connection_.received_packet_manager().ack_frame();
martinduke01ee3222023-03-08 17:08:09 -080017374 // Send two PINGs so that the ACK goes too. The second packet should not
17375 // include an ACK, which checks that the packet state is cleared properly.
17376 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17377 if (connection_.version().HasIetfQuicFrames()) {
17378 QuicConnectionPeer::SendPing(&connection_);
17379 QuicConnectionPeer::SendPing(&connection_);
17380 }
17381 QuicConnectionStats stats = connection_.GetStats();
martindukef8b97fc2024-02-06 12:11:57 -080017382 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17383 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17384 EXPECT_EQ(stats.num_ack_frames_sent_with_ecn,
17385 connection_.version().HasIetfQuicFrames() ? 1 : 0);
martinduke01ee3222023-03-08 17:08:09 -080017386 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 1);
17387 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
17388 EXPECT_EQ(stats.num_ecn_marks_received.ce, 0);
martindukefcfa32a2023-01-12 10:04:44 -080017389}
17390
martindukef33b1da2023-01-12 14:14:29 -080017391TEST_P(QuicConnectionTest, EcnMarksCoalescedPacket) {
martindukef8b97fc2024-02-06 12:11:57 -080017392 if (!connection_.version().CanSendCoalescedPackets()) {
martindukef33b1da2023-01-12 14:14:29 -080017393 return;
17394 }
17395 QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"};
17396 QuicFrames frames1;
17397 frames1.push_back(QuicFrame(&crypto_frame1));
17398 QuicFrames frames2;
17399 QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"};
17400 frames2.push_back(QuicFrame(&crypto_frame2));
17401 std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE},
17402 {3, frames2, ENCRYPTION_FORWARD_SECURE}};
17403 QuicAckFrame ack_frame =
17404 connection_.SupportsMultiplePacketNumberSpaces()
17405 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17406 : connection_.received_packet_manager().ack_frame();
17407 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17408 ack_frame =
17409 connection_.SupportsMultiplePacketNumberSpaces()
17410 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17411 : connection_.received_packet_manager().ack_frame();
17412 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17413 // Deliver packets.
17414 connection_.SetEncrypter(
17415 ENCRYPTION_HANDSHAKE,
17416 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
17417 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
17418 ProcessCoalescedPacket(packets, ECN_ECT0);
martinduke01ee3222023-03-08 17:08:09 -080017419 // Send two PINGs so that the ACKs go too.
17420 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17421 if (connection_.version().HasIetfQuicFrames()) {
17422 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
17423 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
17424 QuicConnectionPeer::SendPing(&connection_);
17425 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17426 QuicConnectionPeer::SendPing(&connection_);
17427 }
17428 QuicConnectionStats stats = connection_.GetStats();
martindukef33b1da2023-01-12 14:14:29 -080017429 ack_frame =
17430 connection_.SupportsMultiplePacketNumberSpaces()
17431 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17432 : connection_.received_packet_manager().ack_frame();
17433 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17434 EXPECT_EQ(ack_frame.ecn_counters->ect0,
17435 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2);
17436 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17437 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17438 ? connection_.received_packet_manager().GetAckFrame(
17439 APPLICATION_DATA)
17440 : connection_.received_packet_manager().ack_frame();
17441 EXPECT_TRUE(ack_frame.ecn_counters.has_value());
17442 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17443 }
martindukef8b97fc2024-02-06 12:11:57 -080017444 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2);
17445 EXPECT_EQ(stats.num_ack_frames_sent_with_ecn,
17446 connection_.version().HasIetfQuicFrames() ? 2 : 0);
martinduke01ee3222023-03-08 17:08:09 -080017447 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
17448 EXPECT_EQ(stats.num_ecn_marks_received.ce, 0);
martindukef33b1da2023-01-12 14:14:29 -080017449}
17450
17451TEST_P(QuicConnectionTest, EcnMarksUndecryptableCoalescedPacket) {
martindukef8b97fc2024-02-06 12:11:57 -080017452 if (!connection_.version().CanSendCoalescedPackets()) {
martindukef33b1da2023-01-12 14:14:29 -080017453 return;
17454 }
17455 // SetFromConfig is always called after construction from InitializeSession.
17456 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080017457 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
17458 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martindukef33b1da2023-01-12 14:14:29 -080017459 QuicConfig config;
17460 config.set_max_undecryptable_packets(100);
17461 connection_.SetFromConfig(config);
17462 QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"};
17463 QuicFrames frames1;
17464 frames1.push_back(QuicFrame(&crypto_frame1));
17465 QuicFrames frames2;
17466 QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"};
17467 frames2.push_back(QuicFrame(&crypto_frame2));
17468 std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE},
17469 {3, frames2, ENCRYPTION_FORWARD_SECURE}};
17470 char coalesced_buffer[kMaxOutgoingPacketSize];
17471 size_t coalesced_size = 0;
17472 for (const auto& packet : packets) {
17473 QuicPacketHeader header =
17474 ConstructPacketHeader(packet.packet_number, packet.level);
17475 // Set the correct encryption level and encrypter on peer_creator and
17476 // peer_framer, respectively.
17477 peer_creator_.set_encryption_level(packet.level);
17478 peer_framer_.SetEncrypter(packet.level,
17479 std::make_unique<TaggingEncrypter>(packet.level));
17480 // Set the corresponding decrypter.
17481 if (packet.level == ENCRYPTION_HANDSHAKE) {
17482 connection_.SetEncrypter(
17483 packet.level, std::make_unique<TaggingEncrypter>(packet.level));
17484 connection_.SetDefaultEncryptionLevel(packet.level);
17485 SetDecrypter(packet.level,
17486 std::make_unique<StrictTaggingDecrypter>(packet.level));
17487 }
17488 // Forward Secure packet is undecryptable.
17489 std::unique_ptr<QuicPacket> constructed_packet(
17490 ConstructPacket(header, packet.frames));
17491
17492 char buffer[kMaxOutgoingPacketSize];
17493 size_t encrypted_length = peer_framer_.EncryptPayload(
17494 packet.level, QuicPacketNumber(packet.packet_number),
17495 *constructed_packet, buffer, kMaxOutgoingPacketSize);
17496 QUICHE_DCHECK_LE(coalesced_size + encrypted_length, kMaxOutgoingPacketSize);
17497 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
17498 coalesced_size += encrypted_length;
17499 }
17500 QuicAckFrame ack_frame =
17501 connection_.SupportsMultiplePacketNumberSpaces()
17502 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17503 : connection_.received_packet_manager().ack_frame();
17504 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17505 ack_frame =
17506 connection_.SupportsMultiplePacketNumberSpaces()
17507 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17508 : connection_.received_packet_manager().ack_frame();
17509 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17510 // Deliver packets, but first remove the Forward Secure decrypter so that
17511 // packet has to be buffered.
17512 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
17513 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
17514 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
17515 connection_.ProcessUdpPacket(
17516 kSelfAddress, kPeerAddress,
17517 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(), false,
17518 0, true, nullptr, 0, true, ECN_ECT0));
17519 if (connection_.GetSendAlarm()->IsSet()) {
17520 connection_.GetSendAlarm()->Fire();
17521 }
17522 ack_frame =
17523 connection_.SupportsMultiplePacketNumberSpaces()
17524 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17525 : connection_.received_packet_manager().ack_frame();
17526 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17527 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17528 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17529 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17530 ? connection_.received_packet_manager().GetAckFrame(
17531 APPLICATION_DATA)
17532 : connection_.received_packet_manager().ack_frame();
17533 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17534 }
17535 // Send PING packet with ECN_CE, which will change the ECN codepoint in
17536 // last_received_packet_info_.
17537 ProcessFramePacketAtLevelWithEcn(4, QuicFrame(QuicPingFrame()),
17538 ENCRYPTION_HANDSHAKE, ECN_CE);
17539 ack_frame =
17540 connection_.SupportsMultiplePacketNumberSpaces()
17541 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17542 : connection_.received_packet_manager().ack_frame();
17543 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17544 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17545 EXPECT_EQ(ack_frame.ecn_counters->ce, 1);
17546 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17547 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17548 ? connection_.received_packet_manager().GetAckFrame(
17549 APPLICATION_DATA)
17550 : connection_.received_packet_manager().ack_frame();
17551 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17552 }
17553 // Install decrypter for ENCRYPTION_FORWARD_SECURE. Make sure the original
17554 // ECN codepoint is incremented.
17555 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
17556 SetDecrypter(
17557 ENCRYPTION_FORWARD_SECURE,
17558 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
17559 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
17560 ack_frame =
17561 connection_.SupportsMultiplePacketNumberSpaces()
17562 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17563 : connection_.received_packet_manager().ack_frame();
17564 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17565 // Should be recorded as ECT(0), not CE.
17566 EXPECT_EQ(ack_frame.ecn_counters->ect0,
17567 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2);
martinduke01ee3222023-03-08 17:08:09 -080017568 QuicConnectionStats stats = connection_.GetStats();
martindukef8b97fc2024-02-06 12:11:57 -080017569 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2);
martinduke01ee3222023-03-08 17:08:09 -080017570 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
martindukef8b97fc2024-02-06 12:11:57 -080017571 EXPECT_EQ(stats.num_ecn_marks_received.ce, 1);
martindukef33b1da2023-01-12 14:14:29 -080017572}
17573
martinduke0bfe7322023-01-18 07:36:34 -080017574TEST_P(QuicConnectionTest, ReceivedPacketInfoDefaults) {
martinduke74528e52023-01-13 12:24:21 -080017575 EXPECT_TRUE(QuicConnectionPeer::TestLastReceivedPacketInfoDefaults());
17576}
17577
danzhb159ab02023-01-30 10:58:46 -080017578TEST_P(QuicConnectionTest, DetectMigrationToPreferredAddress) {
17579 if (!GetParam().version.HasIetfQuicFrames()) {
17580 return;
17581 }
17582 ServerHandlePreferredAddressInit();
17583
17584 // Issue a new server CID associated with the preferred address.
17585 QuicConnectionId server_issued_cid_for_preferred_address =
17586 TestConnectionId(17);
17587 EXPECT_CALL(connection_id_generator_,
17588 GenerateNextConnectionId(connection_id_))
17589 .WillOnce(Return(server_issued_cid_for_preferred_address));
17590 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
vasilvv243b2622023-11-07 17:01:30 -080017591 std::optional<QuicNewConnectionIdFrame> frame =
danzhb159ab02023-01-30 10:58:46 -080017592 connection_.MaybeIssueNewConnectionIdForPreferredAddress();
17593 ASSERT_TRUE(frame.has_value());
17594
17595 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
17596 ASSERT_EQ(packet_creator->GetDestinationConnectionId(),
17597 connection_.client_connection_id());
17598 ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_);
17599
17600 // Process a packet received at the preferred Address.
17601 peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address);
17602 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17603 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17604 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17605 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17606 // The server migrates half-way with the default path unchanged, and
17607 // continuing with the client issued CID 1.
17608 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17609 EXPECT_EQ(kSelfAddress, connection_.self_address());
17610
17611 // The peer retires CID 123.
17612 QuicRetireConnectionIdFrame retire_cid_frame;
17613 retire_cid_frame.sequence_number = 0u;
17614 EXPECT_CALL(connection_id_generator_,
17615 GenerateNextConnectionId(server_issued_cid_for_preferred_address))
17616 .WillOnce(Return(TestConnectionId(456)));
17617 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
17618 EXPECT_CALL(visitor_, SendNewConnectionId(_));
17619 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(retire_cid_frame));
17620
17621 // Process another packet received at Preferred Address.
17622 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17623 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17624 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17625 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17626 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17627 EXPECT_EQ(kSelfAddress, connection_.self_address());
17628}
17629
17630TEST_P(QuicConnectionTest,
17631 DetectSimutanuousServerAndClientAddressChangeWithProbe) {
17632 if (!GetParam().version.HasIetfQuicFrames()) {
17633 return;
17634 }
17635 ServerHandlePreferredAddressInit();
17636
17637 // Issue a new server CID associated with the preferred address.
17638 QuicConnectionId server_issued_cid_for_preferred_address =
17639 TestConnectionId(17);
17640 EXPECT_CALL(connection_id_generator_,
17641 GenerateNextConnectionId(connection_id_))
17642 .WillOnce(Return(server_issued_cid_for_preferred_address));
17643 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
vasilvv243b2622023-11-07 17:01:30 -080017644 std::optional<QuicNewConnectionIdFrame> frame =
danzhb159ab02023-01-30 10:58:46 -080017645 connection_.MaybeIssueNewConnectionIdForPreferredAddress();
17646 ASSERT_TRUE(frame.has_value());
17647
17648 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
17649 ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_);
17650 ASSERT_EQ(packet_creator->GetDestinationConnectionId(),
17651 connection_.client_connection_id());
17652
17653 // Receiving a probing packet from a new client address to the preferred
17654 // address.
17655 peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address);
17656 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
17657 /*port=*/34567);
17658 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
17659 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
17660 QuicEncryptedPacket(probing_packet->encrypted_buffer,
17661 probing_packet->encrypted_length),
17662 clock_.Now()));
17663 uint64_t num_probing_received =
17664 connection_.GetStats().num_connectivity_probing_received;
17665 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17666 .Times(AtLeast(1u))
17667 .WillOnce(Invoke([&]() {
17668 EXPECT_EQ(1u, writer_->path_response_frames().size());
17669 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
fayang1f578d32023-03-20 11:36:15 -070017670 // The responses should be sent from preferred address given server
17671 // has not received packet on original address from the new client
17672 // address.
17673 EXPECT_EQ(kServerPreferredAddress.host(),
17674 writer_->last_write_source_address());
danzhb159ab02023-01-30 10:58:46 -080017675 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
awillia202240c2024-07-08 09:47:00 -070017676 }))
17677 .WillRepeatedly(DoDefault());
danzhb159ab02023-01-30 10:58:46 -080017678 ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received);
17679 EXPECT_EQ(num_probing_received + 1,
17680 connection_.GetStats().num_connectivity_probing_received);
17681 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
17682 kNewPeerAddress));
17683 EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
17684 EXPECT_EQ(received->length(),
17685 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
17686 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17687 EXPECT_EQ(kSelfAddress, connection_.self_address());
17688
17689 // Process a data packet received at the preferred Address from the new client
17690 // address.
17691 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
17692 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17693 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17694 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
17695 // The server migrates half-way with the new peer address but the same default
17696 // self address.
17697 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17698 EXPECT_EQ(kSelfAddress, connection_.self_address());
17699 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
17700 EXPECT_TRUE(connection_.HasPendingPathValidation());
17701 EXPECT_FALSE(QuicConnectionPeer::GetDefaultPath(&connection_)->validated);
17702 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
17703 kPeerAddress));
17704 EXPECT_EQ(packet_creator->GetSourceConnectionId(),
17705 server_issued_cid_for_preferred_address);
17706
17707 // Process another packet received at the preferred Address.
17708 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17709 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17710 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
17711 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
fayang1f578d32023-03-20 11:36:15 -070017712 EXPECT_EQ(kServerPreferredAddress.host(),
17713 writer_->last_write_source_address());
danzhb159ab02023-01-30 10:58:46 -080017714 EXPECT_EQ(kSelfAddress, connection_.self_address());
17715}
17716
martinduke007b2ca2023-04-10 10:43:38 -070017717TEST_P(QuicConnectionTest, EcnCodepointsRejected) {
martinduke007b2ca2023-04-10 10:43:38 -070017718 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke007b2ca2023-04-10 10:43:38 -070017719 if (ecn == ECN_ECT0) {
martinduke57c456d2023-12-01 12:34:18 -080017720 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martinduke007b2ca2023-04-10 10:43:38 -070017721 } else if (ecn == ECN_ECT1) {
martinduke57c456d2023-12-01 12:34:18 -080017722 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
martinduke007b2ca2023-04-10 10:43:38 -070017723 }
martinduke039c1552023-05-23 16:10:57 -070017724 if (ecn == ECN_NOT_ECT) {
17725 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17726 } else {
17727 EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17728 }
17729 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduke007b2ca2023-04-10 10:43:38 -070017730 EXPECT_CALL(connection_, OnSerializedPacket(_));
17731 SendPing();
martinduke007b2ca2023-04-10 10:43:38 -070017732 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17733 }
17734}
17735
17736TEST_P(QuicConnectionTest, EcnCodepointsAccepted) {
martinduke007b2ca2023-04-10 10:43:38 -070017737 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke007b2ca2023-04-10 10:43:38 -070017738 if (ecn == ECN_ECT0) {
martinduke57c456d2023-12-01 12:34:18 -080017739 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martinduke007b2ca2023-04-10 10:43:38 -070017740 } else if (ecn == ECN_ECT1) {
martinduke57c456d2023-12-01 12:34:18 -080017741 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke007b2ca2023-04-10 10:43:38 -070017742 }
martinduke039c1552023-05-23 16:10:57 -070017743 if (ecn == ECN_CE) {
17744 EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17745 } else {
17746 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17747 }
martinduke007b2ca2023-04-10 10:43:38 -070017748 EXPECT_CALL(connection_, OnSerializedPacket(_));
17749 SendPing();
17750 QuicEcnCodepoint expected_codepoint = ecn;
17751 if (ecn == ECN_CE) {
martinduke039c1552023-05-23 16:10:57 -070017752 expected_codepoint = ECN_ECT1;
martinduke007b2ca2023-04-10 10:43:38 -070017753 }
martinduke039c1552023-05-23 16:10:57 -070017754 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
martinduke007b2ca2023-04-10 10:43:38 -070017755 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
17756 }
17757}
17758
17759TEST_P(QuicConnectionTest, EcnValidationDisabled) {
martinduke007b2ca2023-04-10 10:43:38 -070017760 QuicConnectionPeer::DisableEcnCodepointValidation(&connection_);
17761 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke039c1552023-05-23 16:10:57 -070017762 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
martinduke007b2ca2023-04-10 10:43:38 -070017763 EXPECT_CALL(connection_, OnSerializedPacket(_));
17764 SendPing();
martindukeacfdb392023-05-23 15:23:55 -070017765 EXPECT_EQ(connection_.ecn_codepoint(), ecn);
martinduke007b2ca2023-04-10 10:43:38 -070017766 EXPECT_EQ(writer_->last_ecn_sent(), ecn);
17767 }
17768}
17769
martinduked2d9e7b2023-04-20 14:13:01 -070017770TEST_P(QuicConnectionTest, RtoDisablesEcnMarking) {
martinduke57c456d2023-12-01 12:34:18 -080017771 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017772 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martinduked2d9e7b2023-04-20 14:13:01 -070017773 QuicPacketCreatorPeer::SetPacketNumber(
17774 QuicConnectionPeer::GetPacketCreator(&connection_), 1);
17775 SendPing();
vasilvva7d7d442024-05-31 09:42:40 -070017776 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017777 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
martindukeacfdb392023-05-23 15:23:55 -070017778 EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1);
martinduked2d9e7b2023-04-20 14:13:01 -070017779 // On 2nd RTO, QUIC abandons ECN.
vasilvva7d7d442024-05-31 09:42:40 -070017780 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017781 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
martindukeacfdb392023-05-23 15:23:55 -070017782 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduked2d9e7b2023-04-20 14:13:01 -070017783}
17784
17785TEST_P(QuicConnectionTest, RtoDoesntDisableEcnMarkingIfEcnAcked) {
martinduke57c456d2023-12-01 12:34:18 -080017786 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017787 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martinduked2d9e7b2023-04-20 14:13:01 -070017788 QuicPacketCreatorPeer::SetPacketNumber(
17789 QuicConnectionPeer::GetPacketCreator(&connection_), 1);
martinduke0643ea92023-12-06 13:16:20 -080017790 connection_.OnInFlightEcnPacketAcked();
martinduked2d9e7b2023-04-20 14:13:01 -070017791 SendPing();
17792 // Because an ECN packet was acked, PTOs have no effect on ECN settings.
vasilvva7d7d442024-05-31 09:42:40 -070017793 connection_.OnRetransmissionAlarm();
martinduke0643ea92023-12-06 13:16:20 -080017794 QuicEcnCodepoint expected_codepoint = ECN_ECT1;
martinduked2d9e7b2023-04-20 14:13:01 -070017795 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
martindukeacfdb392023-05-23 15:23:55 -070017796 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
vasilvva7d7d442024-05-31 09:42:40 -070017797 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017798 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
martindukeacfdb392023-05-23 15:23:55 -070017799 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
martinduked2d9e7b2023-04-20 14:13:01 -070017800}
17801
17802TEST_P(QuicConnectionTest, InvalidFeedbackCancelsEcn) {
martinduke57c456d2023-12-01 12:34:18 -080017803 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017804 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukeacfdb392023-05-23 15:23:55 -070017805 EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1);
martinduke0643ea92023-12-06 13:16:20 -080017806 connection_.OnInvalidEcnFeedback();
martindukeacfdb392023-05-23 15:23:55 -070017807 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduked2d9e7b2023-04-20 14:13:01 -070017808}
17809
martindukec0da7642023-05-04 17:23:22 -070017810TEST_P(QuicConnectionTest, StateMatchesSentEcn) {
martinduke57c456d2023-12-01 12:34:18 -080017811 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017812 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017813 SendPing();
17814 QuicSentPacketManager* sent_packet_manager =
17815 QuicConnectionPeer::GetSentPacketManager(&connection_);
17816 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1);
17817 EXPECT_EQ(
17818 QuicSentPacketManagerPeer::GetEct1Sent(sent_packet_manager, INITIAL_DATA),
17819 1);
17820}
17821
17822TEST_P(QuicConnectionTest, CoalescedPacketSplitsEcn) {
17823 if (!connection_.version().CanSendCoalescedPackets()) {
17824 return;
17825 }
martinduke57c456d2023-12-01 12:34:18 -080017826 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017827 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017828 // All these steps are necessary to send an INITIAL ping and save it to be
17829 // coalesced, instead of just calling SendPing() and sending it immediately.
17830 char buffer[1000];
17831 creator_->set_encryption_level(ENCRYPTION_INITIAL);
17832 QuicFrames frames;
17833 QuicPingFrame ping;
17834 frames.emplace_back(QuicFrame(ping));
17835 SerializedPacket packet1 = QuicPacketCreatorPeer::SerializeAllFrames(
17836 creator_, frames, buffer, sizeof(buffer));
17837 connection_.SendOrQueuePacket(std::move(packet1));
17838 creator_->set_encryption_level(ENCRYPTION_FORWARD_SECURE);
martinduke57c456d2023-12-01 12:34:18 -080017839 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martindukec0da7642023-05-04 17:23:22 -070017840 // If not for the line below, these packets would coalesce.
martinduke039c1552023-05-23 16:10:57 -070017841 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0));
martindukec0da7642023-05-04 17:23:22 -070017842 EXPECT_EQ(writer_->packets_write_attempts(), 0);
17843 SendPing();
17844 EXPECT_EQ(writer_->packets_write_attempts(), 2);
17845 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT0);
17846}
17847
17848TEST_P(QuicConnectionTest, BufferedPacketRetainsOldEcn) {
martinduke57c456d2023-12-01 12:34:18 -080017849 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017850 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017851 writer_->SetWriteBlocked();
17852 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(2);
17853 SendPing();
martinduke57c456d2023-12-01 12:34:18 -080017854 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017855 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0));
martindukec0da7642023-05-04 17:23:22 -070017856 writer_->SetWritable();
17857 connection_.OnCanWrite();
17858 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1);
17859}
17860
martinduke514a2742023-05-23 16:58:05 -070017861TEST_P(QuicConnectionTest, RejectEcnIfWriterDoesNotSupport) {
martinduke514a2742023-05-23 16:58:05 -070017862 MockPacketWriter mock_writer;
17863 QuicConnectionPeer::SetWriter(&connection_, &mock_writer, false);
17864 EXPECT_CALL(mock_writer, SupportsEcn()).WillOnce(Return(false));
17865 EXPECT_FALSE(connection_.set_ecn_codepoint(ECN_ECT1));
17866 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
17867}
17868
martinduke15c43d02024-09-26 14:00:37 -070017869TEST_P(QuicConnectionTest, RejectResetStreamAtIfNotNegotiated) {
17870 if (!version().HasIetfQuicFrames()) {
17871 return;
17872 }
17873 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080017874 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
17875 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martinduke15c43d02024-09-26 14:00:37 -070017876 QuicConfig config;
17877 config.SetReliableStreamReset(false);
17878 connection_.SetFromConfig(config);
17879 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17880
17881 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
17882 connection_.OnResetStreamAtFrame(QuicResetStreamAtFrame());
17883}
17884
17885TEST_P(QuicConnectionTest, ResetStreamAt) {
17886 if (!version().HasIetfQuicFrames()) {
17887 return;
17888 }
17889 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
martindukeeaf27602024-11-12 14:34:40 -080017890 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
17891 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martinduke15c43d02024-09-26 14:00:37 -070017892 QuicConfig config;
17893 config.SetReliableStreamReset(true);
17894 connection_.SetFromConfig(config);
17895 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17896
17897 EXPECT_CALL(visitor_, OnResetStreamAt(QuicResetStreamAtFrame(
17898 0, 0, QUIC_STREAM_NO_ERROR, 20, 10)))
17899 .Times(1);
17900 connection_.OnResetStreamAtFrame(QuicResetStreamAtFrame(0, 0, 0, 20, 10));
17901}
17902
QUICHE team82040582024-10-03 11:37:09 -070017903TEST_P(QuicConnectionTest, OnParsedClientHelloInfoWithDebugVisitor) {
17904 const ParsedClientHello parsed_chlo{.sni = "sni",
17905 .uaid = "uiad",
17906 .supported_groups = {1, 2, 3},
17907 .cert_compression_algos = {4, 5, 6},
17908 .alpns = {"h2", "http/1.1"},
17909 .retry_token = "retry_token"};
17910 MockQuicConnectionDebugVisitor debug_visitor;
17911 connection_.set_debug_visitor(&debug_visitor);
17912 EXPECT_CALL(debug_visitor, OnParsedClientHelloInfo(parsed_chlo)).Times(1);
17913 connection_.OnParsedClientHelloInfo(parsed_chlo);
17914}
17915
Bence Békybac04052022-04-07 15:44:29 -040017916} // namespace
17917} // namespace test
17918} // namespace quic