blob: 28bb07cdb4055955c3e47e496616022da29fb57a [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"
29#include "quiche/quic/core/frames/quic_rst_stream_frame.h"
30#include "quiche/quic/core/quic_connection_id.h"
31#include "quiche/quic/core/quic_constants.h"
32#include "quiche/quic/core/quic_error_codes.h"
33#include "quiche/quic/core/quic_packet_creator.h"
34#include "quiche/quic/core/quic_packets.h"
35#include "quiche/quic/core/quic_path_validator.h"
36#include "quiche/quic/core/quic_types.h"
37#include "quiche/quic/core/quic_utils.h"
38#include "quiche/quic/core/quic_versions.h"
39#include "quiche/quic/platform/api/quic_expect_bug.h"
40#include "quiche/quic/platform/api/quic_flags.h"
41#include "quiche/quic/platform/api/quic_ip_address.h"
bnc96dc1782022-09-06 08:16:01 -070042#include "quiche/quic/platform/api/quic_ip_address_family.h"
Bence Békybac04052022-04-07 15:44:29 -040043#include "quiche/quic/platform/api/quic_logging.h"
44#include "quiche/quic/platform/api/quic_socket_address.h"
45#include "quiche/quic/platform/api/quic_test.h"
46#include "quiche/quic/test_tools/mock_clock.h"
martinduke605dca22022-09-01 10:40:19 -070047#include "quiche/quic/test_tools/mock_connection_id_generator.h"
Bence Békybac04052022-04-07 15:44:29 -040048#include "quiche/quic/test_tools/mock_random.h"
49#include "quiche/quic/test_tools/quic_coalesced_packet_peer.h"
50#include "quiche/quic/test_tools/quic_config_peer.h"
51#include "quiche/quic/test_tools/quic_connection_peer.h"
52#include "quiche/quic/test_tools/quic_framer_peer.h"
53#include "quiche/quic/test_tools/quic_packet_creator_peer.h"
54#include "quiche/quic/test_tools/quic_path_validator_peer.h"
55#include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h"
56#include "quiche/quic/test_tools/quic_test_utils.h"
57#include "quiche/quic/test_tools/simple_data_producer.h"
58#include "quiche/quic/test_tools/simple_session_notifier.h"
Bence Békybac04052022-04-07 15:44:29 -040059#include "quiche/common/simple_buffer_allocator.h"
60
61using testing::_;
62using testing::AnyNumber;
63using testing::AtLeast;
64using testing::DoAll;
awillia202240c2024-07-08 09:47:00 -070065using testing::DoDefault;
Bence Békybac04052022-04-07 15:44:29 -040066using testing::ElementsAre;
67using testing::Ge;
68using testing::IgnoreResult;
69using testing::InSequence;
70using testing::Invoke;
71using testing::InvokeWithoutArgs;
72using testing::Lt;
73using testing::Ref;
74using testing::Return;
75using testing::SaveArg;
76using testing::SetArgPointee;
77using testing::StrictMock;
78
79namespace quic {
80namespace test {
81namespace {
82
83const char data1[] = "foo data";
84const char data2[] = "bar data";
85
86const bool kHasStopWaiting = true;
87
88const int kDefaultRetransmissionTimeMs = 500;
89
90DiversificationNonce kTestDiversificationNonce = {
91 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
92 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
93 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
94};
95
96const StatelessResetToken kTestStatelessResetToken{
97 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
98 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f};
99
100const QuicSocketAddress kPeerAddress =
101 QuicSocketAddress(QuicIpAddress::Loopback6(),
102 /*port=*/12345);
103const QuicSocketAddress kSelfAddress =
104 QuicSocketAddress(QuicIpAddress::Loopback6(),
105 /*port=*/443);
danzh8fdee2e2023-01-05 15:33:02 -0800106const QuicSocketAddress kServerPreferredAddress = QuicSocketAddress(
107 []() {
108 QuicIpAddress address;
109 address.FromString("2604:31c0::");
110 return address;
111 }(),
112 /*port=*/443);
Bence Békybac04052022-04-07 15:44:29 -0400113
114QuicStreamId GetNthClientInitiatedStreamId(int n,
115 QuicTransportVersion version) {
116 return QuicUtils::GetFirstBidirectionalStreamId(version,
117 Perspective::IS_CLIENT) +
118 n * 2;
119}
120
121QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
122 switch (level) {
123 case ENCRYPTION_INITIAL:
124 return INITIAL;
125 case ENCRYPTION_HANDSHAKE:
126 return HANDSHAKE;
127 case ENCRYPTION_ZERO_RTT:
128 return ZERO_RTT_PROTECTED;
129 case ENCRYPTION_FORWARD_SECURE:
130 QUICHE_DCHECK(false);
131 return INVALID_PACKET_TYPE;
132 default:
133 QUICHE_DCHECK(false);
134 return INVALID_PACKET_TYPE;
135 }
136}
137
martinduke9e0811c2022-12-08 20:35:57 -0800138// A TaggingEncrypterWithConfidentialityLimit is a TaggingEncrypter that allows
Bence Békybac04052022-04-07 15:44:29 -0400139// specifying the confidentiality limit on the maximum number of packets that
140// may be encrypted per key phase in TLS+QUIC.
martinduke9e0811c2022-12-08 20:35:57 -0800141class TaggingEncrypterWithConfidentialityLimit : public TaggingEncrypter {
Bence Békybac04052022-04-07 15:44:29 -0400142 public:
martinduke9e0811c2022-12-08 20:35:57 -0800143 TaggingEncrypterWithConfidentialityLimit(
144 uint8_t tag, QuicPacketCount confidentiality_limit)
145 : TaggingEncrypter(tag), confidentiality_limit_(confidentiality_limit) {}
Bence Békybac04052022-04-07 15:44:29 -0400146
147 QuicPacketCount GetConfidentialityLimit() const override {
148 return confidentiality_limit_;
149 }
150
151 private:
152 QuicPacketCount confidentiality_limit_;
153};
154
155class StrictTaggingDecrypterWithIntegrityLimit : public StrictTaggingDecrypter {
156 public:
157 StrictTaggingDecrypterWithIntegrityLimit(uint8_t tag,
158 QuicPacketCount integrity_limit)
159 : StrictTaggingDecrypter(tag), integrity_limit_(integrity_limit) {}
160
161 QuicPacketCount GetIntegrityLimit() const override {
162 return integrity_limit_;
163 }
164
165 private:
166 QuicPacketCount integrity_limit_;
167};
168
169class TestConnectionHelper : public QuicConnectionHelperInterface {
170 public:
171 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
172 : clock_(clock), random_generator_(random_generator) {
173 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
174 }
175 TestConnectionHelper(const TestConnectionHelper&) = delete;
176 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
177
178 // QuicConnectionHelperInterface
179 const QuicClock* GetClock() const override { return clock_; }
180
181 QuicRandom* GetRandomGenerator() override { return random_generator_; }
182
183 quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override {
184 return &buffer_allocator_;
185 }
186
187 private:
188 MockClock* clock_;
189 MockRandom* random_generator_;
190 quiche::SimpleBufferAllocator buffer_allocator_;
191};
192
193class TestConnection : public QuicConnection {
194 public:
195 TestConnection(QuicConnectionId connection_id,
196 QuicSocketAddress initial_self_address,
197 QuicSocketAddress initial_peer_address,
198 TestConnectionHelper* helper, TestAlarmFactory* alarm_factory,
199 TestPacketWriter* writer, Perspective perspective,
martinduke605dca22022-09-01 10:40:19 -0700200 ParsedQuicVersion version,
201 ConnectionIdGeneratorInterface& generator)
Bence Békybac04052022-04-07 15:44:29 -0400202 : QuicConnection(connection_id, initial_self_address,
203 initial_peer_address, helper, alarm_factory, writer,
204 /* owns_writer= */ false, perspective,
martinduke605dca22022-09-01 10:40:19 -0700205 SupportedVersions(version), generator),
Bence Békybac04052022-04-07 15:44:29 -0400206 notifier_(nullptr) {
207 writer->set_perspective(perspective);
208 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800209 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -0400210 SetDataProducer(&producer_);
211 ON_CALL(*this, OnSerializedPacket(_))
212 .WillByDefault([this](SerializedPacket packet) {
213 QuicConnection::OnSerializedPacket(std::move(packet));
214 });
215 }
216 TestConnection(const TestConnection&) = delete;
217 TestConnection& operator=(const TestConnection&) = delete;
218
219 MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket packet), (override));
220
renjietangff3e9602022-10-25 12:16:49 -0700221 void OnEffectivePeerMigrationValidated(bool is_migration_linkable) override {
222 QuicConnection::OnEffectivePeerMigrationValidated(is_migration_linkable);
223 if (is_migration_linkable) {
224 num_linkable_client_migration_++;
225 } else {
226 num_unlinkable_client_migration_++;
227 }
228 }
229
230 uint32_t num_unlinkable_client_migration() const {
231 return num_unlinkable_client_migration_;
232 }
233
234 uint32_t num_linkable_client_migration() const {
235 return num_linkable_client_migration_;
236 }
237
Bence Békybac04052022-04-07 15:44:29 -0400238 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
239 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
240 }
241
242 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
243 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
244 }
245
246 void SendPacket(EncryptionLevel /*level*/, uint64_t packet_number,
247 std::unique_ptr<QuicPacket> packet,
248 HasRetransmittableData retransmittable, bool has_ack,
249 bool has_pending_frames) {
250 ScopedPacketFlusher flusher(this);
251 char buffer[kMaxOutgoingPacketSize];
252 size_t encrypted_length =
253 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
254 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
255 buffer, kMaxOutgoingPacketSize);
256 SerializedPacket serialized_packet(
257 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
258 encrypted_length, has_ack, has_pending_frames);
259 serialized_packet.peer_address = kPeerAddress;
260 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
261 serialized_packet.retransmittable_frames.push_back(
262 QuicFrame(QuicPingFrame()));
263 }
264 OnSerializedPacket(std::move(serialized_packet));
265 }
266
267 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
268 absl::string_view data,
269 QuicStreamOffset offset,
270 StreamSendingState state) {
QUICHE teamac0a8082022-06-13 09:17:05 -0700271 return SaveAndSendStreamData(id, data, offset, state, NOT_RETRANSMISSION);
272 }
273
274 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
275 absl::string_view data,
276 QuicStreamOffset offset,
277 StreamSendingState state,
278 TransmissionType transmission_type) {
Bence Békybac04052022-04-07 15:44:29 -0400279 ScopedPacketFlusher flusher(this);
280 producer_.SaveStreamData(id, data);
281 if (notifier_ != nullptr) {
QUICHE teamac0a8082022-06-13 09:17:05 -0700282 return notifier_->WriteOrBufferData(id, data.length(), state,
283 transmission_type);
Bence Békybac04052022-04-07 15:44:29 -0400284 }
285 return QuicConnection::SendStreamData(id, data.length(), offset, state);
286 }
287
288 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
289 absl::string_view data,
290 QuicStreamOffset offset,
291 StreamSendingState state) {
292 ScopedPacketFlusher flusher(this);
293 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
294 this->encryption_level() == ENCRYPTION_INITIAL) {
295 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
296 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
297 OnHandshakeComplete();
298 }
299 if (version().SupportsAntiAmplificationLimit()) {
300 QuicConnectionPeer::SetAddressValidated(this);
301 }
302 }
303 return SaveAndSendStreamData(id, data, offset, state);
304 }
305
306 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
307 QuicStreamId id,
308 absl::string_view data,
309 QuicStreamOffset offset,
310 StreamSendingState state) {
311 ScopedPacketFlusher flusher(this);
312 QUICHE_DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -0800313 SetEncrypter(encryption_level,
314 std::make_unique<TaggingEncrypter>(encryption_level));
Bence Békybac04052022-04-07 15:44:29 -0400315 SetDefaultEncryptionLevel(encryption_level);
316 return SaveAndSendStreamData(id, data, offset, state);
317 }
318
319 QuicConsumedData SendStreamData3() {
320 return SendStreamDataWithString(
321 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
322 NO_FIN);
323 }
324
325 QuicConsumedData SendStreamData5() {
326 return SendStreamDataWithString(
327 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
328 NO_FIN);
329 }
330
331 // Ensures the connection can write stream data before writing.
332 QuicConsumedData EnsureWritableAndSendStreamData5() {
333 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
334 return SendStreamData5();
335 }
336
337 // The crypto stream has special semantics so that it is not blocked by a
338 // congestion window limitation, and also so that it gets put into a separate
339 // packet (so that it is easier to reason about a crypto frame not being
340 // split needlessly across packet boundaries). As a result, we have separate
341 // tests for some cases for this stream.
342 QuicConsumedData SendCryptoStreamData() {
343 QuicStreamOffset offset = 0;
344 absl::string_view data("chlo");
345 if (!QuicVersionUsesCryptoFrames(transport_version())) {
346 return SendCryptoDataWithString(data, offset);
347 }
348 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
349 size_t bytes_written;
350 if (notifier_) {
351 bytes_written =
352 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
353 } else {
354 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
355 data.length(), offset);
356 }
357 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
358 }
359
360 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
361 QuicStreamOffset offset) {
362 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
363 }
364
365 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
366 QuicStreamOffset offset,
367 EncryptionLevel encryption_level) {
368 if (!QuicVersionUsesCryptoFrames(transport_version())) {
369 return SendStreamDataWithString(
370 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
371 NO_FIN);
372 }
373 producer_.SaveCryptoData(encryption_level, offset, data);
374 size_t bytes_written;
375 if (notifier_) {
376 bytes_written =
377 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
378 } else {
379 bytes_written = QuicConnection::SendCryptoData(encryption_level,
380 data.length(), offset);
381 }
382 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
383 }
384
385 void set_version(ParsedQuicVersion version) {
386 QuicConnectionPeer::GetFramer(this)->set_version(version);
387 }
388
389 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
390 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
391 writer()->SetSupportedVersions(versions);
392 }
393
394 // This should be called before setting customized encrypters/decrypters for
395 // connection and peer creator.
396 void set_perspective(Perspective perspective) {
397 writer()->set_perspective(perspective);
398 QuicConnectionPeer::ResetPeerIssuedConnectionIdManager(this);
399 QuicConnectionPeer::SetPerspective(this, perspective);
400 QuicSentPacketManagerPeer::SetPerspective(
401 QuicConnectionPeer::GetSentPacketManager(this), perspective);
402 QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators(
403 TestConnectionId());
Bence Békybac04052022-04-07 15:44:29 -0400404 }
405
406 // Enable path MTU discovery. Assumes that the test is performed from the
407 // server perspective and the higher value of MTU target is used.
408 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
409 ASSERT_EQ(Perspective::IS_SERVER, perspective());
410
411 if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) {
412 OnConfigNegotiated();
413 } else {
414 QuicConfig config;
415 QuicTagVector connection_options;
416 connection_options.push_back(kMTUH);
417 config.SetInitialReceivedConnectionOptions(connection_options);
418 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
419 SetFromConfig(config);
420 }
421
422 // Normally, the pacing would be disabled in the test, but calling
423 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
424 // pacing algorithm work.
425 EXPECT_CALL(*send_algorithm, PacingRate(_))
426 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
427 }
428
429 TestAlarmFactory::TestAlarm* GetAckAlarm() {
430 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700431 &QuicConnectionPeer::GetAckAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400432 }
433
434 TestAlarmFactory::TestAlarm* GetPingAlarm() {
435 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700436 &QuicConnectionPeer::GetPingAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400437 }
438
439 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
440 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700441 &QuicConnectionPeer::GetRetransmissionAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400442 }
443
444 TestAlarmFactory::TestAlarm* GetSendAlarm() {
445 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700446 &QuicConnectionPeer::GetSendAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400447 }
448
449 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
450 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700451 &QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400452 }
453
454 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
455 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700456 &QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400457 }
458
459 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
460 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700461 &QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400462 }
463
464 TestAlarmFactory::TestAlarm* GetDiscardPreviousOneRttKeysAlarm() {
465 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700466 &QuicConnectionPeer::GetDiscardPreviousOneRttKeysAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400467 }
468
469 TestAlarmFactory::TestAlarm* GetDiscardZeroRttDecryptionKeysAlarm() {
470 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700471 &QuicConnectionPeer::GetDiscardZeroRttDecryptionKeysAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400472 }
473
474 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
475 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700476 &QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
Bence Békybac04052022-04-07 15:44:29 -0400477 }
478
479 TestAlarmFactory::TestAlarm* GetRetirePeerIssuedConnectionIdAlarm() {
480 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
481 QuicConnectionPeer::GetRetirePeerIssuedConnectionIdAlarm(this));
482 }
483
484 TestAlarmFactory::TestAlarm* GetRetireSelfIssuedConnectionIdAlarm() {
485 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
486 QuicConnectionPeer::GetRetireSelfIssuedConnectionIdAlarm(this));
487 }
488
renjietangfca5c772022-08-25 13:48:21 -0700489 TestAlarmFactory::TestAlarm* GetMultiPortProbingAlarm() {
490 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
vasilvva435ab82024-04-26 06:53:00 -0700491 &QuicConnectionPeer::GetMultiPortProbingAlarm(this));
renjietangfca5c772022-08-25 13:48:21 -0700492 }
493
Bence Békybac04052022-04-07 15:44:29 -0400494 void PathDegradingTimeout() {
495 QUICHE_DCHECK(PathDegradingDetectionInProgress());
496 GetBlackholeDetectorAlarm()->Fire();
497 }
498
499 bool PathDegradingDetectionInProgress() {
500 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
501 }
502
503 bool BlackholeDetectionInProgress() {
504 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
505 .IsInitialized();
506 }
507
508 bool PathMtuReductionDetectionInProgress() {
509 return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this)
510 .IsInitialized();
511 }
512
Bence Békybac04052022-04-07 15:44:29 -0400513 QuicByteCount GetBytesInFlight() {
514 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
515 }
516
517 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
518
519 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
520 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
521 }
522
Bence Békybac04052022-04-07 15:44:29 -0400523 void SendOrQueuePacket(SerializedPacket packet) override {
524 QuicConnection::SendOrQueuePacket(std::move(packet));
525 self_address_on_default_path_while_sending_packet_ = self_address();
526 }
527
528 QuicSocketAddress self_address_on_default_path_while_sending_packet() {
529 return self_address_on_default_path_while_sending_packet_;
530 }
531
532 SimpleDataProducer* producer() { return &producer_; }
533
534 using QuicConnection::active_effective_peer_migration_type;
535 using QuicConnection::IsCurrentPacketConnectivityProbing;
536 using QuicConnection::SelectMutualVersion;
Bence Békybac04052022-04-07 15:44:29 -0400537 using QuicConnection::set_defer_send_in_response_to_packets;
538
539 protected:
540 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
541 if (next_effective_peer_addr_) {
542 return *std::move(next_effective_peer_addr_);
543 }
544 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
545 }
546
547 private:
548 TestPacketWriter* writer() {
549 return static_cast<TestPacketWriter*>(QuicConnection::writer());
550 }
551
552 SimpleDataProducer producer_;
553
554 SimpleSessionNotifier* notifier_;
555
556 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
557
558 QuicSocketAddress self_address_on_default_path_while_sending_packet_;
renjietangff3e9602022-10-25 12:16:49 -0700559
560 uint32_t num_unlinkable_client_migration_ = 0;
561
562 uint32_t num_linkable_client_migration_ = 0;
Bence Békybac04052022-04-07 15:44:29 -0400563};
564
565enum class AckResponse { kDefer, kImmediate };
566
567// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
568struct TestParams {
fayangfc04b8a2023-05-18 09:26:25 -0700569 TestParams(ParsedQuicVersion version, AckResponse ack_response)
570 : version(version), ack_response(ack_response) {}
Bence Békybac04052022-04-07 15:44:29 -0400571
572 ParsedQuicVersion version;
573 AckResponse ack_response;
Bence Békybac04052022-04-07 15:44:29 -0400574};
575
576// Used by ::testing::PrintToStringParamName().
577std::string PrintToString(const TestParams& p) {
578 return absl::StrCat(
579 ParsedQuicVersionToString(p.version), "_",
fayangfc04b8a2023-05-18 09:26:25 -0700580 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"));
Bence Békybac04052022-04-07 15:44:29 -0400581}
582
583// Constructs various test permutations.
584std::vector<TestParams> GetTestParams() {
585 QuicFlagSaver flags;
586 std::vector<TestParams> params;
587 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
588 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
589 for (AckResponse ack_response :
590 {AckResponse::kDefer, AckResponse::kImmediate}) {
fayangfc04b8a2023-05-18 09:26:25 -0700591 params.push_back(TestParams(all_supported_versions[i], ack_response));
Bence Békybac04052022-04-07 15:44:29 -0400592 }
593 }
594 return params;
595}
596
597class QuicConnectionTest : public QuicTestWithParam<TestParams> {
598 public:
599 // For tests that do silent connection closes, no such packet is generated. In
600 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
601 // should invoke this method, saving the frame, and then the test can verify
602 // the contents.
603 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
604 ConnectionCloseSource /*source*/) {
605 saved_connection_close_frame_ = frame;
606 connection_close_frame_count_++;
607 }
608
609 protected:
610 QuicConnectionTest()
611 : connection_id_(TestConnectionId()),
612 framer_(SupportedVersions(version()), QuicTime::Zero(),
613 Perspective::IS_CLIENT, connection_id_.length()),
614 send_algorithm_(new StrictMock<MockSendAlgorithm>),
615 loss_algorithm_(new MockLossAlgorithm()),
616 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
617 alarm_factory_(new TestAlarmFactory()),
618 peer_framer_(SupportedVersions(version()), QuicTime::Zero(),
619 Perspective::IS_SERVER, connection_id_.length()),
620 peer_creator_(connection_id_, &peer_framer_,
621 /*delegate=*/nullptr),
622 writer_(
623 new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)),
624 connection_(connection_id_, kSelfAddress, kPeerAddress, helper_.get(),
625 alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT,
martinduke605dca22022-09-01 10:40:19 -0700626 version(), connection_id_generator_),
Bence Békybac04052022-04-07 15:44:29 -0400627 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
628 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
629 frame1_(0, false, 0, absl::string_view(data1)),
630 frame2_(0, false, 3, absl::string_view(data2)),
631 crypto_frame_(ENCRYPTION_INITIAL, 0, absl::string_view(data1)),
632 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
633 connection_id_included_(CONNECTION_ID_PRESENT),
634 notifier_(&connection_),
635 connection_close_frame_count_(0) {
636 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
637 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
638 AckResponse::kDefer);
639 framer_.SetInitialObfuscators(TestConnectionId());
640 connection_.InstallInitialCrypters(TestConnectionId());
641 CrypterPair crypters;
642 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
643 TestConnectionId(), &crypters);
644 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
645 std::move(crypters.encrypter));
646 if (version().KnowsWhichDecrypterToUse()) {
647 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
648 std::move(crypters.decrypter));
649 } else {
650 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
651 std::move(crypters.decrypter));
652 }
653 for (EncryptionLevel level :
654 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
martinduke9e0811c2022-12-08 20:35:57 -0800655 peer_creator_.SetEncrypter(level,
656 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400657 }
658 QuicFramerPeer::SetLastSerializedServerConnectionId(
659 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
660 QuicFramerPeer::SetLastWrittenPacketNumberLength(
661 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
Bence Békybac04052022-04-07 15:44:29 -0400662 QuicStreamId stream_id;
663 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
664 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
665 version().transport_version, Perspective::IS_CLIENT);
666 } else {
667 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
668 }
669 frame1_.stream_id = stream_id;
670 frame2_.stream_id = stream_id;
671 connection_.set_visitor(&visitor_);
672 connection_.SetSessionNotifier(&notifier_);
673 connection_.set_notifier(&notifier_);
674 connection_.SetSendAlgorithm(send_algorithm_);
675 connection_.SetLossAlgorithm(loss_algorithm_.get());
676 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
677 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
678 .Times(AnyNumber());
679 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
680 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
681 .WillRepeatedly(Return(kDefaultTCPMSS));
682 EXPECT_CALL(*send_algorithm_, PacingRate(_))
683 .WillRepeatedly(Return(QuicBandwidth::Zero()));
684 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
685 .Times(AnyNumber())
686 .WillRepeatedly(Return(QuicBandwidth::Zero()));
687 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
688 .Times(AnyNumber());
689 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
690 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
691 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
692 .Times(AnyNumber());
693 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
694 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
695 .Times(AnyNumber());
wubc9fd4292023-08-14 13:00:21 -0700696 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
697 .WillRepeatedly(
698 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
Bence Békybac04052022-04-07 15:44:29 -0400699 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
700 EXPECT_CALL(visitor_, OnCanWrite())
701 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
702 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
703 .WillRepeatedly(Return(false));
704 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
705 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
706 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
wub85ccecd2024-05-04 05:30:07 -0700707 if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data5)) {
fayang7ea1eee2023-08-15 18:28:33 -0700708 EXPECT_CALL(visitor_, MaybeBundleOpportunistically()).Times(AnyNumber());
wub1093ba22023-11-13 17:12:19 -0800709 EXPECT_CALL(visitor_, GetFlowControlSendWindowSize(_)).Times(AnyNumber());
fayang7ea1eee2023-08-15 18:28:33 -0700710 }
Bence Békybac04052022-04-07 15:44:29 -0400711 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
712 .Times(testing::AtMost(1));
713 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
714 .WillRepeatedly(Return(QuicTime::Zero()));
715 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
716 .Times(AnyNumber());
717 EXPECT_CALL(visitor_, GetHandshakeState())
718 .WillRepeatedly(Return(HANDSHAKE_START));
719 if (connection_.version().KnowsWhichDecrypterToUse()) {
720 connection_.InstallDecrypter(
721 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800722 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
723 } else {
724 connection_.SetAlternativeDecrypter(
725 ENCRYPTION_FORWARD_SECURE,
726 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE),
727 false);
Bence Békybac04052022-04-07 15:44:29 -0400728 }
729 peer_creator_.SetDefaultPeerAddress(kSelfAddress);
730 }
731
732 QuicConnectionTest(const QuicConnectionTest&) = delete;
733 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
734
735 ParsedQuicVersion version() { return GetParam().version; }
736
Bence Békybac04052022-04-07 15:44:29 -0400737 void SetClientConnectionId(const QuicConnectionId& client_connection_id) {
738 connection_.set_client_connection_id(client_connection_id);
739 writer_->framer()->framer()->SetExpectedClientConnectionIdLength(
740 client_connection_id.length());
741 }
742
743 void SetDecrypter(EncryptionLevel level,
744 std::unique_ptr<QuicDecrypter> decrypter) {
745 if (connection_.version().KnowsWhichDecrypterToUse()) {
746 connection_.InstallDecrypter(level, std::move(decrypter));
747 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800748 connection_.SetAlternativeDecrypter(level, std::move(decrypter), false);
Bence Békybac04052022-04-07 15:44:29 -0400749 }
750 }
751
752 void ProcessPacket(uint64_t number) {
753 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
754 ProcessDataPacket(number);
755 if (connection_.GetSendAlarm()->IsSet()) {
756 connection_.GetSendAlarm()->Fire();
757 }
758 }
759
760 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
761 const QuicSocketAddress& peer_address,
762 const QuicReceivedPacket& packet) {
763 connection_.ProcessUdpPacket(self_address, peer_address, packet);
764 if (connection_.GetSendAlarm()->IsSet()) {
765 connection_.GetSendAlarm()->Fire();
766 }
767 }
768
769 QuicFrame MakeCryptoFrame() const {
770 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
771 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
772 }
773 return QuicFrame(QuicStreamFrame(
774 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
775 0u, absl::string_view()));
776 }
777
778 void ProcessFramePacket(QuicFrame frame) {
779 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress,
780 ENCRYPTION_FORWARD_SECURE);
781 }
782
783 void ProcessFramePacketWithAddresses(QuicFrame frame,
784 QuicSocketAddress self_address,
785 QuicSocketAddress peer_address,
786 EncryptionLevel level) {
787 QuicFrames frames;
788 frames.push_back(QuicFrame(frame));
789 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address,
790 level);
791 }
792
793 std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames,
794 EncryptionLevel level,
795 char* buffer,
796 size_t buffer_len) {
797 QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level));
798 peer_creator_.set_encryption_level(level);
799 QuicPacketCreatorPeer::SetSendVersionInPacket(
800 &peer_creator_,
801 level < ENCRYPTION_FORWARD_SECURE &&
802 connection_.perspective() == Perspective::IS_SERVER);
803
804 SerializedPacket serialized_packet =
805 QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
806 buffer, buffer_len);
807 return std::make_unique<QuicReceivedPacket>(
808 serialized_packet.encrypted_buffer, serialized_packet.encrypted_length,
809 clock_.Now());
810 }
811
812 void ProcessFramesPacketWithAddresses(QuicFrames frames,
813 QuicSocketAddress self_address,
814 QuicSocketAddress peer_address,
815 EncryptionLevel level) {
816 char buffer[kMaxOutgoingPacketSize];
817 connection_.ProcessUdpPacket(
818 self_address, peer_address,
819 *ConstructPacket(std::move(frames), level, buffer,
820 kMaxOutgoingPacketSize));
821 if (connection_.GetSendAlarm()->IsSet()) {
822 connection_.GetSendAlarm()->Fire();
823 }
824 }
825
826 // Bypassing the packet creator is unrealistic, but allows us to process
827 // packets the QuicPacketCreator won't allow us to create.
828 void ForceProcessFramePacket(QuicFrame frame) {
829 QuicFrames frames;
830 frames.push_back(QuicFrame(frame));
831 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
832 if (connection_.version().KnowsWhichDecrypterToUse()) {
833 send_version = true;
834 }
835 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
836 QuicPacketHeader header;
837 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
838 char encrypted_buffer[kMaxOutgoingPacketSize];
839 size_t length = peer_framer_.BuildDataPacket(
840 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
841 ENCRYPTION_INITIAL);
842 QUICHE_DCHECK_GT(length, 0u);
843
844 const size_t encrypted_length = peer_framer_.EncryptInPlace(
845 ENCRYPTION_INITIAL, header.packet_number,
846 GetStartOfEncryptedData(peer_framer_.version().transport_version,
847 header),
848 length, kMaxOutgoingPacketSize, encrypted_buffer);
849 QUICHE_DCHECK_GT(encrypted_length, 0u);
850
851 connection_.ProcessUdpPacket(
852 kSelfAddress, kPeerAddress,
853 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
854 }
855
856 size_t ProcessFramePacketAtLevel(uint64_t number, QuicFrame frame,
857 EncryptionLevel level) {
martindukef33b1da2023-01-12 14:14:29 -0800858 return ProcessFramePacketAtLevelWithEcn(number, frame, level, ECN_NOT_ECT);
Bence Békybac04052022-04-07 15:44:29 -0400859 }
860
martindukef33b1da2023-01-12 14:14:29 -0800861 size_t ProcessFramePacketAtLevelWithEcn(uint64_t number, QuicFrame frame,
862 EncryptionLevel level,
863 QuicEcnCodepoint ecn_codepoint) {
864 QuicFrames frames;
865 frames.push_back(frame);
866 return ProcessFramesPacketAtLevelWithEcn(number, frames, level,
867 ecn_codepoint);
868 }
869
870 size_t ProcessFramesPacketAtLevel(uint64_t number, QuicFrames frames,
Bence Békybac04052022-04-07 15:44:29 -0400871 EncryptionLevel level) {
martindukef33b1da2023-01-12 14:14:29 -0800872 return ProcessFramesPacketAtLevelWithEcn(number, frames, level,
873 ECN_NOT_ECT);
874 }
875
876 size_t ProcessFramesPacketAtLevelWithEcn(uint64_t number,
877 const QuicFrames& frames,
878 EncryptionLevel level,
879 QuicEcnCodepoint ecn_codepoint) {
Bence Békybac04052022-04-07 15:44:29 -0400880 QuicPacketHeader header = ConstructPacketHeader(number, level);
881 // Set the correct encryption level and encrypter on peer_creator and
882 // peer_framer, respectively.
883 peer_creator_.set_encryption_level(level);
martinduke9e0811c2022-12-08 20:35:57 -0800884 if (level > ENCRYPTION_INITIAL) {
885 peer_framer_.SetEncrypter(level,
886 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400887 // Set the corresponding decrypter.
888 if (connection_.version().KnowsWhichDecrypterToUse()) {
889 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800890 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400891 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800892 connection_.SetAlternativeDecrypter(
893 level, std::make_unique<StrictTaggingDecrypter>(level), false);
Bence Békybac04052022-04-07 15:44:29 -0400894 }
895 }
896 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
897
898 char buffer[kMaxOutgoingPacketSize];
899 size_t encrypted_length =
900 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
901 buffer, kMaxOutgoingPacketSize);
902 connection_.ProcessUdpPacket(
903 kSelfAddress, kPeerAddress,
martindukef33b1da2023-01-12 14:14:29 -0800904 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false, 0,
905 true, nullptr, 0, false, ecn_codepoint));
Bence Békybac04052022-04-07 15:44:29 -0400906 if (connection_.GetSendAlarm()->IsSet()) {
907 connection_.GetSendAlarm()->Fire();
908 }
909 return encrypted_length;
910 }
911
912 struct PacketInfo {
913 PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level)
914 : packet_number(packet_number), frames(frames), level(level) {}
915
916 uint64_t packet_number;
917 QuicFrames frames;
918 EncryptionLevel level;
919 };
920
921 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) {
martindukef33b1da2023-01-12 14:14:29 -0800922 return ProcessCoalescedPacket(packets, ECN_NOT_ECT);
923 }
924
925 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets,
926 QuicEcnCodepoint ecn_codepoint) {
Bence Békybac04052022-04-07 15:44:29 -0400927 char coalesced_buffer[kMaxOutgoingPacketSize];
928 size_t coalesced_size = 0;
929 bool contains_initial = false;
930 for (const auto& packet : packets) {
931 QuicPacketHeader header =
932 ConstructPacketHeader(packet.packet_number, packet.level);
933 // Set the correct encryption level and encrypter on peer_creator and
934 // peer_framer, respectively.
935 peer_creator_.set_encryption_level(packet.level);
936 if (packet.level == ENCRYPTION_INITIAL) {
937 contains_initial = true;
938 }
martinduke9e0811c2022-12-08 20:35:57 -0800939 EncryptionLevel level =
940 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_);
941 if (level > ENCRYPTION_INITIAL) {
942 peer_framer_.SetEncrypter(level,
943 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400944 // Set the corresponding decrypter.
945 if (connection_.version().KnowsWhichDecrypterToUse()) {
946 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800947 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400948 } else {
949 connection_.SetDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800950 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400951 }
952 }
953 std::unique_ptr<QuicPacket> constructed_packet(
954 ConstructPacket(header, packet.frames));
955
956 char buffer[kMaxOutgoingPacketSize];
957 size_t encrypted_length = peer_framer_.EncryptPayload(
958 packet.level, QuicPacketNumber(packet.packet_number),
959 *constructed_packet, buffer, kMaxOutgoingPacketSize);
960 QUICHE_DCHECK_LE(coalesced_size + encrypted_length,
961 kMaxOutgoingPacketSize);
962 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
963 coalesced_size += encrypted_length;
964 }
965 if (contains_initial) {
966 // Padded coalesced packet to full if it contains initial packet.
967 memset(coalesced_buffer + coalesced_size, '0',
968 kMaxOutgoingPacketSize - coalesced_size);
969 }
970 connection_.ProcessUdpPacket(
971 kSelfAddress, kPeerAddress,
972 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(),
martindukef33b1da2023-01-12 14:14:29 -0800973 false, 0, true, nullptr, 0, false, ecn_codepoint));
Bence Békybac04052022-04-07 15:44:29 -0400974 if (connection_.GetSendAlarm()->IsSet()) {
975 connection_.GetSendAlarm()->Fire();
976 }
977 return coalesced_size;
978 }
979
980 size_t ProcessDataPacket(uint64_t number) {
981 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
982 }
983
984 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
985 return ProcessDataPacketAtLevel(packet_number, false,
986 ENCRYPTION_FORWARD_SECURE);
987 }
988
989 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
990 bool has_stop_waiting,
991 EncryptionLevel level) {
992 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
993 level);
994 }
995
996 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
997 QuicPacketHeader header = ConstructPacketHeader(number, level);
998 QuicFrames frames;
999 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1000 frames.push_back(QuicFrame(&crypto_frame_));
1001 } else {
1002 frames.push_back(QuicFrame(frame1_));
1003 }
1004 if (level == ENCRYPTION_INITIAL) {
1005 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
1006 }
1007 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1008 char buffer[kMaxOutgoingPacketSize];
1009 peer_creator_.set_encryption_level(level);
1010 size_t encrypted_length =
1011 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1012 buffer, kMaxOutgoingPacketSize);
1013 connection_.ProcessUdpPacket(
1014 kSelfAddress, kPeerAddress,
1015 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1016 if (connection_.GetSendAlarm()->IsSet()) {
1017 connection_.GetSendAlarm()->Fire();
1018 }
1019 return encrypted_length;
1020 }
1021
1022 size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting,
1023 EncryptionLevel level) {
1024 std::unique_ptr<QuicPacket> packet(
1025 ConstructDataPacket(number, has_stop_waiting, level));
1026 char buffer[kMaxOutgoingPacketSize];
1027 peer_creator_.set_encryption_level(level);
1028 size_t encrypted_length =
1029 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1030 buffer, kMaxOutgoingPacketSize);
1031 connection_.ProcessUdpPacket(
1032 kSelfAddress, kPeerAddress,
1033 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1034 if (connection_.GetSendAlarm()->IsSet()) {
1035 connection_.GetSendAlarm()->Fire();
1036 }
1037 return encrypted_length;
1038 }
1039
1040 void ProcessClosePacket(uint64_t number) {
1041 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
1042 char buffer[kMaxOutgoingPacketSize];
1043 size_t encrypted_length = peer_framer_.EncryptPayload(
1044 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
1045 kMaxOutgoingPacketSize);
1046 connection_.ProcessUdpPacket(
1047 kSelfAddress, kPeerAddress,
1048 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1049 }
1050
1051 QuicByteCount SendStreamDataToPeer(QuicStreamId id, absl::string_view data,
1052 QuicStreamOffset offset,
1053 StreamSendingState state,
1054 QuicPacketNumber* last_packet) {
QUICHE team24a23852022-10-31 18:03:52 -07001055 QuicByteCount packet_size = 0;
Bence Békybac04052022-04-07 15:44:29 -04001056 // Save the last packet's size.
1057 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1058 .Times(AnyNumber())
1059 .WillRepeatedly(SaveArg<3>(&packet_size));
1060 connection_.SendStreamDataWithString(id, data, offset, state);
1061 if (last_packet != nullptr) {
1062 *last_packet = creator_->packet_number();
1063 }
1064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1065 .Times(AnyNumber());
1066 return packet_size;
1067 }
1068
1069 void SendAckPacketToPeer() {
1070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1071 {
1072 QuicConnection::ScopedPacketFlusher flusher(&connection_);
1073 connection_.SendAck();
1074 }
1075 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1076 .Times(AnyNumber());
1077 }
1078
1079 void SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error,
1080 QuicStreamOffset bytes_written) {
1081 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1082 connection_.OnStreamReset(id, error);
1083 }
1084
1085 void SendPing() { notifier_.WriteOrBufferPing(); }
1086
1087 MessageStatus SendMessage(absl::string_view message) {
1088 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1089 quiche::QuicheMemSlice slice(quiche::QuicheBuffer::Copy(
1090 connection_.helper()->GetStreamSendBufferAllocator(), message));
1091 return connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false);
1092 }
1093
1094 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1095 if (packet_number > 1) {
1096 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1097 } else {
1098 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1099 }
1100 ProcessFramePacket(QuicFrame(frame));
1101 }
1102
1103 void ProcessAckPacket(QuicAckFrame* frame) {
1104 ProcessFramePacket(QuicFrame(frame));
1105 }
1106
1107 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1108 ProcessFramePacket(QuicFrame(frame));
1109 }
1110
1111 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1112 QuicStopWaitingFrame frame,
1113 EncryptionLevel /*level*/) {
1114 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1115 ENCRYPTION_ZERO_RTT);
1116 }
1117
1118 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1119 ProcessFramePacket(QuicFrame(frame));
1120 }
1121
1122 bool IsMissing(uint64_t number) {
1123 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
1124 QuicPacketNumber());
1125 }
1126
1127 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1128 const QuicFrames& frames) {
1129 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1130 EXPECT_NE(nullptr, packet.get());
1131 return packet;
1132 }
1133
1134 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1135 EncryptionLevel level) {
1136 QuicPacketHeader header;
fayangfc04b8a2023-05-18 09:26:25 -07001137 if (level < ENCRYPTION_FORWARD_SECURE) {
Bence Békybac04052022-04-07 15:44:29 -04001138 // Set long header type accordingly.
1139 header.version_flag = true;
1140 header.form = IETF_QUIC_LONG_HEADER_PACKET;
1141 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1142 if (QuicVersionHasLongHeaderLengths(
1143 peer_framer_.version().transport_version)) {
dschinazi35c0ff72022-08-16 12:10:06 -07001144 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04001145 if (header.long_packet_type == INITIAL) {
dschinazi35c0ff72022-08-16 12:10:06 -07001146 header.retry_token_length_length =
1147 quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
Bence Békybac04052022-04-07 15:44:29 -04001148 }
1149 }
1150 }
1151 // Set connection_id to peer's in memory representation as this data packet
1152 // is created by peer_framer.
1153 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1154 header.source_connection_id = connection_id_;
1155 header.source_connection_id_included = connection_id_included_;
1156 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1157 } else {
1158 header.destination_connection_id = connection_id_;
1159 header.destination_connection_id_included = connection_id_included_;
1160 }
fayangfc04b8a2023-05-18 09:26:25 -07001161 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
Bence Békybac04052022-04-07 15:44:29 -04001162 if (!connection_.client_connection_id().IsEmpty()) {
1163 header.destination_connection_id = connection_.client_connection_id();
1164 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
1165 } else {
1166 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1167 }
1168 if (header.version_flag) {
1169 header.source_connection_id = connection_id_;
1170 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1171 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1172 header.long_packet_type == ZERO_RTT_PROTECTED) {
1173 header.nonce = &kTestDiversificationNonce;
1174 }
1175 }
1176 }
1177 header.packet_number_length = packet_number_length_;
1178 header.packet_number = QuicPacketNumber(number);
1179 return header;
1180 }
1181
1182 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1183 bool has_stop_waiting,
1184 EncryptionLevel level) {
1185 QuicPacketHeader header = ConstructPacketHeader(number, level);
1186 QuicFrames frames;
1187 if (VersionHasIetfQuicFrames(version().transport_version) &&
1188 (level == ENCRYPTION_INITIAL || level == ENCRYPTION_HANDSHAKE)) {
1189 frames.push_back(QuicFrame(QuicPingFrame()));
1190 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
1191 } else {
1192 frames.push_back(QuicFrame(frame1_));
1193 if (has_stop_waiting) {
1194 frames.push_back(QuicFrame(stop_waiting_));
1195 }
1196 }
1197 return ConstructPacket(header, frames);
1198 }
1199
1200 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
1201 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1202 if (VersionHasIetfQuicFrames(version().transport_version)) {
1203 QuicPathFrameBuffer payload = {
1204 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1205 return QuicPacketCreatorPeer::
1206 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1207 payload);
1208 }
danzh65153092023-06-16 10:59:32 -07001209 QUICHE_DCHECK(!GetQuicReloadableFlag(quic_ignore_gquic_probing));
Bence Békybac04052022-04-07 15:44:29 -04001210 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1211 &peer_creator_);
1212 }
1213
1214 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1215 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1216 QuicPacketHeader header;
1217 // Set connection_id to peer's in memory representation as this connection
1218 // close packet is created by peer_framer.
1219 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1220 header.source_connection_id = connection_id_;
1221 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04001222 } else {
1223 header.destination_connection_id = connection_id_;
fayangfc04b8a2023-05-18 09:26:25 -07001224 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04001225 }
1226
1227 header.packet_number = QuicPacketNumber(number);
1228
1229 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
1230 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1231 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
1232 /*transport_close_frame_type=*/0);
1233 QuicFrames frames;
1234 frames.push_back(QuicFrame(&qccf));
1235 return ConstructPacket(header, frames);
1236 }
1237
1238 QuicTime::Delta DefaultRetransmissionTime() {
1239 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1240 }
1241
1242 QuicTime::Delta DefaultDelayedAckTime() {
wub349df3d2024-04-26 11:37:32 -07001243 return QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
Bence Békybac04052022-04-07 15:44:29 -04001244 }
1245
1246 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1247 QuicStopWaitingFrame frame;
1248 frame.least_unacked = QuicPacketNumber(least_unacked);
1249 return frame;
1250 }
1251
1252 // Construct a ack_frame that acks all packet numbers between 1 and
1253 // |largest_acked|, except |missing|.
1254 // REQUIRES: 1 <= |missing| < |largest_acked|
1255 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1256 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1257 QuicPacketNumber(missing));
1258 }
1259
1260 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1261 QuicPacketNumber missing) {
1262 if (missing == QuicPacketNumber(1)) {
1263 return InitAckFrame({{missing + 1, largest_acked + 1}});
1264 }
1265 return InitAckFrame(
1266 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1267 }
1268
1269 // Undo nacking a packet within the frame.
1270 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1271 EXPECT_FALSE(frame->packets.Contains(arrived));
1272 frame->packets.Add(arrived);
1273 }
1274
1275 void TriggerConnectionClose() {
1276 // Send an erroneous packet to close the connection.
1277 EXPECT_CALL(visitor_,
1278 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1279 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1280
1281 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1282 // Triggers a connection by receiving ACK of unsent packet.
1283 QuicAckFrame frame = InitAckFrame(10000);
1284 ProcessAckPacket(1, &frame);
1285 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1286 nullptr);
1287 EXPECT_EQ(1, connection_close_frame_count_);
1288 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1289 IsError(QUIC_INVALID_ACK_DATA));
1290 }
1291
1292 void BlockOnNextWrite() {
1293 writer_->BlockOnNextWrite();
1294 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1295 }
1296
1297 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1298
fayangf6607db2022-04-21 18:10:41 -07001299 void ExpectNextPacketUnprocessable() {
1300 writer_->ExpectNextPacketUnprocessable();
1301 }
1302
Bence Békybac04052022-04-07 15:44:29 -04001303 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1304
1305 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1306 writer_->SetWritePauseTimeDelta(delta);
1307 }
1308
1309 void CongestionBlockWrites() {
1310 EXPECT_CALL(*send_algorithm_, CanSend(_))
1311 .WillRepeatedly(testing::Return(false));
1312 }
1313
1314 void CongestionUnblockWrites() {
1315 EXPECT_CALL(*send_algorithm_, CanSend(_))
1316 .WillRepeatedly(testing::Return(true));
1317 }
1318
1319 void set_perspective(Perspective perspective) {
1320 connection_.set_perspective(perspective);
1321 if (perspective == Perspective::IS_SERVER) {
Bence Békybac04052022-04-07 15:44:29 -04001322 connection_.set_can_truncate_connection_ids(true);
1323 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
1324 connection_.OnSuccessfulVersionNegotiation();
1325 }
1326 QuicFramerPeer::SetPerspective(&peer_framer_,
1327 QuicUtils::InvertPerspective(perspective));
1328 peer_framer_.SetInitialObfuscators(TestConnectionId());
1329 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
1330 ENCRYPTION_FORWARD_SECURE}) {
1331 if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) {
martinduke9e0811c2022-12-08 20:35:57 -08001332 peer_creator_.SetEncrypter(level,
1333 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -04001334 }
1335 }
1336 }
1337
1338 void set_packets_between_probes_base(
1339 const QuicPacketCount packets_between_probes_base) {
1340 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1341 &connection_, packets_between_probes_base,
1342 QuicPacketNumber(packets_between_probes_base));
1343 }
1344
1345 bool IsDefaultTestConfiguration() {
1346 TestParams p = GetParam();
1347 return p.ack_response == AckResponse::kImmediate &&
fayangfc04b8a2023-05-18 09:26:25 -07001348 p.version == AllSupportedVersions()[0];
Bence Békybac04052022-04-07 15:44:29 -04001349 }
1350
1351 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1352 // Not strictly needed for this test, but is commonly done.
1353 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1354 nullptr);
1355 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1356 writer_->connection_close_frames();
1357 ASSERT_EQ(1u, connection_close_frames.size());
1358
1359 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1360 IsError(expected_code));
1361
1362 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1363 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1364 IsError(expected_code));
1365 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1366 connection_close_frames[0].close_type);
1367 return;
1368 }
1369
1370 QuicErrorCodeToIetfMapping mapping =
1371 QuicErrorCodeToTransportErrorCode(expected_code);
1372
1373 if (mapping.is_transport_close) {
1374 // This Google QUIC Error Code maps to a transport close,
1375 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1376 connection_close_frames[0].close_type);
1377 } else {
1378 // This maps to an application close.
1379 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1380 connection_close_frames[0].close_type);
1381 }
1382 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
1383 }
1384
1385 void MtuDiscoveryTestInit() {
1386 set_perspective(Perspective::IS_SERVER);
1387 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1388 if (version().SupportsAntiAmplificationLimit()) {
1389 QuicConnectionPeer::SetAddressValidated(&connection_);
1390 }
1391 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1392 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04001393 // Prevent packets from being coalesced.
1394 EXPECT_CALL(visitor_, GetHandshakeState())
1395 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1396 EXPECT_TRUE(connection_.connected());
1397 }
1398
1399 void PathProbeTestInit(Perspective perspective,
1400 bool receive_new_server_connection_id = true) {
1401 set_perspective(perspective);
1402 connection_.CreateConnectionIdManager();
1403 EXPECT_EQ(connection_.perspective(), perspective);
1404 if (perspective == Perspective::IS_SERVER) {
1405 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1406 }
1407 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1408 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1409 // Discard INITIAL key.
1410 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1411 connection_.NeuterUnencryptedPackets();
1412 // Prevent packets from being coalesced.
1413 EXPECT_CALL(visitor_, GetHandshakeState())
1414 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1415 if (version().SupportsAntiAmplificationLimit() &&
1416 perspective == Perspective::IS_SERVER) {
1417 QuicConnectionPeer::SetAddressValidated(&connection_);
1418 }
1419 // Clear direct_peer_address.
1420 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1421 // Clear effective_peer_address, it is the same as direct_peer_address for
1422 // this test.
1423 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1424 QuicSocketAddress());
1425 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1426
1427 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1428 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1429 } else {
1430 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1431 }
1432 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1433 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1434 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1435 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1436 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1437 if (perspective == Perspective::IS_CLIENT &&
1438 receive_new_server_connection_id && version().HasIetfQuicFrames()) {
1439 QuicNewConnectionIdFrame frame;
1440 frame.connection_id = TestConnectionId(1234);
1441 ASSERT_NE(frame.connection_id, connection_.connection_id());
1442 frame.stateless_reset_token =
1443 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
1444 frame.retire_prior_to = 0u;
1445 frame.sequence_number = 1u;
1446 connection_.OnNewConnectionIdFrame(frame);
1447 }
1448 }
1449
danzhb159ab02023-01-30 10:58:46 -08001450 void ServerHandlePreferredAddressInit() {
1451 ASSERT_TRUE(GetParam().version.HasIetfQuicFrames());
1452 set_perspective(Perspective::IS_SERVER);
1453 connection_.CreateConnectionIdManager();
1454 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang1f578d32023-03-20 11:36:15 -07001455 SetQuicReloadableFlag(quic_use_received_client_addresses_cache, true);
danzhb159ab02023-01-30 10:58:46 -08001456 EXPECT_CALL(visitor_, AllowSelfAddressChange())
1457 .WillRepeatedly(Return(true));
1458
1459 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1460 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1461 // Discard INITIAL key.
1462 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1463 connection_.NeuterUnencryptedPackets();
1464 // Prevent packets from being coalesced.
1465 EXPECT_CALL(visitor_, GetHandshakeState())
1466 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1467 if (version().SupportsAntiAmplificationLimit()) {
1468 QuicConnectionPeer::SetAddressValidated(&connection_);
1469 }
1470 // Clear direct_peer_address.
1471 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1472 // Clear effective_peer_address, it is the same as direct_peer_address for
1473 // this test.
1474 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1475 QuicSocketAddress());
1476 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1477
1478 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1479 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1480 } else {
1481 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1482 }
1483 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1484 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1485 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1486 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1487 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1488 QuicConfig config;
danzhb159ab02023-01-30 10:58:46 -08001489 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1490 connection_.SetFromConfig(config);
rchacbdda42024-04-08 13:35:17 -07001491 connection_.set_expected_server_preferred_address(kServerPreferredAddress);
danzhb159ab02023-01-30 10:58:46 -08001492 }
1493
fayangdbd6a302022-12-21 16:24:27 -08001494 // Receive server preferred address.
fayanga0618a62022-12-28 19:31:24 -08001495 void ServerPreferredAddressInit(QuicConfig& config) {
fayangdbd6a302022-12-21 16:24:27 -08001496 ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1497 ASSERT_TRUE(version().HasIetfQuicFrames());
1498 ASSERT_TRUE(connection_.self_address().host().IsIPv6());
fayangdbd6a302022-12-21 16:24:27 -08001499 const QuicConnectionId connection_id = TestConnectionId(17);
1500 const StatelessResetToken reset_token =
1501 QuicUtils::GenerateStatelessResetToken(connection_id);
1502
1503 connection_.CreateConnectionIdManager();
1504
1505 connection_.SendCryptoStreamData();
1506 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07001507 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangdbd6a302022-12-21 16:24:27 -08001508 QuicAckFrame frame = InitAckFrame(1);
1509 // Received ACK for packet 1.
1510 ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
fayang37765f62022-12-27 17:49:13 -08001511 // Discard INITIAL key.
1512 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
fayanga0618a62022-12-28 19:31:24 -08001513 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangdbd6a302022-12-21 16:24:27 -08001514
danzhc251e142023-06-02 11:53:11 -07001515 config.SetConnectionOptionsToSend(QuicTagVector{kSPAD});
fayangdbd6a302022-12-21 16:24:27 -08001516 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
1517 kTestStatelessResetToken);
1518 QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
danzh8fdee2e2023-01-05 15:33:02 -08001519 kServerPreferredAddress);
fayangdbd6a302022-12-21 16:24:27 -08001520 QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
1521 &config, connection_id, reset_token);
1522 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1523 connection_.SetFromConfig(config);
1524
danzhb159ab02023-01-30 10:58:46 -08001525 ASSERT_TRUE(
1526 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)
1527 .IsInitialized());
1528 EXPECT_EQ(
1529 kServerPreferredAddress,
1530 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_));
fayangdbd6a302022-12-21 16:24:27 -08001531 }
1532
wubc9fd4292023-08-14 13:00:21 -07001533 // If defer sending is enabled, tell |visitor_| to return true on the next
1534 // call to WillingAndAbleToWrite().
1535 // This function can be used before a call to ProcessXxxPacket, to allow the
1536 // process function to schedule and fire the send alarm at the end.
1537 void ForceWillingAndAbleToWriteOnceForDeferSending() {
1538 if (GetParam().ack_response == AckResponse::kDefer) {
1539 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
1540 .WillOnce(Return(true))
1541 .RetiresOnSaturation();
1542 }
1543 }
1544
Bence Békybac04052022-04-07 15:44:29 -04001545 void TestClientRetryHandling(bool invalid_retry_tag,
1546 bool missing_original_id_in_config,
1547 bool wrong_original_id_in_config,
1548 bool missing_retry_id_in_config,
1549 bool wrong_retry_id_in_config);
1550
1551 void TestReplaceConnectionIdFromInitial();
1552
1553 QuicConnectionId connection_id_;
1554 QuicFramer framer_;
1555
1556 MockSendAlgorithm* send_algorithm_;
1557 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1558 MockClock clock_;
1559 MockRandom random_generator_;
1560 quiche::SimpleBufferAllocator buffer_allocator_;
1561 std::unique_ptr<TestConnectionHelper> helper_;
1562 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1563 QuicFramer peer_framer_;
1564 QuicPacketCreator peer_creator_;
1565 std::unique_ptr<TestPacketWriter> writer_;
1566 TestConnection connection_;
1567 QuicPacketCreator* creator_;
1568 QuicSentPacketManager* manager_;
1569 StrictMock<MockQuicConnectionVisitor> visitor_;
1570
1571 QuicStreamFrame frame1_;
1572 QuicStreamFrame frame2_;
1573 QuicCryptoFrame crypto_frame_;
1574 QuicAckFrame ack_;
1575 QuicStopWaitingFrame stop_waiting_;
1576 QuicPacketNumberLength packet_number_length_;
1577 QuicConnectionIdIncluded connection_id_included_;
1578
1579 SimpleSessionNotifier notifier_;
1580
1581 QuicConnectionCloseFrame saved_connection_close_frame_;
1582 int connection_close_frame_count_;
martinduke605dca22022-09-01 10:40:19 -07001583 MockConnectionIdGenerator connection_id_generator_;
Bence Békybac04052022-04-07 15:44:29 -04001584};
1585
1586// Run all end to end tests with all supported versions.
1587INSTANTIATE_TEST_SUITE_P(QuicConnectionTests, QuicConnectionTest,
1588 ::testing::ValuesIn(GetTestParams()),
1589 ::testing::PrintToStringParamName());
1590
1591// These two tests ensure that the QuicErrorCode mapping works correctly.
1592// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1593// If running IETF QUIC, the first will generate a transport connection
1594// close, the second an application connection close.
1595// The connection close codes for the two tests are manually chosen;
1596// they are expected to always map to transport- and application-
1597// closes, respectively. If that changes, new codes should be chosen.
1598TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1599 EXPECT_TRUE(connection_.connected());
1600 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1601 connection_.CloseConnection(
1602 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1603 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1604 EXPECT_FALSE(connection_.connected());
1605 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1606}
1607
1608// Test that the IETF QUIC Error code mapping function works
1609// properly for application connection close codes.
1610TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1611 EXPECT_TRUE(connection_.connected());
1612 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1613 connection_.CloseConnection(
1614 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1615 "Should be application close",
1616 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1617 EXPECT_FALSE(connection_.connected());
1618 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1619}
1620
1621TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1622 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1623
1624 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1625 EXPECT_TRUE(connection_.connected());
1626
1627 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1628 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1629 } else {
1630 EXPECT_CALL(visitor_, OnStreamFrame(_));
1631 }
1632 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1633 ENCRYPTION_INITIAL);
1634 // Cause change in self_address.
1635 QuicIpAddress host;
1636 host.FromString("1.1.1.1");
1637 QuicSocketAddress self_address(host, 123);
1638 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1639 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1640 } else {
1641 EXPECT_CALL(visitor_, OnStreamFrame(_));
1642 }
1643 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1644 ENCRYPTION_INITIAL);
1645 EXPECT_TRUE(connection_.connected());
danzh65153092023-06-16 10:59:32 -07001646 EXPECT_NE(connection_.self_address(), self_address);
Bence Békybac04052022-04-07 15:44:29 -04001647}
1648
1649TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1650 set_perspective(Perspective::IS_SERVER);
1651 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1652
1653 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1654 EXPECT_TRUE(connection_.connected());
1655
1656 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1657 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1658 } else {
1659 EXPECT_CALL(visitor_, OnStreamFrame(_));
1660 }
1661 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1662 ENCRYPTION_INITIAL);
1663 // Cause change in self_address.
1664 QuicIpAddress host;
1665 host.FromString("1.1.1.1");
1666 QuicSocketAddress self_address(host, 123);
1667 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
1668 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fayang19027942022-05-16 10:29:29 -07001669 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1670 ENCRYPTION_INITIAL);
1671 EXPECT_TRUE(connection_.connected());
Bence Békybac04052022-04-07 15:44:29 -04001672 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
1673}
1674
1675TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1676 set_perspective(Perspective::IS_SERVER);
1677 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1678
1679 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1680 EXPECT_TRUE(connection_.connected());
1681
1682 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1683 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1684 } else {
1685 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1686 }
1687 QuicIpAddress host;
1688 host.FromString("1.1.1.1");
1689 QuicSocketAddress self_address1(host, 443);
1690 connection_.SetSelfAddress(self_address1);
1691 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1692 kPeerAddress, ENCRYPTION_INITIAL);
1693 // Cause self_address change to mapped Ipv4 address.
1694 QuicIpAddress host2;
1695 host2.FromString(
1696 absl::StrCat("::ffff:", connection_.self_address().host().ToString()));
1697 QuicSocketAddress self_address2(host2, connection_.self_address().port());
1698 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1699 kPeerAddress, ENCRYPTION_INITIAL);
1700 EXPECT_TRUE(connection_.connected());
1701 // self_address change back to Ipv4 address.
1702 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1703 kPeerAddress, ENCRYPTION_INITIAL);
1704 EXPECT_TRUE(connection_.connected());
1705}
1706
1707TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1708 set_perspective(Perspective::IS_SERVER);
1709 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1710 EXPECT_CALL(visitor_, GetHandshakeState())
1711 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1712
1713 // Clear direct_peer_address.
1714 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1715 // Clear effective_peer_address, it is the same as direct_peer_address for
1716 // this test.
1717 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1718 QuicSocketAddress());
1719
1720 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1721 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1722 } else {
1723 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1724 }
1725 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1726 const QuicSocketAddress kNewPeerAddress =
1727 QuicSocketAddress(QuicIpAddress::Loopback6(),
1728 /*port=*/23456);
1729 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1730 kNewPeerAddress, ENCRYPTION_INITIAL);
1731 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1732 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1733
1734 // Decrease packet number to simulate out-of-order packets.
1735 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1736 // This is an old packet, do not migrate.
1737 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1738 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1739 ENCRYPTION_INITIAL);
1740 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1741 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1742}
1743
1744TEST_P(QuicConnectionTest, PeerPortChangeAtServer) {
1745 set_perspective(Perspective::IS_SERVER);
1746 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1747 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1748 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1749 // Prevent packets from being coalesced.
1750 EXPECT_CALL(visitor_, GetHandshakeState())
1751 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1752 if (version().SupportsAntiAmplificationLimit()) {
1753 QuicConnectionPeer::SetAddressValidated(&connection_);
1754 }
1755
1756 // Clear direct_peer_address.
1757 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1758 // Clear effective_peer_address, it is the same as direct_peer_address for
1759 // this test.
1760 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1761 QuicSocketAddress());
1762 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1763
1764 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
1765 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
1766 rtt_stats->set_initial_rtt(default_init_rtt * 2);
1767 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
1768
fayang339f0c82022-04-30 14:20:02 -07001769 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
1770 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001771
1772 const QuicSocketAddress kNewPeerAddress =
1773 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1774 EXPECT_CALL(visitor_, OnStreamFrame(_))
1775 .WillOnce(Invoke(
1776 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1777 .WillOnce(Invoke(
1778 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1779 QuicFrames frames;
1780 frames.push_back(QuicFrame(frame1_));
1781 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1782 ENCRYPTION_FORWARD_SECURE);
1783 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1784 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1785
1786 // Process another packet with a different peer address on server side will
1787 // start connection migration.
1788 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1789 QuicFrames frames2;
1790 frames2.push_back(QuicFrame(frame2_));
1791 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1792 ENCRYPTION_FORWARD_SECURE);
1793 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1794 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1795 // PORT_CHANGE shouldn't state change in sent packet manager.
1796 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07001797 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001798 EXPECT_EQ(manager_->GetSendAlgorithm(), send_algorithm_);
danzh4d58dae2023-06-06 11:13:10 -07001799 if (version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04001800 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1801 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001802 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001803 }
1804}
1805
1806TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServer) {
1807 set_perspective(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -07001808 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07001809 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04001810 return;
1811 }
1812 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1813 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1814 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1815 // Discard INITIAL key.
1816 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1817 connection_.NeuterUnencryptedPackets();
1818 // Prevent packets from being coalesced.
1819 EXPECT_CALL(visitor_, GetHandshakeState())
1820 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1821 QuicConnectionPeer::SetAddressValidated(&connection_);
1822 connection_.OnHandshakeComplete();
1823
1824 // Enable 5 RTO
1825 QuicConfig config;
1826 QuicTagVector connection_options;
1827 connection_options.push_back(k5RTO);
1828 config.SetInitialReceivedConnectionOptions(connection_options);
1829 QuicConfigPeer::SetNegotiated(&config, true);
1830 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
1831 connection_.connection_id());
1832 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
1833 QuicConnectionId());
1834 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1835 connection_.SetFromConfig(config);
1836
1837 // Clear direct_peer_address.
1838 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1839 // Clear effective_peer_address, it is the same as direct_peer_address for
1840 // this test.
1841 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1842 QuicSocketAddress());
1843 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1844
1845 const QuicSocketAddress kNewPeerAddress =
1846 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1847 EXPECT_CALL(visitor_, OnStreamFrame(_))
1848 .WillOnce(Invoke(
1849 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1850 .WillOnce(Invoke(
1851 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1852 QuicFrames frames;
1853 frames.push_back(QuicFrame(frame1_));
1854 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1855 ENCRYPTION_FORWARD_SECURE);
1856 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1857 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1858
1859 // Send some data to make connection has packets in flight.
1860 connection_.SendStreamData3();
1861 EXPECT_EQ(1u, writer_->packets_write_attempts());
1862 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
1863 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1864
1865 // Process another packet with a different peer address on server side will
1866 // start connection migration.
1867 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1868 // IETF QUIC send algorithm should be changed to a different object, so no
1869 // OnPacketSent() called on the old send algorithm.
1870 EXPECT_CALL(*send_algorithm_,
1871 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
1872 .Times(0);
1873 // Do not propagate OnCanWrite() to session notifier.
wubc9fd4292023-08-14 13:00:21 -07001874 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04001875
1876 QuicFrames frames2;
1877 frames2.push_back(QuicFrame(frame2_));
1878 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1879 ENCRYPTION_FORWARD_SECURE);
1880 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1881 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1882 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1883 connection_.active_effective_peer_migration_type());
1884 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
1885 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1886
1887 EXPECT_EQ(2u, writer_->packets_write_attempts());
1888 EXPECT_FALSE(writer_->path_challenge_frames().empty());
1889 QuicPathFrameBuffer payload =
1890 writer_->path_challenge_frames().front().data_buffer;
1891 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
1892 send_algorithm_);
1893 // Switch to use the mock send algorithm.
1894 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
1895 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1896 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1897 .WillRepeatedly(Return(kDefaultTCPMSS));
1898 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1899 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1900 .Times(AnyNumber())
1901 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1902 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1903 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1904 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
1905 connection_.SetSendAlgorithm(send_algorithm_);
1906
1907 // PATH_CHALLENGE is expanded upto the max packet size which may exceeds the
1908 // anti-amplification limit.
1909 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
1910 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1911 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1912 EXPECT_EQ(1u,
1913 connection_.GetStats().num_reverse_path_validtion_upon_migration);
1914
1915 // Verify server is throttled by anti-amplification limit.
1916 connection_.SendCryptoDataWithString("foo", 0);
1917 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1918
1919 // Receiving an ACK to the packet sent after changing peer address doesn't
1920 // finish migration validation.
1921 QuicAckFrame ack_frame = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07001922 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04001923 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1924 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
1925 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1926 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1927 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1928 connection_.active_effective_peer_migration_type());
1929
1930 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
1931 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -07001932 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04001933 EXPECT_CALL(visitor_, MaybeSendAddressToken());
1934 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1935 .Times(testing::AtLeast(1u));
1936 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
1937 ENCRYPTION_FORWARD_SECURE);
1938 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1939
1940 // Verify the anti-amplification limit is lifted by sending a packet larger
1941 // than the anti-amplification limit.
1942 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
1943 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001944 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001945}
1946
1947TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServerWithMissingConnectionId) {
1948 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -07001949 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04001950 return;
1951 }
1952 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1953 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1954
1955 QuicConnectionId client_cid0 = TestConnectionId(1);
1956 QuicConnectionId client_cid1 = TestConnectionId(3);
1957 QuicConnectionId server_cid1;
1958 SetClientConnectionId(client_cid0);
1959 connection_.CreateConnectionIdManager();
1960 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1961 // Prevent packets from being coalesced.
1962 EXPECT_CALL(visitor_, GetHandshakeState())
1963 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1964 QuicConnectionPeer::SetAddressValidated(&connection_);
1965
1966 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07001967 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07001968 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
1969 .WillOnce(Return(TestConnectionId(456)));
1970 }
haoyuewangada6b822022-06-23 13:41:18 -07001971 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
1972 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
1973 server_cid1 = cid;
1974 return true;
1975 }));
Bence Békybac04052022-04-07 15:44:29 -04001976 EXPECT_CALL(visitor_, SendNewConnectionId(_));
1977 connection_.OnHandshakeComplete();
1978
1979 // Clear direct_peer_address.
1980 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1981 // Clear effective_peer_address, it is the same as direct_peer_address for
1982 // this test.
1983 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1984 QuicSocketAddress());
1985 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1986
1987 const QuicSocketAddress kNewPeerAddress =
1988 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1989 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
1990 QuicFrames frames;
1991 frames.push_back(QuicFrame(frame1_));
1992 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1993 ENCRYPTION_FORWARD_SECURE);
1994 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1995 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1996
1997 // Send some data to make connection has packets in flight.
1998 connection_.SendStreamData3();
1999 EXPECT_EQ(1u, writer_->packets_write_attempts());
2000
2001 // Process another packet with a different peer address on server side will
2002 // start connection migration.
2003 peer_creator_.SetServerConnectionId(server_cid1);
2004 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2005 // Do not propagate OnCanWrite() to session notifier.
wubc9fd4292023-08-14 13:00:21 -07002006 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04002007
2008 QuicFrames frames2;
2009 frames2.push_back(QuicFrame(frame2_));
birenroyef686222022-09-12 11:34:34 -07002010 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07002011 frames2.push_back(QuicFrame(QuicPaddingFrame(-1)));
2012 }
Bence Békybac04052022-04-07 15:44:29 -04002013 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2014 ENCRYPTION_FORWARD_SECURE);
2015 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2016 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2017
2018 // Writing path response & reverse path challenge is blocked due to missing
2019 // client connection ID, i.e., packets_write_attempts is unchanged.
2020 EXPECT_EQ(1u, writer_->packets_write_attempts());
2021
2022 // Receives new client CID from client would unblock write.
2023 QuicNewConnectionIdFrame new_cid_frame;
2024 new_cid_frame.connection_id = client_cid1;
2025 new_cid_frame.sequence_number = 1u;
2026 new_cid_frame.retire_prior_to = 0u;
2027 connection_.OnNewConnectionIdFrame(new_cid_frame);
2028 connection_.SendStreamData3();
2029
2030 EXPECT_EQ(2u, writer_->packets_write_attempts());
2031}
2032
2033TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
birenroyef686222022-09-12 11:34:34 -07002034 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07002035 return;
2036 }
Bence Békybac04052022-04-07 15:44:29 -04002037 set_perspective(Perspective::IS_SERVER);
2038 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2039 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2040 if (version().SupportsAntiAmplificationLimit()) {
2041 QuicConnectionPeer::SetAddressValidated(&connection_);
2042 }
2043 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2044 // Discard INITIAL key.
2045 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2046 connection_.NeuterUnencryptedPackets();
2047 EXPECT_CALL(visitor_, GetHandshakeState())
2048 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2049
2050 // Clear direct_peer_address.
2051 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2052 // Clear effective_peer_address, it is different from direct_peer_address for
2053 // this test.
2054 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2055 QuicSocketAddress());
2056 const QuicSocketAddress kEffectivePeerAddress =
2057 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2058 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2059
2060 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2061 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2062 } else {
2063 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2064 }
2065 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2066 ENCRYPTION_FORWARD_SECURE);
2067 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2068 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2069
2070 // Process another packet with the same direct peer address and different
2071 // effective peer address on server side will start connection migration.
2072 const QuicSocketAddress kNewEffectivePeerAddress =
2073 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2074 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2075 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2076 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2077 ENCRYPTION_FORWARD_SECURE);
2078 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2079 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2080 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
danzh4d58dae2023-06-06 11:13:10 -07002081 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002082 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2083 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07002084 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04002085 }
2086
2087 // Process another packet with a different direct peer address and the same
2088 // effective peer address on server side will not start connection migration.
2089 const QuicSocketAddress kNewPeerAddress =
2090 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2091 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2092 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2093
danzh4d58dae2023-06-06 11:13:10 -07002094 if (!GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002095 // ack_frame is used to complete the migration started by the last packet,
2096 // we need to make sure a new migration does not start after the previous
2097 // one is completed.
2098 QuicAckFrame ack_frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07002099 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04002100 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2101 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2102 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2103 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2104 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2105 }
2106
2107 // Process another packet with different direct peer address and different
2108 // effective peer address on server side will start connection migration.
2109 const QuicSocketAddress kNewerEffectivePeerAddress =
2110 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2111 const QuicSocketAddress kFinalPeerAddress =
2112 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2113 connection_.ReturnEffectivePeerAddressForNextPacket(
2114 kNewerEffectivePeerAddress);
2115 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2116 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2117 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2118 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2119 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
danzh4d58dae2023-06-06 11:13:10 -07002120 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002121 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2122 EXPECT_EQ(send_algorithm_,
2123 connection_.sent_packet_manager().GetSendAlgorithm());
2124 EXPECT_EQ(2u, connection_.GetStats().num_validated_peer_migration);
2125 }
2126
2127 // While the previous migration is ongoing, process another packet with the
2128 // same direct peer address and different effective peer address on server
2129 // side will start a new connection migration.
2130 const QuicSocketAddress kNewestEffectivePeerAddress =
2131 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2132 connection_.ReturnEffectivePeerAddressForNextPacket(
2133 kNewestEffectivePeerAddress);
2134 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
danzh4d58dae2023-06-06 11:13:10 -07002135 if (!GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002136 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
2137 }
2138 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2139 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2140 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2141 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2142 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2143 connection_.active_effective_peer_migration_type());
danzh4d58dae2023-06-06 11:13:10 -07002144 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002145 EXPECT_NE(send_algorithm_,
2146 connection_.sent_packet_manager().GetSendAlgorithm());
2147 EXPECT_EQ(kFinalPeerAddress, writer_->last_write_peer_address());
2148 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2149 EXPECT_EQ(0u, connection_.GetStats()
2150 .num_peer_migration_while_validating_default_path);
2151 EXPECT_TRUE(connection_.HasPendingPathValidation());
2152 }
2153}
2154
2155// Regression test for b/200020764.
2156TEST_P(QuicConnectionTest, ConnectionMigrationWithPendingPaddingBytes) {
2157 // TODO(haoyuewang) Move these test setup code to a common member function.
2158 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -07002159 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002160 return;
2161 }
2162 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2163 connection_.CreateConnectionIdManager();
2164 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2165 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2166 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2167 QuicConnectionPeer::SetAddressValidated(&connection_);
2168
2169 // Sends new server CID to client.
2170 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002171 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002172 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2173 .WillOnce(Return(TestConnectionId(456)));
2174 }
haoyuewangada6b822022-06-23 13:41:18 -07002175 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2176 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2177 new_cid = cid;
2178 return true;
2179 }));
Bence Békybac04052022-04-07 15:44:29 -04002180 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2181 // Discard INITIAL key.
2182 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2183 connection_.NeuterUnencryptedPackets();
2184 connection_.OnHandshakeComplete();
2185 EXPECT_CALL(visitor_, GetHandshakeState())
2186 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2187
2188 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2189 packet_creator->FlushCurrentPacket();
2190 packet_creator->AddPendingPadding(50u);
2191 const QuicSocketAddress kPeerAddress3 =
2192 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2193 auto ack_frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07002194 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04002195 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2196 ProcessFramesPacketWithAddresses({QuicFrame(&ack_frame)}, kSelfAddress,
2197 kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
haoyuewang16f86e82023-07-26 14:13:26 -07002198 // Any pending frames/padding should be flushed before default_path_ is
2199 // temporarily reset.
2200 ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2201 .host()
2202 .address_family(),
2203 IpAddressFamily::IP_V6);
Bence Békybac04052022-04-07 15:44:29 -04002204}
2205
2206// Regression test for b/196208556.
2207TEST_P(QuicConnectionTest,
2208 ReversePathValidationResponseReceivedFromUnexpectedPeerAddress) {
2209 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -07002210 if (!version().HasIetfQuicFrames() ||
birenroyef686222022-09-12 11:34:34 -07002211 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04002212 return;
2213 }
2214 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2215 connection_.CreateConnectionIdManager();
2216 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2217 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2218 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2219 QuicConnectionPeer::SetAddressValidated(&connection_);
2220 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2221 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2222
2223 // Sends new server CID to client.
2224 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002225 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002226 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2227 .WillOnce(Return(TestConnectionId(456)));
2228 }
haoyuewangada6b822022-06-23 13:41:18 -07002229 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2230 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2231 new_cid = cid;
2232 return true;
2233 }));
Bence Békybac04052022-04-07 15:44:29 -04002234 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2235 // Discard INITIAL key.
2236 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2237 connection_.NeuterUnencryptedPackets();
2238 connection_.OnHandshakeComplete();
2239 EXPECT_CALL(visitor_, GetHandshakeState())
2240 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2241
2242 // Process a non-probing packet to migrate to path 2 and kick off reverse path
2243 // validation.
2244 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2245 const QuicSocketAddress kPeerAddress2 =
2246 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2247 peer_creator_.SetServerConnectionId(new_cid);
2248 ProcessFramesPacketWithAddresses({QuicFrame(QuicPingFrame())}, kSelfAddress,
2249 kPeerAddress2, ENCRYPTION_FORWARD_SECURE);
2250 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2251 QuicPathFrameBuffer reverse_path_challenge_payload =
2252 writer_->path_challenge_frames().front().data_buffer;
2253
2254 // Receiveds a packet from path 3 with PATH_RESPONSE frame intended to
2255 // validate path 2 and a non-probing frame.
2256 {
2257 QuicConnection::ScopedPacketFlusher flusher(&connection_);
2258 const QuicSocketAddress kPeerAddress3 =
2259 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2260 auto ack_frame = InitAckFrame(1);
2261 EXPECT_CALL(visitor_, OnConnectionMigration(IPV4_TO_IPV6_CHANGE)).Times(1);
2262 EXPECT_CALL(visitor_, MaybeSendAddressToken()).WillOnce(Invoke([this]() {
2263 connection_.SendControlFrame(
2264 QuicFrame(new QuicNewTokenFrame(1, "new_token")));
2265 return true;
2266 }));
wubd0152ca2022-04-08 08:26:44 -07002267 ProcessFramesPacketWithAddresses(
2268 {QuicFrame(QuicPathResponseFrame(0, reverse_path_challenge_payload)),
2269 QuicFrame(&ack_frame)},
2270 kSelfAddress, kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04002271 }
2272}
2273
2274TEST_P(QuicConnectionTest, ReversePathValidationFailureAtServer) {
2275 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -07002276 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002277 return;
2278 }
2279 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2280 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2281 SetClientConnectionId(TestConnectionId(1));
2282 connection_.CreateConnectionIdManager();
2283 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2284 // Discard INITIAL key.
2285 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2286 connection_.NeuterUnencryptedPackets();
2287 // Prevent packets from being coalesced.
2288 EXPECT_CALL(visitor_, GetHandshakeState())
2289 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2290 QuicConnectionPeer::SetAddressValidated(&connection_);
2291
2292 QuicConnectionId client_cid0 = connection_.client_connection_id();
2293 QuicConnectionId client_cid1 = TestConnectionId(2);
2294 QuicConnectionId server_cid0 = connection_.connection_id();
2295 QuicConnectionId server_cid1;
2296 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07002297 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002298 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2299 .WillOnce(Return(TestConnectionId(456)));
2300 }
haoyuewangada6b822022-06-23 13:41:18 -07002301 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2302 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2303 server_cid1 = cid;
2304 return true;
2305 }));
Bence Békybac04052022-04-07 15:44:29 -04002306 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2307 connection_.OnHandshakeComplete();
2308 // Receives new client CID from client.
2309 QuicNewConnectionIdFrame new_cid_frame;
2310 new_cid_frame.connection_id = client_cid1;
2311 new_cid_frame.sequence_number = 1u;
2312 new_cid_frame.retire_prior_to = 0u;
2313 connection_.OnNewConnectionIdFrame(new_cid_frame);
2314 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2315 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2316 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2317
2318 // Clear direct_peer_address.
2319 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2320 // Clear effective_peer_address, it is the same as direct_peer_address for
2321 // this test.
2322 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2323 QuicSocketAddress());
2324 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2325
2326 const QuicSocketAddress kNewPeerAddress =
2327 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2328 EXPECT_CALL(visitor_, OnStreamFrame(_))
2329 .WillOnce(Invoke(
2330 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
2331 .WillOnce(Invoke(
2332 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
2333 QuicFrames frames;
2334 frames.push_back(QuicFrame(frame1_));
2335 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
2336 ENCRYPTION_FORWARD_SECURE);
2337 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2338 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2339
2340 // Process another packet with a different peer address on server side will
2341 // start connection migration.
2342 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2343 // IETF QUIC send algorithm should be changed to a different object, so no
2344 // OnPacketSent() called on the old send algorithm.
2345 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0);
2346
2347 QuicFrames frames2;
2348 frames2.push_back(QuicFrame(frame2_));
2349 QuicPaddingFrame padding;
2350 frames2.push_back(QuicFrame(padding));
2351 peer_creator_.SetServerConnectionId(server_cid1);
2352 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2353 ENCRYPTION_FORWARD_SECURE);
2354 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2355 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2356 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2357 connection_.active_effective_peer_migration_type());
2358 EXPECT_LT(0u, writer_->packets_write_attempts());
2359 EXPECT_TRUE(connection_.HasPendingPathValidation());
2360 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
2361 send_algorithm_);
2362 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2363 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2364 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2365 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
2366 const auto* alternative_path =
2367 QuicConnectionPeer::GetAlternativePath(&connection_);
2368 EXPECT_EQ(default_path->client_connection_id, client_cid1);
2369 EXPECT_EQ(default_path->server_connection_id, server_cid1);
2370 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
2371 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
2372 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
2373 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
2374
2375 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes; ++i) {
2376 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2377 static_cast<TestAlarmFactory::TestAlarm*>(
2378 QuicPathValidatorPeer::retry_timer(
2379 QuicConnectionPeer::path_validator(&connection_)))
2380 ->Fire();
2381 }
2382 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2383 connection_.active_effective_peer_migration_type());
2384
2385 // Make sure anti-amplification limit is not reached.
2386 ProcessFramesPacketWithAddresses(
2387 {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
2388 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2389 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2390 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2391
2392 // Advance the time so that the reverse path validation times out.
2393 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2394 static_cast<TestAlarmFactory::TestAlarm*>(
2395 QuicPathValidatorPeer::retry_timer(
2396 QuicConnectionPeer::path_validator(&connection_)))
2397 ->Fire();
2398 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2399 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2400 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2401 EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
2402 send_algorithm_);
2403 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2404
2405 // Verify that default_path_ is reverted and alternative_path_ is cleared.
2406 EXPECT_EQ(default_path->client_connection_id, client_cid0);
2407 EXPECT_EQ(default_path->server_connection_id, server_cid0);
2408 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
2409 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
2410 auto* retire_peer_issued_cid_alarm =
2411 connection_.GetRetirePeerIssuedConnectionIdAlarm();
2412 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
2413 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
2414 retire_peer_issued_cid_alarm->Fire();
2415 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2416 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2417}
2418
2419TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
danzh65153092023-06-16 10:59:32 -07002420 if (!version().HasIetfQuicFrames() &&
2421 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2422 return;
2423 }
Bence Békybac04052022-04-07 15:44:29 -04002424 PathProbeTestInit(Perspective::IS_SERVER);
2425
2426 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2427 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
2428
2429 // Process a padded PING packet with no peer address change on server side
2430 // will be ignored. But a PATH CHALLENGE packet with no peer address change
2431 // will be considered as path probing.
2432 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2433
2434 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2435 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2436 probing_packet->encrypted_length),
2437 clock_.Now()));
2438
2439 uint64_t num_probing_received =
2440 connection_.GetStats().num_connectivity_probing_received;
2441 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2442
2443 EXPECT_EQ(
2444 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2445 connection_.GetStats().num_connectivity_probing_received);
2446 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2447 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2448}
2449
2450// Regression test for b/150161358.
2451TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
2452 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2453 writer_->SetWriteBlocked();
2454
2455 // Send a MTU packet while blocked. It should be buffered.
2456 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2457 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2458 EXPECT_TRUE(writer_->IsWriteBlocked());
2459
2460 writer_->AlwaysGetPacketTooLarge();
2461 writer_->SetWritable();
2462 connection_.OnCanWrite();
2463}
2464
2465TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2466 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2467 if (!IsDefaultTestConfiguration()) {
2468 return;
2469 }
2470
2471 set_perspective(Perspective::IS_CLIENT);
2472
2473 BlockOnNextWrite();
2474
2475 QuicStreamId stream_id = 2;
2476 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2477
2478 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2479
2480 writer_->SetWritable();
2481 connection_.SendConnectivityProbingPacket(writer_.get(),
2482 connection_.peer_address());
2483 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2484 connection_.OnCanWrite();
2485}
2486
2487TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2488 // Regression test for b/74073386.
2489 {
2490 InSequence seq;
2491 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2492 .Times(AtLeast(1));
2493 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
2494 }
2495
2496 set_perspective(Perspective::IS_CLIENT);
2497
2498 writer_->SimulateNextPacketTooLarge();
2499
2500 // This packet write should fail, which should cause the connection to close
2501 // after sending a connection close packet, then the failed packet should be
2502 // queued.
2503 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2504
2505 EXPECT_FALSE(connection_.connected());
2506 // No need to buffer packets.
2507 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2508
2509 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2510 connection_.OnCanWrite();
2511 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2512}
2513
2514class TestQuicPathValidationContext : public QuicPathValidationContext {
2515 public:
2516 TestQuicPathValidationContext(const QuicSocketAddress& self_address,
2517 const QuicSocketAddress& peer_address,
2518
2519 QuicPacketWriter* writer)
2520 : QuicPathValidationContext(self_address, peer_address),
2521 writer_(writer) {}
2522
2523 QuicPacketWriter* WriterToUse() override { return writer_; }
2524
2525 private:
2526 QuicPacketWriter* writer_;
2527};
2528
2529class TestValidationResultDelegate : public QuicPathValidator::ResultDelegate {
2530 public:
2531 TestValidationResultDelegate(QuicConnection* connection,
2532 const QuicSocketAddress& expected_self_address,
2533 const QuicSocketAddress& expected_peer_address,
2534 bool* success)
2535 : QuicPathValidator::ResultDelegate(),
2536 connection_(connection),
2537 expected_self_address_(expected_self_address),
2538 expected_peer_address_(expected_peer_address),
2539 success_(success) {}
2540 void OnPathValidationSuccess(
wub130bde92022-08-01 14:33:14 -07002541 std::unique_ptr<QuicPathValidationContext> context,
2542 QuicTime /*start_time*/) override {
Bence Békybac04052022-04-07 15:44:29 -04002543 EXPECT_EQ(expected_self_address_, context->self_address());
2544 EXPECT_EQ(expected_peer_address_, context->peer_address());
2545 *success_ = true;
2546 }
2547
2548 void OnPathValidationFailure(
2549 std::unique_ptr<QuicPathValidationContext> context) override {
2550 EXPECT_EQ(expected_self_address_, context->self_address());
2551 EXPECT_EQ(expected_peer_address_, context->peer_address());
2552 if (connection_->perspective() == Perspective::IS_CLIENT) {
danzh8fdee2e2023-01-05 15:33:02 -08002553 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2554 *context);
Bence Békybac04052022-04-07 15:44:29 -04002555 }
2556 *success_ = false;
2557 }
2558
2559 private:
2560 QuicConnection* connection_;
2561 QuicSocketAddress expected_self_address_;
2562 QuicSocketAddress expected_peer_address_;
2563 bool* success_;
2564};
2565
danzh8fdee2e2023-01-05 15:33:02 -08002566// A test implementation which migrates to server preferred address
2567// on path validation suceeds. Otherwise, client cleans up alternative path.
fayang5c6e7012023-01-08 20:06:01 -08002568class ServerPreferredAddressTestResultDelegate
danzh8fdee2e2023-01-05 15:33:02 -08002569 : public QuicPathValidator::ResultDelegate {
2570 public:
2571 explicit ServerPreferredAddressTestResultDelegate(QuicConnection* connection)
2572 : connection_(connection) {}
2573 void OnPathValidationSuccess(
2574 std::unique_ptr<QuicPathValidationContext> context,
2575 QuicTime /*start_time*/) override {
2576 connection_->OnServerPreferredAddressValidated(*context, false);
2577 }
2578
2579 void OnPathValidationFailure(
2580 std::unique_ptr<QuicPathValidationContext> context) override {
2581 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2582 *context);
2583 }
2584
2585 protected:
2586 QuicConnection* connection() { return connection_; }
2587
2588 private:
2589 QuicConnection* connection_;
2590};
2591
danzh65153092023-06-16 10:59:32 -07002592// Receive a path probe request at the server side, in IETF version: receive a
2593// packet contains PATH CHALLENGE with peer address change.
danzhb159ab02023-01-30 10:58:46 -08002594TEST_P(QuicConnectionTest, ReceivePathProbingFromNewPeerAddressAtServer) {
danzh65153092023-06-16 10:59:32 -07002595 if (!version().HasIetfQuicFrames() &&
2596 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2597 return;
2598 }
Bence Békybac04052022-04-07 15:44:29 -04002599 PathProbeTestInit(Perspective::IS_SERVER);
2600
2601 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2602 QuicPathFrameBuffer payload;
2603 if (!GetParam().version.HasIetfQuicFrames()) {
2604 EXPECT_CALL(visitor_,
2605 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2606 .Times(1);
2607 } else {
2608 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
danzh4d58dae2023-06-06 11:13:10 -07002609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2610 .Times(AtLeast(1u))
2611 .WillOnce(Invoke([&]() {
2612 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2613 EXPECT_EQ(1u, writer_->path_response_frames().size());
2614 payload = writer_->path_challenge_frames().front().data_buffer;
awillia202240c2024-07-08 09:47:00 -07002615 }))
2616 .WillRepeatedly(DoDefault());
Bence Békybac04052022-04-07 15:44:29 -04002617 }
2618 // Process a probing packet from a new peer address on server side
2619 // is effectively receiving a connectivity probing.
2620 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2621 /*port=*/23456);
2622
2623 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2624 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2625 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2626 probing_packet->encrypted_length),
2627 clock_.Now()));
2628 uint64_t num_probing_received =
2629 connection_.GetStats().num_connectivity_probing_received;
2630 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2631
2632 EXPECT_EQ(num_probing_received + 1,
2633 connection_.GetStats().num_connectivity_probing_received);
2634 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2635 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhaf2e52a2022-04-20 07:37:03 -07002636 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002637 QuicByteCount bytes_sent =
2638 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_);
2639 EXPECT_LT(0u, bytes_sent);
2640 EXPECT_EQ(received->length(),
2641 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2642
2643 // Receiving one more probing packet should update the bytes count.
2644 probing_packet = ConstructProbingPacket();
2645 received.reset(ConstructReceivedPacket(
2646 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2647 probing_packet->encrypted_length),
2648 clock_.Now()));
2649 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2650
2651 EXPECT_EQ(num_probing_received + 2,
2652 connection_.GetStats().num_connectivity_probing_received);
2653 EXPECT_EQ(2 * bytes_sent,
2654 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2655 EXPECT_EQ(2 * received->length(),
2656 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2657
danzh4d58dae2023-06-06 11:13:10 -07002658 EXPECT_EQ(2 * bytes_sent,
Bence Békybac04052022-04-07 15:44:29 -04002659 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2660 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -07002661 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04002662 ProcessFramesPacketWithAddresses(frames, connection_.self_address(),
2663 kNewPeerAddress,
2664 ENCRYPTION_FORWARD_SECURE);
2665 EXPECT_LT(2 * received->length(),
2666 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
danzh4d58dae2023-06-06 11:13:10 -07002667 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
Bence Békybac04052022-04-07 15:44:29 -04002668 // Receiving another probing packet from a newer address with a different
2669 // port shouldn't trigger another reverse path validation.
2670 QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
2671 /*port=*/34567);
2672 probing_packet = ConstructProbingPacket();
2673 received.reset(ConstructReceivedPacket(
2674 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2675 probing_packet->encrypted_length),
2676 clock_.Now()));
2677 ProcessReceivedPacket(kSelfAddress, kNewerPeerAddress, *received);
2678 EXPECT_FALSE(connection_.HasPendingPathValidation());
danzh4d58dae2023-06-06 11:13:10 -07002679 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
Bence Békybac04052022-04-07 15:44:29 -04002680 }
2681
2682 // Process another packet with the old peer address on server side will not
2683 // start peer migration.
2684 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2685 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2686 ENCRYPTION_INITIAL);
2687 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2688 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2689}
2690
danzhb159ab02023-01-30 10:58:46 -08002691// Receive a packet contains PATH CHALLENGE with self address change.
2692TEST_P(QuicConnectionTest, ReceivePathProbingToPreferredAddressAtServer) {
2693 if (!GetParam().version.HasIetfQuicFrames()) {
2694 return;
2695 }
2696 ServerHandlePreferredAddressInit();
2697
2698 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2699 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2700
2701 // Process a probing packet to the server preferred address.
2702 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2703 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2704 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2705 probing_packet->encrypted_length),
2706 clock_.Now()));
2707 uint64_t num_probing_received =
2708 connection_.GetStats().num_connectivity_probing_received;
2709 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2710 .Times(AtLeast(1u))
2711 .WillOnce(Invoke([&]() {
2712 EXPECT_EQ(1u, writer_->path_response_frames().size());
2713 // Verify that the PATH_RESPONSE is sent from the original self address.
2714 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
2715 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
2716 }));
2717 ProcessReceivedPacket(kServerPreferredAddress, kPeerAddress, *received);
2718
2719 EXPECT_EQ(num_probing_received + 1,
2720 connection_.GetStats().num_connectivity_probing_received);
2721 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
2722 &connection_, kServerPreferredAddress, kPeerAddress));
2723 EXPECT_NE(kServerPreferredAddress, connection_.self_address());
2724
2725 // Receiving another probing packet from a new client address.
2726 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2727 /*port=*/34567);
2728 probing_packet = ConstructProbingPacket();
2729 received.reset(ConstructReceivedPacket(
2730 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2731 probing_packet->encrypted_length),
2732 clock_.Now()));
2733 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2734 .Times(AtLeast(1u))
2735 .WillOnce(Invoke([&]() {
2736 EXPECT_EQ(1u, writer_->path_response_frames().size());
2737 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
fayang1f578d32023-03-20 11:36:15 -07002738 EXPECT_EQ(kServerPreferredAddress.host(),
2739 writer_->last_write_source_address());
2740 // The responses should be sent from preferred address given server
2741 // has not received packet on original address from the new client
2742 // address.
danzhb159ab02023-01-30 10:58:46 -08002743 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2744 }));
2745 ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received);
2746
2747 EXPECT_EQ(num_probing_received + 2,
2748 connection_.GetStats().num_connectivity_probing_received);
2749 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
2750 kNewPeerAddress));
2751 EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2752 EXPECT_EQ(received->length(),
2753 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2754}
2755
Bence Békybac04052022-04-07 15:44:29 -04002756// Receive a padded PING packet with a port change on server side.
2757TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2758 set_perspective(Perspective::IS_SERVER);
2759 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2760 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2761 if (version().SupportsAntiAmplificationLimit()) {
2762 QuicConnectionPeer::SetAddressValidated(&connection_);
2763 }
2764
2765 // Clear direct_peer_address.
2766 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2767 // Clear effective_peer_address, it is the same as direct_peer_address for
2768 // this test.
2769 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2770 QuicSocketAddress());
2771 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2772
2773 if (GetParam().version.UsesCryptoFrames()) {
2774 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2775 } else {
2776 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2777 }
2778 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2779 ENCRYPTION_INITIAL);
2780 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2781 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2782
danzh65153092023-06-16 10:59:32 -07002783 if (GetParam().version.HasIetfQuicFrames() ||
2784 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002785 // In IETF version, a padded PING packet with port change is not taken as
2786 // connectivity probe.
2787 EXPECT_CALL(visitor_, GetHandshakeState())
2788 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2789 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2790 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2791 } else {
2792 // In non-IETF version, process a padded PING packet from a new peer
2793 // address on server side is effectively receiving a connectivity probing.
2794 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2795 EXPECT_CALL(visitor_,
2796 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2797 .Times(1);
2798 }
2799 const QuicSocketAddress kNewPeerAddress =
2800 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2801
2802 QuicFrames frames;
2803 // Write a PING frame, which has no data payload.
2804 QuicPingFrame ping_frame;
2805 frames.push_back(QuicFrame(ping_frame));
2806
2807 // Add padding to the rest of the packet.
2808 QuicPaddingFrame padding_frame;
2809 frames.push_back(QuicFrame(padding_frame));
2810
2811 uint64_t num_probing_received =
2812 connection_.GetStats().num_connectivity_probing_received;
2813
2814 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
2815 ENCRYPTION_INITIAL);
2816
danzh65153092023-06-16 10:59:32 -07002817 if (GetParam().version.HasIetfQuicFrames() ||
2818 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002819 // Padded PING with port changen is not considered as connectivity probe but
2820 // a PORT CHANGE.
2821 EXPECT_EQ(num_probing_received,
2822 connection_.GetStats().num_connectivity_probing_received);
2823 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2824 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2825 } else {
2826 EXPECT_EQ(num_probing_received + 1,
2827 connection_.GetStats().num_connectivity_probing_received);
2828 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2829 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2830 }
2831
danzh65153092023-06-16 10:59:32 -07002832 if (GetParam().version.HasIetfQuicFrames() ||
2833 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002834 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2835 }
danzh65153092023-06-16 10:59:32 -07002836 // Process another packet with the old peer address on server side.
Bence Békybac04052022-04-07 15:44:29 -04002837 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2838 ENCRYPTION_INITIAL);
2839 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2840 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2841}
2842
2843TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
danzh65153092023-06-16 10:59:32 -07002844 if (!GetParam().version.HasIetfQuicFrames() &&
2845 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2846 return;
2847 }
Bence Békybac04052022-04-07 15:44:29 -04002848 PathProbeTestInit(Perspective::IS_SERVER);
2849
2850 // Decrease packet number to simulate out-of-order packets.
2851 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2852
2853 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2854 if (!GetParam().version.HasIetfQuicFrames()) {
2855 EXPECT_CALL(visitor_,
2856 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2857 .Times(1);
2858 } else {
2859 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2860 }
2861
2862 // Process a padded PING packet from a new peer address on server side
2863 // is effectively receiving a connectivity probing, even if a newer packet has
2864 // been received before this one.
2865 const QuicSocketAddress kNewPeerAddress =
2866 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2867
2868 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2869 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2870 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2871 probing_packet->encrypted_length),
2872 clock_.Now()));
2873
2874 uint64_t num_probing_received =
2875 connection_.GetStats().num_connectivity_probing_received;
2876 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2877
danzh65153092023-06-16 10:59:32 -07002878 EXPECT_EQ(num_probing_received +
2879 (!version().HasIetfQuicFrames() &&
2880 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2881 ? 0u
2882 : 1u),
Bence Békybac04052022-04-07 15:44:29 -04002883 connection_.GetStats().num_connectivity_probing_received);
danzh65153092023-06-16 10:59:32 -07002884 EXPECT_EQ((!version().HasIetfQuicFrames() &&
2885 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2886 ? kNewPeerAddress
2887 : kPeerAddress),
2888 connection_.peer_address());
2889 EXPECT_EQ((!version().HasIetfQuicFrames() &&
2890 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2891 ? kNewPeerAddress
2892 : kPeerAddress),
2893 connection_.effective_peer_address());
Bence Békybac04052022-04-07 15:44:29 -04002894}
2895
2896TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
danzh65153092023-06-16 10:59:32 -07002897 if (!GetParam().version.HasIetfQuicFrames() &&
2898 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2899 return;
2900 }
Bence Békybac04052022-04-07 15:44:29 -04002901 PathProbeTestInit(Perspective::IS_SERVER);
2902
2903 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2904 if (!GetParam().version.HasIetfQuicFrames()) {
2905 EXPECT_CALL(visitor_,
2906 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2907 .Times(1);
2908 } else {
2909 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2910 }
2911
2912 // Process a padded PING packet from a new peer address on server side
2913 // is effectively receiving a connectivity probing.
2914 const QuicSocketAddress kNewPeerAddress =
2915 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2916
2917 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2918 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2919 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2920 probing_packet->encrypted_length),
2921 clock_.Now()));
2922 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2923 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2924 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2925
2926 // Process another non-probing packet with the new peer address on server
2927 // side will start peer migration.
2928 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2929
2930 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2931 kNewPeerAddress, ENCRYPTION_INITIAL);
2932 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2933 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2934}
2935
2936TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) {
danzh65153092023-06-16 10:59:32 -07002937 if (!version().HasIetfQuicFrames() &&
2938 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2939 return;
2940 }
Bence Békybac04052022-04-07 15:44:29 -04002941 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2942 PathProbeTestInit(Perspective::IS_CLIENT);
2943
2944 // Client takes all padded PING packet as speculative connectivity
2945 // probing packet, and reports to visitor.
2946 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2947
2948 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2949 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2950 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2951 probing_packet->encrypted_length),
2952 clock_.Now()));
2953 uint64_t num_probing_received =
2954 connection_.GetStats().num_connectivity_probing_received;
2955 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2956
2957 EXPECT_EQ(
2958 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2959 connection_.GetStats().num_connectivity_probing_received);
2960 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2961 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2962}
2963
2964TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
danzh65153092023-06-16 10:59:32 -07002965 if (GetParam().version.HasIetfQuicFrames() ||
2966 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002967 return;
2968 }
2969 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2970 PathProbeTestInit(Perspective::IS_CLIENT);
2971
2972 // Process a padded PING packet with a different self address on client side
2973 // is effectively receiving a connectivity probing.
2974 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2975 if (!GetParam().version.HasIetfQuicFrames()) {
2976 EXPECT_CALL(visitor_,
2977 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2978 .Times(1);
2979 } else {
2980 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2981 }
2982
2983 const QuicSocketAddress kNewSelfAddress =
2984 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2985
2986 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2987 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2988 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2989 probing_packet->encrypted_length),
2990 clock_.Now()));
2991 uint64_t num_probing_received =
2992 connection_.GetStats().num_connectivity_probing_received;
2993 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2994
2995 EXPECT_EQ(num_probing_received + 1,
2996 connection_.GetStats().num_connectivity_probing_received);
2997 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2998 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2999}
3000
3001TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
3002 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3003 set_perspective(Perspective::IS_CLIENT);
3004 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3005
3006 // Clear direct_peer_address.
3007 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
3008 // Clear effective_peer_address, it is the same as direct_peer_address for
3009 // this test.
3010 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
3011 QuicSocketAddress());
3012 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
3013
fayangd1f2c992022-12-21 10:34:55 -08003014 if (connection_.version().HasIetfQuicFrames()) {
3015 // Verify the 2nd packet from unknown server address gets dropped.
3016 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3017 } else if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3018 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -04003019 } else {
fayangd1f2c992022-12-21 10:34:55 -08003020 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -04003021 }
3022 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3023 ENCRYPTION_INITIAL);
3024 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3025 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
Bence Békybac04052022-04-07 15:44:29 -04003026 const QuicSocketAddress kNewPeerAddress =
3027 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3028 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
3029 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3030 kNewPeerAddress, ENCRYPTION_INITIAL);
3031 if (connection_.version().HasIetfQuicFrames()) {
3032 // IETF QUIC disallows server initiated address change.
3033 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3034 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3035 } else {
3036 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
3037 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
3038 }
3039}
3040
wub3cab5622024-02-20 08:30:32 -08003041TEST_P(QuicConnectionTest, NoNormalizedPeerAddressChangeAtClient) {
3042 if (!version().HasIetfQuicFrames()) {
3043 return;
3044 }
3045 QuicIpAddress peer_ip;
3046 peer_ip.FromString("1.1.1.1");
3047
3048 QuicSocketAddress peer_addr = QuicSocketAddress(peer_ip, /*port=*/443);
3049 QuicSocketAddress dualstack_peer_addr =
3050 QuicSocketAddress(peer_addr.host().DualStacked(), peer_addr.port());
3051
3052 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
3053 set_perspective(Perspective::IS_CLIENT);
3054 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3055
3056 QuicConnectionPeer::SetDirectPeerAddress(&connection_, dualstack_peer_addr);
3057
3058 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
3059 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
3060 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, peer_addr,
3061 ENCRYPTION_INITIAL);
3062 EXPECT_TRUE(connection_.connected());
3063
3064 if (GetQuicReloadableFlag(quic_test_peer_addr_change_after_normalize)) {
3065 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
3066 } else {
3067 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
3068 }
3069}
3070
fayangd1f2c992022-12-21 10:34:55 -08003071TEST_P(QuicConnectionTest, ServerAddressChangesToKnownAddress) {
3072 if (!connection_.version().HasIetfQuicFrames()) {
3073 return;
3074 }
3075 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3076 set_perspective(Perspective::IS_CLIENT);
3077 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3078
3079 // Clear direct_peer_address.
3080 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
3081 // Clear effective_peer_address, it is the same as direct_peer_address for
3082 // this test.
3083 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
3084 QuicSocketAddress());
3085 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
3086
3087 // Verify all 3 packets get processed.
3088 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
3089 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3090 ENCRYPTION_INITIAL);
3091 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3092 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3093
3094 // Process another packet with a different but known server address.
3095 const QuicSocketAddress kNewPeerAddress =
3096 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3097 connection_.AddKnownServerAddress(kNewPeerAddress);
3098 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(0);
3099 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3100 kNewPeerAddress, ENCRYPTION_INITIAL);
3101 // Verify peer address does not change.
3102 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3103 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3104
3105 // Process 3rd packet from previous server address.
3106 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3107 ENCRYPTION_INITIAL);
3108 // Verify peer address does not change.
3109 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3110 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3111}
3112
danzh8fdee2e2023-01-05 15:33:02 -08003113TEST_P(QuicConnectionTest,
3114 PeerAddressChangesToPreferredAddressBeforeClientInitiates) {
3115 if (!version().HasIetfQuicFrames()) {
3116 return;
3117 }
3118 ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3119 ASSERT_TRUE(connection_.self_address().host().IsIPv6());
danzh8fdee2e2023-01-05 15:33:02 -08003120 const QuicConnectionId connection_id = TestConnectionId(17);
3121 const StatelessResetToken reset_token =
3122 QuicUtils::GenerateStatelessResetToken(connection_id);
3123
3124 connection_.CreateConnectionIdManager();
3125
3126 connection_.SendCryptoStreamData();
3127 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07003128 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
danzh8fdee2e2023-01-05 15:33:02 -08003129 QuicAckFrame frame = InitAckFrame(1);
3130 // Received ACK for packet 1.
3131 ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
3132 // Discard INITIAL key.
3133 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
3134 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3135
3136 QuicConfig config;
danzhc251e142023-06-02 11:53:11 -07003137 config.SetConnectionOptionsToSend(QuicTagVector{kSPAD});
danzh8fdee2e2023-01-05 15:33:02 -08003138 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
3139 kTestStatelessResetToken);
3140 QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
3141 kServerPreferredAddress);
3142 QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
3143 &config, connection_id, reset_token);
3144 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3145 connection_.SetFromConfig(config);
3146 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3147 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhb159ab02023-01-30 10:58:46 -08003148 ASSERT_TRUE(
3149 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)
3150 .IsInitialized());
3151 EXPECT_EQ(
3152 kServerPreferredAddress,
3153 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_));
danzh8fdee2e2023-01-05 15:33:02 -08003154
3155 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(0);
3156 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3157 kServerPreferredAddress, ENCRYPTION_INITIAL);
3158}
3159
Bence Békybac04052022-04-07 15:44:29 -04003160TEST_P(QuicConnectionTest, MaxPacketSize) {
3161 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3162 EXPECT_EQ(1250u, connection_.max_packet_length());
3163}
3164
3165TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
3166 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3167
3168 // SetFromConfig is always called after construction from InitializeSession.
3169 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3170 constexpr uint32_t kTestMaxPacketSize = 1233u;
3171 QuicConfig config;
3172 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3173 connection_.SetFromConfig(config);
3174
3175 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
3176}
3177
3178TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
3179 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3180
3181 // SetFromConfig is always called after construction from InitializeSession.
3182 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3183 constexpr uint32_t kTestMaxPacketSize = 1450u;
3184 QuicConfig config;
3185 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3186 connection_.SetFromConfig(config);
3187
3188 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3189}
3190
3191TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
3192 TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress,
3193 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003194 Perspective::IS_SERVER, version(),
3195 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003196 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
3197 EXPECT_EQ(1000u, connection.max_packet_length());
3198}
3199
3200TEST_P(QuicConnectionTest, LowerServerResponseMtuTest) {
3201 set_perspective(Perspective::IS_SERVER);
3202 connection_.SetMaxPacketLength(1000);
3203 EXPECT_EQ(1000u, connection_.max_packet_length());
3204
birenroyef686222022-09-12 11:34:34 -07003205 SetQuicFlag(quic_use_lower_server_response_mtu_for_test, true);
Bence Békybac04052022-04-07 15:44:29 -04003206 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(::testing::AtMost(1));
3207 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(::testing::AtMost(1));
3208 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3209 EXPECT_EQ(1250u, connection_.max_packet_length());
3210}
3211
3212TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
3213 set_perspective(Perspective::IS_SERVER);
3214 connection_.SetMaxPacketLength(1000);
3215
3216 QuicPacketHeader header;
3217 header.destination_connection_id = connection_id_;
3218 header.version_flag = true;
3219 header.packet_number = QuicPacketNumber(12);
3220
3221 if (QuicVersionHasLongHeaderLengths(
3222 peer_framer_.version().transport_version)) {
3223 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07003224 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3225 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04003226 }
3227
3228 QuicFrames frames;
3229 QuicPaddingFrame padding;
3230 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3231 frames.push_back(QuicFrame(&crypto_frame_));
3232 } else {
3233 frames.push_back(QuicFrame(frame1_));
3234 }
3235 frames.push_back(QuicFrame(padding));
3236 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3237 char buffer[kMaxOutgoingPacketSize];
3238 size_t encrypted_length =
3239 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3240 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08003241 EXPECT_EQ(kMaxOutgoingPacketSize,
3242 encrypted_length +
3243 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003244
3245 framer_.set_version(version());
3246 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3247 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3248 } else {
3249 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3250 }
3251 connection_.ProcessUdpPacket(
3252 kSelfAddress, kPeerAddress,
3253 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3254 false));
3255
martinduke9e0811c2022-12-08 20:35:57 -08003256 EXPECT_EQ(kMaxOutgoingPacketSize,
3257 connection_.max_packet_length() +
3258 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003259}
3260
3261TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
3262 const QuicByteCount lower_max_packet_size = 1240;
3263 writer_->set_max_packet_size(lower_max_packet_size);
3264 set_perspective(Perspective::IS_SERVER);
3265 connection_.SetMaxPacketLength(1000);
3266 EXPECT_EQ(1000u, connection_.max_packet_length());
3267
3268 QuicPacketHeader header;
3269 header.destination_connection_id = connection_id_;
3270 header.version_flag = true;
3271 header.packet_number = QuicPacketNumber(12);
3272
3273 if (QuicVersionHasLongHeaderLengths(
3274 peer_framer_.version().transport_version)) {
3275 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07003276 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3277 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04003278 }
3279
3280 QuicFrames frames;
3281 QuicPaddingFrame padding;
3282 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3283 frames.push_back(QuicFrame(&crypto_frame_));
3284 } else {
3285 frames.push_back(QuicFrame(frame1_));
3286 }
3287 frames.push_back(QuicFrame(padding));
3288 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3289 char buffer[kMaxOutgoingPacketSize];
3290 size_t encrypted_length =
3291 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3292 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08003293 EXPECT_EQ(kMaxOutgoingPacketSize,
3294 encrypted_length +
3295 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003296
3297 framer_.set_version(version());
3298 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3299 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3300 } else {
3301 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3302 }
3303 connection_.ProcessUdpPacket(
3304 kSelfAddress, kPeerAddress,
3305 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3306 false));
3307
3308 // Here, the limit imposed by the writer is lower than the size of the packet
3309 // received, so the writer max packet size is used.
3310 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3311}
3312
3313TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
3314 const QuicByteCount lower_max_packet_size = 1240;
3315 writer_->set_max_packet_size(lower_max_packet_size);
3316
3317 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
3318 "Default maximum packet size is too low");
3319 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
3320
3321 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3322}
3323
3324TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
3325 const QuicConnectionId connection_id = TestConnectionId(17);
3326 const QuicByteCount lower_max_packet_size = 1240;
3327 writer_->set_max_packet_size(lower_max_packet_size);
3328 TestConnection connection(connection_id, kSelfAddress, kPeerAddress,
3329 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003330 Perspective::IS_CLIENT, version(),
3331 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003332 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
3333 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
3334}
3335
3336TEST_P(QuicConnectionTest, PacketsInOrder) {
3337 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3338
3339 ProcessPacket(1);
3340 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
3341 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3342
3343 ProcessPacket(2);
3344 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
3345 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3346
3347 ProcessPacket(3);
3348 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3349 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3350}
3351
3352TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
3353 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3354
3355 ProcessPacket(3);
3356 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3357 EXPECT_TRUE(IsMissing(2));
3358 EXPECT_TRUE(IsMissing(1));
3359
3360 ProcessPacket(2);
3361 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3362 EXPECT_FALSE(IsMissing(2));
3363 EXPECT_TRUE(IsMissing(1));
3364
3365 ProcessPacket(1);
3366 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3367 EXPECT_FALSE(IsMissing(2));
3368 EXPECT_FALSE(IsMissing(1));
3369}
3370
3371TEST_P(QuicConnectionTest, DuplicatePacket) {
3372 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3373
3374 ProcessPacket(3);
3375 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3376 EXPECT_TRUE(IsMissing(2));
3377 EXPECT_TRUE(IsMissing(1));
3378
3379 // Send packet 3 again, but do not set the expectation that
3380 // the visitor OnStreamFrame() will be called.
3381 ProcessDataPacket(3);
3382 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3383 EXPECT_TRUE(IsMissing(2));
3384 EXPECT_TRUE(IsMissing(1));
3385}
3386
3387TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
3388 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3389 return;
3390 }
3391 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3392
3393 ProcessPacket(3);
3394 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3395 EXPECT_TRUE(IsMissing(2));
3396 EXPECT_TRUE(IsMissing(1));
3397
3398 ProcessPacket(2);
3399 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3400 EXPECT_TRUE(IsMissing(1));
3401
3402 ProcessPacket(5);
3403 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
3404 EXPECT_TRUE(IsMissing(1));
3405 EXPECT_TRUE(IsMissing(4));
3406
3407 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
3408 // packet the peer will not retransmit. It indicates this by sending 'least
3409 // awaiting' is 4. The connection should then realize 1 will not be
3410 // retransmitted, and will remove it from the missing list.
3411 QuicAckFrame frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07003412 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003413 ProcessAckPacket(6, &frame);
3414
3415 // Force an ack to be sent.
3416 SendAckPacketToPeer();
3417 EXPECT_TRUE(IsMissing(4));
3418}
3419
3420TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
3421 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
3422 if (!IsDefaultTestConfiguration() ||
3423 VersionHasIetfQuicFrames(version().transport_version)) {
3424 return;
3425 }
3426
3427 // Process an unencrypted packet from the non-crypto stream.
3428 frame1_.stream_id = 3;
3429 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3430 EXPECT_CALL(visitor_,
3431 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3432 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
3433 "");
3434 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
3435}
3436
3437TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
3438 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3439
3440 ProcessPacket(3);
3441 // Should not cause an ack.
3442 EXPECT_EQ(0u, writer_->packets_write_attempts());
3443
3444 ProcessPacket(2);
3445 // Should ack immediately, since this fills the last hole.
3446 EXPECT_EQ(1u, writer_->packets_write_attempts());
3447
3448 ProcessPacket(1);
3449 // Should ack immediately, since this fills the last hole.
3450 EXPECT_EQ(2u, writer_->packets_write_attempts());
3451
3452 ProcessPacket(4);
3453 // Should not cause an ack.
3454 EXPECT_EQ(2u, writer_->packets_write_attempts());
3455}
3456
3457TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
3458 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3459
3460 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3461 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3462 EXPECT_EQ(2u, writer_->packets_write_attempts());
3463
3464 QuicAckFrame ack1 = InitAckFrame(1);
3465 QuicAckFrame ack2 = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07003466 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003467 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3468 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
3469 }
3470 ProcessAckPacket(2, &ack2);
3471 // Should ack immediately since we have missing packets.
3472 EXPECT_EQ(2u, writer_->packets_write_attempts());
3473
3474 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3475 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
3476 }
3477 ProcessAckPacket(1, &ack1);
3478 // Should not ack an ack filling a missing packet.
3479 EXPECT_EQ(2u, writer_->packets_write_attempts());
3480}
3481
3482TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
3483 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3484 QuicPacketNumber original, second;
3485
3486 QuicByteCount packet_size =
3487 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3488 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3489
3490 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3491 // First nack triggers early retransmit.
3492 LostPacketVector lost_packets;
3493 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
3494 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3495 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3496 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07003497 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003498 QuicPacketNumber retransmission;
3499 // Packet 1 is short header for IETF QUIC because the encryption level
3500 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangfc04b8a2023-05-18 09:26:25 -07003501 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _))
Bence Békybac04052022-04-07 15:44:29 -04003502 .WillOnce(SaveArg<2>(&retransmission));
3503
3504 ProcessAckPacket(&frame);
3505
3506 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
martindukeba002452023-03-21 08:10:46 -07003507 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003508 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3509 ProcessAckPacket(&frame2);
3510
3511 // Now if the peer sends an ack which still reports the retransmitted packet
3512 // as missing, that will bundle an ack with data after two acks in a row
3513 // indicate the high water mark needs to be raised.
3514 EXPECT_CALL(*send_algorithm_,
3515 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3516 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
3517 // No ack sent.
3518 size_t padding_frame_count = writer_->padding_frames().size();
3519 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3520 EXPECT_EQ(1u, writer_->stream_frames().size());
3521
3522 // No more packet loss for the rest of the test.
3523 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3524 .Times(AnyNumber());
3525 ProcessAckPacket(&frame2);
3526 EXPECT_CALL(*send_algorithm_,
3527 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3528 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
3529 // Ack bundled.
fayangfc04b8a2023-05-18 09:26:25 -07003530 // Do not ACK acks.
3531 EXPECT_EQ(1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04003532 EXPECT_EQ(1u, writer_->stream_frames().size());
fayangfc04b8a2023-05-18 09:26:25 -07003533 EXPECT_TRUE(writer_->ack_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04003534
3535 // But an ack with no missing packets will not send an ack.
3536 AckPacket(original, &frame2);
3537 ProcessAckPacket(&frame2);
3538 ProcessAckPacket(&frame2);
3539}
3540
3541TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) {
3542 if (!GetParam().version.HasIetfQuicFrames()) {
3543 return;
3544 }
3545 connection_.set_can_receive_ack_frequency_frame();
3546
3547 // Expect 13 acks, every 3rd packet including the first packet with
3548 // AckFrequencyFrame.
3549 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
3550 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3551
3552 QuicAckFrequencyFrame ack_frequency_frame;
3553 ack_frequency_frame.packet_tolerance = 3;
3554 ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
3555 ENCRYPTION_FORWARD_SECURE);
3556
3557 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38);
3558 // Receives packets 2 - 39.
3559 for (size_t i = 2; i <= 39; ++i) {
3560 ProcessDataPacket(i);
3561 }
3562}
3563
3564TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
3565 const size_t kMinRttMs = 40;
3566 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
3567 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
3568 QuicTime::Delta::Zero(), QuicTime::Zero());
3569 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
3570
3571 // Start ack decimation from 10th packet.
3572 connection_.set_min_received_before_ack_decimation(10);
3573
3574 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3575 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
3576
3577 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
3578 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
3579 // Receives packets 1 - 29.
3580 for (size_t i = 1; i <= 29; ++i) {
3581 ProcessDataPacket(i);
3582 }
3583
3584 // We now receive the 30th packet, and so we send an ack.
3585 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3586 ProcessDataPacket(30);
3587}
3588
3589TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
3590 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3591 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3592 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3593
3594 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3595 // Receives packets 1 - 39.
3596 for (size_t i = 1; i <= 39; ++i) {
3597 ProcessDataPacket(i);
3598 }
3599 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3600 // WINDOW_UPDATE.
3601 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3602 .WillOnce(Invoke([this]() {
3603 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3604 }));
3605 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3606 EXPECT_EQ(0u, writer_->window_update_frames().size());
3607 ProcessDataPacket(40);
3608 EXPECT_EQ(1u, writer_->window_update_frames().size());
3609
3610 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3611 // Receives packets 41 - 59.
3612 for (size_t i = 41; i <= 59; ++i) {
3613 ProcessDataPacket(i);
3614 }
3615 // Send a packet containing stream frame.
3616 SendStreamDataToPeer(
3617 QuicUtils::GetFirstBidirectionalStreamId(
3618 connection_.version().transport_version, Perspective::IS_CLIENT),
3619 "bar", 0, NO_FIN, nullptr);
3620
3621 // Session will not be informed until receiving another 20 packets.
3622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3623 for (size_t i = 60; i <= 98; ++i) {
3624 ProcessDataPacket(i);
3625 EXPECT_EQ(0u, writer_->window_update_frames().size());
3626 }
3627 // Session does not add a retransmittable frame.
3628 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3629 .WillOnce(Invoke([this]() {
3630 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3631 }));
3632 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3633 EXPECT_EQ(0u, writer_->ping_frames().size());
3634 ProcessDataPacket(99);
3635 EXPECT_EQ(0u, writer_->window_update_frames().size());
3636 // A ping frame will be added.
3637 EXPECT_EQ(1u, writer_->ping_frames().size());
3638}
3639
3640TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
Bence Békybac04052022-04-07 15:44:29 -04003641 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3642 QuicConfig config;
3643 QuicTagVector connection_options;
3644 connection_options.push_back(kEACK);
3645 config.SetConnectionOptionsToSend(connection_options);
3646 connection_.SetFromConfig(config);
3647
3648 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3649 connection_.OnHandshakeComplete();
3650
3651 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3652 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3653
3654 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3655 // Receive packets 1 - 9.
3656 for (size_t i = 1; i <= 9; ++i) {
3657 ProcessDataPacket(i);
3658 }
3659
3660 // Send a ping and fire the retransmission alarm.
3661 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3662 SendPing();
3663 QuicTime retransmission_time =
3664 connection_.GetRetransmissionAlarm()->deadline();
3665 clock_.AdvanceTime(retransmission_time - clock_.Now());
3666 connection_.GetRetransmissionAlarm()->Fire();
fayang339f0c82022-04-30 14:20:02 -07003667 ASSERT_LT(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04003668
3669 // Process a packet, which requests a retransmittable frame be bundled
3670 // with the ACK.
3671 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3672 .WillOnce(Invoke([this]() {
3673 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3674 }));
3675 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3676 ProcessDataPacket(11);
3677 EXPECT_EQ(1u, writer_->window_update_frames().size());
3678}
3679
Bence Békybac04052022-04-07 15:44:29 -04003680TEST_P(QuicConnectionTest, TooManySentPackets) {
3681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3682
3683 QuicPacketCount max_tracked_packets = 50;
3684 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3685
3686 const int num_packets = max_tracked_packets + 5;
3687
3688 for (int i = 0; i < num_packets; ++i) {
3689 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3690 }
3691
3692 EXPECT_CALL(visitor_,
3693 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3694
3695 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3696
3697 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
3698}
3699
3700TEST_P(QuicConnectionTest, LargestObservedLower) {
3701 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3702
3703 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3704 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3705 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
martindukeba002452023-03-21 08:10:46 -07003706 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003707
3708 // Start out saying the largest observed is 2.
3709 QuicAckFrame frame1 = InitAckFrame(1);
3710 QuicAckFrame frame2 = InitAckFrame(2);
3711 ProcessAckPacket(&frame2);
3712
wubc9fd4292023-08-14 13:00:21 -07003713 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04003714 ProcessAckPacket(&frame1);
3715}
3716
3717TEST_P(QuicConnectionTest, AckUnsentData) {
3718 // Ack a packet which has not been sent.
3719 EXPECT_CALL(visitor_,
3720 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3721 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3722 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3723 QuicAckFrame frame = InitAckFrame(1);
3724 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3725 ProcessAckPacket(&frame);
3726 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
3727}
3728
3729TEST_P(QuicConnectionTest, BasicSending) {
3730 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3731 return;
3732 }
3733 const QuicConnectionStats& stats = connection_.GetStats();
3734 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
3735 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3736 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3737 ProcessDataPacket(1);
3738 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3739 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3740 QuicPacketNumber last_packet;
3741 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3742 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3743 SendAckPacketToPeer(); // Packet 2
3744
Bence Békybac04052022-04-07 15:44:29 -04003745 SendAckPacketToPeer(); // Packet 3
Bence Békybac04052022-04-07 15:44:29 -04003746
3747 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3748 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3749 SendAckPacketToPeer(); // Packet 5
Bence Békybac04052022-04-07 15:44:29 -04003750
martindukeba002452023-03-21 08:10:46 -07003751 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003752
3753 // Peer acks up to packet 3.
3754 QuicAckFrame frame = InitAckFrame(3);
3755 ProcessAckPacket(&frame);
3756 SendAckPacketToPeer(); // Packet 6
3757
martindukeba002452023-03-21 08:10:46 -07003758 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003759
3760 // Peer acks up to packet 4, the last packet.
3761 QuicAckFrame frame2 = InitAckFrame(6);
3762 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3763
3764 // Verify that we did not send an ack.
3765 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3766
Bence Békybac04052022-04-07 15:44:29 -04003767 // If we force an ack, we shouldn't change our retransmit state.
3768 SendAckPacketToPeer(); // Packet 7
Bence Békybac04052022-04-07 15:44:29 -04003769
3770 // But if we send more data it should.
3771 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3772 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3773 SendAckPacketToPeer(); // Packet 9
Bence Békybac04052022-04-07 15:44:29 -04003774 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3775}
3776
3777// QuicConnection should record the packet sent-time prior to sending the
3778// packet.
3779TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3780 // We're using a MockClock for the tests, so we have complete control over the
3781 // time.
3782 // Our recorded timestamp for the last packet sent time will be passed in to
3783 // the send_algorithm. Make sure that it is set to the correct value.
3784 QuicTime actual_recorded_send_time = QuicTime::Zero();
3785 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3786 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3787
3788 // First send without any pause and check the result.
3789 QuicTime expected_recorded_send_time = clock_.Now();
3790 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3791 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3792 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3793 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3794
3795 // Now pause during the write, and check the results.
3796 actual_recorded_send_time = QuicTime::Zero();
3797 const QuicTime::Delta write_pause_time_delta =
3798 QuicTime::Delta::FromMilliseconds(5000);
3799 SetWritePauseTimeDelta(write_pause_time_delta);
3800 expected_recorded_send_time = clock_.Now();
3801
3802 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3803 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3804 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3805 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3806 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3807 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3808}
3809
QUICHE teamac0a8082022-06-13 09:17:05 -07003810TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithRetransmissions) {
3811 // Send two stream frames in 1 packet by queueing them.
3812 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3813
3814 {
3815 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3816 connection_.SaveAndSendStreamData(
3817 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3818 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3819 connection_.SaveAndSendStreamData(
3820 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3821 "helloworld", 0, NO_FIN, LOSS_RETRANSMISSION);
3822 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3823 }
3824
3825 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3826 EXPECT_FALSE(connection_.HasQueuedData());
3827
3828 EXPECT_EQ(2u, writer_->frame_count());
3829 for (auto& frame : writer_->stream_frames()) {
3830 EXPECT_EQ(frame->data_length, 10u);
3831 }
3832
3833 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3834 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 20u);
3835}
3836
3837TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithMixedFrames) {
3838 // Send two stream frames in 1 packet by queueing them.
3839 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3840
3841 {
3842 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3843 // First frame is retransmission. Second is NOT_RETRANSMISSION but the
3844 // packet retains the PTO_RETRANSMISSION type.
3845 connection_.SaveAndSendStreamData(
3846 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3847 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3848 connection_.SaveAndSendStreamData(
3849 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3850 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3851 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3852 }
3853
3854 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3855 EXPECT_FALSE(connection_.HasQueuedData());
3856
3857 EXPECT_EQ(2u, writer_->frame_count());
3858 for (auto& frame : writer_->stream_frames()) {
3859 EXPECT_EQ(frame->data_length, 10u);
3860 }
3861
3862 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3863 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 10u);
3864}
3865
3866TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_NoRetransmission) {
3867 // Send two stream frames in 1 packet by queueing them.
3868 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3869
3870 {
3871 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3872 // Both frames are NOT_RETRANSMISSION
3873 connection_.SaveAndSendStreamData(
3874 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3875 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3876 connection_.SaveAndSendStreamData(
3877 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3878 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3879 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3880 }
3881
3882 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3883 EXPECT_FALSE(connection_.HasQueuedData());
3884
3885 EXPECT_EQ(2u, writer_->frame_count());
3886 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 0u);
3887 ASSERT_EQ(connection_.GetStats().bytes_retransmitted, 0u);
3888}
3889
Bence Békybac04052022-04-07 15:44:29 -04003890TEST_P(QuicConnectionTest, FramePacking) {
3891 // Send two stream frames in 1 packet by queueing them.
3892 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3893 {
3894 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3895 connection_.SendStreamData3();
3896 connection_.SendStreamData5();
3897 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3898 }
3899 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3900 EXPECT_FALSE(connection_.HasQueuedData());
3901
3902 // Parse the last packet and ensure it's an ack and two stream frames from
3903 // two different streams.
fayangfc04b8a2023-05-18 09:26:25 -07003904 EXPECT_EQ(2u, writer_->frame_count());
3905 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04003906
3907 EXPECT_TRUE(writer_->ack_frames().empty());
3908
3909 ASSERT_EQ(2u, writer_->stream_frames().size());
3910 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3911 writer_->stream_frames()[0]->stream_id);
3912 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3913 writer_->stream_frames()[1]->stream_id);
3914}
3915
3916TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3917 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3918 // queueing them.
3919 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3920 {
3921 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3922 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3923 connection_.SendStreamData3();
3924 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08003925 // Set the crypters for INITIAL packets in the TestPacketWriter.
3926 if (!connection_.version().KnowsWhichDecrypterToUse()) {
3927 writer_->framer()->framer()->SetAlternativeDecrypter(
3928 ENCRYPTION_INITIAL,
3929 std::make_unique<NullDecrypter>(Perspective::IS_SERVER), false);
3930 }
Bence Békybac04052022-04-07 15:44:29 -04003931 connection_.SendCryptoStreamData();
3932 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3933 }
3934 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3935 EXPECT_FALSE(connection_.HasQueuedData());
3936
3937 // Parse the last packet and ensure it contains a crypto stream frame.
3938 EXPECT_LE(2u, writer_->frame_count());
3939 ASSERT_LE(1u, writer_->padding_frames().size());
3940 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3941 ASSERT_EQ(1u, writer_->stream_frames().size());
3942 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3943 writer_->stream_frames()[0]->stream_id);
3944 } else {
3945 EXPECT_LE(1u, writer_->crypto_frames().size());
3946 }
3947}
3948
3949TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3950 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3951 // queueing them.
3952 {
3953 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3954 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3955 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3956 connection_.SendCryptoStreamData();
3957 connection_.SendStreamData3();
3958 }
3959 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3960 EXPECT_FALSE(connection_.HasQueuedData());
3961
3962 // Parse the last packet and ensure it's the stream frame from stream 3.
3963 size_t padding_frame_count = writer_->padding_frames().size();
3964 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3965 ASSERT_EQ(1u, writer_->stream_frames().size());
3966 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3967 writer_->stream_frames()[0]->stream_id);
3968}
3969
3970TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3971 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3972 // Process a data packet to queue up a pending ack.
3973 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3974 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3975 } else {
3976 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3977 }
3978 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3979
3980 QuicPacketNumber last_packet;
3981 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3982 connection_.SendCryptoDataWithString("foo", 0);
3983 } else {
3984 SendStreamDataToPeer(
3985 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3986 NO_FIN, &last_packet);
3987 }
3988 // Verify ack is bundled with outging packet.
3989 EXPECT_FALSE(writer_->ack_frames().empty());
3990
3991 EXPECT_CALL(visitor_, OnCanWrite())
3992 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3993 &connection_, &TestConnection::SendStreamData3)),
3994 IgnoreResult(InvokeWithoutArgs(
3995 &connection_, &TestConnection::SendStreamData5))));
3996
3997 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3998
3999 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
4000 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martinduke9e0811c2022-12-08 20:35:57 -08004001 peer_framer_.SetEncrypter(
4002 ENCRYPTION_FORWARD_SECURE,
4003 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
4004 SetDecrypter(
4005 ENCRYPTION_FORWARD_SECURE,
4006 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
wubc9fd4292023-08-14 13:00:21 -07004007 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04004008 ProcessDataPacket(2);
4009
4010 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4011 EXPECT_FALSE(connection_.HasQueuedData());
4012
4013 // Parse the last packet and ensure it's an ack and two stream frames from
4014 // two different streams.
fayangfc04b8a2023-05-18 09:26:25 -07004015 EXPECT_EQ(3u, writer_->frame_count());
4016 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04004017 EXPECT_FALSE(writer_->ack_frames().empty());
4018 ASSERT_EQ(2u, writer_->stream_frames().size());
4019 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4020 writer_->stream_frames()[0]->stream_id);
4021 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4022 writer_->stream_frames()[1]->stream_id);
4023}
4024
4025TEST_P(QuicConnectionTest, FramePackingSendv) {
4026 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4028
4029 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4030 connection_.transport_version(), Perspective::IS_CLIENT);
4031 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4032
4033 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4034 EXPECT_FALSE(connection_.HasQueuedData());
4035
4036 // Parse the last packet and ensure multiple iovector blocks have
4037 // been packed into a single stream frame from one stream.
4038 EXPECT_EQ(1u, writer_->frame_count());
4039 EXPECT_EQ(1u, writer_->stream_frames().size());
4040 EXPECT_EQ(0u, writer_->padding_frames().size());
4041 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4042 EXPECT_EQ(stream_id, frame->stream_id);
4043 EXPECT_EQ("ABCDEF",
4044 absl::string_view(frame->data_buffer, frame->data_length));
4045}
4046
4047TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
4048 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4049 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4050
4051 BlockOnNextWrite();
4052 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4053 connection_.transport_version(), Perspective::IS_CLIENT);
4054 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4055
4056 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4057 EXPECT_TRUE(connection_.HasQueuedData());
4058
4059 // Unblock the writes and actually send.
4060 writer_->SetWritable();
4061 connection_.OnCanWrite();
4062 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4063
4064 // Parse the last packet and ensure it's one stream frame from one stream.
4065 EXPECT_EQ(1u, writer_->frame_count());
4066 EXPECT_EQ(1u, writer_->stream_frames().size());
4067 EXPECT_EQ(0u, writer_->padding_frames().size());
4068 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4069 EXPECT_EQ(stream_id, frame->stream_id);
4070 EXPECT_EQ("ABCDEF",
4071 absl::string_view(frame->data_buffer, frame->data_length));
4072}
4073
4074TEST_P(QuicConnectionTest, SendingZeroBytes) {
4075 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4076 // Send a zero byte write with a fin using writev.
4077 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4078 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4079 connection_.transport_version(), Perspective::IS_CLIENT);
4080 connection_.SaveAndSendStreamData(stream_id, {}, 0, FIN);
4081
4082 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4083 EXPECT_FALSE(connection_.HasQueuedData());
4084
4085 // Padding frames are added by v99 to ensure a minimum packet size.
4086 size_t extra_padding_frames = 0;
4087 if (GetParam().version.HasHeaderProtection()) {
4088 extra_padding_frames = 1;
4089 }
4090
4091 // Parse the last packet and ensure it's one stream frame from one stream.
4092 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
4093 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
4094 ASSERT_EQ(1u, writer_->stream_frames().size());
4095 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
4096 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4097}
4098
4099TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
4100 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4101 EXPECT_CALL(visitor_, GetHandshakeState())
4102 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
4103 // Set the ack alarm by processing a ping frame.
4104 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4105
4106 // Processs a PING frame.
4107 ProcessFramePacket(QuicFrame(QuicPingFrame()));
4108 // Ensure that this has caused the ACK alarm to be set.
4109 EXPECT_TRUE(connection_.HasPendingAcks());
4110
4111 // Send data and ensure the ack is bundled.
4112 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
4113 const std::string data(10000, '?');
4114 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
4115 GetNthClientInitiatedStreamId(0, connection_.transport_version()), data,
4116 0, FIN);
4117 EXPECT_EQ(data.length(), consumed.bytes_consumed);
4118 EXPECT_TRUE(consumed.fin_consumed);
4119 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4120 EXPECT_FALSE(connection_.HasQueuedData());
4121
4122 // Parse the last packet and ensure it's one stream frame with a fin.
4123 EXPECT_EQ(1u, writer_->frame_count());
4124 ASSERT_EQ(1u, writer_->stream_frames().size());
4125 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4126 writer_->stream_frames()[0]->stream_id);
4127 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4128 // Ensure the ack alarm was cancelled when the ack was sent.
4129 EXPECT_FALSE(connection_.HasPendingAcks());
4130}
4131
4132TEST_P(QuicConnectionTest, OnCanWrite) {
4133 // Visitor's OnCanWrite will send data, but will have more pending writes.
4134 EXPECT_CALL(visitor_, OnCanWrite())
4135 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
4136 &connection_, &TestConnection::SendStreamData3)),
4137 IgnoreResult(InvokeWithoutArgs(
4138 &connection_, &TestConnection::SendStreamData5))));
4139 {
4140 InSequence seq;
4141 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
4142 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
4143 .WillRepeatedly(Return(false));
4144 }
4145
4146 EXPECT_CALL(*send_algorithm_, CanSend(_))
4147 .WillRepeatedly(testing::Return(true));
4148
4149 connection_.OnCanWrite();
4150
4151 // Parse the last packet and ensure it's the two stream frames from
4152 // two different streams.
4153 EXPECT_EQ(2u, writer_->frame_count());
4154 EXPECT_EQ(2u, writer_->stream_frames().size());
4155 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4156 writer_->stream_frames()[0]->stream_id);
4157 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4158 writer_->stream_frames()[1]->stream_id);
4159}
4160
4161TEST_P(QuicConnectionTest, RetransmitOnNack) {
4162 QuicPacketNumber last_packet;
4163 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
4164 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet);
4165 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet);
4166
4167 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4168
4169 // Don't lose a packet on an ack, and nothing is retransmitted.
martindukeba002452023-03-21 08:10:46 -07004170 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004171 QuicAckFrame ack_one = InitAckFrame(1);
4172 ProcessAckPacket(&ack_one);
4173
4174 // Lose a packet and ensure it triggers retransmission.
4175 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4176 LostPacketVector lost_packets;
4177 lost_packets.push_back(
4178 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4179 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4180 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4181 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004182 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004183 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4184 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4185 ProcessAckPacket(&nack_two);
4186}
4187
4188TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
4189 // Block the connection to queue the packet.
4190 BlockOnNextWrite();
4191
4192 QuicStreamId stream_id = 2;
4193 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4194
4195 // Now that there is a queued packet, reset the stream.
4196 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4197
4198 // Unblock the connection and verify that only the RST_STREAM is sent.
4199 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4200 writer_->SetWritable();
4201 connection_.OnCanWrite();
4202 size_t padding_frame_count = writer_->padding_frames().size();
4203 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4204 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4205}
4206
4207TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
4208 // Block the connection to queue the packet.
4209 BlockOnNextWrite();
4210
4211 QuicStreamId stream_id = 2;
4212 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4213 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4214
4215 // Now that there is a queued packet, reset the stream.
4216 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4217
4218 // Unblock the connection and verify that the RST_STREAM is sent and the data
4219 // packet is sent.
4220 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4221 writer_->SetWritable();
4222 connection_.OnCanWrite();
4223 size_t padding_frame_count = writer_->padding_frames().size();
4224 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4225 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4226}
4227
4228TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
4229 QuicStreamId stream_id = 2;
4230 QuicPacketNumber last_packet;
4231 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4232 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4233 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4234
4235 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4236 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4237
4238 // Lose a packet and ensure it does not trigger retransmission.
4239 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4240 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4241 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004242 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004243 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4244 ProcessAckPacket(&nack_two);
4245}
4246
4247TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
4248 QuicStreamId stream_id = 2;
4249 QuicPacketNumber last_packet;
4250 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4251 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4252 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4253
4254 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4255 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4256
4257 // Lose a packet, ensure it triggers retransmission.
4258 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4259 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4260 LostPacketVector lost_packets;
4261 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4262 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4263 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4264 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004265 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004266 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4267 ProcessAckPacket(&nack_two);
4268}
4269
4270TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
4271 QuicStreamId stream_id = 2;
4272 QuicPacketNumber last_packet;
4273 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4274
4275 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4276 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4277
4278 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
4279 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4280 clock_.AdvanceTime(DefaultRetransmissionTime());
4281 connection_.GetRetransmissionAlarm()->Fire();
4282 size_t padding_frame_count = writer_->padding_frames().size();
4283 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4284 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4285 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4286}
4287
4288// Ensure that if the only data in flight is non-retransmittable, the
4289// retransmission alarm is not set.
4290TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
4291 QuicStreamId stream_id = 2;
4292 QuicPacketNumber last_data_packet;
4293 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
4294
4295 // Cancel the stream.
4296 const QuicPacketNumber rst_packet = last_data_packet + 1;
4297 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
4298 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4299
4300 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
4301 // packet, which is no longer retransmittable since the stream was cancelled.
4302 QuicAckFrame nack_stream_data =
4303 ConstructAckFrame(rst_packet, last_data_packet);
4304 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07004305 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4307 ProcessAckPacket(&nack_stream_data);
4308
4309 // Ensure that the data is still in flight, but the retransmission alarm is no
4310 // longer set.
4311 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
4312 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4313}
4314
fayang339f0c82022-04-30 14:20:02 -07004315TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnPTO) {
Bence Békybac04052022-04-07 15:44:29 -04004316 QuicStreamId stream_id = 2;
4317 QuicPacketNumber last_packet;
4318 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4319
4320 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4321 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4322
4323 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
4324 // is sent.
fayang339f0c82022-04-30 14:20:02 -07004325 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
Bence Békybac04052022-04-07 15:44:29 -04004326 clock_.AdvanceTime(DefaultRetransmissionTime());
4327 connection_.GetRetransmissionAlarm()->Fire();
4328 size_t padding_frame_count = writer_->padding_frames().size();
4329 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04004330}
4331
4332TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
4333 QuicStreamId stream_id = 2;
4334 QuicPacketNumber last_packet;
4335 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4336 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4337 BlockOnNextWrite();
4338 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4339
4340 // Lose a packet which will trigger a pending retransmission.
4341 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4342 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4343 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004344 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004345 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4346 ProcessAckPacket(&ack);
4347
4348 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4349
4350 // Unblock the connection and verify that the RST_STREAM is sent but not the
4351 // second data packet nor a retransmit.
4352 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4353 writer_->SetWritable();
4354 connection_.OnCanWrite();
4355 size_t padding_frame_count = writer_->padding_frames().size();
4356 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4357 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
4358 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4359}
4360
4361TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
4362 QuicStreamId stream_id = 2;
4363 QuicPacketNumber last_packet;
4364 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4365 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4366 BlockOnNextWrite();
4367 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4368
4369 // Lose a packet which will trigger a pending retransmission.
4370 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4371 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4372 LostPacketVector lost_packets;
4373 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4374 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4375 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4376 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004377 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004378 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4379 ProcessAckPacket(&ack);
4380
4381 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4382
4383 // Unblock the connection and verify that the RST_STREAM is sent and the
4384 // second data packet or a retransmit is sent.
4385 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
4386 writer_->SetWritable();
4387 connection_.OnCanWrite();
4388 // The RST_STREAM_FRAME is sent after queued packets and pending
4389 // retransmission.
4390 connection_.SendControlFrame(QuicFrame(
4391 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
4392 size_t padding_frame_count = writer_->padding_frames().size();
4393 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4394 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4395}
4396
4397TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
4398 QuicPacketNumber last_packet;
4399 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4400 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
4401 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
4402
4403 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4404
4405 // Instigate a loss with an ack.
4406 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4407 // The first nack should trigger a fast retransmission, but we'll be
4408 // write blocked, so the packet will be queued.
4409 BlockOnNextWrite();
4410
4411 LostPacketVector lost_packets;
4412 lost_packets.push_back(
4413 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4414 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4415 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4416 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004417 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004418 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4419 .Times(1);
4420 ProcessAckPacket(&nack_two);
4421 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4422
4423 // Now, ack the previous transmission.
4424 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004425 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004426 QuicAckFrame ack_all = InitAckFrame(3);
4427 ProcessAckPacket(&ack_all);
4428
4429 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4430 .Times(0);
4431
4432 writer_->SetWritable();
4433 connection_.OnCanWrite();
4434
4435 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4436 // We do not store retransmittable frames of this retransmission.
4437 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
4438}
4439
4440TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
4441 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4442 QuicPacketNumber original, second;
4443
4444 QuicByteCount packet_size =
4445 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
4446 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
4447
4448 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
4449 // The first nack should retransmit the largest observed packet.
4450 LostPacketVector lost_packets;
4451 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
4452 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4453 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4454 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004455 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004456 // Packet 1 is short header for IETF QUIC because the encryption level
4457 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangfc04b8a2023-05-18 09:26:25 -07004458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _));
Bence Békybac04052022-04-07 15:44:29 -04004459 ProcessAckPacket(&frame);
4460}
4461
Bence Békybac04052022-04-07 15:44:29 -04004462TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
4463 BlockOnNextWrite();
4464 writer_->set_is_write_blocked_data_buffered(true);
4465 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4466 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4467 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4468
4469 writer_->SetWritable();
4470 connection_.OnCanWrite();
4471 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4472}
4473
4474TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
4475 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4476 BlockOnNextWrite();
4477 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4478 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4479 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4480 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4481
4482 // The second packet should also be queued, in order to ensure packets are
4483 // never sent out of order.
4484 writer_->SetWritable();
4485 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4486 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4487 EXPECT_EQ(2u, connection_.NumQueuedPackets());
4488
4489 // Now both are sent in order when we unblock.
4490 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4491 connection_.OnCanWrite();
4492 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4493 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4494}
4495
4496TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
4497 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4498 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4499 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4500
4501 BlockOnNextWrite();
4502 writer_->set_is_write_blocked_data_buffered(true);
4503 // Simulate the retransmission alarm firing.
4504 clock_.AdvanceTime(DefaultRetransmissionTime());
4505 connection_.GetRetransmissionAlarm()->Fire();
4506
4507 // Ack the sent packet before the callback returns, which happens in
4508 // rare circumstances with write blocked sockets.
4509 QuicAckFrame ack = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07004510 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004511 ProcessAckPacket(&ack);
4512
4513 writer_->SetWritable();
4514 connection_.OnCanWrite();
4515 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang339f0c82022-04-30 14:20:02 -07004516 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 3));
Bence Békybac04052022-04-07 15:44:29 -04004517}
4518
4519TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4520 // Block the connection.
4521 BlockOnNextWrite();
4522 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4523 EXPECT_EQ(1u, writer_->packets_write_attempts());
4524 EXPECT_TRUE(writer_->IsWriteBlocked());
4525
4526 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4527 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4528 connection_.GetSendAlarm()->Fire();
4529 EXPECT_TRUE(writer_->IsWriteBlocked());
4530 EXPECT_EQ(1u, writer_->packets_write_attempts());
4531}
4532
4533TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4534 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4535
4536 // Block the connection.
4537 BlockOnNextWrite();
4538 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4539 EXPECT_TRUE(writer_->IsWriteBlocked());
4540 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4541 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4542
4543 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4544 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4545 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4546 // is returned.
4547 const uint64_t received_packet_num = 1;
4548 const bool has_stop_waiting = false;
4549 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4550 std::unique_ptr<QuicPacket> packet(
4551 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4552 char buffer[kMaxOutgoingPacketSize];
4553 size_t encrypted_length =
4554 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4555 *packet, buffer, kMaxOutgoingPacketSize);
4556 connection_.ProcessUdpPacket(
4557 kSelfAddress, kPeerAddress,
4558 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4559
4560 EXPECT_TRUE(writer_->IsWriteBlocked());
4561 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4562}
4563
QUICHE team32d62792023-04-27 11:47:01 -07004564TEST_P(QuicConnectionTest, SendAlarmNonZeroDelay) {
4565 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4566 // Set a 10 ms send alarm delay. The send alarm after processing the packet
4567 // should fire after waiting 10ms, not immediately.
4568 connection_.set_defer_send_in_response_to_packets(true);
4569 connection_.sent_packet_manager().SetDeferredSendAlarmDelay(
4570 QuicTime::Delta::FromMilliseconds(10));
4571 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4572
4573 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4574 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4575 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4576 // is returned.
4577 const uint64_t received_packet_num = 1;
4578 const bool has_stop_waiting = false;
4579 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4580 std::unique_ptr<QuicPacket> packet(
4581 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4582 char buffer[kMaxOutgoingPacketSize];
4583 size_t encrypted_length =
4584 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4585 *packet, buffer, kMaxOutgoingPacketSize);
wubc9fd4292023-08-14 13:00:21 -07004586 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
QUICHE team32d62792023-04-27 11:47:01 -07004587 connection_.ProcessUdpPacket(
4588 kSelfAddress, kPeerAddress,
4589 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4590
4591 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
4592 // It was set to be 10 ms in the future, so it should at the least be greater
4593 // than now + 5 ms.
4594 EXPECT_TRUE(connection_.GetSendAlarm()->deadline() >
4595 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5));
4596}
4597
Bence Békybac04052022-04-07 15:44:29 -04004598TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4599 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4600 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4601
4602 // Simulate the case where a shared writer gets blocked by another connection.
4603 writer_->SetWriteBlocked();
4604
4605 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4606 QuicAckFrame ack1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07004607 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004608 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4609 ProcessAckPacket(1, &ack1);
4610}
4611
4612TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4613 writer_->SetBatchMode(true);
4614 EXPECT_TRUE(connection_.connected());
4615 // Have to explicitly grab the OnConnectionClosed frame and check
4616 // its parameters because this is a silent connection close and the
4617 // frame is not also transmitted to the peer.
4618 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4619 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4620
4621 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4622
4623 {
4624 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4625 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4626 ConnectionCloseBehavior::SILENT_CLOSE);
4627
4628 EXPECT_FALSE(connection_.connected());
4629 writer_->SetWriteBlocked();
4630 }
4631 EXPECT_EQ(1, connection_close_frame_count_);
4632 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4633 IsError(QUIC_PEER_GOING_AWAY));
4634}
4635
4636TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4637 writer_->SetBatchMode(true);
4638 writer_->BlockOnNextFlush();
4639
4640 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4641 {
4642 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4643 // flusher's destructor will call connection_.FlushPackets, which should add
4644 // the connection to the write blocked list.
4645 }
4646}
4647
4648TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4649 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4650 int offset = 0;
4651 // Send packets 1 to 15.
4652 for (int i = 0; i < 15; ++i) {
4653 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4654 offset += 3;
4655 }
4656
4657 // Ack 15, nack 1-14.
4658
4659 QuicAckFrame nack =
4660 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4661
4662 // 14 packets have been NACK'd and lost.
4663 LostPacketVector lost_packets;
4664 for (int i = 1; i < 15; ++i) {
4665 lost_packets.push_back(
4666 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
4667 }
4668 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4669 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4670 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004671 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004672 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4673 ProcessAckPacket(&nack);
4674}
4675
4676// Test sending multiple acks from the connection to the session.
4677TEST_P(QuicConnectionTest, MultipleAcks) {
4678 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4679 return;
4680 }
4681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4682 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4683 ProcessDataPacket(1);
4684 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4685 QuicPacketNumber last_packet;
4686 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4687 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4688 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4689 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4690 SendAckPacketToPeer(); // Packet 3
4691 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4692 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4693 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4694 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4695 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4696 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4697
4698 // Client will ack packets 1, 2, [!3], 4, 5.
martindukeba002452023-03-21 08:10:46 -07004699 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004700 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4701 ProcessAckPacket(&frame1);
4702
4703 // Now the client implicitly acks 3, and explicitly acks 6.
martindukeba002452023-03-21 08:10:46 -07004704 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004705 QuicAckFrame frame2 = InitAckFrame(6);
4706 ProcessAckPacket(&frame2);
4707}
4708
4709TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
4710 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4711 return;
4712 }
4713 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4714 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4715 ProcessDataPacket(1);
4716 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4717 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4718 // From now on, we send acks, so the send algorithm won't mark them pending.
4719 SendAckPacketToPeer(); // Packet 2
4720
martindukeba002452023-03-21 08:10:46 -07004721 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004722 QuicAckFrame frame = InitAckFrame(1);
4723 ProcessAckPacket(&frame);
4724
martindukeba002452023-03-21 08:10:46 -07004725 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004726 frame = InitAckFrame(2);
4727 ProcessAckPacket(&frame);
Bence Békybac04052022-04-07 15:44:29 -04004728
4729 // When we send an ack, we make sure our least-unacked makes sense. In this
4730 // case since we're not waiting on an ack for 2 and all packets are acked, we
4731 // set it to 3.
4732 SendAckPacketToPeer(); // Packet 3
Bence Békybac04052022-04-07 15:44:29 -04004733
4734 // Ack the ack, which updates the rtt and raises the least unacked.
martindukeba002452023-03-21 08:10:46 -07004735 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004736 frame = InitAckFrame(3);
4737 ProcessAckPacket(&frame);
4738
4739 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
haoyuewang16f86e82023-07-26 14:13:26 -07004740 SendAckPacketToPeer(); // Packet 5
Bence Békybac04052022-04-07 15:44:29 -04004741
4742 // Send two data packets at the end, and ensure if the last one is acked,
4743 // the least unacked is raised above the ack packets.
4744 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4745 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4746
martindukeba002452023-03-21 08:10:46 -07004747 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004748 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4749 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4750 ProcessAckPacket(&frame);
Bence Békybac04052022-04-07 15:44:29 -04004751}
4752
Bence Békybac04052022-04-07 15:44:29 -04004753TEST_P(QuicConnectionTest, SendHandshakeMessages) {
Bence Békybac04052022-04-07 15:44:29 -04004754 // Attempt to send a handshake message and have the socket block.
4755 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4756 BlockOnNextWrite();
4757 connection_.SendCryptoDataWithString("foo", 0);
4758 // The packet should be serialized, but not queued.
4759 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4760
4761 // Switch to the new encrypter.
martinduke9e0811c2022-12-08 20:35:57 -08004762 connection_.SetEncrypter(
4763 ENCRYPTION_ZERO_RTT,
4764 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004765 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4766
4767 // Now become writeable and flush the packets.
4768 writer_->SetWritable();
4769 EXPECT_CALL(visitor_, OnCanWrite());
4770 connection_.OnCanWrite();
4771 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4772
martinduke9e0811c2022-12-08 20:35:57 -08004773 // Verify that the handshake packet went out with Initial encryption.
4774 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -04004775}
4776
martinduke9e0811c2022-12-08 20:35:57 -08004777TEST_P(QuicConnectionTest, DropRetransmitsForInitialPacketAfterForwardSecure) {
Bence Békybac04052022-04-07 15:44:29 -04004778 connection_.SendCryptoStreamData();
Bence Békybac04052022-04-07 15:44:29 -04004779 // Simulate the retransmission alarm firing and the socket blocking.
4780 BlockOnNextWrite();
4781 clock_.AdvanceTime(DefaultRetransmissionTime());
4782 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4783 connection_.GetRetransmissionAlarm()->Fire();
4784 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4785
4786 // Go forward secure.
4787 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4788 std::make_unique<TaggingEncrypter>(0x02));
4789 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4790 notifier_.NeuterUnencryptedData();
4791 connection_.NeuterUnencryptedPackets();
4792 connection_.OnHandshakeComplete();
4793
4794 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4795 // Unblock the socket and ensure that no packets are sent.
4796 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4797 writer_->SetWritable();
4798 connection_.OnCanWrite();
4799}
4800
4801TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
Bence Békybac04052022-04-07 15:44:29 -04004802 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
4803
4804 connection_.SendCryptoDataWithString("foo", 0);
4805
martinduke9e0811c2022-12-08 20:35:57 -08004806 connection_.SetEncrypter(
4807 ENCRYPTION_ZERO_RTT,
4808 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004809 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -08004810 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4811 writer_->framer()->framer()->SetAlternativeDecrypter(
4812 ENCRYPTION_ZERO_RTT,
4813 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT), false);
4814 }
Bence Békybac04052022-04-07 15:44:29 -04004815
4816 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4817 EXPECT_FALSE(notifier_.HasLostStreamData());
4818 connection_.MarkZeroRttPacketsForRetransmission(0);
4819 EXPECT_TRUE(notifier_.HasLostStreamData());
4820}
4821
4822TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
4823 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4824 return;
4825 }
4826 // SetFromConfig is always called after construction from InitializeSession.
4827 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4828 QuicConfig config;
4829 connection_.SetFromConfig(config);
4830 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004831
martinduke9e0811c2022-12-08 20:35:57 -08004832 peer_framer_.SetEncrypter(
4833 ENCRYPTION_ZERO_RTT,
4834 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4835 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4836 writer_->framer()->framer()->SetDecrypter(
4837 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4838 }
Bence Békybac04052022-04-07 15:44:29 -04004839
4840 // Process an encrypted packet which can not yet be decrypted which should
4841 // result in the packet being buffered.
4842 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4843
4844 // Transition to the new encryption state and process another encrypted packet
4845 // which should result in the original packet being processed.
4846 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004847 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
4848 connection_.SetEncrypter(
4849 ENCRYPTION_ZERO_RTT,
4850 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004851 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4852 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4853 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4854
4855 // Finally, process a third packet and note that we do not reprocess the
4856 // buffered packet.
4857 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4858 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4859}
4860
Bence Békybac04052022-04-07 15:44:29 -04004861TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
4862 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4863 return;
4864 }
4865 // SetFromConfig is always called after construction from InitializeSession.
4866 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4867 QuicConfig config;
4868 config.set_max_undecryptable_packets(100);
4869 connection_.SetFromConfig(config);
4870 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004871
martinduke9e0811c2022-12-08 20:35:57 -08004872 peer_framer_.SetEncrypter(
4873 ENCRYPTION_ZERO_RTT,
4874 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004875
4876 // Process an encrypted packet which can not yet be decrypted which should
4877 // result in the packet being buffered.
4878 for (uint64_t i = 1; i <= 100; ++i) {
4879 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4880 }
4881
4882 // Transition to the new encryption state and process another encrypted packet
4883 // which should result in the original packets being processed.
4884 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4885 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004886 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004887 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -08004888 connection_.SetEncrypter(
4889 ENCRYPTION_ZERO_RTT,
4890 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004891 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4892
4893 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
martinduke9e0811c2022-12-08 20:35:57 -08004894 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4895 writer_->framer()->framer()->SetDecrypter(
4896 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4897 }
Bence Békybac04052022-04-07 15:44:29 -04004898 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4899
4900 // Finally, process a third packet and note that we do not reprocess the
4901 // buffered packet.
4902 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4903 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4904}
4905
4906TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4907 BlockOnNextWrite();
4908 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4909 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4910 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4911
4912 // Test that RTO is started once we write to the socket.
4913 writer_->SetWritable();
4914 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4915 connection_.OnCanWrite();
4916 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4917}
4918
Bence Békybac04052022-04-07 15:44:29 -04004919TEST_P(QuicConnectionTest, TestQueued) {
Bence Békybac04052022-04-07 15:44:29 -04004920 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4921 BlockOnNextWrite();
4922 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4923 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4924
4925 // Unblock the writes and actually send.
4926 writer_->SetWritable();
4927 connection_.OnCanWrite();
4928 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4929}
4930
4931TEST_P(QuicConnectionTest, InitialTimeout) {
4932 EXPECT_TRUE(connection_.connected());
4933 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4934 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4935
4936 // SetFromConfig sets the initial timeouts before negotiation.
4937 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4938 QuicConfig config;
4939 connection_.SetFromConfig(config);
4940 // Subtract a second from the idle timeout on the client side.
4941 QuicTime default_timeout =
4942 clock_.ApproximateNow() +
4943 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4944 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4945
4946 EXPECT_CALL(visitor_,
4947 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4948 // Simulate the timeout alarm firing.
4949 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4950 connection_.GetTimeoutAlarm()->Fire();
4951
4952 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4953 EXPECT_FALSE(connection_.connected());
4954
4955 EXPECT_FALSE(connection_.HasPendingAcks());
4956 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4957 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4958 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4959 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4960 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4961 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4962}
4963
4964TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4965 EXPECT_TRUE(connection_.connected());
4966 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4967 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4968
4969 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4970 QuicConfig config;
4971 connection_.SetFromConfig(config);
4972 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4973 QuicTime initial_ddl =
4974 clock_.ApproximateNow() +
4975 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4976 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4977 EXPECT_TRUE(connection_.connected());
4978
4979 // Advance the time and send the first packet to the peer.
4980 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4981 QuicPacketNumber last_packet;
4982 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4983 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4984 // This will be the updated deadline for the connection to idle time out.
4985 QuicTime new_ddl = clock_.ApproximateNow() +
4986 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4987
4988 // Simulate the timeout alarm firing, the connection should not be closed as
4989 // a new packet has been sent.
4990 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
4991 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4992 clock_.AdvanceTime(delay);
4993 // Verify the timeout alarm deadline is updated.
4994 EXPECT_TRUE(connection_.connected());
4995 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4996 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4997
4998 // Simulate the timeout alarm firing again, the connection now should be
4999 // closed.
5000 EXPECT_CALL(visitor_,
5001 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5002 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
5003 connection_.GetTimeoutAlarm()->Fire();
5004 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5005 EXPECT_FALSE(connection_.connected());
5006
5007 EXPECT_FALSE(connection_.HasPendingAcks());
5008 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5009 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5010 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5011 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5012 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5013}
5014
5015TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
5016 EXPECT_TRUE(connection_.connected());
5017 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5018 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5019
5020 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5021 QuicConfig config;
5022 connection_.SetFromConfig(config);
5023 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5024 QuicTime initial_ddl =
5025 clock_.ApproximateNow() +
5026 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5027 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
5028 EXPECT_TRUE(connection_.connected());
5029
5030 // Immediately send the first packet, this is a rare case but test code will
5031 // hit this issue often as MockClock used for tests doesn't move with code
5032 // execution until manually adjusted.
5033 QuicPacketNumber last_packet;
5034 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5035 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
5036
5037 // Advance the time and send the second packet to the peer.
5038 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
5039 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5040 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
5041
5042 // Simulate the timeout alarm firing, the connection will be closed.
5043 EXPECT_CALL(visitor_,
5044 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5045 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
5046 connection_.GetTimeoutAlarm()->Fire();
5047
5048 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5049 EXPECT_FALSE(connection_.connected());
5050
5051 EXPECT_FALSE(connection_.HasPendingAcks());
5052 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5053 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5054 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5055 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5056 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5057}
5058
5059TEST_P(QuicConnectionTest, HandshakeTimeout) {
5060 // Use a shorter handshake timeout than idle timeout for this test.
5061 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
5062 connection_.SetNetworkTimeouts(timeout, timeout);
5063 EXPECT_TRUE(connection_.connected());
5064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5065
5066 QuicTime handshake_timeout =
5067 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
5068 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
5069 EXPECT_TRUE(connection_.connected());
5070
5071 // Send and ack new data 3 seconds later to lengthen the idle timeout.
5072 SendStreamDataToPeer(
5073 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5074 "GET /", 0, FIN, nullptr);
5075 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
5076 QuicAckFrame frame = InitAckFrame(1);
5077 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005078 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005079 ProcessAckPacket(&frame);
5080
5081 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5082 EXPECT_TRUE(connection_.connected());
5083
5084 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
5085
5086 EXPECT_CALL(visitor_,
5087 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5088 // Simulate the timeout alarm firing.
5089 connection_.GetTimeoutAlarm()->Fire();
5090
5091 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5092 EXPECT_FALSE(connection_.connected());
5093
5094 EXPECT_FALSE(connection_.HasPendingAcks());
5095 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5096 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5097 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5098 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
5099}
5100
5101TEST_P(QuicConnectionTest, PingAfterSend) {
5102 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5103 return;
5104 }
5105 EXPECT_TRUE(connection_.connected());
5106 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5107 .WillRepeatedly(Return(true));
5108 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5109
5110 // Advance to 5ms, and send a packet to the peer, which will set
5111 // the ping alarm.
5112 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5113 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5114 SendStreamDataToPeer(
5115 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5116 "GET /", 0, FIN, nullptr);
5117 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5118 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
5119 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5120
5121 // Now recevie an ACK of the previous packet, which will move the
5122 // ping alarm forward.
5123 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5124 QuicAckFrame frame = InitAckFrame(1);
5125 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005126 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005127 ProcessAckPacket(&frame);
5128 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5129 // The ping timer is set slightly less than 15 seconds in the future, because
5130 // of the 1s ping timer alarm granularity.
5131 EXPECT_EQ(
5132 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
5133 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5134
5135 writer_->Reset();
5136 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
5137 connection_.GetPingAlarm()->Fire();
5138 size_t padding_frame_count = writer_->padding_frames().size();
5139 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5140 ASSERT_EQ(1u, writer_->ping_frames().size());
5141 writer_->Reset();
5142
5143 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5144 .WillRepeatedly(Return(false));
5145 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5146 SendAckPacketToPeer();
5147
5148 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5149}
5150
5151TEST_P(QuicConnectionTest, ReducedPingTimeout) {
5152 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5153 return;
5154 }
5155 EXPECT_TRUE(connection_.connected());
5156 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5157 .WillRepeatedly(Return(true));
5158 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5159
5160 // Use a reduced ping timeout for this connection.
fayang5d393332022-04-18 13:34:54 -07005161 connection_.set_keep_alive_ping_timeout(QuicTime::Delta::FromSeconds(10));
Bence Békybac04052022-04-07 15:44:29 -04005162
5163 // Advance to 5ms, and send a packet to the peer, which will set
5164 // the ping alarm.
5165 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5166 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5167 SendStreamDataToPeer(
5168 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5169 "GET /", 0, FIN, nullptr);
5170 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5171 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
5172 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5173
5174 // Now recevie an ACK of the previous packet, which will move the
5175 // ping alarm forward.
5176 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5177 QuicAckFrame frame = InitAckFrame(1);
5178 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005179 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005180 ProcessAckPacket(&frame);
5181 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5182 // The ping timer is set slightly less than 10 seconds in the future, because
5183 // of the 1s ping timer alarm granularity.
5184 EXPECT_EQ(
5185 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5186 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5187
5188 writer_->Reset();
5189 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5190 connection_.GetPingAlarm()->Fire();
5191 size_t padding_frame_count = writer_->padding_frames().size();
5192 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5193 ASSERT_EQ(1u, writer_->ping_frames().size());
5194 writer_->Reset();
5195
5196 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5197 .WillRepeatedly(Return(false));
5198 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5199 SendAckPacketToPeer();
5200
5201 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5202}
5203
5204// Tests whether sending an MTU discovery packet to peer successfully causes the
5205// maximum packet size to increase.
5206TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
5207 MtuDiscoveryTestInit();
5208
5209 // Send an MTU probe.
5210 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5211 QuicByteCount mtu_probe_size;
5212 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5213 .WillOnce(SaveArg<3>(&mtu_probe_size));
5214 connection_.SendMtuDiscoveryPacket(new_mtu);
5215 EXPECT_EQ(new_mtu, mtu_probe_size);
5216 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5217
5218 // Send more than MTU worth of data. No acknowledgement was received so far,
5219 // so the MTU should be at its old value.
5220 const std::string data(kDefaultMaxPacketSize + 1, '.');
5221 QuicByteCount size_before_mtu_change;
5222 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5223 .Times(2)
5224 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5225 .WillOnce(Return());
5226 connection_.SendStreamDataWithString(3, data, 0, FIN);
5227 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5228 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5229
5230 // Acknowledge all packets so far.
5231 QuicAckFrame probe_ack = InitAckFrame(3);
martindukeba002452023-03-21 08:10:46 -07005232 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005233 ProcessAckPacket(&probe_ack);
5234 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5235
5236 // Send the same data again. Check that it fits into a single packet now.
5237 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5238 connection_.SendStreamDataWithString(3, data, 0, FIN);
5239 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5240}
5241
5242// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5243// the writer is flushed immediately.
5244TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5245 writer_->SetBatchMode(true);
5246 MtuDiscoveryTestInit();
5247
5248 // Send an MTU probe.
5249 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5250 QuicByteCount mtu_probe_size;
5251 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5252 .WillOnce(SaveArg<3>(&mtu_probe_size));
5253 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5254 connection_.SendMtuDiscoveryPacket(target_mtu);
5255 EXPECT_EQ(target_mtu, mtu_probe_size);
5256 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
5257}
5258
5259// Tests whether MTU discovery does not happen when it is not explicitly enabled
5260// by the connection options.
5261TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
5262 MtuDiscoveryTestInit();
5263
5264 const QuicPacketCount packets_between_probes_base = 10;
5265 set_packets_between_probes_base(packets_between_probes_base);
5266
5267 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5268 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5269 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5270 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5271 EXPECT_EQ(0u, connection_.mtu_probe_count());
5272 }
5273}
5274
5275// Tests whether MTU discovery works when all probes are acknowledged on the
5276// first try.
5277TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
5278 MtuDiscoveryTestInit();
5279
5280 const QuicPacketCount packets_between_probes_base = 5;
5281 set_packets_between_probes_base(packets_between_probes_base);
5282
5283 connection_.EnablePathMtuDiscovery(send_algorithm_);
5284
5285 // Send enough packets so that the next one triggers path MTU discovery.
5286 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5287 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5288 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5289 }
5290
5291 // Trigger the probe.
5292 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5293 nullptr);
5294 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5295 QuicByteCount probe_size;
5296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5297 .WillOnce(SaveArg<3>(&probe_size));
5298 connection_.GetMtuDiscoveryAlarm()->Fire();
5299
5300 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5301 kMtuDiscoveryTargetPacketSizeHigh));
5302
5303 const QuicPacketNumber probe_packet_number =
5304 FirstSendingPacketNumber() + packets_between_probes_base;
5305 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5306
5307 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005308 {
5309 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5310 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5311 .Times(AnyNumber());
5312 ProcessAckPacket(&probe_ack);
5313 EXPECT_EQ(probe_size, connection_.max_packet_length());
5314 EXPECT_EQ(0u, connection_.GetBytesInFlight());
Bence Békybac04052022-04-07 15:44:29 -04005315
QUICHE teame2a24ee2024-01-09 06:34:35 -08005316 EXPECT_EQ(1u, connection_.mtu_probe_count());
5317 }
Bence Békybac04052022-04-07 15:44:29 -04005318
5319 QuicStreamOffset stream_offset = packets_between_probes_base;
5320 QuicByteCount last_probe_size = 0;
5321 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5322 ++num_probes) {
5323 // Send just enough packets without triggering the next probe.
5324 for (QuicPacketCount i = 0;
5325 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5326 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5327 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5328 }
5329
5330 // Trigger the next probe.
5331 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5332 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5333 QuicByteCount new_probe_size;
5334 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5335 .WillOnce(SaveArg<3>(&new_probe_size));
5336 connection_.GetMtuDiscoveryAlarm()->Fire();
5337 EXPECT_THAT(new_probe_size,
5338 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5339 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5340
5341 // Acknowledge all packets sent so far.
5342 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5343 ProcessAckPacket(&probe_ack);
5344 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5345 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5346
5347 last_probe_size = probe_size;
5348 probe_size = new_probe_size;
5349 }
5350
5351 // The last probe size should be equal to the target.
5352 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
5353
5354 writer_->SetShouldWriteFail();
5355
5356 // Ignore PACKET_WRITE_ERROR once.
5357 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5358 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5359 EXPECT_TRUE(connection_.connected());
5360
5361 // Close connection on another PACKET_WRITE_ERROR.
5362 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5363 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5364 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5365 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5366 EXPECT_FALSE(connection_.connected());
5367 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5368 IsError(QUIC_PACKET_WRITE_ERROR));
5369}
5370
5371// After a successful MTU probe, one and only one write error should be ignored
5372// if it happened in QuicConnection::FlushPacket.
5373TEST_P(QuicConnectionTest,
5374 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5375 MtuDiscoveryTestInit();
5376 writer_->SetBatchMode(true);
5377
5378 const QuicPacketCount packets_between_probes_base = 5;
5379 set_packets_between_probes_base(packets_between_probes_base);
5380
5381 connection_.EnablePathMtuDiscovery(send_algorithm_);
5382
5383 const QuicByteCount original_max_packet_length =
5384 connection_.max_packet_length();
5385 // Send enough packets so that the next one triggers path MTU discovery.
5386 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5387 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5388 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5389 }
5390
5391 // Trigger the probe.
5392 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5393 nullptr);
5394 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5395 QuicByteCount probe_size;
5396 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5397 .WillOnce(SaveArg<3>(&probe_size));
5398 connection_.GetMtuDiscoveryAlarm()->Fire();
5399
5400 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5401 kMtuDiscoveryTargetPacketSizeHigh));
5402
5403 const QuicPacketNumber probe_packet_number =
5404 FirstSendingPacketNumber() + packets_between_probes_base;
5405 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5406
5407 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005408 {
5409 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5410 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5411 .Times(AnyNumber());
5412 ProcessAckPacket(&probe_ack);
5413 EXPECT_EQ(probe_size, connection_.max_packet_length());
5414 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5415 }
Bence Békybac04052022-04-07 15:44:29 -04005416
5417 EXPECT_EQ(1u, connection_.mtu_probe_count());
5418
5419 writer_->SetShouldWriteFail();
5420
5421 // Ignore PACKET_WRITE_ERROR once.
5422 {
5423 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5424 // flusher's destructor will call connection_.FlushPackets, which should
5425 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5426 }
5427 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5428 EXPECT_TRUE(connection_.connected());
5429
5430 // Close connection on another PACKET_WRITE_ERROR.
5431 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5432 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5433 {
5434 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5435 // flusher's destructor will call connection_.FlushPackets, which should
5436 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5437 }
5438 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5439 EXPECT_FALSE(connection_.connected());
5440 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5441 IsError(QUIC_PACKET_WRITE_ERROR));
5442}
5443
5444// Simulate the case where the first attempt to send a probe is write blocked,
5445// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5446TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
5447 MtuDiscoveryTestInit();
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 // Send enough packets so that the next one triggers path MTU discovery.
5455 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5456 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5457 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5458 }
5459
5460 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5461
5462 // Trigger the probe.
5463 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5464 nullptr);
5465 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5466 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5467 BlockOnNextWrite();
5468 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5469 connection_.GetMtuDiscoveryAlarm()->Fire();
5470 EXPECT_EQ(1u, connection_.mtu_probe_count());
5471 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5472 ASSERT_TRUE(connection_.connected());
5473
5474 writer_->SetWritable();
5475 SimulateNextPacketTooLarge();
5476 connection_.OnCanWrite();
5477 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5478 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5479 EXPECT_TRUE(connection_.connected());
5480}
5481
5482// Tests whether MTU discovery works correctly when the probes never get
5483// acknowledged.
5484TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5485 MtuDiscoveryTestInit();
5486
5487 // Lower the number of probes between packets in order to make the test go
5488 // much faster.
5489 const QuicPacketCount packets_between_probes_base = 5;
5490 set_packets_between_probes_base(packets_between_probes_base);
5491
5492 connection_.EnablePathMtuDiscovery(send_algorithm_);
5493
5494 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5495
5496 EXPECT_EQ(packets_between_probes_base,
5497 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5498
5499 // This tests sends more packets than strictly necessary to make sure that if
5500 // the connection was to send more discovery packets than needed, those would
5501 // get caught as well.
5502 const QuicPacketCount number_of_packets =
5503 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5504 std::vector<QuicPacketNumber> mtu_discovery_packets;
5505 // Called on many acks.
martindukeba002452023-03-21 08:10:46 -07005506 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04005507 .Times(AnyNumber());
5508 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5509 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5510 clock_.AdvanceTime(rtt);
5511
5512 // Receive an ACK, which marks all data packets as received, and all MTU
5513 // discovery packets as missing.
5514
5515 QuicAckFrame ack;
5516
5517 if (!mtu_discovery_packets.empty()) {
5518 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5519 mtu_discovery_packets.end());
5520 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5521 mtu_discovery_packets.end());
5522 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5523 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5524 creator_->packet_number() + 1);
5525 ack.largest_acked = creator_->packet_number();
5526
5527 } else {
5528 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5529 ack.largest_acked = creator_->packet_number();
5530 }
5531
5532 ProcessAckPacket(&ack);
5533
5534 // Trigger MTU probe if it would be scheduled now.
5535 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5536 continue;
5537 }
5538
5539 // Fire the alarm. The alarm should cause a packet to be sent.
5540 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5541 connection_.GetMtuDiscoveryAlarm()->Fire();
5542 // Record the packet number of the MTU discovery packet in order to
5543 // mark it as NACK'd.
5544 mtu_discovery_packets.push_back(creator_->packet_number());
5545 }
5546
5547 // Ensure the number of packets between probes grows exponentially by checking
5548 // it against the closed-form expression for the packet number.
5549 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5550 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5551 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5552 const QuicPacketCount packets_between_probes =
5553 packets_between_probes_base * ((1 << (i + 1)) - 1);
5554 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5555 mtu_discovery_packets[i]);
5556 }
5557
5558 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5559 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5560 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5561}
5562
5563// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5564TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
5565 MtuDiscoveryTestInit();
5566
5567 const QuicPacketCount packets_between_probes_base = 5;
5568 set_packets_between_probes_base(packets_between_probes_base);
5569
5570 connection_.EnablePathMtuDiscovery(send_algorithm_);
5571
5572 // Send enough packets so that the next one triggers path MTU discovery.
5573 QuicStreamOffset stream_offset = 0;
5574 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5575 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5576 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5577 }
5578
5579 // Trigger the probe.
5580 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5581 nullptr);
5582 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5583 QuicByteCount probe_size;
5584 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5585 .WillOnce(SaveArg<3>(&probe_size));
5586 connection_.GetMtuDiscoveryAlarm()->Fire();
5587 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5588 kMtuDiscoveryTargetPacketSizeHigh));
5589
5590 const QuicPacketNumber probe_packet_number =
5591 FirstSendingPacketNumber() + packets_between_probes_base;
5592 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5593
5594 // Acknowledge all packets sent so far.
5595 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
martindukeba002452023-03-21 08:10:46 -07005596 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04005597 .Times(AnyNumber());
5598 ProcessAckPacket(&first_ack);
5599 EXPECT_EQ(probe_size, connection_.max_packet_length());
5600 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5601
5602 EXPECT_EQ(1u, connection_.mtu_probe_count());
5603
5604 // Send just enough packets without triggering the second probe.
5605 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5606 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5607 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5608 }
5609
5610 // Trigger the second probe.
5611 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5612 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5613 QuicByteCount second_probe_size;
5614 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5615 .WillOnce(SaveArg<3>(&second_probe_size));
5616 connection_.GetMtuDiscoveryAlarm()->Fire();
5617 EXPECT_THAT(second_probe_size,
5618 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5619 EXPECT_EQ(2u, connection_.mtu_probe_count());
5620
5621 // Acknowledge all packets sent so far, except the second probe.
5622 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5623 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5624 ProcessAckPacket(&first_ack);
5625 EXPECT_EQ(probe_size, connection_.max_packet_length());
5626
5627 // Send just enough packets without triggering the third probe.
5628 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5629 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5630 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5631 }
5632
5633 // Trigger the third probe.
5634 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5635 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5636 QuicByteCount third_probe_size;
5637 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5638 .WillOnce(SaveArg<3>(&third_probe_size));
5639 connection_.GetMtuDiscoveryAlarm()->Fire();
5640 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5641 EXPECT_EQ(3u, connection_.mtu_probe_count());
5642
5643 // Acknowledge all packets sent so far, except the second probe.
5644 QuicAckFrame third_ack =
5645 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5646 ProcessAckPacket(&third_ack);
5647 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5648
5649 SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr);
5650 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5651
5652 if (connection_.PathDegradingDetectionInProgress() &&
5653 QuicConnectionPeer::GetPathDegradingDeadline(&connection_) <
5654 QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(
5655 &connection_)) {
5656 // Fire path degrading alarm first.
5657 connection_.PathDegradingTimeout();
5658 }
5659
5660 // Verify the max packet size has not reduced.
5661 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5662
5663 // Fire alarm to get path mtu reduction callback called.
5664 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5665 connection_.GetBlackholeDetectorAlarm()->Fire();
5666
5667 // Verify the max packet size has reduced to the previous value.
5668 EXPECT_EQ(probe_size, connection_.max_packet_length());
5669}
5670
5671// Tests whether MTU discovery works when the writer has a limit on how large a
5672// packet can be.
5673TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5674 MtuDiscoveryTestInit();
5675
5676 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5677 writer_->set_max_packet_size(mtu_limit);
5678
5679 const QuicPacketCount packets_between_probes_base = 5;
5680 set_packets_between_probes_base(packets_between_probes_base);
5681
5682 connection_.EnablePathMtuDiscovery(send_algorithm_);
5683
5684 // Send enough packets so that the next one triggers path MTU discovery.
5685 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5686 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5687 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5688 }
5689
5690 // Trigger the probe.
5691 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5692 nullptr);
5693 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5694 QuicByteCount probe_size;
5695 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5696 .WillOnce(SaveArg<3>(&probe_size));
5697 connection_.GetMtuDiscoveryAlarm()->Fire();
5698
5699 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
5700
5701 const QuicPacketNumber probe_sequence_number =
5702 FirstSendingPacketNumber() + packets_between_probes_base;
5703 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5704
5705 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005706 {
5707 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5708 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5709 .Times(AnyNumber());
5710 ProcessAckPacket(&probe_ack);
5711 EXPECT_EQ(probe_size, connection_.max_packet_length());
5712 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5713 }
Bence Békybac04052022-04-07 15:44:29 -04005714
5715 EXPECT_EQ(1u, connection_.mtu_probe_count());
5716
5717 QuicStreamOffset stream_offset = packets_between_probes_base;
5718 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5719 ++num_probes) {
5720 // Send just enough packets without triggering the next probe.
5721 for (QuicPacketCount i = 0;
5722 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5723 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5724 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5725 }
5726
5727 // Trigger the next probe.
5728 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5729 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5730 QuicByteCount new_probe_size;
5731 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5732 .WillOnce(SaveArg<3>(&new_probe_size));
5733 connection_.GetMtuDiscoveryAlarm()->Fire();
5734 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5735 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5736
5737 // Acknowledge all packets sent so far.
5738 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5739 ProcessAckPacket(&probe_ack);
5740 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5741 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5742
5743 probe_size = new_probe_size;
5744 }
5745
5746 // The last probe size should be equal to the target.
5747 EXPECT_EQ(probe_size, mtu_limit);
5748}
5749
5750// Tests whether MTU discovery works when the writer returns an error despite
5751// advertising higher packet length.
5752TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5753 MtuDiscoveryTestInit();
5754
5755 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5756 const QuicByteCount initial_mtu = connection_.max_packet_length();
5757 EXPECT_LT(initial_mtu, mtu_limit);
5758 writer_->set_max_packet_size(mtu_limit);
5759
5760 const QuicPacketCount packets_between_probes_base = 5;
5761 set_packets_between_probes_base(packets_between_probes_base);
5762
5763 connection_.EnablePathMtuDiscovery(send_algorithm_);
5764
5765 // Send enough packets so that the next one triggers path MTU discovery.
5766 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5767 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5768 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5769 }
5770
5771 // Trigger the probe.
5772 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5773 nullptr);
5774 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5775 writer_->SimulateNextPacketTooLarge();
5776 connection_.GetMtuDiscoveryAlarm()->Fire();
5777 ASSERT_TRUE(connection_.connected());
5778
5779 // Send more data.
5780 QuicPacketNumber probe_number = creator_->packet_number();
5781 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5782 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5783 connection_.EnsureWritableAndSendStreamData5();
5784 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5785 }
5786
5787 // Acknowledge all packets sent so far, except for the lost probe.
5788 QuicAckFrame probe_ack =
5789 ConstructAckFrame(creator_->packet_number(), probe_number);
martindukeba002452023-03-21 08:10:46 -07005790 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005791 ProcessAckPacket(&probe_ack);
5792 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5793
5794 // Send more packets, and ensure that none of them sets the alarm.
5795 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5796 connection_.EnsureWritableAndSendStreamData5();
5797 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5798 }
5799
5800 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5801 EXPECT_EQ(1u, connection_.mtu_probe_count());
5802}
5803
5804TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5805 MtuDiscoveryTestInit();
5806
5807 const QuicPacketCount packets_between_probes_base = 10;
5808 set_packets_between_probes_base(packets_between_probes_base);
5809
5810 connection_.EnablePathMtuDiscovery(send_algorithm_);
5811
5812 // Send enough packets so that the next one triggers path MTU discovery.
5813 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5814 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5815 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5816 }
5817
5818 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5819 nullptr);
5820 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5821
5822 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
5823 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5824 ConnectionCloseBehavior::SILENT_CLOSE);
5825 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5826}
5827
5828TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
5829 EXPECT_TRUE(connection_.connected());
5830 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5831 QuicConfig config;
5832 connection_.SetFromConfig(config);
5833
5834 const QuicTime::Delta initial_idle_timeout =
5835 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5836 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5837 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5838
5839 // When we send a packet, the timeout will change to 5ms +
5840 // kInitialIdleTimeoutSecs.
5841 clock_.AdvanceTime(five_ms);
5842 SendStreamDataToPeer(
5843 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5844 0, FIN, nullptr);
5845 EXPECT_EQ(default_timeout + five_ms,
5846 connection_.GetTimeoutAlarm()->deadline());
5847
5848 // Now send more data. This will not move the timeout because
5849 // no data has been received since the previous write.
5850 clock_.AdvanceTime(five_ms);
5851 SendStreamDataToPeer(
5852 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5853 3, FIN, nullptr);
5854 EXPECT_EQ(default_timeout + five_ms,
5855 connection_.GetTimeoutAlarm()->deadline());
5856
5857 // The original alarm will fire. We should not time out because we had a
5858 // network event at t=5ms. The alarm will reregister.
5859 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5860 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5861 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5862 EXPECT_TRUE(connection_.connected());
5863 EXPECT_EQ(default_timeout + five_ms,
5864 connection_.GetTimeoutAlarm()->deadline());
5865
5866 // This time, we should time out.
5867 EXPECT_CALL(visitor_,
5868 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5869 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5870 clock_.AdvanceTime(five_ms);
5871 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5872 connection_.GetTimeoutAlarm()->Fire();
5873 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5874 EXPECT_FALSE(connection_.connected());
5875 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5876}
5877
Bence Békybac04052022-04-07 15:44:29 -04005878TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5879 // When the idle timeout fires, verify that by default we do not send any
5880 // connection close packets.
5881 EXPECT_TRUE(connection_.connected());
5882 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5883 QuicConfig config;
5884
5885 // Create a handshake message that also enables silent close.
5886 CryptoHandshakeMessage msg;
5887 std::string error_details;
5888 QuicConfig client_config;
5889 client_config.SetInitialStreamFlowControlWindowToSend(
5890 kInitialStreamFlowControlWindowForTest);
5891 client_config.SetInitialSessionFlowControlWindowToSend(
5892 kInitialSessionFlowControlWindowForTest);
5893 client_config.SetIdleNetworkTimeout(
5894 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5895 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5896 const QuicErrorCode error =
5897 config.ProcessPeerHello(msg, CLIENT, &error_details);
5898 EXPECT_THAT(error, IsQuicNoError());
5899
5900 if (connection_.version().UsesTls()) {
5901 QuicConfigPeer::SetReceivedOriginalConnectionId(
5902 &config, connection_.connection_id());
5903 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5904 &config, connection_.connection_id());
5905 }
5906 connection_.SetFromConfig(config);
5907
5908 const QuicTime::Delta default_idle_timeout =
5909 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5910 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5911 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5912
5913 // When we send a packet, the timeout will change to 5ms +
5914 // kInitialIdleTimeoutSecs.
5915 clock_.AdvanceTime(five_ms);
5916 SendStreamDataToPeer(
5917 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5918 0, FIN, nullptr);
5919 EXPECT_EQ(default_timeout + five_ms,
5920 connection_.GetTimeoutAlarm()->deadline());
5921
5922 // Now send more data. This will not move the timeout because
5923 // no data has been received since the previous write.
5924 clock_.AdvanceTime(five_ms);
5925 SendStreamDataToPeer(
5926 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5927 3, FIN, nullptr);
5928 EXPECT_EQ(default_timeout + five_ms,
5929 connection_.GetTimeoutAlarm()->deadline());
5930
5931 // The original alarm will fire. We should not time out because we had a
5932 // network event at t=5ms. The alarm will reregister.
5933 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5934 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5935 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5936 EXPECT_TRUE(connection_.connected());
5937 EXPECT_EQ(default_timeout + five_ms,
5938 connection_.GetTimeoutAlarm()->deadline());
5939
5940 // This time, we should time out.
5941 // This results in a SILENT_CLOSE, so the writer will not be invoked
5942 // and will not save the frame. Grab the frame from OnConnectionClosed
5943 // directly.
5944 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5945 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5946
5947 clock_.AdvanceTime(five_ms);
5948 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5949 connection_.GetTimeoutAlarm()->Fire();
5950 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5951 EXPECT_FALSE(connection_.connected());
5952 EXPECT_EQ(1, connection_close_frame_count_);
5953 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5954 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
5955}
5956
Bence Békybac04052022-04-07 15:44:29 -04005957TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5958 // Same test as above, but having open streams causes a connection close
5959 // to be sent.
5960 EXPECT_TRUE(connection_.connected());
5961 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5962 QuicConfig config;
5963
5964 // Create a handshake message that also enables silent close.
5965 CryptoHandshakeMessage msg;
5966 std::string error_details;
5967 QuicConfig client_config;
5968 client_config.SetInitialStreamFlowControlWindowToSend(
5969 kInitialStreamFlowControlWindowForTest);
5970 client_config.SetInitialSessionFlowControlWindowToSend(
5971 kInitialSessionFlowControlWindowForTest);
5972 client_config.SetIdleNetworkTimeout(
5973 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5974 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5975 const QuicErrorCode error =
5976 config.ProcessPeerHello(msg, CLIENT, &error_details);
5977 EXPECT_THAT(error, IsQuicNoError());
5978
5979 if (connection_.version().UsesTls()) {
5980 QuicConfigPeer::SetReceivedOriginalConnectionId(
5981 &config, connection_.connection_id());
5982 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5983 &config, connection_.connection_id());
5984 }
5985 connection_.SetFromConfig(config);
5986
5987 const QuicTime::Delta default_idle_timeout =
5988 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5989 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5990 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5991
5992 // When we send a packet, the timeout will change to 5ms +
5993 // kInitialIdleTimeoutSecs.
5994 clock_.AdvanceTime(five_ms);
5995 SendStreamDataToPeer(
5996 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5997 0, FIN, nullptr);
5998 EXPECT_EQ(default_timeout + five_ms,
5999 connection_.GetTimeoutAlarm()->deadline());
6000
6001 // Indicate streams are still open.
6002 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
6003 .WillRepeatedly(Return(true));
6004 if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) {
6005 EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return(""));
6006 }
6007
6008 // This time, we should time out and send a connection close due to the TLP.
6009 EXPECT_CALL(visitor_,
6010 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6011 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6012 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
6013 clock_.ApproximateNow() + five_ms);
6014 connection_.GetTimeoutAlarm()->Fire();
6015 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6016 EXPECT_FALSE(connection_.connected());
6017 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6018}
6019
6020TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
6021 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6022 EXPECT_TRUE(connection_.connected());
6023 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6024 QuicConfig config;
6025 connection_.SetFromConfig(config);
6026
6027 const QuicTime::Delta initial_idle_timeout =
6028 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6029 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6030 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6031
6032 connection_.SendStreamDataWithString(
6033 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6034 0, NO_FIN);
6035 connection_.SendStreamDataWithString(
6036 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6037 3, NO_FIN);
6038
6039 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6040 clock_.AdvanceTime(five_ms);
6041
6042 // When we receive a packet, the timeout will change to 5ms +
6043 // kInitialIdleTimeoutSecs.
6044 QuicAckFrame ack = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07006045 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006046 ProcessAckPacket(&ack);
6047
6048 // The original alarm will fire. We should not time out because we had a
6049 // network event at t=5ms. The alarm will reregister.
6050 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6051 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6052 EXPECT_TRUE(connection_.connected());
6053 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6054 EXPECT_EQ(default_timeout + five_ms,
6055 connection_.GetTimeoutAlarm()->deadline());
6056
6057 // This time, we should time out.
6058 EXPECT_CALL(visitor_,
6059 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6060 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6061 clock_.AdvanceTime(five_ms);
6062 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6063 connection_.GetTimeoutAlarm()->Fire();
6064 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6065 EXPECT_FALSE(connection_.connected());
6066 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6067}
6068
6069TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6070 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6071 EXPECT_TRUE(connection_.connected());
6072 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6073 QuicConfig config;
6074 connection_.SetFromConfig(config);
6075
6076 const QuicTime::Delta initial_idle_timeout =
6077 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6078 connection_.SetNetworkTimeouts(
6079 QuicTime::Delta::Infinite(),
6080 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6081 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6082 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6083
6084 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6085 connection_.SendStreamDataWithString(
6086 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6087 0, NO_FIN);
6088 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6089 connection_.SendStreamDataWithString(
6090 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6091 3, NO_FIN);
6092
6093 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6094
6095 clock_.AdvanceTime(five_ms);
6096
6097 // When we receive a packet, the timeout will change to 5ms +
6098 // kInitialIdleTimeoutSecs.
6099 QuicAckFrame ack = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07006100 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006101 ProcessAckPacket(&ack);
6102
6103 // The original alarm will fire. We should not time out because we had a
6104 // network event at t=5ms. The alarm will reregister.
6105 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6106 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6107 EXPECT_TRUE(connection_.connected());
6108 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6109 EXPECT_EQ(default_timeout + five_ms,
6110 connection_.GetTimeoutAlarm()->deadline());
6111
6112 // Now, send packets while advancing the time and verify that the connection
6113 // eventually times out.
6114 EXPECT_CALL(visitor_,
6115 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6116 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6117 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6118 QUIC_LOG(INFO) << "sending data packet";
6119 connection_.SendStreamDataWithString(
6120 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6121 "foo", 0, NO_FIN);
6122 connection_.GetTimeoutAlarm()->Fire();
6123 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6124 }
6125 EXPECT_FALSE(connection_.connected());
6126 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6127 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6128}
6129
Bence Békybac04052022-04-07 15:44:29 -04006130TEST_P(QuicConnectionTest, SendScheduler) {
6131 // Test that if we send a packet without delay, it is not queued.
6132 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6133 std::unique_ptr<QuicPacket> packet =
6134 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6135 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6136 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6137 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6138 HAS_RETRANSMITTABLE_DATA, false, false);
6139 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6140}
6141
6142TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6143 // Test that the connection does not crash when it fails to send the first
6144 // packet at which point self_address_ might be uninitialized.
6145 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6146 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
6147 std::unique_ptr<QuicPacket> packet =
6148 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6149 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6150 writer_->SetShouldWriteFail();
6151 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6152 HAS_RETRANSMITTABLE_DATA, false, false);
6153}
6154
6155TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6156 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6157 std::unique_ptr<QuicPacket> packet =
6158 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6159 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6160 BlockOnNextWrite();
6161 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6162 .Times(0);
6163 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6164 HAS_RETRANSMITTABLE_DATA, false, false);
6165 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6166}
6167
6168TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
6169 // Queue the first packet.
6170 size_t payload_length = connection_.max_packet_length();
6171 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
6172 const std::string payload(payload_length, 'a');
6173 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6174 connection_.version().transport_version, Perspective::IS_CLIENT));
6175 EXPECT_EQ(0u, connection_
6176 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6177 NO_FIN)
6178 .bytes_consumed);
6179 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6180}
6181
6182TEST_P(QuicConnectionTest, SendingThreePackets) {
6183 // Make the payload twice the size of the packet, so 3 packets are written.
6184 size_t total_payload_length = 2 * connection_.max_packet_length();
6185 const std::string payload(total_payload_length, 'a');
6186 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6187 connection_.version().transport_version, Perspective::IS_CLIENT));
6188 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6189 EXPECT_EQ(payload.size(), connection_
6190 .SendStreamDataWithString(first_bidi_stream_id,
6191 payload, 0, NO_FIN)
6192 .bytes_consumed);
6193}
6194
6195TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6196 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -04006197 // Set up a larger payload than will fit in one packet.
6198 const std::string payload(connection_.max_packet_length(), 'a');
6199 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6200
6201 // Now send some packets with no truncation.
6202 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6203 EXPECT_EQ(payload.size(),
6204 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6205 .bytes_consumed);
6206 // Track the size of the second packet here. The overhead will be the largest
6207 // we see in this test, due to the non-truncated connection id.
6208 size_t non_truncated_packet_size = writer_->last_packet_size();
6209
6210 // Change to a 0 byte connection id.
6211 QuicConfig config;
6212 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6213 connection_.SetFromConfig(config);
6214 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6215 EXPECT_EQ(payload.size(),
6216 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6217 .bytes_consumed);
fayangfc04b8a2023-05-18 09:26:25 -07006218 // Short header packets sent from server omit connection ID already, and
6219 // stream offset size increases from 0 to 2.
6220 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
Bence Békybac04052022-04-07 15:44:29 -04006221}
6222
6223TEST_P(QuicConnectionTest, SendDelayedAck) {
6224 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6225 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6226 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006227 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006228 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6229 peer_framer_.SetEncrypter(
6230 ENCRYPTION_ZERO_RTT,
6231 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006232 // Process a packet from the non-crypto stream.
6233 frame1_.stream_id = 3;
6234
6235 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6236 // instead of ENCRYPTION_INITIAL.
6237 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6238 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6239
6240 // Check if delayed ack timer is running for the expected interval.
6241 EXPECT_TRUE(connection_.HasPendingAcks());
6242 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6243 // Simulate delayed ack alarm firing.
6244 clock_.AdvanceTime(DefaultDelayedAckTime());
6245 connection_.GetAckAlarm()->Fire();
6246 // Check that ack is sent and that delayed ack alarm is reset.
6247 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006248 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6249 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006250 EXPECT_FALSE(writer_->ack_frames().empty());
6251 EXPECT_FALSE(connection_.HasPendingAcks());
6252}
6253
6254TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6255 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6256
6257 const size_t kMinRttMs = 40;
6258 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6259 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6260 QuicTime::Delta::Zero(), QuicTime::Zero());
6261 // The ack time should be based on min_rtt/4, since it's less than the
6262 // default delayed ack time.
6263 QuicTime ack_time = clock_.ApproximateNow() +
6264 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6265 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6266 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006267 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006268 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6269 peer_framer_.SetEncrypter(
6270 ENCRYPTION_ZERO_RTT,
6271 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006272 // Process a packet from the non-crypto stream.
6273 frame1_.stream_id = 3;
6274
6275 // Process all the initial packets in order so there aren't missing packets.
6276 uint64_t kFirstDecimatedPacket = 101;
6277 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6278 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6279 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6280 }
6281 EXPECT_FALSE(connection_.HasPendingAcks());
6282 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6283 // instead of ENCRYPTION_INITIAL.
6284 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6285 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6286 ENCRYPTION_ZERO_RTT);
6287
6288 // Check if delayed ack timer is running for the expected interval.
6289 EXPECT_TRUE(connection_.HasPendingAcks());
6290 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6291
6292 // The 10th received packet causes an ack to be sent.
6293 for (int i = 0; i < 9; ++i) {
6294 EXPECT_TRUE(connection_.HasPendingAcks());
6295 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6296 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6297 ENCRYPTION_ZERO_RTT);
6298 }
6299 // Check that ack is sent and that delayed ack alarm is reset.
6300 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006301 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6302 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006303 EXPECT_FALSE(writer_->ack_frames().empty());
6304 EXPECT_FALSE(connection_.HasPendingAcks());
6305}
6306
6307TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6308 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6309 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6310 QuicConfig config;
6311 QuicTagVector connection_options;
6312 // No limit on the number of packets received before sending an ack.
6313 connection_options.push_back(kAKDU);
6314 config.SetConnectionOptionsToSend(connection_options);
6315 connection_.SetFromConfig(config);
6316
6317 const size_t kMinRttMs = 40;
6318 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6319 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6320 QuicTime::Delta::Zero(), QuicTime::Zero());
6321 // The ack time should be based on min_rtt/4, since it's less than the
6322 // default delayed ack time.
6323 QuicTime ack_time = clock_.ApproximateNow() +
6324 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6325 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6326 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006327 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006328 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6329 peer_framer_.SetEncrypter(
6330 ENCRYPTION_ZERO_RTT,
6331 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006332 // Process a packet from the non-crypto stream.
6333 frame1_.stream_id = 3;
6334
6335 // Process all the initial packets in order so there aren't missing packets.
6336 uint64_t kFirstDecimatedPacket = 101;
6337 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6338 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6339 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6340 }
6341 EXPECT_FALSE(connection_.HasPendingAcks());
6342 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6343 // instead of ENCRYPTION_INITIAL.
6344 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6345 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6346 ENCRYPTION_ZERO_RTT);
6347
6348 // Check if delayed ack timer is running for the expected interval.
6349 EXPECT_TRUE(connection_.HasPendingAcks());
6350 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6351
6352 // 18 packets will not cause an ack to be sent. 19 will because when
6353 // stop waiting frames are in use, we ack every 20 packets no matter what.
6354 for (int i = 0; i < 18; ++i) {
6355 EXPECT_TRUE(connection_.HasPendingAcks());
6356 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6357 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6358 ENCRYPTION_ZERO_RTT);
6359 }
6360 // The delayed ack timer should still be set to the expected deadline.
6361 EXPECT_TRUE(connection_.HasPendingAcks());
6362 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6363}
6364
6365TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6366 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6367 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6368
6369 const size_t kMinRttMs = 40;
6370 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6371 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6372 QuicTime::Delta::Zero(), QuicTime::Zero());
6373 // The ack time should be based on min_rtt/8, since it's less than the
6374 // default delayed ack time.
6375 QuicTime ack_time = clock_.ApproximateNow() +
6376 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6377 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6378 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006379 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006380 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6381 peer_framer_.SetEncrypter(
6382 ENCRYPTION_ZERO_RTT,
6383 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006384 // Process a packet from the non-crypto stream.
6385 frame1_.stream_id = 3;
6386
6387 // Process all the initial packets in order so there aren't missing packets.
6388 uint64_t kFirstDecimatedPacket = 101;
6389 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6390 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6391 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6392 }
6393 EXPECT_FALSE(connection_.HasPendingAcks());
6394 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6395 // instead of ENCRYPTION_INITIAL.
6396 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6397 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6398 ENCRYPTION_ZERO_RTT);
6399
6400 // Check if delayed ack timer is running for the expected interval.
6401 EXPECT_TRUE(connection_.HasPendingAcks());
6402 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6403
6404 // The 10th received packet causes an ack to be sent.
6405 for (int i = 0; i < 9; ++i) {
6406 EXPECT_TRUE(connection_.HasPendingAcks());
6407 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6408 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6409 ENCRYPTION_ZERO_RTT);
6410 }
6411 // Check that ack is sent and that delayed ack alarm is reset.
6412 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006413 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6414 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006415 EXPECT_FALSE(writer_->ack_frames().empty());
6416 EXPECT_FALSE(connection_.HasPendingAcks());
6417}
6418
6419TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6420 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6421 ProcessPacket(1);
6422 // Check that ack is sent and that delayed ack alarm is set.
6423 EXPECT_TRUE(connection_.HasPendingAcks());
6424 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6425 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6426
6427 // Completing the handshake as the server does nothing.
6428 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6429 connection_.OnHandshakeComplete();
6430 EXPECT_TRUE(connection_.HasPendingAcks());
6431 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6432
6433 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6434 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6435 connection_.OnHandshakeComplete();
6436 EXPECT_TRUE(connection_.HasPendingAcks());
6437 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6438 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6439 connection_.GetAckAlarm()->deadline());
6440 } else {
6441 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6442 }
6443}
6444
6445TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6446 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6447 ProcessPacket(1);
6448 ProcessPacket(2);
6449 // Check that ack is sent and that delayed ack alarm is reset.
6450 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006451 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6452 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006453 EXPECT_FALSE(writer_->ack_frames().empty());
6454 EXPECT_FALSE(connection_.HasPendingAcks());
6455}
6456
6457TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6458 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6460 ProcessPacket(2);
fayangfc04b8a2023-05-18 09:26:25 -07006461 size_t frames_per_ack = 1;
Bence Békybac04052022-04-07 15:44:29 -04006462
6463 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6464 ProcessPacket(3);
6465 size_t padding_frame_count = writer_->padding_frames().size();
6466 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6467 EXPECT_FALSE(writer_->ack_frames().empty());
6468 writer_->Reset();
6469
6470 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6471 ProcessPacket(4);
6472 EXPECT_EQ(0u, writer_->frame_count());
6473
6474 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6475 ProcessPacket(5);
6476 padding_frame_count = writer_->padding_frames().size();
6477 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6478 EXPECT_FALSE(writer_->ack_frames().empty());
6479 writer_->Reset();
6480
6481 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6482 // Now only set the timer on the 6th packet, instead of sending another ack.
6483 ProcessPacket(6);
6484 padding_frame_count = writer_->padding_frames().size();
6485 EXPECT_EQ(padding_frame_count, writer_->frame_count());
6486 EXPECT_TRUE(connection_.HasPendingAcks());
6487}
6488
6489TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6490 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6491 EXPECT_CALL(visitor_, OnStreamFrame(_));
martinduke9e0811c2022-12-08 20:35:57 -08006492 peer_framer_.SetEncrypter(
6493 ENCRYPTION_FORWARD_SECURE,
6494 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
6495 SetDecrypter(
6496 ENCRYPTION_FORWARD_SECURE,
6497 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04006498 ProcessDataPacket(1);
6499 connection_.SendStreamDataWithString(
6500 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6501 0, NO_FIN);
6502 // Check that ack is bundled with outgoing data and that delayed ack
6503 // alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006504 EXPECT_EQ(2u, writer_->frame_count());
6505 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006506 EXPECT_FALSE(writer_->ack_frames().empty());
6507 EXPECT_FALSE(connection_.HasPendingAcks());
6508}
6509
6510TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6511 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6512 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6513 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6514 } else {
6515 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6516 }
6517 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6518 connection_.SendCryptoDataWithString("foo", 0);
6519 // Check that ack is bundled with outgoing crypto data.
fayangfc04b8a2023-05-18 09:26:25 -07006520 EXPECT_EQ(3u, writer_->frame_count());
6521 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006522 EXPECT_FALSE(connection_.HasPendingAcks());
6523}
6524
6525TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6526 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6527 ProcessPacket(1);
6528 BlockOnNextWrite();
6529 writer_->set_is_write_blocked_data_buffered(true);
6530 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6531 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6532 } else {
6533 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6534 }
6535 connection_.SendCryptoDataWithString("foo", 0);
6536 EXPECT_TRUE(writer_->IsWriteBlocked());
6537 EXPECT_FALSE(connection_.HasQueuedData());
6538 connection_.SendCryptoDataWithString("bar", 3);
6539 EXPECT_TRUE(writer_->IsWriteBlocked());
6540 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6541 // CRYPTO frames are not flushed when writer is blocked.
6542 EXPECT_FALSE(connection_.HasQueuedData());
6543 } else {
6544 EXPECT_TRUE(connection_.HasQueuedData());
6545 }
6546}
6547
6548TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6549 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6550 EXPECT_FALSE(connection_.HasPendingAcks());
6551 EXPECT_CALL(visitor_, OnCanWrite())
6552 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6553 &connection_, &TestConnection::SendCryptoStreamData)));
6554 // Process a packet from the crypto stream, which is frame1_'s default.
6555 // Receiving the CHLO as packet 2 first will cause the connection to
6556 // immediately send an ack, due to the packet gap.
6557 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6558 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6559 } else {
6560 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6561 }
wubc9fd4292023-08-14 13:00:21 -07006562 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006563 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6564 // Check that ack is sent and that delayed ack alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006565 EXPECT_EQ(3u, writer_->frame_count());
6566 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006567 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6568 EXPECT_EQ(1u, writer_->stream_frames().size());
6569 } else {
6570 EXPECT_EQ(1u, writer_->crypto_frames().size());
6571 }
6572 EXPECT_EQ(1u, writer_->padding_frames().size());
6573 ASSERT_FALSE(writer_->ack_frames().empty());
6574 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6575 EXPECT_FALSE(connection_.HasPendingAcks());
6576}
6577
6578TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6579 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6580 EXPECT_FALSE(connection_.HasPendingAcks());
6581
6582 // Process two packets from the crypto stream, which is frame1_'s default,
6583 // simulating a 2 packet reject.
6584 {
6585 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6586 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6587 } else {
6588 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6589 }
6590 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6591 // Send the new CHLO when the REJ is processed.
6592 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6593 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6594 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6595 &connection_, &TestConnection::SendCryptoStreamData)));
6596 } else {
6597 EXPECT_CALL(visitor_, OnStreamFrame(_))
6598 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6599 &connection_, &TestConnection::SendCryptoStreamData)));
6600 }
wubc9fd4292023-08-14 13:00:21 -07006601 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006602 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6603 }
6604 // Check that ack is sent and that delayed ack alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006605 EXPECT_EQ(3u, writer_->frame_count());
6606 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006607 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6608 EXPECT_EQ(1u, writer_->stream_frames().size());
6609 } else {
6610 EXPECT_EQ(1u, writer_->crypto_frames().size());
6611 }
6612 EXPECT_EQ(1u, writer_->padding_frames().size());
6613 ASSERT_FALSE(writer_->ack_frames().empty());
6614 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6615 EXPECT_FALSE(connection_.HasPendingAcks());
6616}
6617
6618TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6619 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6620 connection_.SendStreamDataWithString(
6621 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6622 0, NO_FIN);
6623 connection_.SendStreamDataWithString(
6624 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6625 3, NO_FIN);
6626 // Ack the second packet, which will retransmit the first packet.
6627 QuicAckFrame ack = ConstructAckFrame(2, 1);
6628 LostPacketVector lost_packets;
6629 lost_packets.push_back(
6630 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6631 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6632 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
6633 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07006634 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006635 ProcessAckPacket(&ack);
6636 size_t padding_frame_count = writer_->padding_frames().size();
6637 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6638 EXPECT_EQ(1u, writer_->stream_frames().size());
6639 writer_->Reset();
6640
6641 // Now ack the retransmission, which will both raise the high water mark
6642 // and see if there is more data to send.
6643 ack = ConstructAckFrame(3, 1);
6644 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07006645 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006646 ProcessAckPacket(&ack);
6647
6648 // Check that no packet is sent and the ack alarm isn't set.
6649 EXPECT_EQ(0u, writer_->frame_count());
6650 EXPECT_FALSE(connection_.HasPendingAcks());
6651 writer_->Reset();
6652
6653 // Send the same ack, but send both data and an ack together.
6654 ack = ConstructAckFrame(3, 1);
6655 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6656 EXPECT_CALL(visitor_, OnCanWrite())
6657 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6658 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
wubc9fd4292023-08-14 13:00:21 -07006659 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006660 ProcessAckPacket(&ack);
6661
6662 // Check that ack is bundled with outgoing data and the delayed ack
6663 // alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006664 // Do not ACK acks.
6665 EXPECT_EQ(1u, writer_->frame_count());
6666 EXPECT_TRUE(writer_->ack_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006667 EXPECT_EQ(1u, writer_->stream_frames().size());
6668 EXPECT_FALSE(connection_.HasPendingAcks());
6669}
6670
6671TEST_P(QuicConnectionTest, NoAckSentForClose) {
6672 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6673 ProcessPacket(1);
6674 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6675 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6676 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6677 ProcessClosePacket(2);
6678 EXPECT_EQ(1, connection_close_frame_count_);
6679 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6680 IsError(QUIC_PEER_GOING_AWAY));
6681}
6682
6683TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6684 EXPECT_TRUE(connection_.connected());
6685 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6686 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6687 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6688 ConnectionCloseBehavior::SILENT_CLOSE);
6689 EXPECT_FALSE(connection_.connected());
6690 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6691 EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
6692 /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
6693}
6694
6695TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6696 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
6697 if (!IsDefaultTestConfiguration()) {
6698 return;
6699 }
6700
6701 EXPECT_TRUE(connection_.connected());
6702 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6703 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6704 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6705 ConnectionCloseBehavior::SILENT_CLOSE);
6706 EXPECT_FALSE(connection_.connected());
6707 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6708
6709 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6710 .Times(0);
6711
6712 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6713 writer_.get(), connection_.peer_address()),
6714 "Not sending connectivity probing packet as connection is "
6715 "disconnected.");
6716 EXPECT_EQ(1, connection_close_frame_count_);
6717 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6718 IsError(QUIC_PEER_GOING_AWAY));
6719}
6720
6721TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6722 PathProbeTestInit(Perspective::IS_CLIENT);
6723 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6724 // Block next write so that sending connectivity probe will encounter a
6725 // blocked write when send a connectivity probe to the peer.
6726 probing_writer.BlockOnNextWrite();
6727 // Connection will not be marked as write blocked as connectivity probe only
6728 // affects the probing_writer which is not the default.
6729 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6730
6731 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6732 .Times(1);
6733 connection_.SendConnectivityProbingPacket(&probing_writer,
6734 connection_.peer_address());
6735}
6736
6737TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6738 PathProbeTestInit(Perspective::IS_SERVER);
6739 if (version().SupportsAntiAmplificationLimit()) {
6740 QuicConnectionPeer::SetAddressValidated(&connection_);
6741 }
6742
6743 // Block next write so that sending connectivity probe will encounter a
6744 // blocked write when send a connectivity probe to the peer.
6745 writer_->BlockOnNextWrite();
6746 // Connection will be marked as write blocked as server uses the default
6747 // writer to send connectivity probes.
6748 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6749
6750 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6751 .Times(1);
6752 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6753 QuicPathFrameBuffer payload{
6754 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
6755 QuicConnection::ScopedPacketFlusher flusher(&connection_);
6756 connection_.SendPathChallenge(
6757 payload, connection_.self_address(), connection_.peer_address(),
6758 connection_.effective_peer_address(), writer_.get());
6759 } else {
6760 connection_.SendConnectivityProbingPacket(writer_.get(),
6761 connection_.peer_address());
6762 }
6763}
6764
6765TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6766 PathProbeTestInit(Perspective::IS_CLIENT);
6767 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6768 probing_writer.SetShouldWriteFail();
6769
6770 // Connection should not be closed if a connectivity probe is failed to be
6771 // sent.
6772 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6773
6774 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6775 .Times(0);
6776 connection_.SendConnectivityProbingPacket(&probing_writer,
6777 connection_.peer_address());
6778}
6779
6780TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6781 PathProbeTestInit(Perspective::IS_SERVER);
6782
6783 writer_->SetShouldWriteFail();
6784 // Connection should not be closed if a connectivity probe is failed to be
6785 // sent.
6786 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6787
6788 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6789 .Times(0);
6790 connection_.SendConnectivityProbingPacket(writer_.get(),
6791 connection_.peer_address());
6792}
6793
Bence Békybac04052022-04-07 15:44:29 -04006794TEST_P(QuicConnectionTest, IetfStatelessReset) {
Bence Békybac04052022-04-07 15:44:29 -04006795 QuicConfig config;
6796 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6797 kTestStatelessResetToken);
6798 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6799 connection_.SetFromConfig(config);
6800 std::unique_ptr<QuicEncryptedPacket> packet(
6801 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6802 /*received_packet_length=*/100,
6803 kTestStatelessResetToken));
6804 std::unique_ptr<QuicReceivedPacket> received(
6805 ConstructReceivedPacket(*packet, QuicTime::Zero()));
Bence Békybac04052022-04-07 15:44:29 -04006806 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6807 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6808 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6809 EXPECT_EQ(1, connection_close_frame_count_);
6810 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6811 IsError(QUIC_PUBLIC_RESET));
6812}
6813
6814TEST_P(QuicConnectionTest, GoAway) {
6815 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6816 // GoAway is not available in version 99.
6817 return;
6818 }
6819
6820 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6821
6822 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
6823 goaway->last_good_stream_id = 1;
6824 goaway->error_code = QUIC_PEER_GOING_AWAY;
6825 goaway->reason_phrase = "Going away.";
6826 EXPECT_CALL(visitor_, OnGoAway(_));
6827 ProcessGoAwayPacket(goaway);
6828}
6829
6830TEST_P(QuicConnectionTest, WindowUpdate) {
6831 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6832
6833 QuicWindowUpdateFrame window_update;
6834 window_update.stream_id = 3;
6835 window_update.max_data = 1234;
6836 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6837 ProcessFramePacket(QuicFrame(window_update));
6838}
6839
6840TEST_P(QuicConnectionTest, Blocked) {
6841 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6842
6843 QuicBlockedFrame blocked;
6844 blocked.stream_id = 3;
6845 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6846 ProcessFramePacket(QuicFrame(blocked));
6847 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6848 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6849}
6850
6851TEST_P(QuicConnectionTest, ZeroBytePacket) {
6852 // Don't close the connection for zero byte packets.
6853 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6854 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6855 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6856}
6857
Bence Békybac04052022-04-07 15:44:29 -04006858TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
6859 // All supported versions except the one the connection supports.
6860 ParsedQuicVersionVector versions;
6861 for (auto version : AllSupportedVersions()) {
6862 if (version != connection_.version()) {
6863 versions.push_back(version);
6864 }
6865 }
6866
6867 // Send a version negotiation packet.
6868 std::unique_ptr<QuicEncryptedPacket> encrypted(
6869 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07006870 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04006871 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6872 std::unique_ptr<QuicReceivedPacket> received(
6873 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6874 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6875 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6876 // Verify no connection close packet gets sent.
6877 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6878 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6879 EXPECT_FALSE(connection_.connected());
6880 EXPECT_EQ(1, connection_close_frame_count_);
6881 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6882 IsError(QUIC_INVALID_VERSION));
6883}
6884
6885TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiationWithConnectionClose) {
6886 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6887 QuicConfig config;
6888 QuicTagVector connection_options;
6889 connection_options.push_back(kINVC);
6890 config.SetClientConnectionOptions(connection_options);
6891 connection_.SetFromConfig(config);
6892
6893 // All supported versions except the one the connection supports.
6894 ParsedQuicVersionVector versions;
6895 for (auto version : AllSupportedVersions()) {
6896 if (version != connection_.version()) {
6897 versions.push_back(version);
6898 }
6899 }
6900
6901 // Send a version negotiation packet.
6902 std::unique_ptr<QuicEncryptedPacket> encrypted(
6903 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07006904 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04006905 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6906 std::unique_ptr<QuicReceivedPacket> received(
6907 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6908 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6909 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6910 // Verify connection close packet gets sent.
6911 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1u));
6912 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6913 EXPECT_FALSE(connection_.connected());
6914 EXPECT_EQ(1, connection_close_frame_count_);
6915 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6916 IsError(QUIC_INVALID_VERSION));
6917}
6918
6919TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6920 // Send a version negotiation packet with the version the client started with.
6921 // It should be rejected.
6922 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6923 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6924 std::unique_ptr<QuicEncryptedPacket> encrypted(
6925 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07006926 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04006927 connection_.version().HasLengthPrefixedConnectionIds(),
6928 AllSupportedVersions()));
6929 std::unique_ptr<QuicReceivedPacket> received(
6930 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6931 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6932 EXPECT_EQ(1, connection_close_frame_count_);
6933 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6934 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
6935}
6936
Bence Békybac04052022-04-07 15:44:29 -04006937TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
6938 // Construct a packet with stream frame and connection close frame.
6939 QuicPacketHeader header;
6940 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
6941 header.source_connection_id = connection_id_;
6942 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04006943 } else {
6944 header.destination_connection_id = connection_id_;
fayangfc04b8a2023-05-18 09:26:25 -07006945 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04006946 }
6947 header.packet_number = QuicPacketNumber(1);
6948 header.version_flag = false;
6949
6950 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
6951 // This QuicConnectionCloseFrame will default to being for a Google QUIC
6952 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
6953 // depending on the mapping.
6954 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
6955 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
6956 /*transport_close_frame_type=*/0);
6957 QuicFrames frames;
6958 frames.push_back(QuicFrame(frame1_));
6959 frames.push_back(QuicFrame(&qccf));
6960 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6961 EXPECT_TRUE(nullptr != packet);
6962 char buffer[kMaxOutgoingPacketSize];
6963 size_t encrypted_length = peer_framer_.EncryptPayload(
6964 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
6965 kMaxOutgoingPacketSize);
6966
6967 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6968 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6969 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6970 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6971
6972 connection_.ProcessUdpPacket(
6973 kSelfAddress, kPeerAddress,
6974 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6975 EXPECT_EQ(1, connection_close_frame_count_);
6976 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6977 IsError(QUIC_PEER_GOING_AWAY));
6978}
6979
6980TEST_P(QuicConnectionTest, SelectMutualVersion) {
6981 connection_.SetSupportedVersions(AllSupportedVersions());
6982 // Set the connection to speak the lowest quic version.
6983 connection_.set_version(QuicVersionMin());
6984 EXPECT_EQ(QuicVersionMin(), connection_.version());
6985
6986 // Pass in available versions which includes a higher mutually supported
6987 // version. The higher mutually supported version should be selected.
6988 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
6989 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
6990 EXPECT_EQ(QuicVersionMax(), connection_.version());
6991
6992 // Expect that the lowest version is selected.
6993 // Ensure the lowest supported version is less than the max, unless they're
6994 // the same.
6995 ParsedQuicVersionVector lowest_version_vector;
6996 lowest_version_vector.push_back(QuicVersionMin());
6997 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
6998 EXPECT_EQ(QuicVersionMin(), connection_.version());
6999
7000 // Shouldn't be able to find a mutually supported version.
7001 ParsedQuicVersionVector unsupported_version;
7002 unsupported_version.push_back(UnsupportedQuicVersion());
7003 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7004}
7005
7006TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7007 EXPECT_FALSE(writer_->IsWriteBlocked());
7008
7009 // Send a packet.
7010 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7011 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7012 EXPECT_EQ(1u, writer_->packets_write_attempts());
7013
7014 TriggerConnectionClose();
7015 EXPECT_LE(2u, writer_->packets_write_attempts());
7016}
7017
7018TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7019 BlockOnNextWrite();
7020 TriggerConnectionClose();
7021 EXPECT_EQ(1u, writer_->packets_write_attempts());
7022 EXPECT_TRUE(writer_->IsWriteBlocked());
7023}
7024
7025TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7026 BlockOnNextWrite();
7027 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7028 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7029 EXPECT_EQ(1u, writer_->packets_write_attempts());
7030 EXPECT_TRUE(writer_->IsWriteBlocked());
7031 TriggerConnectionClose();
7032 EXPECT_EQ(1u, writer_->packets_write_attempts());
7033}
7034
7035TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7036 PathProbeTestInit(Perspective::IS_CLIENT);
7037 MockQuicConnectionDebugVisitor debug_visitor;
7038 connection_.set_debug_visitor(&debug_visitor);
7039
wub92727922023-07-13 08:47:39 -07007040 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007041 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7042
wub92727922023-07-13 08:47:39 -07007043 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007044 connection_.SendConnectivityProbingPacket(writer_.get(),
7045 connection_.peer_address());
7046}
7047
7048TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7049 QuicPacketHeader header;
7050 header.packet_number = QuicPacketNumber(1);
fayangfc04b8a2023-05-18 09:26:25 -07007051 header.form = IETF_QUIC_LONG_HEADER_PACKET;
Bence Békybac04052022-04-07 15:44:29 -04007052
7053 MockQuicConnectionDebugVisitor debug_visitor;
7054 connection_.set_debug_visitor(&debug_visitor);
7055 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header), _, _)).Times(1);
7056 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7057 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7058 connection_.OnPacketHeader(header);
7059}
7060
7061TEST_P(QuicConnectionTest, Pacing) {
7062 TestConnection server(connection_id_, kPeerAddress, kSelfAddress,
7063 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07007064 Perspective::IS_SERVER, version(),
7065 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04007066 TestConnection client(connection_id_, kSelfAddress, kPeerAddress,
7067 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07007068 Perspective::IS_CLIENT, version(),
7069 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04007070 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7071 static_cast<const QuicSentPacketManager*>(
7072 &client.sent_packet_manager())));
7073 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7074 static_cast<const QuicSentPacketManager*>(
7075 &server.sent_packet_manager())));
7076}
7077
7078TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7079 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7080
7081 // Send a WINDOW_UPDATE frame.
7082 QuicWindowUpdateFrame window_update;
7083 window_update.stream_id = 3;
7084 window_update.max_data = 1234;
7085 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7086 ProcessFramePacket(QuicFrame(window_update));
7087
7088 // Ensure that this has caused the ACK alarm to be set.
7089 EXPECT_TRUE(connection_.HasPendingAcks());
7090}
7091
7092TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7093 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7094
7095 // Send a BLOCKED frame.
7096 QuicBlockedFrame blocked;
7097 blocked.stream_id = 3;
7098 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7099 ProcessFramePacket(QuicFrame(blocked));
7100
7101 // Ensure that this has caused the ACK alarm to be set.
7102 EXPECT_TRUE(connection_.HasPendingAcks());
7103}
7104
7105TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7106 // Enable pacing.
7107 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7108 QuicConfig config;
7109 connection_.SetFromConfig(config);
7110
7111 // Send two packets. One packet is not sufficient because if it gets acked,
7112 // there will be no packets in flight after that and the pacer will always
7113 // allow the next packet in that situation.
7114 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7115 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7116 connection_.SendStreamDataWithString(
7117 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7118 0, NO_FIN);
7119 connection_.SendStreamDataWithString(
7120 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7121 3, NO_FIN);
7122 connection_.OnCanWrite();
7123
7124 // Schedule the next packet for a few milliseconds in future.
7125 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7126 QuicTime scheduled_pacing_time =
7127 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7128 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7129 scheduled_pacing_time);
7130
7131 // Send a packet and have it be blocked by congestion control.
7132 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7133 connection_.SendStreamDataWithString(
7134 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7135 6, NO_FIN);
7136 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7137
7138 // Process an ack and the send alarm will be set to the new 5ms delay.
7139 QuicAckFrame ack = InitAckFrame(1);
7140 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07007141 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007142 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7143 ProcessAckPacket(&ack);
7144 size_t padding_frame_count = writer_->padding_frames().size();
7145 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
7146 EXPECT_EQ(1u, writer_->stream_frames().size());
7147 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7148 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7149 writer_->Reset();
7150}
7151
7152TEST_P(QuicConnectionTest, SendAcksImmediately) {
7153 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7154 return;
7155 }
7156 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7157 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7158 ProcessDataPacket(1);
7159 CongestionBlockWrites();
7160 SendAckPacketToPeer();
7161}
7162
7163TEST_P(QuicConnectionTest, SendPingImmediately) {
7164 MockQuicConnectionDebugVisitor debug_visitor;
7165 connection_.set_debug_visitor(&debug_visitor);
7166
7167 CongestionBlockWrites();
7168 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7169 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wub92727922023-07-13 08:47:39 -07007170 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007171 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7172 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7173 EXPECT_FALSE(connection_.HasQueuedData());
7174}
7175
7176TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7177 MockQuicConnectionDebugVisitor debug_visitor;
7178 connection_.set_debug_visitor(&debug_visitor);
7179
7180 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7181 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wub92727922023-07-13 08:47:39 -07007182 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007183 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
QUICHE team1a271082022-05-18 10:22:22 -07007184 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04007185 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7186 EXPECT_FALSE(connection_.HasQueuedData());
7187}
7188
7189TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7190 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7191 return;
7192 }
7193 MockQuicConnectionDebugVisitor debug_visitor;
7194 connection_.set_debug_visitor(&debug_visitor);
QUICHE team1a271082022-05-18 10:22:22 -07007195 QuicBlockedFrame blocked(1, 3, 0);
Bence Békybac04052022-04-07 15:44:29 -04007196
7197 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
wub92727922023-07-13 08:47:39 -07007198 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(0);
Bence Békybac04052022-04-07 15:44:29 -04007199 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7200 connection_.SendControlFrame(QuicFrame(blocked));
7201 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7202 EXPECT_FALSE(connection_.HasQueuedData());
7203}
7204
7205TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7206 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7207 if (!IsDefaultTestConfiguration()) {
7208 return;
7209 }
7210
vasilvvac2e30d2022-06-02 14:26:59 -07007211 EXPECT_QUIC_BUG(
7212 {
7213 EXPECT_CALL(visitor_,
7214 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7215 .WillOnce(
7216 Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7217 connection_.SaveAndSendStreamData(3, {}, 0, FIN);
7218 EXPECT_FALSE(connection_.connected());
7219 EXPECT_EQ(1, connection_close_frame_count_);
7220 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7221 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
7222 },
7223 "Cannot send stream data with level: ENCRYPTION_INITIAL");
Bence Békybac04052022-04-07 15:44:29 -04007224}
7225
7226TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7227 EXPECT_TRUE(connection_.connected());
7228 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7229
7230 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7231 connection_.SendCryptoStreamData();
7232
7233 // Verify retransmission timer is correctly set after crypto packet has been
7234 // sent.
7235 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7236 QuicTime retransmission_time =
7237 QuicConnectionPeer::GetSentPacketManager(&connection_)
7238 ->GetRetransmissionTime();
7239 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7240 EXPECT_EQ(retransmission_time,
7241 connection_.GetRetransmissionAlarm()->deadline());
7242
7243 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7244 connection_.GetRetransmissionAlarm()->Fire();
7245}
7246
7247// Includes regression test for b/69979024.
7248TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
7249 EXPECT_TRUE(connection_.connected());
7250 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7251 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007252 EXPECT_CALL(visitor_, GetHandshakeState())
7253 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7254 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007255
7256 const char data[] = "data";
7257 size_t data_size = strlen(data);
7258 QuicStreamOffset offset = 0;
7259
7260 for (int i = 0; i < 2; ++i) {
7261 // Send a packet. Now there's a retransmittable packet on the wire, so the
7262 // path degrading detection should be set.
7263 connection_.SendStreamDataWithString(
7264 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7265 offset, NO_FIN);
7266 offset += data_size;
7267 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7268 // Check the deadline of the path degrading detection.
7269 QuicTime::Delta delay =
7270 QuicConnectionPeer::GetSentPacketManager(&connection_)
7271 ->GetPathDegradingDelay();
7272 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7273 clock_.ApproximateNow());
7274
7275 // Send a second packet. The path degrading detection's deadline should
7276 // remain the same.
7277 // Regression test for b/69979024.
7278 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7279 QuicTime prev_deadline =
7280 connection_.GetBlackholeDetectorAlarm()->deadline();
7281 connection_.SendStreamDataWithString(
7282 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7283 offset, NO_FIN);
7284 offset += data_size;
7285 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7286 EXPECT_EQ(prev_deadline,
7287 connection_.GetBlackholeDetectorAlarm()->deadline());
7288
7289 // Now receive an ACK of the first packet. This should advance the path
7290 // degrading detection's deadline since forward progress has been made.
7291 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7292 if (i == 0) {
7293 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7294 }
martindukeba002452023-03-21 08:10:46 -07007295 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007296 QuicAckFrame frame = InitAckFrame(
7297 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7298 ProcessAckPacket(&frame);
7299 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7300 // Check the deadline of the path degrading detection.
7301 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7302 ->GetPathDegradingDelay();
7303 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7304 clock_.ApproximateNow());
7305
7306 if (i == 0) {
7307 // Now receive an ACK of the second packet. Since there are no more
7308 // retransmittable packets on the wire, this should cancel the path
7309 // degrading detection.
7310 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007311 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007312 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7313 ProcessAckPacket(&frame);
7314 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7315 } else {
7316 // Advance time to the path degrading alarm's deadline and simulate
7317 // firing the alarm.
7318 clock_.AdvanceTime(delay);
7319 EXPECT_CALL(visitor_, OnPathDegrading());
7320 connection_.PathDegradingTimeout();
7321 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7322 }
7323 }
7324 EXPECT_TRUE(connection_.IsPathDegrading());
7325}
7326
7327TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7328 const QuicTime::Delta retransmittable_on_wire_timeout =
7329 QuicTime::Delta::FromMilliseconds(50);
7330 connection_.set_initial_retransmittable_on_wire_timeout(
7331 retransmittable_on_wire_timeout);
7332
7333 EXPECT_TRUE(connection_.connected());
7334 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7335 .WillRepeatedly(Return(true));
7336
7337 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7338 EXPECT_FALSE(connection_.IsPathDegrading());
7339 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
fayang59e518a2022-11-29 11:16:45 -08007340 EXPECT_CALL(visitor_, GetHandshakeState())
7341 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7342 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007343
7344 const char data[] = "data";
7345 size_t data_size = strlen(data);
7346 QuicStreamOffset offset = 0;
7347
7348 // Send a packet.
7349 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7350 offset += data_size;
7351 // Now there's a retransmittable packet on the wire, so the path degrading
7352 // alarm should be set.
7353 // The retransmittable-on-wire alarm should not be set.
7354 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7355 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7356 ->GetPathDegradingDelay();
7357 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7358 clock_.ApproximateNow());
7359 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7360 // The ping alarm is set for the ping timeout, not the shorter
7361 // retransmittable_on_wire_timeout.
7362 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7363 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7364 EXPECT_EQ(ping_delay,
7365 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7366
7367 // Now receive an ACK of the packet.
7368 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7369 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007370 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007371 QuicAckFrame frame =
7372 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7373 ProcessAckPacket(&frame);
7374 // No more retransmittable packets on the wire, so the path degrading alarm
7375 // should be cancelled, and the ping alarm should be set to the
7376 // retransmittable_on_wire_timeout.
7377 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7378 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7379 EXPECT_EQ(retransmittable_on_wire_timeout,
7380 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7381
7382 // Simulate firing the ping alarm and sending a PING.
7383 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7384 connection_.GetPingAlarm()->Fire();
7385
7386 // Now there's a retransmittable packet (PING) on the wire, so the path
7387 // degrading alarm should be set.
fayang59e518a2022-11-29 11:16:45 -08007388 ASSERT_TRUE(connection_.PathDegradingDetectionInProgress());
Bence Békybac04052022-04-07 15:44:29 -04007389 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7390 ->GetPathDegradingDelay();
7391 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7392 clock_.ApproximateNow());
7393}
7394
7395TEST_P(QuicConnectionTest, ServerRetransmittableOnWire) {
7396 set_perspective(Perspective::IS_SERVER);
7397 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7398 SetQuicReloadableFlag(quic_enable_server_on_wire_ping, true);
7399
7400 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7401 QuicConfig config;
7402 QuicTagVector connection_options;
7403 connection_options.push_back(kSRWP);
7404 config.SetInitialReceivedConnectionOptions(connection_options);
7405 connection_.SetFromConfig(config);
7406
7407 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7408 .WillRepeatedly(Return(true));
7409
7410 ProcessPacket(1);
7411
7412 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7413 QuicTime::Delta ping_delay = QuicTime::Delta::FromMilliseconds(200);
7414 EXPECT_EQ(ping_delay,
7415 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7416
7417 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
7418 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
7419 // Verify PING alarm gets cancelled.
7420 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7421
7422 // Now receive an ACK of the packet.
7423 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
martindukeba002452023-03-21 08:10:46 -07007424 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007425 QuicAckFrame frame =
7426 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7427 ProcessAckPacket(2, &frame);
7428 // Verify PING alarm gets scheduled.
7429 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7430 EXPECT_EQ(ping_delay,
7431 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7432}
7433
fayangf6607db2022-04-21 18:10:41 -07007434TEST_P(QuicConnectionTest, RetransmittableOnWireSendFirstPacket) {
fayang9b455102022-11-29 18:19:20 -08007435 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007436 return;
7437 }
7438 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7439 .WillRepeatedly(Return(true));
7440 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7441
7442 const QuicTime::Delta kRetransmittableOnWireTimeout =
7443 QuicTime::Delta::FromMilliseconds(200);
7444 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7445
7446 connection_.set_initial_retransmittable_on_wire_timeout(
7447 kRetransmittableOnWireTimeout);
7448
7449 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7450 QuicConfig config;
7451 QuicTagVector connection_options;
7452 connection_options.push_back(kROWF);
7453 config.SetClientConnectionOptions(connection_options);
7454 connection_.SetFromConfig(config);
7455
7456 // Send a request.
7457 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7458 // Receive an ACK after 1-RTT.
7459 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007460 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007461 QuicAckFrame frame =
7462 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7463 ProcessAckPacket(&frame);
7464 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7465 EXPECT_EQ(kRetransmittableOnWireTimeout,
7466 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7467 EXPECT_EQ(1u, writer_->packets_write_attempts());
7468
7469 // Fire retransmittable-on-wire alarm.
7470 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7471 connection_.GetPingAlarm()->Fire();
7472 EXPECT_EQ(2u, writer_->packets_write_attempts());
7473 // Verify alarm is set in keep-alive mode.
7474 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7475 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7476 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7477}
7478
7479TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytes) {
fayang9b455102022-11-29 18:19:20 -08007480 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007481 return;
7482 }
7483 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7484 .WillRepeatedly(Return(true));
7485 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7486
7487 const QuicTime::Delta kRetransmittableOnWireTimeout =
7488 QuicTime::Delta::FromMilliseconds(200);
7489 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7490
7491 connection_.set_initial_retransmittable_on_wire_timeout(
7492 kRetransmittableOnWireTimeout);
7493
7494 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7495 QuicConfig config;
7496 QuicTagVector connection_options;
7497 connection_options.push_back(kROWR);
7498 config.SetClientConnectionOptions(connection_options);
7499 connection_.SetFromConfig(config);
7500
7501 // Send a request.
7502 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7503 // Receive an ACK after 1-RTT.
7504 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007505 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007506 QuicAckFrame frame =
7507 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7508 ProcessAckPacket(&frame);
7509 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7510 EXPECT_EQ(kRetransmittableOnWireTimeout,
7511 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7512 EXPECT_EQ(1u, writer_->packets_write_attempts());
7513
7514 // Fire retransmittable-on-wire alarm.
7515 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7516 // Next packet is not processable by the framer in the test writer.
7517 ExpectNextPacketUnprocessable();
7518 connection_.GetPingAlarm()->Fire();
7519 EXPECT_EQ(2u, writer_->packets_write_attempts());
7520 // Verify alarm is set in keep-alive mode.
7521 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7522 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7523 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7524}
7525
7526TEST_P(QuicConnectionTest,
7527 RetransmittableOnWireSendRandomBytesWithWriterBlocked) {
fayang9b455102022-11-29 18:19:20 -08007528 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007529 return;
7530 }
7531 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7532 .WillRepeatedly(Return(true));
7533 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7534 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7535
7536 const QuicTime::Delta kRetransmittableOnWireTimeout =
7537 QuicTime::Delta::FromMilliseconds(200);
7538 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7539
7540 connection_.set_initial_retransmittable_on_wire_timeout(
7541 kRetransmittableOnWireTimeout);
7542
7543 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7544 QuicConfig config;
7545 QuicTagVector connection_options;
7546 connection_options.push_back(kROWR);
7547 config.SetClientConnectionOptions(connection_options);
7548 connection_.SetFromConfig(config);
7549
7550 // Send a request.
7551 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7552 // Receive an ACK after 1-RTT.
7553 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007554 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007555 QuicAckFrame frame =
7556 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7557 ProcessAckPacket(&frame);
7558 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7559 EXPECT_EQ(kRetransmittableOnWireTimeout,
7560 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7561 EXPECT_EQ(1u, writer_->packets_write_attempts());
7562 // Receive an out of order data packet and block the ACK packet.
7563 BlockOnNextWrite();
7564 ProcessDataPacket(3);
7565 EXPECT_EQ(2u, writer_->packets_write_attempts());
7566 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7567
7568 // Fire retransmittable-on-wire alarm.
7569 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7570 connection_.GetPingAlarm()->Fire();
7571 // Verify the random bytes packet gets queued.
7572 EXPECT_EQ(2u, connection_.NumQueuedPackets());
7573}
7574
Bence Békybac04052022-04-07 15:44:29 -04007575// This test verifies that the connection marks path as degrading and does not
7576// spin timer to detect path degrading when a new packet is sent on the
7577// degraded path.
7578TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
7579 EXPECT_TRUE(connection_.connected());
7580 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7581 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007582 EXPECT_CALL(visitor_, GetHandshakeState())
7583 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7584 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007585
7586 const char data[] = "data";
7587 size_t data_size = strlen(data);
7588 QuicStreamOffset offset = 0;
7589
7590 // Send the first packet. Now there's a retransmittable packet on the wire, so
7591 // the path degrading alarm should be set.
7592 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7593 offset += data_size;
7594 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7595 // Check the deadline of the path degrading detection.
7596 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7597 ->GetPathDegradingDelay();
7598 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7599 clock_.ApproximateNow());
7600
7601 // Send a second packet. The path degrading detection's deadline should remain
7602 // the same.
7603 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7604 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7605 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7606 offset += data_size;
7607 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7608 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7609
7610 // Now receive an ACK of the first packet. This should advance the path
7611 // degrading detection's deadline since forward progress has been made.
7612 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7613 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007614 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007615 QuicAckFrame frame =
7616 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7617 ProcessAckPacket(&frame);
7618 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7619 // Check the deadline of the path degrading alarm.
7620 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7621 ->GetPathDegradingDelay();
7622 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7623 clock_.ApproximateNow());
7624
7625 // Advance time to the path degrading detection's deadline and simulate
7626 // firing the path degrading detection. This path will be considered as
7627 // degrading.
7628 clock_.AdvanceTime(delay);
7629 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7630 connection_.PathDegradingTimeout();
7631 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7632 EXPECT_TRUE(connection_.IsPathDegrading());
7633
7634 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7635 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7636 // Send a third packet. The path degrading detection is no longer set but path
7637 // should still be marked as degrading.
7638 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7639 offset += data_size;
7640 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7641 EXPECT_TRUE(connection_.IsPathDegrading());
7642}
7643
fayang59e518a2022-11-29 11:16:45 -08007644TEST_P(QuicConnectionTest, NoPathDegradingDetectionBeforeHandshakeConfirmed) {
7645 EXPECT_TRUE(connection_.connected());
7646 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7647 EXPECT_FALSE(connection_.IsPathDegrading());
7648 EXPECT_CALL(visitor_, GetHandshakeState())
7649 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
7650
7651 connection_.SendStreamDataWithString(1, "data", 0, NO_FIN);
7652 if (GetQuicReloadableFlag(
7653 quic_no_path_degrading_before_handshake_confirmed) &&
7654 connection_.SupportsMultiplePacketNumberSpaces()) {
7655 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7656 } else {
7657 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7658 }
7659}
7660
Bence Békybac04052022-04-07 15:44:29 -04007661// This test verifies that the connection unmarks path as degrarding and spins
7662// the timer to detect future path degrading when forward progress is made
7663// after path has been marked degrading.
7664TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7665 EXPECT_TRUE(connection_.connected());
7666 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7667 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007668 EXPECT_CALL(visitor_, GetHandshakeState())
7669 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7670 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007671
7672 const char data[] = "data";
7673 size_t data_size = strlen(data);
7674 QuicStreamOffset offset = 0;
7675
7676 // Send the first packet. Now there's a retransmittable packet on the wire, so
7677 // the path degrading alarm should be set.
7678 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7679 offset += data_size;
7680 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7681 // Check the deadline of the path degrading alarm.
7682 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7683 ->GetPathDegradingDelay();
7684 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7685 clock_.ApproximateNow());
7686
7687 // Send a second packet. The path degrading alarm's deadline should remain
7688 // the same.
7689 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7690 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7691 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7692 offset += data_size;
7693 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7694 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7695
7696 // Now receive an ACK of the first packet. This should advance the path
7697 // degrading alarm's deadline since forward progress has been made.
7698 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7699 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007700 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007701 QuicAckFrame frame =
7702 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7703 ProcessAckPacket(&frame);
7704 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7705 // Check the deadline of the path degrading alarm.
7706 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7707 ->GetPathDegradingDelay();
7708 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7709 clock_.ApproximateNow());
7710
7711 // Advance time to the path degrading alarm's deadline and simulate
7712 // firing the alarm.
7713 clock_.AdvanceTime(delay);
7714 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7715 connection_.PathDegradingTimeout();
7716 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7717 EXPECT_TRUE(connection_.IsPathDegrading());
7718
7719 // Send a third packet. The path degrading alarm is no longer set but path
7720 // should still be marked as degrading.
7721 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7722 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7723 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7724 offset += data_size;
7725 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7726 EXPECT_TRUE(connection_.IsPathDegrading());
7727
7728 // Now receive an ACK of the second packet. This should unmark the path as
7729 // degrading. And will set a timer to detect new path degrading.
7730 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007731 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007732 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
7733 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7734 ProcessAckPacket(&frame);
renjietang201bfa52023-04-24 18:12:27 -07007735 EXPECT_EQ(1,
7736 connection_.GetStats().num_forward_progress_after_path_degrading);
Bence Békybac04052022-04-07 15:44:29 -04007737 EXPECT_FALSE(connection_.IsPathDegrading());
7738 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7739}
7740
7741TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
7742 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7743 return;
7744 }
7745 set_perspective(Perspective::IS_SERVER);
7746 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7747
7748 EXPECT_FALSE(connection_.IsPathDegrading());
7749 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7750
7751 // Send data.
7752 const char data[] = "data";
7753 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7754 EXPECT_FALSE(connection_.IsPathDegrading());
7755 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7756
7757 // Ack data.
7758 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007759 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007760 QuicAckFrame frame =
7761 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7762 ProcessAckPacket(&frame);
7763 EXPECT_FALSE(connection_.IsPathDegrading());
7764 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7765}
7766
7767TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
7768 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7769 return;
7770 }
7771 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7772 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7773 ProcessDataPacket(1);
7774 SendAckPacketToPeer();
7775 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7776 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7777 EXPECT_FALSE(connection_.IsPathDegrading());
7778 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7779}
7780
7781TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7782 // Verifies that multiple calls to CloseConnection do not
7783 // result in multiple attempts to close the connection - it will be marked as
7784 // disconnected after the first call.
7785 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
7786 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7787 ConnectionCloseBehavior::SILENT_CLOSE);
7788 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7789 ConnectionCloseBehavior::SILENT_CLOSE);
7790}
7791
7792TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7793 set_perspective(Perspective::IS_SERVER);
7794 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang161ce6e2022-07-01 18:02:11 -07007795 QuicConnectionPeer::SetAddressValidated(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04007796
7797 CryptoHandshakeMessage message;
7798 CryptoFramer framer;
7799 message.set_tag(kCHLO);
7800 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7801 frame1_.stream_id = 10;
7802 frame1_.data_buffer = data->data();
7803 frame1_.data_length = data->length();
7804
7805 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7806 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7807 }
7808 EXPECT_CALL(visitor_,
7809 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7810 ForceProcessFramePacket(QuicFrame(frame1_));
7811 if (VersionHasIetfQuicFrames(version().transport_version)) {
7812 // INITIAL packet should not contain STREAM frame.
7813 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7814 } else {
7815 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7816 }
7817}
7818
7819TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7820 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7821
7822 CryptoHandshakeMessage message;
7823 CryptoFramer framer;
7824 message.set_tag(kREJ);
7825 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7826 frame1_.stream_id = 10;
7827 frame1_.data_buffer = data->data();
7828 frame1_.data_length = data->length();
7829
7830 EXPECT_CALL(visitor_,
7831 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7832 ForceProcessFramePacket(QuicFrame(frame1_));
7833 if (VersionHasIetfQuicFrames(version().transport_version)) {
7834 // INITIAL packet should not contain STREAM frame.
7835 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7836 } else {
7837 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7838 }
7839}
7840
7841TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7842 SimulateNextPacketTooLarge();
7843 // A connection close packet is sent
7844 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7845 .Times(1);
7846 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7847 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7848}
7849
7850TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7851 // Test even we always get packet too large, we do not infinitely try to send
7852 // close packet.
7853 AlwaysGetPacketTooLarge();
7854 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7855 .Times(1);
7856 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7857 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7858}
7859
7860TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
7861 // Regression test for crbug.com/979507.
7862 //
7863 // If we get a write error when writing queued packets, we should attempt to
7864 // send a connection close packet, but if sending that fails, it shouldn't get
7865 // queued.
7866
7867 // Queue a packet to write.
7868 BlockOnNextWrite();
7869 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7870 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7871
7872 // Configure writer to always fail.
7873 AlwaysGetPacketTooLarge();
7874
7875 // Expect that we attempt to close the connection exactly once.
7876 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7877 .Times(1);
7878
7879 // Unblock the writes and actually send.
7880 writer_->SetWritable();
7881 connection_.OnCanWrite();
7882 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7883
7884 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7885}
7886
7887// Verify that if connection has no outstanding data, it notifies the send
7888// algorithm after the write.
7889TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7890 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7891 {
7892 InSequence seq;
7893 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7894 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7895 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7896 .WillRepeatedly(Return(false));
7897 }
7898
7899 connection_.SendStreamData3();
7900}
7901
7902// Verify that the connection does not become app-limited if there is
7903// outstanding data to send after the write.
7904TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7905 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7906 {
7907 InSequence seq;
7908 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7909 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7910 }
7911
7912 connection_.SendStreamData3();
7913}
7914
7915// Verify that the connection does not become app-limited after blocked write
7916// even if there is outstanding data to send after the write.
7917TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7918 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7919 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7920 BlockOnNextWrite();
7921
7922 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7923 connection_.SendStreamData3();
7924
7925 // Now unblock the writer, become congestion control blocked,
7926 // and ensure we become app-limited after writing.
7927 writer_->SetWritable();
7928 CongestionBlockWrites();
7929 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7930 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7931 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7932 connection_.OnCanWrite();
7933}
7934
Bence Békybac04052022-04-07 15:44:29 -04007935TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
7936 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7937 // Send an ack by simulating delayed ack alarm firing.
7938 ProcessPacket(1);
7939 EXPECT_TRUE(connection_.HasPendingAcks());
7940 connection_.GetAckAlarm()->Fire();
7941 // Simulate data packet causes write error.
7942 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7943 SimulateNextPacketTooLarge();
7944 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7945 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7946 // Ack frame is not bundled in connection close packet.
7947 EXPECT_TRUE(writer_->ack_frames().empty());
7948 if (writer_->padding_frames().empty()) {
7949 EXPECT_EQ(1u, writer_->frame_count());
7950 } else {
7951 EXPECT_EQ(2u, writer_->frame_count());
7952 }
7953
7954 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7955}
7956
7957TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
7958 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7959 return;
7960 }
7961
7962 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7963 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7964 connection_.CloseConnection(
7965 kQuicErrorCode, "Some random error message",
7966 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7967
7968 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7969
7970 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7971 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7972
7973 if (!connection_.version().CanSendCoalescedPackets()) {
7974 // Each connection close packet should be sent in distinct UDP packets.
7975 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7976 writer_->connection_close_packets());
7977 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7978 writer_->packets_write_attempts());
7979 return;
7980 }
7981
7982 // A single UDP packet should be sent with multiple connection close packets
7983 // coalesced together.
7984 EXPECT_EQ(1u, writer_->packets_write_attempts());
7985
7986 // Only the first packet has been processed yet.
7987 EXPECT_EQ(1u, writer_->connection_close_packets());
7988
7989 // ProcessPacket resets the visitor and frees the coalesced packet.
7990 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
7991 auto packet = writer_->coalesced_packet()->Clone();
7992 writer_->framer()->ProcessPacket(*packet);
7993 EXPECT_EQ(1u, writer_->connection_close_packets());
7994 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7995}
7996
7997TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
7998 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7999 return;
8000 }
8001
8002 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8003 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8004 connection_.CloseConnection(
8005 kQuicErrorCode, "Some random error message",
8006 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8007
8008 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8009
8010 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8011 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8012 EXPECT_EQ(1u, writer_->connection_close_packets());
8013 EXPECT_EQ(1u, writer_->packets_write_attempts());
8014 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8015}
8016
8017TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8018 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8019 return;
8020 }
8021 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07008022 // Receives packet 1000 in initial data.
8023 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8024 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -04008025
8026 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
8027 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
8028 }
8029 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8030 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8031 connection_.CloseConnection(
8032 kQuicErrorCode, "Some random error message",
8033 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8034
8035 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8036
8037 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8038 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8039 EXPECT_TRUE(writer_->padding_frames().empty());
8040 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8041}
8042
8043// Regression test for b/63620844.
8044TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8045 SimulateNextPacketTooLarge();
8046 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8047 .Times(1);
8048
8049 connection_.SendCryptoStreamData();
8050 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8051}
8052
8053TEST_P(QuicConnectionTest, MaxPacingRate) {
8054 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8055 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8056 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8057}
8058
8059TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8060 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8061 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8062 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8063 EXPECT_EQ(CONNECTION_ID_PRESENT,
8064 writer_->last_packet_header().destination_connection_id_included);
8065
8066 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8067 QuicConfig config;
8068 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8069 connection_.SetFromConfig(config);
8070
8071 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8072 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8073 // Verify connection id is still sent in the packet.
8074 EXPECT_EQ(CONNECTION_ID_PRESENT,
8075 writer_->last_packet_header().destination_connection_id_included);
8076}
8077
Bence Békybac04052022-04-07 15:44:29 -04008078TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8079 const QuicTime::Delta retransmittable_on_wire_timeout =
8080 QuicTime::Delta::FromMilliseconds(50);
8081 connection_.set_initial_retransmittable_on_wire_timeout(
8082 retransmittable_on_wire_timeout);
8083
8084 EXPECT_TRUE(connection_.connected());
8085 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8086 .WillRepeatedly(Return(true));
8087
8088 const char data[] = "data";
8089 size_t data_size = strlen(data);
8090 QuicStreamOffset offset = 0;
8091
8092 // Advance 5ms, send a retransmittable packet to the peer.
8093 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8094 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8095 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8096 offset += data_size;
8097 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8098 // The ping alarm is set for the ping timeout, not the shorter
8099 // retransmittable_on_wire_timeout.
8100 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8101 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8102 EXPECT_EQ(ping_delay,
8103 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8104
8105 // Advance 5ms, send a second retransmittable packet to the peer.
8106 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8107 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8108 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8109 offset += data_size;
8110 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8111
8112 // Now receive an ACK of the first packet. This should not set the
8113 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8114 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8115 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07008116 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008117 QuicAckFrame frame =
8118 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8119 ProcessAckPacket(&frame);
8120 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8121 // The ping alarm is set for the ping timeout, not the shorter
8122 // retransmittable_on_wire_timeout.
8123 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8124 // The ping alarm has a 1 second granularity, and the clock has been advanced
8125 // 10ms since it was originally set.
8126 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8127 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8128
8129 // Now receive an ACK of the second packet. This should set the
8130 // retransmittable-on-wire alarm now that no retransmittable packets are on
8131 // the wire.
8132 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07008133 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008134 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8135 ProcessAckPacket(&frame);
8136 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8137 EXPECT_EQ(retransmittable_on_wire_timeout,
8138 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8139
8140 // Now receive a duplicate ACK of the second packet. This should not update
8141 // the ping alarm.
8142 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8143 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8144 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8145 ProcessAckPacket(&frame);
8146 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8147 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8148
8149 // Now receive a non-ACK packet. This should not update the ping alarm.
8150 prev_deadline = connection_.GetPingAlarm()->deadline();
8151 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8152 ProcessPacket(4);
8153 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8154 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8155
8156 // Simulate the alarm firing and check that a PING is sent.
8157 connection_.GetPingAlarm()->Fire();
8158 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07008159 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04008160 ASSERT_EQ(1u, writer_->ping_frames().size());
8161}
8162
8163TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8164 const QuicTime::Delta retransmittable_on_wire_timeout =
8165 QuicTime::Delta::FromMilliseconds(50);
8166 connection_.set_initial_retransmittable_on_wire_timeout(
8167 retransmittable_on_wire_timeout);
8168
8169 EXPECT_TRUE(connection_.connected());
8170 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8171 .WillRepeatedly(Return(true));
8172
8173 const char data[] = "data";
8174 size_t data_size = strlen(data);
8175 QuicStreamOffset offset = 0;
8176
8177 // Advance 5ms, send a retransmittable packet to the peer.
8178 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8179 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8180 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8181 offset += data_size;
8182 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8183 // The ping alarm is set for the ping timeout, not the shorter
8184 // retransmittable_on_wire_timeout.
8185 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8186 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8187 EXPECT_EQ(ping_delay,
8188 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8189
8190 // Now receive an ACK of the first packet. This should set the
8191 // retransmittable-on-wire alarm now that no retransmittable packets are on
8192 // the wire.
8193 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8194 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07008195 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008196 QuicAckFrame frame =
8197 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8198 ProcessAckPacket(&frame);
8199 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8200 EXPECT_EQ(retransmittable_on_wire_timeout,
8201 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8202
8203 // Before the alarm fires, send another retransmittable packet. This should
8204 // cancel the retransmittable-on-wire alarm since now there's a
8205 // retransmittable packet on the wire.
8206 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8207 offset += data_size;
8208 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8209
8210 // Now receive an ACK of the second packet. This should set the
8211 // retransmittable-on-wire alarm now that no retransmittable packets are on
8212 // the wire.
8213 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07008214 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008215 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8216 ProcessAckPacket(&frame);
8217 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8218 EXPECT_EQ(retransmittable_on_wire_timeout,
8219 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8220
8221 // Simulate the alarm firing and check that a PING is sent.
8222 writer_->Reset();
8223 connection_.GetPingAlarm()->Fire();
8224 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07008225 // Do not ACK acks.
8226 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04008227 ASSERT_EQ(1u, writer_->ping_frames().size());
8228}
8229
8230// When there is no stream data received but are open streams, send the
8231// first few consecutive pings with aggressive retransmittable-on-wire
8232// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8233// afterwards until it exceeds the default ping timeout.
8234TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8235 int max_aggressive_retransmittable_on_wire_ping_count = 5;
birenroyef686222022-09-12 11:34:34 -07008236 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008237 max_aggressive_retransmittable_on_wire_ping_count);
8238 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8239 QuicTime::Delta::FromMilliseconds(200);
8240 connection_.set_initial_retransmittable_on_wire_timeout(
8241 initial_retransmittable_on_wire_timeout);
8242
8243 EXPECT_TRUE(connection_.connected());
8244 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8245 .WillRepeatedly(Return(true));
8246
8247 const char data[] = "data";
8248 // Advance 5ms, send a retransmittable data packet to the peer.
8249 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8250 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8251 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8252 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8253 // The ping alarm is set for the ping timeout, not the shorter
8254 // retransmittable_on_wire_timeout.
8255 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008256 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008257 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8258
8259 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008260 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008261 .Times(AnyNumber());
8262
8263 // Verify that the first few consecutive retransmittable on wire pings are
8264 // sent with aggressive timeout.
8265 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8266 // Receive an ACK of the previous packet. This should set the ping alarm
8267 // with the initial retransmittable-on-wire timeout.
8268 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8269 QuicPacketNumber ack_num = creator_->packet_number();
8270 QuicAckFrame frame = InitAckFrame(
8271 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8272 ProcessAckPacket(&frame);
8273 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8274 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8275 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8276 // Simulate the alarm firing and check that a PING is sent.
8277 writer_->Reset();
8278 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8279 connection_.GetPingAlarm()->Fire();
8280 }
8281
8282 QuicTime::Delta retransmittable_on_wire_timeout =
8283 initial_retransmittable_on_wire_timeout;
8284
8285 // Verify subsequent pings are sent with timeout that is exponentially backed
8286 // off.
fayang5d393332022-04-18 13:34:54 -07008287 while (retransmittable_on_wire_timeout * 2 <
8288 QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) {
Bence Békybac04052022-04-07 15:44:29 -04008289 // Receive an ACK for the previous PING. This should set the
8290 // ping alarm with backed off retransmittable-on-wire timeout.
8291 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8292 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8293 QuicPacketNumber ack_num = creator_->packet_number();
8294 QuicAckFrame frame = InitAckFrame(
8295 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8296 ProcessAckPacket(&frame);
8297 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8298 EXPECT_EQ(retransmittable_on_wire_timeout,
8299 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8300
8301 // Simulate the alarm firing and check that a PING is sent.
8302 writer_->Reset();
8303 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8304 connection_.GetPingAlarm()->Fire();
8305 }
8306
8307 // The ping alarm is set with default ping timeout.
8308 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008309 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008310 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8311
8312 // Receive an ACK for the previous PING. The ping alarm is set with an
8313 // earlier deadline.
8314 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8315 QuicPacketNumber ack_num = creator_->packet_number();
8316 QuicAckFrame frame = InitAckFrame(
8317 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8318 ProcessAckPacket(&frame);
8319 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008320 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) -
8321 QuicTime::Delta::FromMilliseconds(5),
Bence Békybac04052022-04-07 15:44:29 -04008322 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8323}
8324
8325// This test verify that the count of consecutive aggressive pings is reset
8326// when new data is received. And it also verifies the connection resets
8327// the exponential back-off of the retransmittable-on-wire ping timeout
8328// after receiving new stream data.
8329TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8330 int max_aggressive_retransmittable_on_wire_ping_count = 3;
birenroyef686222022-09-12 11:34:34 -07008331 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
Bence Békybac04052022-04-07 15:44:29 -04008332 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8333 QuicTime::Delta::FromMilliseconds(200);
8334 connection_.set_initial_retransmittable_on_wire_timeout(
8335 initial_retransmittable_on_wire_timeout);
8336
8337 EXPECT_TRUE(connection_.connected());
8338 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8339 .WillRepeatedly(Return(true));
8340 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008341 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008342 .Times(AnyNumber());
8343
8344 const char data[] = "data";
8345 // Advance 5ms, send a retransmittable data packet to the peer.
8346 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8347 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8348 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8349 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8350 // The ping alarm is set for the ping timeout, not the shorter
8351 // retransmittable_on_wire_timeout.
8352 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008353 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008354 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8355
8356 // Receive an ACK of the first packet. This should set the ping alarm with
8357 // initial retransmittable-on-wire timeout since there is no retransmittable
8358 // packet on the wire.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008359 {
8360 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8361 QuicAckFrame frame =
8362 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8363 ProcessAckPacket(&frame);
8364 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8365 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8366 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8367 }
Bence Békybac04052022-04-07 15:44:29 -04008368
8369 // Simulate the alarm firing and check that a PING is sent.
8370 writer_->Reset();
8371 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8372 connection_.GetPingAlarm()->Fire();
8373
8374 // Receive an ACK for the previous PING. Ping alarm will be set with
8375 // aggressive timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008376 {
8377 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8378 QuicPacketNumber ack_num = creator_->packet_number();
8379 QuicAckFrame frame = InitAckFrame(
8380 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8381 ProcessAckPacket(&frame);
8382 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8383 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8384 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8385 }
Bence Békybac04052022-04-07 15:44:29 -04008386
8387 // Process a data packet.
8388 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8389 ProcessDataPacket(peer_creator_.packet_number() + 1);
8390 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8391 peer_creator_.packet_number() + 1);
8392 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8393 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
fayang327663d2022-05-10 18:25:36 -07008394 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8395 connection_.GetPingAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -04008396
8397 // Verify the count of consecutive aggressive pings is reset.
8398 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8399 // Receive an ACK of the previous packet. This should set the ping alarm
8400 // with the initial retransmittable-on-wire timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008401 const QuicPacketNumber ack_num = creator_->packet_number();
Bence Békybac04052022-04-07 15:44:29 -04008402 QuicAckFrame frame = InitAckFrame(
8403 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8404 ProcessAckPacket(&frame);
8405 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8406 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8407 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8408 // Simulate the alarm firing and check that a PING is sent.
8409 writer_->Reset();
8410 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8411 connection_.GetPingAlarm()->Fire();
8412 // Advance 5ms to receive next packet.
8413 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8414 }
8415
8416 // Receive another ACK for the previous PING. This should set the
8417 // ping alarm with backed off retransmittable-on-wire timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008418 {
8419 const QuicPacketNumber ack_num = creator_->packet_number();
8420 QuicAckFrame frame = InitAckFrame(
8421 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8422 ProcessAckPacket(&frame);
8423 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8424 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8425 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8426 }
Bence Békybac04052022-04-07 15:44:29 -04008427
8428 writer_->Reset();
8429 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8430 connection_.GetPingAlarm()->Fire();
8431
8432 // Process another data packet and a new ACK packet. The ping alarm is set
8433 // with aggressive ping timeout again.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008434 {
8435 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8436 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8437 ProcessDataPacket(peer_creator_.packet_number() + 1);
8438 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8439 peer_creator_.packet_number() + 1);
8440 const QuicPacketNumber ack_num = creator_->packet_number();
8441 QuicAckFrame frame = InitAckFrame(
8442 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8443 ProcessAckPacket(&frame);
8444 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8445 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8446 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8447 }
Bence Békybac04052022-04-07 15:44:29 -04008448}
8449
8450// Make sure that we never send more retransmissible on the wire pings than
8451// the limit in FLAGS_quic_max_retransmittable_on_wire_ping_count.
8452TEST_P(QuicConnectionTest, RetransmittableOnWirePingLimit) {
8453 static constexpr int kMaxRetransmittableOnWirePingCount = 3;
birenroyef686222022-09-12 11:34:34 -07008454 SetQuicFlag(quic_max_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008455 kMaxRetransmittableOnWirePingCount);
8456 static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout =
8457 QuicTime::Delta::FromMilliseconds(200);
8458 static constexpr QuicTime::Delta short_delay =
8459 QuicTime::Delta::FromMilliseconds(5);
8460 ASSERT_LT(short_delay * 10, initial_retransmittable_on_wire_timeout);
8461 connection_.set_initial_retransmittable_on_wire_timeout(
8462 initial_retransmittable_on_wire_timeout);
8463
8464 EXPECT_TRUE(connection_.connected());
8465 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8466 .WillRepeatedly(Return(true));
8467
8468 const char data[] = "data";
8469 // Advance 5ms, send a retransmittable data packet to the peer.
8470 clock_.AdvanceTime(short_delay);
8471 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8472 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8473 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8474 // The ping alarm is set for the ping timeout, not the shorter
8475 // retransmittable_on_wire_timeout.
8476 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008477 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008478 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8479
8480 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008481 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008482 .Times(AnyNumber());
8483
8484 // Verify that the first few consecutive retransmittable on wire pings are
8485 // sent with aggressive timeout.
8486 for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) {
8487 // Receive an ACK of the previous packet. This should set the ping alarm
8488 // with the initial retransmittable-on-wire timeout.
8489 clock_.AdvanceTime(short_delay);
8490 QuicPacketNumber ack_num = creator_->packet_number();
8491 QuicAckFrame frame = InitAckFrame(
8492 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8493 ProcessAckPacket(&frame);
8494 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8495 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8496 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8497 // Simulate the alarm firing and check that a PING is sent.
8498 writer_->Reset();
8499 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8500 connection_.GetPingAlarm()->Fire();
8501 }
8502
8503 // Receive an ACK of the previous packet. This should set the ping alarm
8504 // but this time with the default ping timeout.
8505 QuicPacketNumber ack_num = creator_->packet_number();
8506 QuicAckFrame frame = InitAckFrame(
8507 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8508 ProcessAckPacket(&frame);
8509 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008510 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008511 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8512}
8513
8514TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8515 const StatelessResetToken kTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8516 0, 1, 0, 1, 0, 1, 0, 1};
8517 const StatelessResetToken kWrongTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8518 0, 1, 0, 1, 0, 1, 0, 2};
8519 QuicConfig config;
8520 // No token has been received.
8521 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8522
8523 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8524 // Token is different from received token.
8525 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8526 connection_.SetFromConfig(config);
8527 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8528
8529 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8530 connection_.SetFromConfig(config);
8531 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8532}
8533
8534TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8535 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8536 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8537 BlockOnNextWrite();
8538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8539 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8540 // This causes connection to be closed because packet 1 has not been sent yet.
8541 QuicAckFrame frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07008542 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008543 ProcessAckPacket(1, &frame);
8544 EXPECT_EQ(0, connection_close_frame_count_);
8545}
8546
8547TEST_P(QuicConnectionTest, SendMessage) {
Bence Békybac04052022-04-07 15:44:29 -04008548 if (connection_.version().UsesTls()) {
8549 QuicConfig config;
8550 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8551 &config, kMaxAcceptedDatagramFrameSize);
8552 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8553 connection_.SetFromConfig(config);
8554 }
8555 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
8556 quiche::QuicheMemSlice slice;
8557 {
8558 QuicConnection::ScopedPacketFlusher flusher(&connection_);
8559 connection_.SendStreamData3();
8560 // Send a message which cannot fit into current open packet, and 2 packets
8561 // get sent, one contains stream frame, and the other only contains the
8562 // message frame.
8563 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8564 slice = MemSliceFromString(absl::string_view(
8565 message.data(), connection_.GetCurrentLargestMessagePayload()));
8566 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8567 connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false));
8568 }
8569 // Fail to send a message if connection is congestion control blocked.
8570 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8571 slice = MemSliceFromString("message");
8572 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8573 connection_.SendMessage(2, absl::MakeSpan(&slice, 1), false));
8574
8575 // Always fail to send a message which cannot fit into one packet.
8576 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8577 slice = MemSliceFromString(absl::string_view(
8578 message.data(), connection_.GetCurrentLargestMessagePayload() + 1));
8579 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8580 connection_.SendMessage(3, absl::MakeSpan(&slice, 1), false));
8581}
8582
8583TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
martinduke225e91a2022-11-28 17:18:13 -08008584 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008585 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
8586 expected_largest_payload += 3;
8587 }
8588 if (connection_.version().HasLongHeaderLengths()) {
8589 expected_largest_payload -= 2;
8590 }
8591 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8592 expected_largest_payload -= 1;
8593 }
8594 if (connection_.version().UsesTls()) {
8595 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8596 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8597 QuicConfig config;
8598 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8599 &config, kMaxAcceptedDatagramFrameSize);
8600 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8601 connection_.SetFromConfig(config);
8602 // Verify the value post-handshake.
8603 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8604 expected_largest_payload);
8605 } else {
8606 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8607 expected_largest_payload);
8608 }
8609}
8610
8611TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
martinduke225e91a2022-11-28 17:18:13 -08008612 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008613 if (connection_.version().HasLongHeaderLengths()) {
8614 expected_largest_payload -= 2;
8615 }
8616 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8617 expected_largest_payload -= 1;
8618 }
8619 if (connection_.version().UsesTls()) {
8620 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8621 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8622 QuicConfig config;
8623 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8624 &config, kMaxAcceptedDatagramFrameSize);
8625 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8626 connection_.SetFromConfig(config);
8627 // Verify the value post-handshake.
8628 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8629 expected_largest_payload);
8630 } else {
8631 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8632 expected_largest_payload);
8633 }
8634}
8635
8636TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
fayangfc04b8a2023-05-18 09:26:25 -07008637 if (!connection_.version().UsesTls()) {
Bence Békybac04052022-04-07 15:44:29 -04008638 return;
8639 }
8640 constexpr QuicPacketLength kFrameSizeLimit = 1000;
8641 constexpr QuicPacketLength kPayloadSizeLimit =
8642 kFrameSizeLimit - kQuicFrameTypeSize;
8643 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8644 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8645 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8646 QuicConfig config;
8647 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
8648 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8649 connection_.SetFromConfig(config);
8650 // Verify the value post-handshake.
8651 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
8652 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8653 kPayloadSizeLimit);
8654}
8655
8656// Test to check that the path challenge/path response logic works
8657// correctly. This test is only for version-99
8658TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) {
8659 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8660 return;
8661 }
8662 PathProbeTestInit(Perspective::IS_SERVER);
8663 QuicConnectionPeer::SetAddressValidated(&connection_);
8664 // First check if the server can send probing packet.
8665 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8666
8667 // Create and send the probe request (PATH_CHALLENGE frame).
8668 // SendConnectivityProbingPacket ends up calling
8669 // TestPacketWriter::WritePacket() which in turns receives and parses the
8670 // packet by calling framer_.ProcessPacket() -- which in turn calls
8671 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8672 // the packet in writer_->path_challenge_frames()
8673 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8674 connection_.SendConnectivityProbingPacket(writer_.get(),
8675 connection_.peer_address());
8676 // Save the random contents of the challenge for later comparison to the
8677 // response.
8678 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8679 QuicPathFrameBuffer challenge_data =
8680 writer_->path_challenge_frames().front().data_buffer;
8681
8682 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8683 // called and it will perform actions to ensure that the rest of the protocol
8684 // is performed.
8685 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8686 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8687 writer_->path_challenge_frames().front()));
8688 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8689 creator_->FlushCurrentPacket();
8690
8691 // The final check is to ensure that the random data in the response matches
8692 // the random data from the challenge.
8693 EXPECT_EQ(1u, writer_->path_response_frames().size());
8694 EXPECT_EQ(0, memcmp(&challenge_data,
8695 &(writer_->path_response_frames().front().data_buffer),
8696 sizeof(challenge_data)));
8697}
8698
8699TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnDefaulSocket) {
8700 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8701 return;
8702 }
8703 PathProbeTestInit(Perspective::IS_CLIENT);
8704 // First check if the client can send probing packet.
8705 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8706
8707 // Create and send the probe request (PATH_CHALLENGE frame).
8708 // SendConnectivityProbingPacket ends up calling
8709 // TestPacketWriter::WritePacket() which in turns receives and parses the
8710 // packet by calling framer_.ProcessPacket() -- which in turn calls
8711 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8712 // the packet in writer_->path_challenge_frames()
8713 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8714 connection_.SendConnectivityProbingPacket(writer_.get(),
8715 connection_.peer_address());
8716 // Save the random contents of the challenge for later validation against the
8717 // response.
8718 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8719 QuicPathFrameBuffer challenge_data =
8720 writer_->path_challenge_frames().front().data_buffer;
8721
8722 // Normally, QuicConnection::OnPathChallengeFrame would be
8723 // called and it will perform actions to ensure that the rest of the protocol
8724 // is performed.
8725 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8726 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8727 writer_->path_challenge_frames().front()));
8728 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8729 creator_->FlushCurrentPacket();
8730
8731 // The final check is to ensure that the random data in the response matches
8732 // the random data from the challenge.
8733 EXPECT_EQ(1u, writer_->path_response_frames().size());
8734 EXPECT_EQ(0, memcmp(&challenge_data,
8735 &(writer_->path_response_frames().front().data_buffer),
8736 sizeof(challenge_data)));
8737}
8738
8739TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnAlternativeSocket) {
danzh87605712022-04-11 14:36:39 -07008740 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -04008741 return;
8742 }
8743 PathProbeTestInit(Perspective::IS_CLIENT);
8744 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8745
8746 QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8747 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8748 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8749 .Times(AtLeast(1u))
8750 .WillOnce(Invoke([&]() {
8751 EXPECT_EQ(1u, new_writer.packets_write_attempts());
8752 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
8753 EXPECT_EQ(1u, new_writer.padding_frames().size());
8754 EXPECT_EQ(kNewSelfAddress.host(),
8755 new_writer.last_write_source_address());
8756 }));
8757 bool success = false;
8758 connection_.ValidatePath(
8759 std::make_unique<TestQuicPathValidationContext>(
8760 kNewSelfAddress, connection_.peer_address(), &new_writer),
8761 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -08008762 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
8763 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -04008764
8765 // Receiving a PATH_CHALLENGE on the alternative path. Response to this
8766 // PATH_CHALLENGE should be sent via the alternative writer.
8767 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8768 .Times(AtLeast(1u))
8769 .WillOnce(Invoke([&]() {
8770 EXPECT_EQ(2u, new_writer.packets_write_attempts());
8771 EXPECT_EQ(1u, new_writer.path_response_frames().size());
8772 EXPECT_EQ(1u, new_writer.padding_frames().size());
8773 EXPECT_EQ(kNewSelfAddress.host(),
8774 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -07008775 }))
8776 .WillRepeatedly(DoDefault());
8777 ;
Bence Békybac04052022-04-07 15:44:29 -04008778 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8779 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8780 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8781 probing_packet->encrypted_length),
8782 clock_.Now()));
8783 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8784
8785 QuicSocketAddress kNewerSelfAddress(QuicIpAddress::Loopback6(),
8786 /*port=*/34567);
8787 // Receiving a PATH_CHALLENGE on an unknown socket should be ignored.
8788 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
8789 ProcessReceivedPacket(kNewerSelfAddress, kPeerAddress, *received);
8790}
8791
8792TEST_P(QuicConnectionTest,
8793 RestartPathDegradingDetectionAfterMigrationWithProbe) {
danzh65153092023-06-16 10:59:32 -07008794 if (!version().HasIetfQuicFrames() &&
8795 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
8796 return;
8797 }
Bence Békybac04052022-04-07 15:44:29 -04008798 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8799 PathProbeTestInit(Perspective::IS_CLIENT);
8800
8801 // Send data and verify the path degrading detection is set.
8802 const char data[] = "data";
8803 size_t data_size = strlen(data);
8804 QuicStreamOffset offset = 0;
8805 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8806 offset += data_size;
8807
8808 // Verify the path degrading detection is in progress.
8809 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8810 EXPECT_FALSE(connection_.IsPathDegrading());
8811 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
8812
8813 // Simulate the firing of path degrading.
8814 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
8815 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
8816 connection_.PathDegradingTimeout();
8817 EXPECT_TRUE(connection_.IsPathDegrading());
8818 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8819
8820 if (!GetParam().version.HasIetfQuicFrames()) {
8821 // Simulate path degrading handling by sending a probe on an alternet path.
8822 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8823 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
8824 connection_.SendConnectivityProbingPacket(&probing_writer,
8825 connection_.peer_address());
8826 // Verify that path degrading detection is not reset.
8827 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8828
8829 // Simulate successful path degrading handling by receiving probe response.
8830 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
8831
8832 EXPECT_CALL(visitor_,
8833 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
8834 .Times(1);
8835 const QuicSocketAddress kNewSelfAddress =
8836 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8837
8838 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8839 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8840 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8841 probing_packet->encrypted_length),
8842 clock_.Now()));
8843 uint64_t num_probing_received =
8844 connection_.GetStats().num_connectivity_probing_received;
8845 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8846
danzh65153092023-06-16 10:59:32 -07008847 EXPECT_EQ(num_probing_received +
8848 (GetQuicReloadableFlag(quic_ignore_gquic_probing) ? 0u : 1u),
Bence Békybac04052022-04-07 15:44:29 -04008849 connection_.GetStats().num_connectivity_probing_received);
8850 EXPECT_EQ(kPeerAddress, connection_.peer_address());
8851 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8852 EXPECT_TRUE(connection_.IsPathDegrading());
8853 }
8854
8855 // Verify new path degrading detection is activated.
8856 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
8857 connection_.OnSuccessfulMigration(/*is_port_change*/ true);
8858 EXPECT_FALSE(connection_.IsPathDegrading());
8859 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8860}
8861
8862TEST_P(QuicConnectionTest, ClientsResetCwndAfterConnectionMigration) {
8863 if (!GetParam().version.HasIetfQuicFrames()) {
8864 return;
8865 }
8866 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8867 PathProbeTestInit(Perspective::IS_CLIENT);
8868 EXPECT_EQ(kSelfAddress, connection_.self_address());
8869
8870 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
8871 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
8872 rtt_stats->set_initial_rtt(default_init_rtt * 2);
8873 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
8874
fayang339f0c82022-04-30 14:20:02 -07008875 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
8876 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008877 const SendAlgorithmInterface* send_algorithm = manager_->GetSendAlgorithm();
8878
8879 // Migrate to a new address with different IP.
8880 const QuicSocketAddress kNewSelfAddress =
8881 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
8882 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8883 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
8884 &new_writer, false);
8885 EXPECT_EQ(default_init_rtt, manager_->GetRttStats()->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07008886 EXPECT_EQ(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008887 EXPECT_NE(send_algorithm, manager_->GetSendAlgorithm());
8888}
8889
8890// Regression test for b/110259444
8891TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8892 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8893 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8894 writer_->SetWriteBlocked();
8895
8896 ProcessPacket(1);
8897 // Verify ack alarm is set.
8898 EXPECT_TRUE(connection_.HasPendingAcks());
8899 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8900 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8901 connection_.GetAckAlarm()->Fire();
8902
8903 writer_->SetWritable();
8904 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8905 ProcessPacket(2);
8906 // Verify ack alarm is not set.
8907 EXPECT_FALSE(connection_.HasPendingAcks());
8908}
8909
8910TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8911 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8912 writer_->set_supports_release_time(true);
8913 QuicConfig config;
8914 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8915 connection_.SetFromConfig(config);
8916 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8917
8918 QuicTagVector connection_options;
8919 connection_options.push_back(kNPCO);
8920 config.SetConnectionOptionsToSend(connection_options);
8921 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8922 connection_.SetFromConfig(config);
8923 // Verify pacing offload is disabled.
8924 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8925}
8926
8927// Regression test for b/110259444
8928// Get a path response without having issued a path challenge...
8929TEST_P(QuicConnectionTest, OrphanPathResponse) {
8930 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8931
8932 QuicPathResponseFrame frame(99, data);
8933 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8934 // If PATH_RESPONSE was accepted (payload matches the payload saved
8935 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8936 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8937 // Since this PATH_RESPONSE does not match, current_packet_content_
8938 // must not be FIRST_FRAME_IS_PING.
8939 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8940 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8941}
8942
Bence Békybac04052022-04-07 15:44:29 -04008943TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
8944 if (!VersionHasIetfQuicFrames(version().transport_version)) {
8945 return;
8946 }
8947 // Set first_sending_packet_number to be 0 to allow successfully processing
8948 // acks which ack packet number 0.
8949 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8950 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8951
8952 ProcessPacket(0);
8953 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8954 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8955
8956 ProcessPacket(1);
8957 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8958 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8959
8960 ProcessPacket(2);
8961 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8962 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8963}
8964
8965TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8966 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8967 return;
8968 }
Bence Békybac04052022-04-07 15:44:29 -04008969 connection_.SendCryptoStreamData();
8970 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8971 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07008972 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008973 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8974 QuicAckFrame frame1 = InitAckFrame(1);
8975 // Received ACK for packet 1.
8976 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8977
8978 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8979 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8980 NO_FIN);
8981 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8982 NO_FIN);
8983 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8984 8, NO_FIN);
8985 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8986 12, FIN);
8987 // Received ACK for packets 2, 4, 5.
8988 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07008989 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008990 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8991 QuicAckFrame frame2 =
8992 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8993 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8994 // Make sure although the same packet number is used, but they are in
8995 // different packet number spaces.
8996 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8997}
8998
8999TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9000 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9001 return;
9002 }
Bence Békybac04052022-04-07 15:44:29 -04009003 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9004 std::make_unique<TaggingEncrypter>(0x01));
9005
9006 connection_.SendCryptoStreamData();
9007 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9008 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07009009 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04009010 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9011 QuicAckFrame frame1 = InitAckFrame(1);
9012 // Received ACK for packet 1.
9013 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9014
9015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9016 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9017 NO_FIN);
9018 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9019 NO_FIN);
9020
9021 // Received ACK for packets 2 and 3 in wrong packet number space.
9022 QuicAckFrame invalid_ack =
9023 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
9024 EXPECT_CALL(visitor_,
9025 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9026 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9027 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
9028 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
9029}
9030
9031TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9032 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9033 return;
9034 }
9035 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9036 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9037 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9038 }
9039 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009040 // Receives packet 1000 in initial data.
9041 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9042 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009043 peer_framer_.SetEncrypter(
9044 ENCRYPTION_FORWARD_SECURE,
9045 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
9046 SetDecrypter(
9047 ENCRYPTION_FORWARD_SECURE,
9048 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009049 // Receives packet 1000 in application data.
9050 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
9051 EXPECT_TRUE(connection_.HasPendingAcks());
9052 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9053 0, NO_FIN);
9054 // Verify application data ACK gets bundled with outgoing data.
9055 EXPECT_EQ(2u, writer_->frame_count());
9056 // Make sure ACK alarm is still set because initial data is not ACKed.
9057 EXPECT_TRUE(connection_.HasPendingAcks());
9058 // Receive packet 1001 in application data.
9059 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_FORWARD_SECURE);
9060 clock_.AdvanceTime(DefaultRetransmissionTime());
9061 // Simulates ACK alarm fires and verify two ACKs are flushed.
9062 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
martinduke9e0811c2022-12-08 20:35:57 -08009063 connection_.SetEncrypter(
9064 ENCRYPTION_FORWARD_SECURE,
9065 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009066 connection_.GetAckAlarm()->Fire();
9067 EXPECT_FALSE(connection_.HasPendingAcks());
9068 // Receives more packets in application data.
9069 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_FORWARD_SECURE);
9070 EXPECT_TRUE(connection_.HasPendingAcks());
9071
9072 // Verify zero rtt and forward secure packets get acked in the same packet.
9073 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9074 ProcessDataPacket(1003);
9075 EXPECT_FALSE(connection_.HasPendingAcks());
9076}
9077
9078TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9079 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9080 return;
9081 }
9082 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9083 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9084 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9085 }
9086 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009087 // Receives packet 1000 in initial data.
9088 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9089 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009090 peer_framer_.SetEncrypter(
9091 ENCRYPTION_ZERO_RTT,
9092 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009093 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08009094 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009095 // Receives packet 1000 in application data.
9096 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9097 EXPECT_TRUE(connection_.HasPendingAcks());
9098
9099 writer_->SetWriteBlocked();
9100 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9101 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9102 // blocked.
9103 clock_.AdvanceTime(DefaultDelayedAckTime());
9104 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9105 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9106 std::make_unique<TaggingEncrypter>(0x02));
9107 connection_.GetAckAlarm()->Fire();
9108 // Verify ACK alarm is not set.
9109 EXPECT_FALSE(connection_.HasPendingAcks());
9110
9111 writer_->SetWritable();
9112 // Verify 2 ACKs are sent when connection gets unblocked.
9113 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9114 connection_.OnCanWrite();
9115 EXPECT_FALSE(connection_.HasPendingAcks());
9116}
9117
9118// Make sure a packet received with the right client connection ID is processed.
9119TEST_P(QuicConnectionTest, ValidClientConnectionId) {
9120 if (!framer_.version().SupportsClientConnectionIds()) {
9121 return;
9122 }
9123 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9124 SetClientConnectionId(TestConnectionId(0x33));
9125 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9126 header.destination_connection_id = TestConnectionId(0x33);
9127 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9128 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9129 QuicFrames frames;
9130 QuicPingFrame ping_frame;
9131 QuicPaddingFrame padding_frame;
9132 frames.push_back(QuicFrame(ping_frame));
9133 frames.push_back(QuicFrame(padding_frame));
9134 std::unique_ptr<QuicPacket> packet =
9135 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9136 char buffer[kMaxOutgoingPacketSize];
9137 size_t encrypted_length = peer_framer_.EncryptPayload(
9138 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9139 kMaxOutgoingPacketSize);
9140 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9141 false);
9142 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9143 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9144 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9145}
9146
9147// Make sure a packet received with a different client connection ID is dropped.
9148TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
9149 if (!framer_.version().SupportsClientConnectionIds()) {
9150 return;
9151 }
9152 SetClientConnectionId(TestConnectionId(0x33));
9153 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9154 header.destination_connection_id = TestConnectionId(0xbad);
9155 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9156 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9157 QuicFrames frames;
9158 QuicPingFrame ping_frame;
9159 QuicPaddingFrame padding_frame;
9160 frames.push_back(QuicFrame(ping_frame));
9161 frames.push_back(QuicFrame(padding_frame));
9162 std::unique_ptr<QuicPacket> packet =
9163 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9164 char buffer[kMaxOutgoingPacketSize];
9165 size_t encrypted_length = peer_framer_.EncryptPayload(
9166 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9167 kMaxOutgoingPacketSize);
9168 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9169 false);
9170 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9171 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9172 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9173}
9174
9175// Make sure the first packet received with a different client connection ID on
9176// the server is processed and it changes the client connection ID.
9177TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
9178 if (!framer_.version().SupportsClientConnectionIds()) {
9179 return;
9180 }
9181 set_perspective(Perspective::IS_SERVER);
9182 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9183 header.source_connection_id = TestConnectionId(0x33);
9184 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9185 QuicFrames frames;
9186 QuicPingFrame ping_frame;
9187 QuicPaddingFrame padding_frame;
9188 frames.push_back(QuicFrame(ping_frame));
9189 frames.push_back(QuicFrame(padding_frame));
9190 std::unique_ptr<QuicPacket> packet =
9191 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9192 char buffer[kMaxOutgoingPacketSize];
9193 size_t encrypted_length =
9194 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9195 *packet, buffer, kMaxOutgoingPacketSize);
9196 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9197 false);
9198 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9199 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9200 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9201 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9202}
9203void QuicConnectionTest::TestReplaceConnectionIdFromInitial() {
9204 if (!framer_.version().AllowsVariableLengthConnectionIds()) {
9205 return;
9206 }
9207 // We start with a known connection ID.
9208 EXPECT_TRUE(connection_.connected());
9209 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9210 EXPECT_NE(TestConnectionId(0x33), connection_.connection_id());
9211 // Receiving an initial can replace the connection ID once.
9212 {
9213 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9214 header.source_connection_id = TestConnectionId(0x33);
9215 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9216 QuicFrames frames;
9217 QuicPingFrame ping_frame;
9218 QuicPaddingFrame padding_frame;
9219 frames.push_back(QuicFrame(ping_frame));
9220 frames.push_back(QuicFrame(padding_frame));
9221 std::unique_ptr<QuicPacket> packet =
9222 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9223 char buffer[kMaxOutgoingPacketSize];
9224 size_t encrypted_length =
9225 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9226 *packet, buffer, kMaxOutgoingPacketSize);
9227 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9228 false);
9229 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9230 }
9231 EXPECT_TRUE(connection_.connected());
9232 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9233 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9234 // Trying to replace the connection ID a second time drops the packet.
9235 {
9236 QuicPacketHeader header = ConstructPacketHeader(2, ENCRYPTION_INITIAL);
9237 header.source_connection_id = TestConnectionId(0x66);
9238 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9239 QuicFrames frames;
9240 QuicPingFrame ping_frame;
9241 QuicPaddingFrame padding_frame;
9242 frames.push_back(QuicFrame(ping_frame));
9243 frames.push_back(QuicFrame(padding_frame));
9244 std::unique_ptr<QuicPacket> packet =
9245 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9246 char buffer[kMaxOutgoingPacketSize];
9247 size_t encrypted_length =
9248 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9249 *packet, buffer, kMaxOutgoingPacketSize);
9250 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9251 false);
9252 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9253 }
9254 EXPECT_TRUE(connection_.connected());
9255 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9256 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9257}
9258
9259TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromInitial) {
9260 TestReplaceConnectionIdFromInitial();
9261}
9262
9263TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromRetryAndInitial) {
9264 // First make the connection process a RETRY and replace the server connection
9265 // ID a first time.
9266 TestClientRetryHandling(/*invalid_retry_tag=*/false,
9267 /*missing_original_id_in_config=*/false,
9268 /*wrong_original_id_in_config=*/false,
9269 /*missing_retry_id_in_config=*/false,
9270 /*wrong_retry_id_in_config=*/false);
9271 // Reset the test framer to use the right connection ID.
9272 peer_framer_.SetInitialObfuscators(connection_.connection_id());
9273 // Now process an INITIAL and replace the server connection ID a second time.
9274 TestReplaceConnectionIdFromInitial();
9275}
9276
9277// Regression test for b/134416344.
9278TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9279 // This test mimics a scenario where a connection processes 2 packets and the
9280 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9281 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9282 // because connection is disconnected.
9283 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9284 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9285 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
9286 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
9287 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
9288 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9289 NO_IETF_QUIC_ERROR, "",
9290 /*transport_close_frame_type=*/0));
9291
9292 // Received 2 packets.
9293 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9294 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9295 } else {
9296 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9297 }
9298 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
9299 ENCRYPTION_INITIAL);
9300 EXPECT_TRUE(connection_.HasPendingAcks());
9301 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
9302 kSelfAddress, kPeerAddress,
9303 ENCRYPTION_INITIAL);
9304 // Verify ack alarm is not set.
9305 EXPECT_FALSE(connection_.HasPendingAcks());
9306}
9307
9308// Verify that a packet containing three coalesced packets is parsed correctly.
9309TEST_P(QuicConnectionTest, CoalescedPacket) {
9310 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9311 // Coalesced packets can only be encoded using long header lengths.
9312 return;
9313 }
9314 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9315 EXPECT_TRUE(connection_.connected());
9316 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9317 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9318 } else {
9319 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9320 }
9321
9322 uint64_t packet_numbers[3] = {1, 2, 3};
9323 EncryptionLevel encryption_levels[3] = {
9324 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9325 char buffer[kMaxOutgoingPacketSize] = {};
9326 size_t total_encrypted_length = 0;
9327 for (int i = 0; i < 3; i++) {
9328 QuicPacketHeader header =
9329 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9330 QuicFrames frames;
9331 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9332 frames.push_back(QuicFrame(&crypto_frame_));
9333 } else {
9334 frames.push_back(QuicFrame(frame1_));
9335 }
9336 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9337 peer_creator_.set_encryption_level(encryption_levels[i]);
9338 size_t encrypted_length = peer_framer_.EncryptPayload(
9339 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9340 buffer + total_encrypted_length,
9341 sizeof(buffer) - total_encrypted_length);
9342 EXPECT_GT(encrypted_length, 0u);
9343 total_encrypted_length += encrypted_length;
9344 }
9345 connection_.ProcessUdpPacket(
9346 kSelfAddress, kPeerAddress,
9347 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9348 if (connection_.GetSendAlarm()->IsSet()) {
9349 connection_.GetSendAlarm()->Fire();
9350 }
9351
9352 EXPECT_TRUE(connection_.connected());
9353}
9354
9355// Regression test for crbug.com/992831.
9356TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9357 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9358 // Coalesced packets can only be encoded using long header lengths.
9359 return;
9360 }
9361 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9362 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9363 return;
9364 }
9365 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9366 EXPECT_TRUE(connection_.connected());
9367 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9368 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9369 .Times(3)
9370 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9371 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009372 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009373 });
9374 } else {
9375 EXPECT_CALL(visitor_, OnStreamFrame(_))
9376 .Times(3)
9377 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9378 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009379 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009380 });
9381 }
9382
9383 uint64_t packet_numbers[3] = {1, 2, 3};
9384 EncryptionLevel encryption_levels[3] = {
9385 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9386 char buffer[kMaxOutgoingPacketSize] = {};
9387 size_t total_encrypted_length = 0;
9388 for (int i = 0; i < 3; i++) {
9389 QuicPacketHeader header =
9390 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9391 QuicFrames frames;
9392 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9393 frames.push_back(QuicFrame(&crypto_frame_));
9394 } else {
9395 frames.push_back(QuicFrame(frame1_));
9396 }
9397 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9398 peer_creator_.set_encryption_level(encryption_levels[i]);
9399 size_t encrypted_length = peer_framer_.EncryptPayload(
9400 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9401 buffer + total_encrypted_length,
9402 sizeof(buffer) - total_encrypted_length);
9403 EXPECT_GT(encrypted_length, 0u);
9404 total_encrypted_length += encrypted_length;
9405 }
9406 connection_.ProcessUdpPacket(
9407 kSelfAddress, kPeerAddress,
9408 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9409 if (connection_.GetSendAlarm()->IsSet()) {
9410 connection_.GetSendAlarm()->Fire();
9411 }
9412
9413 EXPECT_TRUE(connection_.connected());
9414
9415 SendAckPacketToPeer();
9416}
9417
9418// Regresstion test for b/138962304.
9419TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
9420 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9421
9422 QuicStreamId stream_id = 2;
9423 QuicPacketNumber last_data_packet;
9424 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9425 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9426
9427 // Writer gets blocked.
9428 writer_->SetWriteBlocked();
9429
9430 // Cancel the stream.
9431 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9432 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9433 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9434 .WillRepeatedly(
9435 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
9436 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9437
9438 // Retransmission timer fires in RTO mode.
9439 connection_.GetRetransmissionAlarm()->Fire();
9440 // Verify no packets get flushed when writer is blocked.
9441 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9442}
9443
9444// Regresstion test for b/138962304.
fayang339f0c82022-04-30 14:20:02 -07009445TEST_P(QuicConnectionTest, PtoAndWriteBlocked) {
Bence Békybac04052022-04-07 15:44:29 -04009446 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
Bence Békybac04052022-04-07 15:44:29 -04009447
9448 QuicStreamId stream_id = 2;
9449 QuicPacketNumber last_data_packet;
9450 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9451 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9452 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9453
9454 // Writer gets blocked.
9455 writer_->SetWriteBlocked();
9456
9457 // Cancel stream 2.
9458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9459 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9460 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9461
9462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9463 // Retransmission timer fires in TLP mode.
9464 connection_.GetRetransmissionAlarm()->Fire();
9465 // Verify one packets is forced flushed when writer is blocked.
9466 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9467}
9468
Bence Békybac04052022-04-07 15:44:29 -04009469TEST_P(QuicConnectionTest, ProbeTimeout) {
9470 QuicConfig config;
9471 QuicTagVector connection_options;
9472 connection_options.push_back(k2PTO);
9473 config.SetConnectionOptionsToSend(connection_options);
9474 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9475 connection_.SetFromConfig(config);
9476 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9477
9478 QuicStreamId stream_id = 2;
9479 QuicPacketNumber last_packet;
9480 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9481 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9482 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9483
9484 // Reset stream.
9485 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9486 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9487
9488 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9489 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9490 connection_.GetRetransmissionAlarm()->Fire();
9491 EXPECT_EQ(0u, writer_->stream_frames().size());
9492 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9493 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9494}
9495
9496TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
9497 QuicConfig config;
9498 QuicTagVector connection_options;
9499 connection_options.push_back(k1PTO);
9500 connection_options.push_back(k6PTO);
9501 config.SetConnectionOptionsToSend(connection_options);
9502 QuicConfigPeer::SetNegotiated(&config, true);
9503 if (connection_.version().UsesTls()) {
9504 QuicConfigPeer::SetReceivedOriginalConnectionId(
9505 &config, connection_.connection_id());
9506 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9507 &config, connection_.connection_id());
9508 }
9509 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9510 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009511 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9512 GetQuicReloadableFlag(
9513 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009514 EXPECT_CALL(visitor_, GetHandshakeState())
9515 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9516 }
9517 connection_.OnHandshakeComplete();
9518 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9519
9520 // Send stream data.
9521 SendStreamDataToPeer(
9522 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9523 0, FIN, nullptr);
9524
9525 // Fire the retransmission alarm 5 times.
9526 for (int i = 0; i < 5; ++i) {
9527 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9528 connection_.GetRetransmissionAlarm()->Fire();
9529 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9530 EXPECT_TRUE(connection_.connected());
9531 }
9532 EXPECT_CALL(visitor_, OnPathDegrading());
9533 connection_.PathDegradingTimeout();
9534
Bence Békybac04052022-04-07 15:44:29 -04009535 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9536 // Closes connection on 6th PTO.
9537 // May send multiple connecction close packets with multiple PN spaces.
9538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9539 EXPECT_CALL(visitor_,
9540 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9541 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9542 connection_.GetBlackholeDetectorAlarm()->Fire();
9543 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9544 EXPECT_FALSE(connection_.connected());
9545 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9546}
9547
9548TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
9549 QuicConfig config;
9550 QuicTagVector connection_options;
9551 connection_options.push_back(k2PTO);
9552 connection_options.push_back(k7PTO);
9553 config.SetConnectionOptionsToSend(connection_options);
9554 QuicConfigPeer::SetNegotiated(&config, true);
9555 if (connection_.version().UsesTls()) {
9556 QuicConfigPeer::SetReceivedOriginalConnectionId(
9557 &config, connection_.connection_id());
9558 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9559 &config, connection_.connection_id());
9560 }
9561 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9562 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009563 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9564 GetQuicReloadableFlag(
9565 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009566 EXPECT_CALL(visitor_, GetHandshakeState())
9567 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9568 }
9569 connection_.OnHandshakeComplete();
9570 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9571
9572 // Send stream data.
9573 SendStreamDataToPeer(
9574 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9575 0, FIN, nullptr);
9576
9577 // Fire the retransmission alarm 6 times.
9578 for (int i = 0; i < 6; ++i) {
9579 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9580 connection_.GetRetransmissionAlarm()->Fire();
9581 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9582 EXPECT_TRUE(connection_.connected());
9583 }
9584 EXPECT_CALL(visitor_, OnPathDegrading());
9585 connection_.PathDegradingTimeout();
9586
Bence Békybac04052022-04-07 15:44:29 -04009587 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9588 // Closes connection on 7th PTO.
9589 EXPECT_CALL(visitor_,
9590 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9591 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9592 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9593 connection_.GetBlackholeDetectorAlarm()->Fire();
9594 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9595 EXPECT_FALSE(connection_.connected());
9596 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9597}
9598
9599TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
9600 QuicConfig config;
9601 QuicTagVector connection_options;
9602 connection_options.push_back(k2PTO);
9603 connection_options.push_back(k8PTO);
9604 QuicConfigPeer::SetNegotiated(&config, true);
9605 if (connection_.version().UsesTls()) {
9606 QuicConfigPeer::SetReceivedOriginalConnectionId(
9607 &config, connection_.connection_id());
9608 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9609 &config, connection_.connection_id());
9610 }
9611 config.SetConnectionOptionsToSend(connection_options);
9612 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9613 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009614 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9615 GetQuicReloadableFlag(
9616 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009617 EXPECT_CALL(visitor_, GetHandshakeState())
9618 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9619 }
9620 connection_.OnHandshakeComplete();
9621 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9622
9623 // Send stream data.
9624 SendStreamDataToPeer(
9625 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9626 0, FIN, nullptr);
9627
9628 // Fire the retransmission alarm 7 times.
9629 for (int i = 0; i < 7; ++i) {
9630 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9631 connection_.GetRetransmissionAlarm()->Fire();
9632 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9633 EXPECT_TRUE(connection_.connected());
9634 }
9635 EXPECT_CALL(visitor_, OnPathDegrading());
9636 connection_.PathDegradingTimeout();
9637
Bence Békybac04052022-04-07 15:44:29 -04009638 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9639 // Closes connection on 8th PTO.
9640 EXPECT_CALL(visitor_,
9641 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9642 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9643 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9644 connection_.GetBlackholeDetectorAlarm()->Fire();
9645 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9646 EXPECT_FALSE(connection_.connected());
9647 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9648}
9649
9650TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9651 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9652 return;
9653 }
9654 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9655 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9656
9657 // Send CHLO.
9658 connection_.SendCryptoStreamData();
9659 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9660
9661 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07009662 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04009663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9664 QuicAckFrame frame1 = InitAckFrame(1);
9665 // Received ACK for packet 1.
9666 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9667
9668 // Verify retransmission alarm is still set because handshake is not
9669 // confirmed although there is nothing in flight.
9670 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9671 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9672 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9673
9674 // PTO fires, verify a PING packet gets sent because there is no data to send.
9675 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9676 connection_.GetRetransmissionAlarm()->Fire();
9677 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9678 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
9679 EXPECT_EQ(1u, writer_->ping_frames().size());
9680}
9681
9682TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009683 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009684 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009685 return;
9686 }
9687 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9688
9689 set_perspective(Perspective::IS_SERVER);
9690 // Verify no data can be sent at the beginning because bytes received is 0.
9691 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9692 connection_.SendCryptoDataWithString("foo", 0);
9693 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9694 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9695 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9696
9697 // Receives packet 1.
9698 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009699 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009700 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9701
9702 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -07009703 GetQuicFlag(quic_anti_amplification_factor);
Bence Békybac04052022-04-07 15:44:29 -04009704 // Verify now packets can be sent.
9705 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9706 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9707 connection_.SendCryptoDataWithString("foo", i * 3);
9708 // Verify retransmission alarm is not set if throttled by anti-amplification
9709 // limit.
9710 EXPECT_EQ(i != anti_amplification_factor - 1,
9711 connection_.GetRetransmissionAlarm()->IsSet());
9712 }
9713 // Verify server is throttled by anti-amplification limit.
9714 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9715 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9716
9717 // Receives packet 2.
9718 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009719 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009720 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9721 // Verify more packets can be sent.
9722 for (size_t i = anti_amplification_factor + 1;
9723 i < anti_amplification_factor * 2; ++i) {
9724 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9725 connection_.SendCryptoDataWithString("foo", i * 3);
9726 }
9727 // Verify server is throttled by anti-amplification limit.
9728 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9729 connection_.SendCryptoDataWithString("foo",
9730 2 * anti_amplification_factor * 3);
9731
9732 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009733 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009734 ProcessPacket(3);
9735 // Verify anti-amplification limit is gone after address validation.
9736 for (size_t i = 0; i < 100; ++i) {
9737 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9738 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9739 }
9740}
9741
9742TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009743 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009744 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009745 return;
9746 }
9747 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9748
9749 set_perspective(Perspective::IS_SERVER);
9750 QuicConfig config;
9751 QuicTagVector connection_options;
9752 connection_options.push_back(k3AFF);
9753 config.SetInitialReceivedConnectionOptions(connection_options);
9754 if (connection_.version().UsesTls()) {
9755 QuicConfigPeer::SetReceivedOriginalConnectionId(
9756 &config, connection_.connection_id());
9757 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9758 QuicConnectionId());
9759 }
9760 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9761 connection_.SetFromConfig(config);
9762
9763 // Verify no data can be sent at the beginning because bytes received is 0.
9764 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9765 connection_.SendCryptoDataWithString("foo", 0);
9766 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9767 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9768 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9769
9770 // Receives packet 1.
9771 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009772 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009773 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9774
9775 const size_t anti_amplification_factor = 3;
9776 // Verify now packets can be sent.
9777 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9778 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9779 connection_.SendCryptoDataWithString("foo", i * 3);
9780 // Verify retransmission alarm is not set if throttled by anti-amplification
9781 // limit.
9782 EXPECT_EQ(i != anti_amplification_factor - 1,
9783 connection_.GetRetransmissionAlarm()->IsSet());
9784 }
9785 // Verify server is throttled by anti-amplification limit.
9786 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9787 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9788
9789 // Receives packet 2.
9790 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009791 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009792 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9793 // Verify more packets can be sent.
9794 for (size_t i = anti_amplification_factor + 1;
9795 i < anti_amplification_factor * 2; ++i) {
9796 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9797 connection_.SendCryptoDataWithString("foo", i * 3);
9798 }
9799 // Verify server is throttled by anti-amplification limit.
9800 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9801 connection_.SendCryptoDataWithString("foo",
9802 2 * anti_amplification_factor * 3);
9803
9804 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009805 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009806 ProcessPacket(3);
9807 // Verify anti-amplification limit is gone after address validation.
9808 for (size_t i = 0; i < 100; ++i) {
9809 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9810 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9811 }
9812}
9813
9814TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009815 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009816 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009817 return;
9818 }
9819 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9820
9821 set_perspective(Perspective::IS_SERVER);
9822 QuicConfig config;
9823 QuicTagVector connection_options;
9824 connection_options.push_back(k10AF);
9825 config.SetInitialReceivedConnectionOptions(connection_options);
9826 if (connection_.version().UsesTls()) {
9827 QuicConfigPeer::SetReceivedOriginalConnectionId(
9828 &config, connection_.connection_id());
9829 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9830 QuicConnectionId());
9831 }
9832 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9833 connection_.SetFromConfig(config);
9834
9835 // Verify no data can be sent at the beginning because bytes received is 0.
9836 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9837 connection_.SendCryptoDataWithString("foo", 0);
9838 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9839 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9840 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9841
9842 // Receives packet 1.
9843 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009844 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009845 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9846
9847 const size_t anti_amplification_factor = 10;
9848 // Verify now packets can be sent.
9849 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9850 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9851 connection_.SendCryptoDataWithString("foo", i * 3);
9852 // Verify retransmission alarm is not set if throttled by anti-amplification
9853 // limit.
9854 EXPECT_EQ(i != anti_amplification_factor - 1,
9855 connection_.GetRetransmissionAlarm()->IsSet());
9856 }
9857 // Verify server is throttled by anti-amplification limit.
9858 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9859 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9860
9861 // Receives packet 2.
9862 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009863 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009864 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9865 // Verify more packets can be sent.
9866 for (size_t i = anti_amplification_factor + 1;
9867 i < anti_amplification_factor * 2; ++i) {
9868 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9869 connection_.SendCryptoDataWithString("foo", i * 3);
9870 }
9871 // Verify server is throttled by anti-amplification limit.
9872 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9873 connection_.SendCryptoDataWithString("foo",
9874 2 * anti_amplification_factor * 3);
9875
9876 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009877 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009878 ProcessPacket(3);
9879 // Verify anti-amplification limit is gone after address validation.
9880 for (size_t i = 0; i < 100; ++i) {
9881 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9882 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9883 }
9884}
9885
9886TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
9887 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9888 return;
9889 }
9890 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9891 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
9892 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -04009893 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9894 // Receives packet 1.
9895 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08009896 connection_.SetEncrypter(
9897 ENCRYPTION_HANDSHAKE,
9898 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -04009899 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9900 EXPECT_TRUE(connection_.HasPendingAcks());
9901 // Send response in different encryption level and cause amplification factor
9902 // throttled.
9903 size_t i = 0;
9904 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
9905 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
9906 ENCRYPTION_HANDSHAKE);
9907 ++i;
9908 }
9909 // Verify ACK is still pending.
9910 EXPECT_TRUE(connection_.HasPendingAcks());
9911
9912 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
9913 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
9914 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9915 connection_.GetAckAlarm()->Fire();
9916 // Verify ACK alarm is cancelled.
9917 EXPECT_FALSE(connection_.HasPendingAcks());
9918
9919 // Receives packet 2 and verify ACK gets flushed.
9920 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9921 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9922 EXPECT_FALSE(writer_->ack_frames().empty());
9923}
9924
9925TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9926 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9927 // Test relevent only for IETF QUIC.
9928 return;
9929 }
9930 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9931 // Use the (unknown) frame type of 9999 to avoid triggering any logic
9932 // which might be associated with the processing of a known frame type.
9933 const uint64_t kTransportCloseFrameType = 9999u;
9934 QuicFramerPeer::set_current_received_frame_type(
9935 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9936 // Do a transport connection close
9937 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9938 connection_.CloseConnection(
9939 kQuicErrorCode, "Some random error message",
9940 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9941 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9942 writer_->connection_close_frames();
9943 ASSERT_EQ(1u, connection_close_frames.size());
9944 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9945 connection_close_frames[0].close_type);
9946 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
9947 EXPECT_EQ(kTransportCloseFrameType,
9948 connection_close_frames[0].transport_close_frame_type);
9949}
9950
Bence Békybac04052022-04-07 15:44:29 -04009951TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
9952 QuicConfig config;
9953 QuicTagVector connection_options;
9954 connection_options.push_back(k1PTO);
9955 connection_options.push_back(kPTOS);
9956 config.SetConnectionOptionsToSend(connection_options);
9957 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9958 connection_.SetFromConfig(config);
9959 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9960
9961 QuicStreamId stream_id = 2;
9962 QuicPacketNumber last_packet;
9963 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9964 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9965 EXPECT_EQ(QuicPacketNumber(2), last_packet);
9966 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9967
9968 // Fire PTO and verify the PTO retransmission skips one packet number.
9969 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9970 connection_.GetRetransmissionAlarm()->Fire();
9971 EXPECT_EQ(1u, writer_->stream_frames().size());
9972 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9973 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9974}
9975
9976TEST_P(QuicConnectionTest, SendCoalescedPackets) {
9977 if (!connection_.version().CanSendCoalescedPackets()) {
9978 return;
9979 }
9980 MockQuicConnectionDebugVisitor debug_visitor;
9981 connection_.set_debug_visitor(&debug_visitor);
wub92727922023-07-13 08:47:39 -07009982 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -04009983 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
9984 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
9985 {
9986 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04009987 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9988 connection_.SendCryptoDataWithString("foo", 0);
9989 // Verify this packet is on hold.
9990 EXPECT_EQ(0u, writer_->packets_write_attempts());
9991
9992 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9993 std::make_unique<TaggingEncrypter>(0x02));
9994 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9995 connection_.SendCryptoDataWithString("bar", 3);
9996 EXPECT_EQ(0u, writer_->packets_write_attempts());
9997
9998 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9999 std::make_unique<TaggingEncrypter>(0x03));
10000 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10001 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10002 }
10003 // Verify all 3 packets are coalesced in the same UDP datagram.
10004 EXPECT_EQ(1u, writer_->packets_write_attempts());
10005 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10006 // Verify the packet is padded to full.
10007 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10008
10009 // Verify packet process.
10010 EXPECT_EQ(1u, writer_->crypto_frames().size());
10011 EXPECT_EQ(0u, writer_->stream_frames().size());
10012 // Verify there is coalesced packet.
10013 EXPECT_NE(nullptr, writer_->coalesced_packet());
10014}
10015
10016TEST_P(QuicConnectionTest, FailToCoalescePacket) {
10017 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
10018 if (!IsDefaultTestConfiguration() ||
fayang161ce6e2022-07-01 18:02:11 -070010019 !connection_.version().CanSendCoalescedPackets() ||
birenroyef686222022-09-12 11:34:34 -070010020 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040010021 return;
10022 }
10023
10024 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040010025
Bence Békybac04052022-04-07 15:44:29 -040010026 auto test_body = [&] {
vasilvvac2e30d2022-06-02 14:26:59 -070010027 EXPECT_CALL(visitor_,
10028 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10029 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
Bence Békybac04052022-04-07 15:44:29 -040010030
vasilvvac2e30d2022-06-02 14:26:59 -070010031 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -040010032
vasilvvac2e30d2022-06-02 14:26:59 -070010033 {
10034 QuicConnection::ScopedPacketFlusher flusher(&connection_);
vasilvvac2e30d2022-06-02 14:26:59 -070010035 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10036 connection_.SendCryptoDataWithString("foo", 0);
10037 // Verify this packet is on hold.
10038 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -040010039
vasilvvac2e30d2022-06-02 14:26:59 -070010040 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10041 std::make_unique<TaggingEncrypter>(0x02));
10042 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10043 connection_.SendCryptoDataWithString("bar", 3);
10044 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -040010045
vasilvvac2e30d2022-06-02 14:26:59 -070010046 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10047 std::make_unique<TaggingEncrypter>(0x03));
10048 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10049 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
Bence Békybac04052022-04-07 15:44:29 -040010050
vasilvvac2e30d2022-06-02 14:26:59 -070010051 creator_->Flush();
10052
10053 auto& coalesced_packet =
10054 QuicConnectionPeer::GetCoalescedPacket(&connection_);
10055 QuicPacketLength coalesced_packet_max_length =
10056 coalesced_packet.max_packet_length();
10057 QuicCoalescedPacketPeer::SetMaxPacketLength(coalesced_packet,
10058 coalesced_packet.length());
10059
10060 // Make the coalescer's FORWARD_SECURE packet longer.
10061 *QuicCoalescedPacketPeer::GetMutableEncryptedBuffer(
10062 coalesced_packet, ENCRYPTION_FORWARD_SECURE) += "!!! TEST !!!";
10063
10064 QUIC_LOG(INFO) << "Reduced coalesced_packet_max_length from "
10065 << coalesced_packet_max_length << " to "
10066 << coalesced_packet.max_packet_length()
10067 << ", coalesced_packet.length:"
10068 << coalesced_packet.length()
10069 << ", coalesced_packet.packet_lengths:"
10070 << absl::StrJoin(coalesced_packet.packet_lengths(), ":");
10071 }
10072
10073 EXPECT_FALSE(connection_.connected());
10074 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10075 IsError(QUIC_FAILED_TO_SERIALIZE_PACKET));
10076 EXPECT_EQ(saved_connection_close_frame_.error_details,
10077 "Failed to serialize coalesced packet.");
Bence Békybac04052022-04-07 15:44:29 -040010078 };
10079
10080 EXPECT_QUIC_BUG(test_body(), "SerializeCoalescedPacket failed.");
Bence Békybac04052022-04-07 15:44:29 -040010081}
10082
Bence Békybac04052022-04-07 15:44:29 -040010083TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10084 if (!connection_.version().UsesTls()) {
10085 return;
10086 }
10087 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10088 QuicFrames frames;
10089 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10090 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10091 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10092}
10093
10094TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10095 if (!connection_.version().UsesTls()) {
10096 return;
10097 }
10098 set_perspective(Perspective::IS_SERVER);
10099 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10100 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
10101 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
10102 }
10103 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10104 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10105 QuicFrames frames;
10106 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10107 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10108 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10109 EXPECT_EQ(1, connection_close_frame_count_);
10110 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10111 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10112}
10113
10114TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10115 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10116 return;
10117 }
Bence Békybac04052022-04-07 15:44:29 -040010118 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010119 connection_.SetEncrypter(
10120 ENCRYPTION_HANDSHAKE,
10121 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010122 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10123 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10124 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080010125 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010126
10127 // Send application data.
10128 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10129 0, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010130 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010131 QuicTime retransmission_time =
10132 connection_.GetRetransmissionAlarm()->deadline();
10133 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10134
10135 // Retransmit handshake data.
10136 clock_.AdvanceTime(retransmission_time - clock_.Now());
10137 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _));
10138 connection_.GetRetransmissionAlarm()->Fire();
10139 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010140 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010141
10142 // Send application data.
10143 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10144 4, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010145 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010146 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10147 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10148
10149 // Retransmit handshake data again.
10150 clock_.AdvanceTime(retransmission_time - clock_.Now());
10151 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _));
10152 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(8), _, _));
10153 connection_.GetRetransmissionAlarm()->Fire();
10154 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010155 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010156
10157 // Discard handshake key.
10158 connection_.OnHandshakeComplete();
10159 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10160 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10161
10162 // Retransmit application data.
10163 clock_.AdvanceTime(retransmission_time - clock_.Now());
10164 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(11), _, _));
10165 connection_.GetRetransmissionAlarm()->Fire();
martinduke9e0811c2022-12-08 20:35:57 -080010166 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010167}
10168
10169void QuicConnectionTest::TestClientRetryHandling(
10170 bool invalid_retry_tag, bool missing_original_id_in_config,
10171 bool wrong_original_id_in_config, bool missing_retry_id_in_config,
10172 bool wrong_retry_id_in_config) {
10173 if (invalid_retry_tag) {
10174 ASSERT_FALSE(missing_original_id_in_config);
10175 ASSERT_FALSE(wrong_original_id_in_config);
10176 ASSERT_FALSE(missing_retry_id_in_config);
10177 ASSERT_FALSE(wrong_retry_id_in_config);
10178 } else {
10179 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10180 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
10181 }
10182 if (!version().UsesTls()) {
10183 return;
10184 }
10185
10186 // These values come from draft-ietf-quic-v2 Appendix A.4.
10187 uint8_t retry_packet_rfcv2[] = {
martindukea2cb68a2022-12-12 17:24:39 -080010188 0xcf, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10189 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xc8, 0x64, 0x6c, 0xe8,
10190 0xbf, 0xe3, 0x39, 0x52, 0xd9, 0x55, 0x54, 0x36, 0x65, 0xdc, 0xc7, 0xb6};
Bence Békybac04052022-04-07 15:44:29 -040010191 // These values come from RFC9001 Appendix A.4.
10192 uint8_t retry_packet_rfcv1[] = {
10193 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10194 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba,
10195 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba};
10196 uint8_t retry_packet29[] = {
10197 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10198 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10199 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
10200
10201 uint8_t* retry_packet;
10202 size_t retry_packet_length;
martinduke88918ac2023-06-02 10:44:08 -070010203 if (version() == ParsedQuicVersion::RFCv2()) {
Bence Békybac04052022-04-07 15:44:29 -040010204 retry_packet = retry_packet_rfcv2;
10205 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv2);
10206 } else if (version() == ParsedQuicVersion::RFCv1()) {
10207 retry_packet = retry_packet_rfcv1;
10208 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv1);
10209 } else if (version() == ParsedQuicVersion::Draft29()) {
10210 retry_packet = retry_packet29;
10211 retry_packet_length = ABSL_ARRAYSIZE(retry_packet29);
10212 } else {
10213 // TODO(dschinazi) generate retry packets for all versions once we have
10214 // server-side support for generating these programmatically.
10215 return;
10216 }
10217
10218 uint8_t original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10219 0x3e, 0x51, 0x57, 0x08};
10220 uint8_t new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10221 0x2a, 0x42, 0x62, 0xb5};
10222 uint8_t retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10223
10224 QuicConnectionId original_connection_id(
10225 reinterpret_cast<char*>(original_connection_id_bytes),
10226 ABSL_ARRAYSIZE(original_connection_id_bytes));
10227 QuicConnectionId new_connection_id(
10228 reinterpret_cast<char*>(new_connection_id_bytes),
10229 ABSL_ARRAYSIZE(new_connection_id_bytes));
10230
10231 std::string retry_token(reinterpret_cast<char*>(retry_token_bytes),
10232 ABSL_ARRAYSIZE(retry_token_bytes));
10233
10234 if (invalid_retry_tag) {
10235 // Flip the last bit of the retry packet to prevent the integrity tag
10236 // from validating correctly.
10237 retry_packet[retry_packet_length - 1] ^= 1;
10238 }
10239
10240 QuicConnectionId config_original_connection_id = original_connection_id;
10241 if (wrong_original_id_in_config) {
10242 // Flip the first bit of the connection ID.
10243 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10244 config_original_connection_id.mutable_data()[0] ^= 0x80;
10245 }
10246 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10247 if (wrong_retry_id_in_config) {
10248 // Flip the first bit of the connection ID.
10249 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10250 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10251 }
10252
10253 // Make sure the connection uses the connection ID from the test vectors,
10254 QuicConnectionPeer::SetServerConnectionId(&connection_,
10255 original_connection_id);
10256 // Make sure our fake framer has the new post-retry INITIAL keys so that any
10257 // retransmission triggered by retry can be decrypted.
10258 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10259
10260 // Process the RETRY packet.
10261 connection_.ProcessUdpPacket(
10262 kSelfAddress, kPeerAddress,
10263 QuicReceivedPacket(reinterpret_cast<char*>(retry_packet),
10264 retry_packet_length, clock_.Now()));
10265
10266 if (invalid_retry_tag) {
10267 // Make sure we refuse to process a RETRY with invalid tag.
10268 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10269 EXPECT_EQ(connection_.connection_id(), original_connection_id);
10270 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
10271 QuicConnectionPeer::GetPacketCreator(&connection_))
10272 .empty());
10273 return;
10274 }
10275
10276 // Make sure we correctly parsed the RETRY.
10277 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10278 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10279 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10280 QuicConnectionPeer::GetPacketCreator(&connection_)),
10281 retry_token);
10282
10283 // Test validating the original_connection_id from the config.
10284 QuicConfig received_config;
10285 QuicConfigPeer::SetNegotiated(&received_config, true);
10286 if (connection_.version().UsesTls()) {
10287 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10288 &received_config, connection_.connection_id());
10289 if (!missing_retry_id_in_config) {
10290 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10291 &received_config, config_retry_source_connection_id);
10292 }
10293 }
10294 if (!missing_original_id_in_config) {
10295 QuicConfigPeer::SetReceivedOriginalConnectionId(
10296 &received_config, config_original_connection_id);
10297 }
10298
10299 if (missing_original_id_in_config || wrong_original_id_in_config ||
10300 missing_retry_id_in_config || wrong_retry_id_in_config) {
10301 EXPECT_CALL(visitor_,
10302 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10303 .Times(1);
10304 } else {
10305 EXPECT_CALL(visitor_,
10306 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10307 .Times(0);
10308 }
10309 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10310 connection_.SetFromConfig(received_config);
10311 if (missing_original_id_in_config || wrong_original_id_in_config ||
10312 missing_retry_id_in_config || wrong_retry_id_in_config) {
10313 ASSERT_FALSE(connection_.connected());
10314 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10315 } else {
10316 EXPECT_TRUE(connection_.connected());
10317 }
10318}
10319
10320TEST_P(QuicConnectionTest, ClientParsesRetry) {
10321 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10322 /*missing_original_id_in_config=*/false,
10323 /*wrong_original_id_in_config=*/false,
10324 /*missing_retry_id_in_config=*/false,
10325 /*wrong_retry_id_in_config=*/false);
10326}
10327
10328TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
10329 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10330 /*missing_original_id_in_config=*/false,
10331 /*wrong_original_id_in_config=*/false,
10332 /*missing_retry_id_in_config=*/false,
10333 /*wrong_retry_id_in_config=*/false);
10334}
10335
10336TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
10337 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10338 /*missing_original_id_in_config=*/true,
10339 /*wrong_original_id_in_config=*/false,
10340 /*missing_retry_id_in_config=*/false,
10341 /*wrong_retry_id_in_config=*/false);
10342}
10343
10344TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
10345 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10346 /*missing_original_id_in_config=*/false,
10347 /*wrong_original_id_in_config=*/true,
10348 /*missing_retry_id_in_config=*/false,
10349 /*wrong_retry_id_in_config=*/false);
10350}
10351
10352TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10353 if (!connection_.version().UsesTls()) {
10354 // Versions that do not authenticate connection IDs never send the
10355 // retry_source_connection_id transport parameter.
10356 return;
10357 }
10358 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10359 /*missing_original_id_in_config=*/false,
10360 /*wrong_original_id_in_config=*/false,
10361 /*missing_retry_id_in_config=*/true,
10362 /*wrong_retry_id_in_config=*/false);
10363}
10364
10365TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10366 if (!connection_.version().UsesTls()) {
10367 // Versions that do not authenticate connection IDs never send the
10368 // retry_source_connection_id transport parameter.
10369 return;
10370 }
10371 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10372 /*missing_original_id_in_config=*/false,
10373 /*wrong_original_id_in_config=*/false,
10374 /*missing_retry_id_in_config=*/false,
10375 /*wrong_retry_id_in_config=*/true);
10376}
10377
10378TEST_P(QuicConnectionTest, ClientRetransmitsInitialPacketsOnRetry) {
10379 if (!connection_.version().HasIetfQuicFrames()) {
10380 // TestClientRetryHandling() currently only supports IETF draft versions.
10381 return;
10382 }
10383 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10384
10385 connection_.SendCryptoStreamData();
10386
10387 EXPECT_EQ(1u, writer_->packets_write_attempts());
10388 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10389 /*missing_original_id_in_config=*/false,
10390 /*wrong_original_id_in_config=*/false,
10391 /*missing_retry_id_in_config=*/false,
10392 /*wrong_retry_id_in_config=*/false);
10393
10394 // Verify that initial data is retransmitted immediately after receiving
10395 // RETRY.
10396 if (GetParam().ack_response == AckResponse::kImmediate) {
10397 EXPECT_EQ(2u, writer_->packets_write_attempts());
10398 EXPECT_EQ(1u, writer_->framer()->crypto_frames().size());
10399 }
10400}
10401
10402TEST_P(QuicConnectionTest, NoInitialPacketsRetransmissionOnInvalidRetry) {
10403 if (!connection_.version().HasIetfQuicFrames()) {
10404 return;
10405 }
10406 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10407
10408 connection_.SendCryptoStreamData();
10409
10410 EXPECT_EQ(1u, writer_->packets_write_attempts());
10411 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10412 /*missing_original_id_in_config=*/false,
10413 /*wrong_original_id_in_config=*/false,
10414 /*missing_retry_id_in_config=*/false,
10415 /*wrong_retry_id_in_config=*/false);
10416
10417 EXPECT_EQ(1u, writer_->packets_write_attempts());
10418}
10419
10420TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
10421 if (!connection_.version().UsesTls()) {
10422 // QUIC+TLS is required to transmit connection ID transport parameters.
10423 return;
10424 }
10425 if (connection_.version().UsesTls()) {
10426 // Versions that authenticate connection IDs always send the
10427 // original_destination_connection_id transport parameter.
10428 return;
10429 }
10430 // Make sure that receiving the original_destination_connection_id transport
10431 // parameter fails the handshake when no RETRY packet was received before it.
10432 QuicConfig received_config;
10433 QuicConfigPeer::SetNegotiated(&received_config, true);
10434 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10435 TestConnectionId(0x12345));
10436 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10437 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10438 .Times(1);
10439 connection_.SetFromConfig(received_config);
10440 EXPECT_FALSE(connection_.connected());
10441 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10442}
10443
10444TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10445 if (!connection_.version().UsesTls()) {
10446 // Versions that do not authenticate connection IDs never send the
10447 // retry_source_connection_id transport parameter.
10448 return;
10449 }
10450 // Make sure that receiving the retry_source_connection_id transport parameter
10451 // fails the handshake when no RETRY packet was received before it.
10452 QuicConfig received_config;
10453 QuicConfigPeer::SetNegotiated(&received_config, true);
10454 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10455 TestConnectionId(0x12345));
10456 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10457 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10458 .Times(1);
10459 connection_.SetFromConfig(received_config);
10460 EXPECT_FALSE(connection_.connected());
10461 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10462}
10463
10464// Regression test for http://crbug/1047977
10465TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10466 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10467 return;
10468 }
10469 // Received frame causes connection close.
10470 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10471 .WillOnce(InvokeWithoutArgs([this]() {
10472 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10473 connection_.CloseConnection(
10474 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10475 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10476 return true;
10477 }));
10478 QuicFrames frames;
10479 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10480 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10481 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10482}
10483
10484TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10485 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10486 return;
10487 }
10488 // Received frame causes connection close.
10489 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10490 .WillOnce(InvokeWithoutArgs([this]() {
10491 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10492 connection_.CloseConnection(
10493 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10494 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10495 return true;
10496 }));
10497 QuicFrames frames;
10498 frames.push_back(
10499 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10500 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10501 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10502}
10503
10504TEST_P(QuicConnectionTest,
10505 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10506 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10507 return;
10508 }
10509 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10510 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10511 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10512 // Receives packet 1000 in initial data.
10513 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10514 // Receives packet 2000 in application data.
10515 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10516 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10517 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10518 connection_.CloseConnection(
10519 kQuicErrorCode, "Some random error message",
10520 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10521
10522 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10523
10524 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10525 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10526 // Verify ack is bundled.
10527 EXPECT_EQ(1u, writer_->ack_frames().size());
10528
10529 if (!connection_.version().CanSendCoalescedPackets()) {
10530 // Each connection close packet should be sent in distinct UDP packets.
10531 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10532 writer_->connection_close_packets());
10533 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10534 writer_->packets_write_attempts());
10535 return;
10536 }
10537
10538 // A single UDP packet should be sent with multiple connection close packets
10539 // coalesced together.
10540 EXPECT_EQ(1u, writer_->packets_write_attempts());
10541
10542 // Only the first packet has been processed yet.
10543 EXPECT_EQ(1u, writer_->connection_close_packets());
10544
10545 // ProcessPacket resets the visitor and frees the coalesced packet.
10546 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10547 auto packet = writer_->coalesced_packet()->Clone();
10548 writer_->framer()->ProcessPacket(*packet);
10549 EXPECT_EQ(1u, writer_->connection_close_packets());
10550 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10551 // Verify ack is bundled.
10552 EXPECT_EQ(1u, writer_->ack_frames().size());
10553 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10554}
10555
10556// Regression test for b/151220135.
10557TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
Bence Békybac04052022-04-07 15:44:29 -040010558 QuicConfig config;
10559 QuicTagVector connection_options;
10560 connection_options.push_back(kPTOS);
10561 connection_options.push_back(k1PTO);
10562 config.SetConnectionOptionsToSend(connection_options);
10563 if (connection_.version().UsesTls()) {
10564 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10565 &config, kMaxAcceptedDatagramFrameSize);
10566 }
10567 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10568 connection_.SetFromConfig(config);
10569 connection_.OnHandshakeComplete();
10570 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10571
10572 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10573 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10574
10575 // PTO fires, verify a PING packet gets sent because there is no data to
10576 // send.
10577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10578 connection_.GetRetransmissionAlarm()->Fire();
10579 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10580 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10581 EXPECT_EQ(1u, writer_->ping_frames().size());
10582}
10583
10584// Regression test for b/155757133
10585TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10586 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10587 return;
10588 }
10589 const size_t kMinRttMs = 40;
10590 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10591 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10592 QuicTime::Delta::Zero(), QuicTime::Zero());
10593 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -070010594 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040010595 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10596 // Discard INITIAL key.
10597 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10598 connection_.NeuterUnencryptedPackets();
10599 EXPECT_CALL(visitor_, GetHandshakeState())
10600 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10601
10602 ProcessPacket(2);
10603 ProcessPacket(3);
10604 ProcessPacket(4);
10605 // Process a packet containing stream frame followed by ACK of packets 1.
10606 QuicFrames frames;
10607 frames.push_back(QuicFrame(QuicStreamFrame(
10608 QuicUtils::GetFirstBidirectionalStreamId(
10609 connection_.version().transport_version, Perspective::IS_CLIENT),
10610 false, 0u, absl::string_view())));
10611 QuicAckFrame ack_frame = InitAckFrame(1);
10612 frames.push_back(QuicFrame(&ack_frame));
10613 // Receiving stream frame causes something to send.
10614 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10615 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
10616 // Verify now the queued ACK contains packet number 2.
10617 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10618 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10619 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10620 }));
10621 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10622 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10623}
10624
martinduke9e0811c2022-12-08 20:35:57 -080010625TEST_P(QuicConnectionTest, DoNotExtendIdleTimeOnUndecryptablePackets) {
Bence Békybac04052022-04-07 15:44:29 -040010626 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10627 QuicConfig config;
10628 connection_.SetFromConfig(config);
10629 // Subtract a second from the idle timeout on the client side.
10630 QuicTime initial_deadline =
10631 clock_.ApproximateNow() +
10632 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10633 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10634
10635 // Received an undecryptable packet.
10636 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080010637 peer_framer_.SetEncrypter(
10638 ENCRYPTION_FORWARD_SECURE,
10639 std::make_unique<quic::NullEncrypter>(Perspective::IS_CLIENT));
Bence Békybac04052022-04-07 15:44:29 -040010640 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10641 // Verify deadline does not get extended.
10642 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10643 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10644 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10645 clock_.AdvanceTime(delay);
10646 connection_.GetTimeoutAlarm()->Fire();
10647 // Verify connection gets closed.
10648 EXPECT_FALSE(connection_.connected());
10649}
10650
10651TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10652 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10653 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10654
10655 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10656 notifier_.WriteOrBufferWindowUpate(0, 0);
10657 }));
10658 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10659 ProcessDataPacket(1);
10660 // Verify ACK is bundled with WINDOW_UPDATE.
10661 EXPECT_FALSE(writer_->ack_frames().empty());
10662 EXPECT_FALSE(connection_.HasPendingAcks());
10663}
10664
10665TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10666 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10667 return;
10668 }
10669 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10670 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10671 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10672 }
10673 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010674 // Receives packet 1000 in initial data.
10675 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10676 EXPECT_TRUE(connection_.HasPendingAcks());
10677
martinduke9e0811c2022-12-08 20:35:57 -080010678 peer_framer_.SetEncrypter(
10679 ENCRYPTION_ZERO_RTT,
10680 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040010681 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080010682 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040010683 // Receives packet 1000 in application data.
10684 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
10685 EXPECT_TRUE(connection_.HasPendingAcks());
10686 // Verify ACK deadline does not change.
10687 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10688 connection_.GetAckAlarm()->deadline());
10689
10690 // Ack alarm fires early.
10691 // Verify the earliest ACK is flushed.
10692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10693 connection_.GetAckAlarm()->Fire();
10694 EXPECT_TRUE(connection_.HasPendingAcks());
10695 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10696 connection_.GetAckAlarm()->deadline());
10697}
10698
10699TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
10700 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10701 return;
10702 }
10703 QuicConfig config;
10704 QuicTagVector connection_options;
10705 connection_options.push_back(kCBHD);
10706 config.SetConnectionOptionsToSend(connection_options);
10707 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10708 connection_.SetFromConfig(config);
10709 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080010710 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
10711 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -040010712 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10713 // Send stream data.
10714 SendStreamDataToPeer(
10715 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10716 0, FIN, nullptr);
10717 // Verify blackhole detection is in progress.
10718 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10719}
10720
10721TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
10722 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10723 return;
10724 }
10725 set_perspective(Perspective::IS_SERVER);
10726 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10727 if (version().SupportsAntiAmplificationLimit()) {
10728 QuicConnectionPeer::SetAddressValidated(&connection_);
10729 }
10730 QuicConfig config;
10731 QuicTagVector connection_options;
10732 connection_options.push_back(kCBHD);
10733 config.SetInitialReceivedConnectionOptions(connection_options);
10734 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10735 connection_.SetFromConfig(config);
10736 EXPECT_CALL(visitor_, GetHandshakeState())
10737 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10738 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10739 // Send stream data.
10740 SendStreamDataToPeer(
10741 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10742 0, FIN, nullptr);
10743 // Verify blackhole detection is disabled.
10744 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10745}
10746
Bence Békybac04052022-04-07 15:44:29 -040010747// Regresstion test for b/158491591.
10748TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
10749 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10750 return;
10751 }
Bence Békybac04052022-04-07 15:44:29 -040010752 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010753 connection_.SetEncrypter(
10754 ENCRYPTION_HANDSHAKE,
10755 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010756 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10757 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10758 QuicConfig config;
10759 QuicTagVector connection_options;
10760 connection_options.push_back(k5RTO);
10761 config.SetConnectionOptionsToSend(connection_options);
10762 QuicConfigPeer::SetNegotiated(&config, true);
fayang59e518a2022-11-29 11:16:45 -080010763 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10764 GetQuicReloadableFlag(
10765 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040010766 EXPECT_CALL(visitor_, GetHandshakeState())
10767 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10768 }
10769 if (connection_.version().UsesTls()) {
10770 QuicConfigPeer::SetReceivedOriginalConnectionId(
10771 &config, connection_.connection_id());
10772 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10773 &config, connection_.connection_id());
10774 }
10775 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10776 connection_.SetFromConfig(config);
10777
10778 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
fayang59e518a2022-11-29 11:16:45 -080010779 if (GetQuicReloadableFlag(
10780 quic_no_path_degrading_before_handshake_confirmed)) {
10781 // No blackhole detection before handshake confirmed.
10782 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10783 } else {
10784 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10785 }
Bence Békybac04052022-04-07 15:44:29 -040010786 // Discard handshake keys.
fayang59e518a2022-11-29 11:16:45 -080010787 EXPECT_CALL(visitor_, GetHandshakeState())
10788 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040010789 connection_.OnHandshakeComplete();
fayang59e518a2022-11-29 11:16:45 -080010790 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10791 GetQuicReloadableFlag(
10792 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040010793 // Verify blackhole detection stops.
10794 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10795 } else {
10796 // Problematic: although there is nothing in flight, blackhole detection is
10797 // still in progress.
10798 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10799 }
10800}
10801
10802TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
10803 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10804 return;
10805 }
10806 // SetFromConfig is always called after construction from InitializeSession.
10807 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10808 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10809 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10810 QuicConfig config;
10811 connection_.SetFromConfig(config);
10812 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10813 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040010814
martinduke9e0811c2022-12-08 20:35:57 -080010815 peer_framer_.SetEncrypter(
10816 ENCRYPTION_HANDSHAKE,
10817 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10818 peer_framer_.SetEncrypter(
10819 ENCRYPTION_FORWARD_SECURE,
10820 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010821
10822 for (uint64_t i = 1; i <= 3; ++i) {
10823 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10824 }
10825 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10826 for (uint64_t j = 5; j <= 7; ++j) {
10827 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10828 }
10829 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10830 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10831 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080010832 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010833 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080010834 connection_.SetEncrypter(
10835 ENCRYPTION_HANDSHAKE,
10836 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010837 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10838 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
10839 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10840 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
10841 }
10842 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10843 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10844
martinduke9e0811c2022-12-08 20:35:57 -080010845 SetDecrypter(
10846 ENCRYPTION_FORWARD_SECURE,
10847 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010848 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10849 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080010850 connection_.SetEncrypter(
10851 ENCRYPTION_FORWARD_SECURE,
10852 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010853 // Verify the 1-RTT packet gets processed.
10854 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
10855 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10856 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10857}
10858
10859TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
10860 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10861 return;
10862 }
10863 set_perspective(Perspective::IS_SERVER);
10864 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10865 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10866 }
10867 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010868 // Receives packet 1000 in initial data.
10869 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10870 EXPECT_TRUE(connection_.HasPendingAcks());
10871
Bence Békybac04052022-04-07 15:44:29 -040010872 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10873 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10874 QuicTime expected_pto_time =
10875 connection_.sent_packet_manager().GetRetransmissionTime();
10876
10877 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10878 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10879 std::make_unique<TaggingEncrypter>(0x02));
10880 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10881 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10882 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10883 // Verify PTO time does not change.
10884 EXPECT_EQ(expected_pto_time,
10885 connection_.sent_packet_manager().GetRetransmissionTime());
10886
10887 // Receives packet 1001 in initial data.
10888 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
10889 EXPECT_TRUE(connection_.HasPendingAcks());
10890 // Receives packet 1002 in initial data.
10891 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
10892 EXPECT_FALSE(writer_->ack_frames().empty());
10893 // Verify CRYPTO frame is bundled with INITIAL ACK.
10894 EXPECT_FALSE(writer_->crypto_frames().empty());
10895 // Verify PTO time changes.
10896 EXPECT_NE(expected_pto_time,
10897 connection_.sent_packet_manager().GetRetransmissionTime());
10898}
10899
10900TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
10901 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10902 return;
10903 }
10904 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
10905 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10906 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10907 }
10908 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
martinduke9e0811c2022-12-08 20:35:57 -080010909 connection_.SetEncrypter(
10910 ENCRYPTION_HANDSHAKE,
10911 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010912 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10913 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080010914 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
10915 peer_framer_.SetEncrypter(
10916 ENCRYPTION_HANDSHAKE,
10917 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010918 // Receives packet 1000 in handshake data.
10919 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
10920 EXPECT_TRUE(connection_.HasPendingAcks());
10921 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10922 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10923
10924 // Receives packet 1001 in handshake data.
10925 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
10926 EXPECT_TRUE(connection_.HasPendingAcks());
10927 // Receives packet 1002 in handshake data.
10928 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
10929 EXPECT_FALSE(writer_->ack_frames().empty());
10930 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
10931 EXPECT_FALSE(writer_->crypto_frames().empty());
10932}
10933
10934// Regresstion test for b/156232673.
10935TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
10936 if (!connection_.version().CanSendCoalescedPackets()) {
10937 return;
10938 }
10939 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10940 {
10941 QuicConnection::ScopedPacketFlusher flusher(&connection_);
martinduke9e0811c2022-12-08 20:35:57 -080010942 connection_.SetEncrypter(
10943 ENCRYPTION_HANDSHAKE,
10944 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10945 connection_.SetEncrypter(
10946 ENCRYPTION_FORWARD_SECURE,
10947 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010948 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10949 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
10950 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10951 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
10952 // Verify soft max packet length gets resumed and handshake packet gets
10953 // successfully sent.
10954 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
10955 }
10956}
10957
10958// Regression test for b/160790422.
10959TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
10960 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10961 return;
10962 }
10963 set_perspective(Perspective::IS_SERVER);
10964 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10965 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10966 }
10967 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010968 // Receives packet 1000 in initial data.
10969 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10970 EXPECT_TRUE(connection_.HasPendingAcks());
10971
Bence Békybac04052022-04-07 15:44:29 -040010972 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10973 // Send INITIAL 1.
10974 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10975 QuicTime expected_pto_time =
10976 connection_.sent_packet_manager().GetRetransmissionTime();
10977
10978 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martinduke9e0811c2022-12-08 20:35:57 -080010979 connection_.SetEncrypter(
10980 ENCRYPTION_HANDSHAKE,
10981 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010982 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10983 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10984 // Send HANDSHAKE 2 and 3.
10985 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10986 connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
10987 // Verify PTO time does not change.
10988 EXPECT_EQ(expected_pto_time,
10989 connection_.sent_packet_manager().GetRetransmissionTime());
10990
10991 // Receives ACK for HANDSHAKE 2.
10992 QuicFrames frames;
10993 auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
10994 frames.push_back(QuicFrame(&ack_frame));
martindukeba002452023-03-21 08:10:46 -070010995 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040010996 ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
10997 // Discard INITIAL key.
10998 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10999 connection_.NeuterUnencryptedPackets();
11000 // Receives PING from peer.
11001 frames.clear();
11002 frames.push_back(QuicFrame(QuicPingFrame()));
11003 frames.push_back(QuicFrame(QuicPaddingFrame(3)));
11004 ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
11005 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
11006 connection_.GetAckAlarm()->deadline());
11007 // Fire ACK alarm.
11008 clock_.AdvanceTime(kAlarmGranularity);
11009 connection_.GetAckAlarm()->Fire();
11010 EXPECT_FALSE(writer_->ack_frames().empty());
11011 // Verify handshake data gets retransmitted early.
11012 EXPECT_FALSE(writer_->crypto_frames().empty());
11013}
11014
11015// Regression test for b/161228202
11016TEST_P(QuicConnectionTest, InflatedRttSample) {
11017 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11018 return;
11019 }
11020 // 30ms RTT.
11021 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
11022 set_perspective(Perspective::IS_SERVER);
11023 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
Bence Békybac04052022-04-07 15:44:29 -040011024 // Receives packet 1000 in initial data.
11025 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11026 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11027 }
11028 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11029 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11030 EXPECT_TRUE(connection_.HasPendingAcks());
11031
Bence Békybac04052022-04-07 15:44:29 -040011032 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11033 // Send INITIAL 1.
11034 std::string initial_crypto_data(512, 'a');
11035 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11036 ENCRYPTION_INITIAL);
11037 ASSERT_TRUE(connection_.sent_packet_manager()
11038 .GetRetransmissionTime()
11039 .IsInitialized());
11040 QuicTime::Delta pto_timeout =
11041 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11042 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011043 connection_.SetEncrypter(
11044 ENCRYPTION_HANDSHAKE,
11045 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011046 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11047 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11048 std::string handshake_crypto_data(1024, 'a');
11049 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11050 ENCRYPTION_HANDSHAKE);
11051
11052 // INITIAL 1 gets lost and PTO fires.
11053 clock_.AdvanceTime(pto_timeout);
11054 connection_.GetRetransmissionAlarm()->Fire();
11055
11056 clock_.AdvanceTime(kTestRTT);
11057 // Assume retransmitted INITIAL gets received.
11058 QuicFrames frames;
11059 auto ack_frame = InitAckFrame({{QuicPacketNumber(4), QuicPacketNumber(5)}});
11060 frames.push_back(QuicFrame(&ack_frame));
martindukeba002452023-03-21 08:10:46 -070011061 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040011062 .Times(AnyNumber());
11063 ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
11064 EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
11065 // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
11066 frames.clear();
11067 // HANDSHAKE 5 is also processed.
11068 QuicAckFrame ack_frame2 =
11069 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
11070 {QuicPacketNumber(5), QuicPacketNumber(6)}});
11071 ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
11072 frames.push_back(QuicFrame(&ack_frame2));
11073 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
11074 // Verify RTT inflation gets mitigated.
11075 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
11076}
11077
11078// Regression test for b/161228202
martinduke9e0811c2022-12-08 20:35:57 -080011079TEST_P(QuicConnectionTest, CoalescingPacketCausesInfiniteLoop) {
Bence Békybac04052022-04-07 15:44:29 -040011080 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11081 return;
11082 }
11083 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040011084 // Receives packet 1000 in initial data.
11085 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11086 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11087 }
11088 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11089
11090 // Set anti amplification factor to 2, such that RetransmitDataOfSpaceIfAny
11091 // makes no forward progress and causes infinite loop.
birenroyef686222022-09-12 11:34:34 -070011092 SetQuicFlag(quic_anti_amplification_factor, 2);
Bence Békybac04052022-04-07 15:44:29 -040011093
11094 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11095 EXPECT_TRUE(connection_.HasPendingAcks());
11096
Bence Békybac04052022-04-07 15:44:29 -040011097 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11098 // Send INITIAL 1.
11099 std::string initial_crypto_data(512, 'a');
11100 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11101 ENCRYPTION_INITIAL);
11102 ASSERT_TRUE(connection_.sent_packet_manager()
11103 .GetRetransmissionTime()
11104 .IsInitialized());
11105 QuicTime::Delta pto_timeout =
11106 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11107 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011108 connection_.SetEncrypter(
11109 ENCRYPTION_HANDSHAKE,
11110 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011111 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11112 // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
11113 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11114 std::string handshake_crypto_data(1024, 'a');
11115 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11116 ENCRYPTION_HANDSHAKE);
11117
11118 // INITIAL 1 gets lost and PTO fires.
11119 clock_.AdvanceTime(pto_timeout);
11120 connection_.GetRetransmissionAlarm()->Fire();
11121}
11122
11123TEST_P(QuicConnectionTest, ClientAckDelayForAsyncPacketProcessing) {
11124 if (!version().HasIetfQuicFrames()) {
11125 return;
11126 }
11127 // SetFromConfig is always called after construction from InitializeSession.
11128 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11129 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11130 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11131 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11132 connection_.NeuterUnencryptedPackets();
11133 }));
11134 QuicConfig config;
11135 connection_.SetFromConfig(config);
11136 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080011137 peer_framer_.SetEncrypter(
11138 ENCRYPTION_HANDSHAKE,
11139 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011140 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11141
11142 // Received undecryptable HANDSHAKE 2.
11143 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11144 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11145 // Received INITIAL 4 (which is retransmission of INITIAL 1) after 100ms.
11146 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
11147 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL);
11148 // Generate HANDSHAKE key.
11149 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080011150 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011151 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080011152 connection_.SetEncrypter(
11153 ENCRYPTION_HANDSHAKE,
11154 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011155 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11156 // Verify HANDSHAKE packet gets processed.
fayangfea655c2022-05-17 08:19:12 -070011157 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -040011158 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
fayangfea655c2022-05-17 08:19:12 -070011159 // Verify immediate ACK has been sent out when flush went out of scope.
11160 ASSERT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -040011161 ASSERT_FALSE(writer_->ack_frames().empty());
fayangfea655c2022-05-17 08:19:12 -070011162 // Verify the ack_delay_time in the sent HANDSHAKE ACK frame is 100ms.
11163 EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
Bence Békybac04052022-04-07 15:44:29 -040011164 writer_->ack_frames()[0].ack_delay_time);
11165 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
11166}
11167
11168TEST_P(QuicConnectionTest, TestingLiveness) {
11169 const size_t kMinRttMs = 40;
11170 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11171 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11172 QuicTime::Delta::Zero(), QuicTime::Zero());
11173 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11174 QuicConfig config;
11175
11176 CryptoHandshakeMessage msg;
11177 std::string error_details;
11178 QuicConfig client_config;
11179 client_config.SetInitialStreamFlowControlWindowToSend(
11180 kInitialStreamFlowControlWindowForTest);
11181 client_config.SetInitialSessionFlowControlWindowToSend(
11182 kInitialSessionFlowControlWindowForTest);
11183 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11184 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11185 const QuicErrorCode error =
11186 config.ProcessPeerHello(msg, CLIENT, &error_details);
11187 EXPECT_THAT(error, IsQuicNoError());
11188
11189 if (connection_.version().UsesTls()) {
11190 QuicConfigPeer::SetReceivedOriginalConnectionId(
11191 &config, connection_.connection_id());
11192 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11193 &config, connection_.connection_id());
11194 }
11195
11196 connection_.SetFromConfig(config);
11197 connection_.OnHandshakeComplete();
11198 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11199 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11200 EXPECT_FALSE(connection_.MaybeTestLiveness());
11201
haoyuewang7b43efb2022-04-20 16:26:03 -070011202 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040011203 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11204 // Advance time to near the idle timeout.
11205 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11206 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11207 EXPECT_TRUE(connection_.MaybeTestLiveness());
11208 // Verify idle deadline does not change.
haoyuewang7b43efb2022-04-20 16:26:03 -070011209 EXPECT_EQ(deadline, QuicConnectionPeer::GetIdleNetworkDeadline(&connection_));
Bence Békybac04052022-04-07 15:44:29 -040011210}
11211
fayang5783c332022-12-14 09:30:25 -080011212TEST_P(QuicConnectionTest, DisableLivenessTesting) {
11213 const size_t kMinRttMs = 40;
11214 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11215 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11216 QuicTime::Delta::Zero(), QuicTime::Zero());
11217 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11218 QuicConfig config;
11219
11220 CryptoHandshakeMessage msg;
11221 std::string error_details;
11222 QuicConfig client_config;
11223 client_config.SetInitialStreamFlowControlWindowToSend(
11224 kInitialStreamFlowControlWindowForTest);
11225 client_config.SetInitialSessionFlowControlWindowToSend(
11226 kInitialSessionFlowControlWindowForTest);
11227 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11228 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11229 const QuicErrorCode error =
11230 config.ProcessPeerHello(msg, CLIENT, &error_details);
11231 EXPECT_THAT(error, IsQuicNoError());
11232
11233 if (connection_.version().UsesTls()) {
11234 QuicConfigPeer::SetReceivedOriginalConnectionId(
11235 &config, connection_.connection_id());
11236 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11237 &config, connection_.connection_id());
11238 }
11239
11240 connection_.SetFromConfig(config);
11241 connection_.OnHandshakeComplete();
11242 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11243 connection_.DisableLivenessTesting();
11244 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11245 EXPECT_FALSE(connection_.MaybeTestLiveness());
11246
11247 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
11248 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11249 // Advance time to near the idle timeout.
11250 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11251 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11252 EXPECT_FALSE(connection_.MaybeTestLiveness());
11253}
11254
Bence Békybac04052022-04-07 15:44:29 -040011255TEST_P(QuicConnectionTest, SilentIdleTimeout) {
11256 set_perspective(Perspective::IS_SERVER);
11257 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11258 if (version().SupportsAntiAmplificationLimit()) {
11259 QuicConnectionPeer::SetAddressValidated(&connection_);
11260 }
11261
11262 QuicConfig config;
11263 QuicConfigPeer::SetNegotiated(&config, true);
11264 if (connection_.version().UsesTls()) {
11265 QuicConfigPeer::SetReceivedOriginalConnectionId(
11266 &config, connection_.connection_id());
11267 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
11268 QuicConnectionId());
11269 }
11270 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11271 connection_.SetFromConfig(config);
11272
11273 EXPECT_TRUE(connection_.connected());
11274 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11275
11276 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
11277 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
11278 }
11279 EXPECT_CALL(visitor_,
11280 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11281 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11282 connection_.GetTimeoutAlarm()->Fire();
11283 // Verify the connection close packets get serialized and added to
11284 // termination packets list.
11285 EXPECT_NE(nullptr,
11286 QuicConnectionPeer::GetConnectionClosePacket(&connection_));
11287}
11288
martinduke9e0811c2022-12-08 20:35:57 -080011289TEST_P(QuicConnectionTest, DoNotSendPing) {
Bence Békybac04052022-04-07 15:44:29 -040011290 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11291 connection_.OnHandshakeComplete();
11292 EXPECT_TRUE(connection_.connected());
11293 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11294 .WillRepeatedly(Return(true));
11295 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
11296 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11297
11298 SendStreamDataToPeer(
11299 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
11300 "GET /", 0, FIN, nullptr);
11301 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11302 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11303 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
11304 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11305
11306 // Now recevie an ACK and response of the previous packet, which will move the
11307 // ping alarm forward.
11308 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11309 QuicFrames frames;
11310 QuicAckFrame ack_frame = InitAckFrame(1);
11311 frames.push_back(QuicFrame(&ack_frame));
11312 frames.push_back(QuicFrame(QuicStreamFrame(
11313 GetNthClientInitiatedStreamId(0, connection_.transport_version()), true,
11314 0u, absl::string_view())));
11315 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -070011316 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040011317 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11318 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
11319 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11320 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11321 // The ping timer is set slightly less than 15 seconds in the future, because
11322 // of the 1s ping timer alarm granularity.
11323 EXPECT_EQ(
11324 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
11325 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11326
11327 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
11328 // Suppose now ShouldKeepConnectionAlive returns false.
11329 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11330 .WillRepeatedly(Return(false));
11331 // Verify PING does not get sent.
11332 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11333 connection_.GetPingAlarm()->Fire();
11334}
11335
11336// Regression test for b/159698337
11337TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) {
11338 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11339 return;
11340 }
11341 // Finish handshake.
11342 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11343 notifier_.NeuterUnencryptedData();
11344 connection_.NeuterUnencryptedPackets();
11345 connection_.OnHandshakeComplete();
11346 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080011347 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040011348
11349 std::string data(1200, 'a');
11350 // Send data packets 1 - 5.
11351 for (size_t i = 0; i < 5; ++i) {
11352 SendStreamDataToPeer(
11353 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
11354 i * 1200, i == 4 ? FIN : NO_FIN, nullptr);
11355 }
11356 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
11357
martindukeba002452023-03-21 08:10:46 -070011358 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
11359 .Times(3);
Bence Békybac04052022-04-07 15:44:29 -040011360
11361 // ACK packet 5 and 1 and 2 are detected lost.
11362 QuicAckFrame frame =
11363 InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}});
11364 LostPacketVector lost_packets;
11365 lost_packets.push_back(
11366 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
11367 lost_packets.push_back(
11368 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
11369 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11370 .Times(AnyNumber())
11371 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
awillia202240c2024-07-08 09:47:00 -070011372 Return(LossDetectionInterface::DetectionStats())))
11373 .WillRepeatedly(DoDefault());
11374 ;
Bence Békybac04052022-04-07 15:44:29 -040011375 ProcessAckPacket(1, &frame);
11376 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11377 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
11378 EXPECT_TRUE(retransmission_alarm->IsSet());
11379
11380 // ACK packet 1 - 5 and 7.
11381 QuicAckFrame frame2 =
11382 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)},
11383 {QuicPacketNumber(7), QuicPacketNumber(8)}});
11384 ProcessAckPacket(2, &frame2);
11385 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11386
11387 // ACK packet 7 again and assume packet 6 is detected lost.
11388 QuicAckFrame frame3 =
11389 InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}});
11390 lost_packets.clear();
11391 lost_packets.push_back(
11392 LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize));
11393 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11394 .Times(AnyNumber())
11395 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11396 Return(LossDetectionInterface::DetectionStats())));
11397 ProcessAckPacket(3, &frame3);
11398 // Make sure loss detection is cancelled even there is no new acked packets.
11399 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11400}
11401
11402TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) {
11403 EXPECT_TRUE(connection_.connected());
11404 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11405 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
11406 QuicTime::Delta::Zero(), QuicTime::Zero());
11407
11408 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11409 QuicConfig config;
11410 config.SetClientConnectionOptions(QuicTagVector{kFIDT});
11411 QuicConfigPeer::SetNegotiated(&config, true);
11412 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11413 EXPECT_CALL(visitor_, GetHandshakeState())
11414 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11415 }
11416 if (connection_.version().UsesTls()) {
11417 QuicConfigPeer::SetReceivedOriginalConnectionId(
11418 &config, connection_.connection_id());
11419 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11420 &config, connection_.connection_id());
11421 }
11422 connection_.SetFromConfig(config);
11423
11424 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11425 // Send a packet close to timeout.
11426 QuicTime::Delta timeout =
11427 connection_.GetTimeoutAlarm()->deadline() - clock_.Now();
11428 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1));
11429 // Send stream data.
11430 SendStreamDataToPeer(
11431 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11432 0, FIN, nullptr);
11433 // Verify this sent packet does not extend idle timeout since 1s is > PTO
11434 // delay.
11435 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11436 EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
11437 connection_.GetTimeoutAlarm()->deadline() - clock_.Now());
11438
11439 // Received an ACK 100ms later.
11440 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100));
11441 QuicAckFrame ack = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070011442 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040011443 ProcessAckPacket(1, &ack);
11444 // Verify idle timeout gets extended.
11445 EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline());
11446}
11447
11448// Regression test for b/166255274
11449TEST_P(QuicConnectionTest,
11450 ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) {
11451 if (!connection_.version().CanSendCoalescedPackets()) {
11452 return;
11453 }
Bence Békybac04052022-04-07 15:44:29 -040011454 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11455 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11456 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11457 EXPECT_TRUE(connection_.HasPendingAcks());
11458 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11459 std::make_unique<TaggingEncrypter>(0x02));
11460 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11461 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11462 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11463 connection_.NeuterUnencryptedPackets();
11464 }));
11465 {
11466 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11467 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11468 // Verify the packet is on hold.
11469 EXPECT_EQ(0u, writer_->packets_write_attempts());
11470 // Flush pending ACKs.
11471 connection_.GetAckAlarm()->Fire();
11472 }
11473 EXPECT_FALSE(connection_.packet_creator().HasPendingFrames());
11474 // The ACK frame is deleted along with initial_packet_ in coalescer. Sending
11475 // connection close would cause this (released) ACK frame be serialized (and
11476 // crashes).
11477 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11478 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
11479 EXPECT_TRUE(connection_.connected());
11480}
11481
11482TEST_P(QuicConnectionTest, PathValidationOnNewSocketSuccess) {
danzh87605712022-04-11 14:36:39 -070011483 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011484 return;
11485 }
11486 PathProbeTestInit(Perspective::IS_CLIENT);
11487 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11488 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11489 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11490 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11491 .Times(AtLeast(1u))
11492 .WillOnce(Invoke([&]() {
11493 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11494 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11495 EXPECT_EQ(1u, new_writer.padding_frames().size());
11496 EXPECT_EQ(kNewSelfAddress.host(),
11497 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070011498 }))
11499 .WillRepeatedly(DoDefault());
11500 ;
Bence Békybac04052022-04-07 15:44:29 -040011501 bool success = false;
11502 connection_.ValidatePath(
11503 std::make_unique<TestQuicPathValidationContext>(
11504 kNewSelfAddress, connection_.peer_address(), &new_writer),
11505 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011506 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11507 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011508 EXPECT_EQ(0u, writer_->packets_write_attempts());
11509
11510 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011511 frames.push_back(QuicFrame(QuicPathResponseFrame(
Bence Békybac04052022-04-07 15:44:29 -040011512 99, new_writer.path_challenge_frames().front().data_buffer)));
11513 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
11514 ENCRYPTION_FORWARD_SECURE);
11515 EXPECT_TRUE(success);
11516}
11517
danzh90315e82023-06-08 14:09:49 -070011518TEST_P(QuicConnectionTest, PathValidationOnNewSocketWriteBlocked) {
11519 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11520 return;
11521 }
11522 PathProbeTestInit(Perspective::IS_CLIENT);
11523 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11524 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11525 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11526 new_writer.SetWriteBlocked();
11527 bool success = false;
11528 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11529 connection_.ValidatePath(
11530 std::make_unique<TestQuicPathValidationContext>(
11531 kNewSelfAddress, connection_.peer_address(), &new_writer),
11532 std::make_unique<TestValidationResultDelegate>(
11533 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11534 PathValidationReason::kReasonUnknown);
11535 EXPECT_EQ(0u, new_writer.packets_write_attempts());
11536 EXPECT_TRUE(connection_.HasPendingPathValidation());
11537
11538 new_writer.SetWritable();
11539 // Retry after time out.
11540 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11541 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11542 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11543 .WillOnce(Invoke([&]() {
11544 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11545 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11546 EXPECT_EQ(1u, new_writer.padding_frames().size());
11547 EXPECT_EQ(kNewSelfAddress.host(),
11548 new_writer.last_write_source_address());
11549 }));
11550 static_cast<TestAlarmFactory::TestAlarm*>(
11551 QuicPathValidatorPeer::retry_timer(
11552 QuicConnectionPeer::path_validator(&connection_)))
11553 ->Fire();
11554 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11555
11556 QuicFrames frames;
11557 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11558 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
11559 new_writer.SetWriteBlocked();
11560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11561 .WillRepeatedly(Invoke([&] {
11562 // Packets other than PATH_RESPONSE may be sent over the default writer.
11563 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11564 EXPECT_TRUE(new_writer.path_response_frames().empty());
11565 EXPECT_EQ(1u, writer_->packets_write_attempts());
11566 }));
11567 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
11568 connection_.peer_address(),
11569 ENCRYPTION_FORWARD_SECURE);
11570 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11571}
11572
Bence Békybac04052022-04-07 15:44:29 -040011573TEST_P(QuicConnectionTest, NewPathValidationCancelsPreviousOne) {
danzh87605712022-04-11 14:36:39 -070011574 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011575 return;
11576 }
11577 PathProbeTestInit(Perspective::IS_CLIENT);
11578 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11579 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11580 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11581 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11582 .Times(AtLeast(1u))
11583 .WillOnce(Invoke([&]() {
11584 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11585 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11586 EXPECT_EQ(1u, new_writer.padding_frames().size());
11587 EXPECT_EQ(kNewSelfAddress.host(),
11588 new_writer.last_write_source_address());
11589 }));
11590 bool success = true;
11591 connection_.ValidatePath(
11592 std::make_unique<TestQuicPathValidationContext>(
11593 kNewSelfAddress, connection_.peer_address(), &new_writer),
11594 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011595 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11596 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011597 EXPECT_EQ(0u, writer_->packets_write_attempts());
11598
11599 // Start another path validation request.
11600 const QuicSocketAddress kNewSelfAddress2(QuicIpAddress::Any4(), 12346);
11601 EXPECT_NE(kNewSelfAddress2, connection_.self_address());
11602 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
Bence Békybac04052022-04-07 15:44:29 -040011603 bool success2 = false;
11604 connection_.ValidatePath(
11605 std::make_unique<TestQuicPathValidationContext>(
11606 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
11607 std::make_unique<TestValidationResultDelegate>(
11608 &connection_, kNewSelfAddress2, connection_.peer_address(),
renjietange499db42023-01-17 15:42:33 -080011609 &success2),
11610 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011611 EXPECT_FALSE(success);
danzh7c0ef5f2023-06-08 12:10:35 -070011612 // There is no pening path validation as there is no available connection ID.
11613 EXPECT_FALSE(connection_.HasPendingPathValidation());
Bence Békybac04052022-04-07 15:44:29 -040011614}
11615
11616// Regression test for b/182571515.
11617TEST_P(QuicConnectionTest, PathValidationRetry) {
danzh87605712022-04-11 14:36:39 -070011618 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011619 return;
11620 }
11621 PathProbeTestInit(Perspective::IS_CLIENT);
11622
11623 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11624 .Times(2u)
11625 .WillRepeatedly(Invoke([&]() {
11626 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11627 EXPECT_EQ(1u, writer_->padding_frames().size());
11628 }));
11629 bool success = true;
11630 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11631 connection_.self_address(),
11632 connection_.peer_address(), writer_.get()),
11633 std::make_unique<TestValidationResultDelegate>(
11634 &connection_, connection_.self_address(),
renjietange499db42023-01-17 15:42:33 -080011635 connection_.peer_address(), &success),
11636 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011637 EXPECT_EQ(1u, writer_->packets_write_attempts());
11638 EXPECT_TRUE(connection_.HasPendingPathValidation());
11639
11640 // Retry after time out.
11641 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11642 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11643 static_cast<TestAlarmFactory::TestAlarm*>(
11644 QuicPathValidatorPeer::retry_timer(
11645 QuicConnectionPeer::path_validator(&connection_)))
11646 ->Fire();
11647 EXPECT_EQ(2u, writer_->packets_write_attempts());
11648}
11649
11650TEST_P(QuicConnectionTest, PathValidationReceivesStatelessReset) {
danzh87605712022-04-11 14:36:39 -070011651 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011652 return;
11653 }
11654 PathProbeTestInit(Perspective::IS_CLIENT);
11655 QuicConfig config;
11656 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
11657 kTestStatelessResetToken);
11658 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11659 connection_.SetFromConfig(config);
11660 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11661 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11662 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11664 .Times(AtLeast(1u))
11665 .WillOnce(Invoke([&]() {
11666 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11667 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11668 EXPECT_EQ(1u, new_writer.padding_frames().size());
11669 EXPECT_EQ(kNewSelfAddress.host(),
11670 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070011671 }))
11672 .WillRepeatedly(DoDefault());
11673 ;
Bence Békybac04052022-04-07 15:44:29 -040011674 bool success = true;
11675 connection_.ValidatePath(
11676 std::make_unique<TestQuicPathValidationContext>(
11677 kNewSelfAddress, connection_.peer_address(), &new_writer),
11678 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011679 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11680 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011681 EXPECT_EQ(0u, writer_->packets_write_attempts());
11682 EXPECT_TRUE(connection_.HasPendingPathValidation());
11683
11684 std::unique_ptr<QuicEncryptedPacket> packet(
11685 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
11686 /*received_packet_length=*/100,
11687 kTestStatelessResetToken));
11688 std::unique_ptr<QuicReceivedPacket> received(
11689 ConstructReceivedPacket(*packet, QuicTime::Zero()));
11690 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
11691 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
11692 EXPECT_FALSE(connection_.HasPendingPathValidation());
11693 EXPECT_FALSE(success);
11694}
11695
11696// Tests that PATH_CHALLENGE is dropped if it is sent via a blocked alternative
11697// writer.
11698TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedNewSocket) {
danzh7c0ef5f2023-06-08 12:10:35 -070011699 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011700 return;
11701 }
11702 PathProbeTestInit(Perspective::IS_CLIENT);
11703 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11704 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11705 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11706 new_writer.BlockOnNextWrite();
11707 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
11708 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11709 .Times(AtLeast(1))
11710 .WillOnce(Invoke([&]() {
11711 // Even though the socket is blocked, the PATH_CHALLENGE should still be
11712 // treated as sent.
11713 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11714 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11715 EXPECT_EQ(1u, new_writer.padding_frames().size());
11716 EXPECT_EQ(kNewSelfAddress.host(),
11717 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070011718 }))
11719 .WillRepeatedly(DoDefault());
11720 ;
Bence Békybac04052022-04-07 15:44:29 -040011721 bool success = false;
11722 connection_.ValidatePath(
11723 std::make_unique<TestQuicPathValidationContext>(
11724 kNewSelfAddress, connection_.peer_address(), &new_writer),
11725 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011726 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11727 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011728 EXPECT_EQ(0u, writer_->packets_write_attempts());
11729
11730 new_writer.SetWritable();
11731 // Write event on the default socket shouldn't make any difference.
11732 connection_.OnCanWrite();
11733 // A NEW_CONNECTION_ID frame is received in PathProbeTestInit and OnCanWrite
11734 // will write a acking packet.
11735 EXPECT_EQ(1u, writer_->packets_write_attempts());
11736 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11737}
11738
11739// Tests that PATH_CHALLENGE is dropped if it is sent via the default writer
11740// and the writer is blocked.
11741TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedDefaultSocket) {
danzh87605712022-04-11 14:36:39 -070011742 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011743 return;
11744 }
11745 PathProbeTestInit(Perspective::IS_SERVER);
11746 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11747 writer_->BlockOnNextWrite();
11748 // 1st time is after writer returns WRITE_STATUS_BLOCKED. 2nd time is in
11749 // ShouldGeneratePacket().
11750 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(2));
11751 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
11752 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11753 .Times(AtLeast(1u))
11754 .WillOnce(Invoke([&]() {
11755 // This packet isn't sent actually, instead it is buffered in the
11756 // connection.
11757 EXPECT_EQ(1u, writer_->packets_write_attempts());
danzh4d58dae2023-06-06 11:13:10 -070011758 EXPECT_EQ(1u, writer_->path_response_frames().size());
11759 EXPECT_EQ(0,
11760 memcmp(&path_challenge_payload,
11761 &writer_->path_response_frames().front().data_buffer,
11762 sizeof(path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040011763 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11764 EXPECT_EQ(1u, writer_->padding_frames().size());
11765 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11766 }))
11767 .WillRepeatedly(Invoke([&]() {
11768 // Only one PATH_CHALLENGE should be sent out.
11769 EXPECT_EQ(0u, writer_->path_challenge_frames().size());
11770 }));
danzh4d58dae2023-06-06 11:13:10 -070011771 // Receiving a PATH_CHALLENGE from the new peer address should trigger address
11772 // validation.
11773 QuicFrames frames;
11774 frames.push_back(
11775 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
11776 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11777 ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040011778 EXPECT_EQ(1u, writer_->packets_write_attempts());
11779
11780 // Try again with the new socket blocked from the beginning. The 2nd
11781 // PATH_CHALLENGE shouldn't be serialized, but be dropped.
11782 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11783 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11784 static_cast<TestAlarmFactory::TestAlarm*>(
11785 QuicPathValidatorPeer::retry_timer(
11786 QuicConnectionPeer::path_validator(&connection_)))
11787 ->Fire();
11788
11789 // No more write attempt should be made.
11790 EXPECT_EQ(1u, writer_->packets_write_attempts());
11791
11792 writer_->SetWritable();
11793 // OnCanWrite() should actually write out the 1st PATH_CHALLENGE packet
11794 // buffered earlier, thus incrementing the write counter. It may also send
11795 // ACKs to previously received packets.
11796 connection_.OnCanWrite();
11797 EXPECT_LE(2u, writer_->packets_write_attempts());
11798}
11799
11800// Tests that write error on the alternate socket should be ignored.
11801TEST_P(QuicConnectionTest, SendPathChallengeFailOnNewSocket) {
danzh87605712022-04-11 14:36:39 -070011802 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011803 return;
11804 }
11805 PathProbeTestInit(Perspective::IS_CLIENT);
11806 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11807 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11808 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11809 new_writer.SetShouldWriteFail();
11810 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11811 .Times(0);
11812 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11813
11814 bool success = false;
11815 connection_.ValidatePath(
11816 std::make_unique<TestQuicPathValidationContext>(
11817 kNewSelfAddress, connection_.peer_address(), &new_writer),
11818 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011819 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11820 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011821 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11822 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11823 EXPECT_EQ(1u, new_writer.padding_frames().size());
11824 EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address());
11825
11826 EXPECT_EQ(0u, writer_->packets_write_attempts());
11827 // Regardless of the write error, the connection should still be connected.
11828 EXPECT_TRUE(connection_.connected());
11829}
11830
11831// Tests that write error while sending PATH_CHALLANGE from the default socket
11832// should close the connection.
11833TEST_P(QuicConnectionTest, SendPathChallengeFailOnDefaultPath) {
danzh87605712022-04-11 14:36:39 -070011834 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011835 return;
11836 }
11837 PathProbeTestInit(Perspective::IS_CLIENT);
11838
11839 writer_->SetShouldWriteFail();
11840 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11841 .WillOnce(
11842 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11843 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11844 }));
11845 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11846 {
11847 // Add a flusher to force flush, otherwise the frames will remain in the
11848 // packet creator.
11849 bool success = false;
11850 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11851 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11852 connection_.self_address(),
11853 connection_.peer_address(), writer_.get()),
11854 std::make_unique<TestValidationResultDelegate>(
11855 &connection_, connection_.self_address(),
renjietange499db42023-01-17 15:42:33 -080011856 connection_.peer_address(), &success),
11857 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011858 }
11859 EXPECT_EQ(1u, writer_->packets_write_attempts());
11860 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11861 EXPECT_EQ(1u, writer_->padding_frames().size());
11862 EXPECT_EQ(connection_.peer_address(), writer_->last_write_peer_address());
11863 EXPECT_FALSE(connection_.connected());
11864 // Closing connection should abandon ongoing path validation.
11865 EXPECT_FALSE(connection_.HasPendingPathValidation());
11866}
11867
11868TEST_P(QuicConnectionTest, SendPathChallengeFailOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011869 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011870 return;
11871 }
11872 PathProbeTestInit(Perspective::IS_CLIENT);
11873
11874 writer_->SetShouldWriteFail();
11875 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11876 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11877 .WillOnce(
11878 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11879 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11880 }));
11881 // Sending PATH_CHALLENGE to trigger a flush write which will fail and close
11882 // the connection.
11883 bool success = false;
11884 connection_.ValidatePath(
11885 std::make_unique<TestQuicPathValidationContext>(
11886 connection_.self_address(), kNewPeerAddress, writer_.get()),
11887 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011888 &connection_, connection_.self_address(), kNewPeerAddress, &success),
11889 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011890
11891 EXPECT_EQ(1u, writer_->packets_write_attempts());
11892 EXPECT_FALSE(connection_.HasPendingPathValidation());
11893 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11894 EXPECT_EQ(1u, writer_->padding_frames().size());
11895 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11896 EXPECT_FALSE(connection_.connected());
11897}
11898
11899TEST_P(QuicConnectionTest,
11900 SendPathChallengeFailPacketTooBigOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011901 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011902 return;
11903 }
11904 PathProbeTestInit(Perspective::IS_CLIENT);
11905 // Make sure there is no outstanding ACK_FRAME to write.
11906 connection_.OnCanWrite();
11907 uint32_t num_packets_write_attempts = writer_->packets_write_attempts();
11908
11909 writer_->SetShouldWriteFail();
11910 writer_->SetWriteError(*writer_->MessageTooBigErrorCode());
11911 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11912 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11913 .Times(0u);
11914 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11915 // Sending PATH_CHALLENGE to trigger a flush write which will fail with
11916 // MSG_TOO_BIG.
11917 bool success = false;
11918 connection_.ValidatePath(
11919 std::make_unique<TestQuicPathValidationContext>(
11920 connection_.self_address(), kNewPeerAddress, writer_.get()),
11921 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011922 &connection_, connection_.self_address(), kNewPeerAddress, &success),
11923 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011924 EXPECT_TRUE(connection_.HasPendingPathValidation());
11925 // Connection shouldn't be closed.
11926 EXPECT_TRUE(connection_.connected());
11927 EXPECT_EQ(++num_packets_write_attempts, writer_->packets_write_attempts());
11928 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11929 EXPECT_EQ(1u, writer_->padding_frames().size());
11930 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11931}
11932
11933// Check that if there are two PATH_CHALLENGE frames in the packet, the latter
11934// one is ignored.
11935TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) {
11936 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11937 return;
11938 }
11939 PathProbeTestInit(Perspective::IS_SERVER);
11940
11941 QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7};
11942 QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15};
11943 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011944 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer1)));
11945 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer2)));
Bence Békybac04052022-04-07 15:44:29 -040011946 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11947 /*port=*/23456);
11948
11949 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
11950
11951 // Expect 2 packets to be sent: the first are padded PATH_RESPONSE(s) to the
11952 // alternative peer address. The 2nd is a ACK-only packet to the original
11953 // peer address.
11954 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11955 .Times(2)
11956 .WillOnce(Invoke([=]() {
11957 EXPECT_EQ(1u, writer_->path_response_frames().size());
11958 // The final check is to ensure that the random data in the response
11959 // matches the random data from the challenge.
11960 EXPECT_EQ(0,
11961 memcmp(path_frame_buffer1.data(),
11962 &(writer_->path_response_frames().front().data_buffer),
11963 sizeof(path_frame_buffer1)));
11964 EXPECT_EQ(1u, writer_->padding_frames().size());
11965 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11966 }))
11967 .WillOnce(Invoke([=]() {
11968 // The last write of ACK-only packet should still use the old peer
11969 // address.
11970 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11971 }));
11972 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11973 ENCRYPTION_FORWARD_SECURE);
11974}
11975
11976TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) {
11977 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11978 return;
11979 }
11980 PathProbeTestInit(Perspective::IS_SERVER);
11981
11982 QuicFrames frames;
11983 frames.push_back(QuicFrame(frame1_));
11984 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070011985 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
fayang161ce6e2022-07-01 18:02:11 -070011986 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
Bence Békybac04052022-04-07 15:44:29 -040011987 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
11988 /*port=*/23456);
11989
11990 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
danzh4d58dae2023-06-06 11:13:10 -070011991 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040011992 EXPECT_CALL(visitor_, OnStreamFrame(_))
11993 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
11994 // Send some data on the stream. The STREAM_FRAME should be built into
11995 // one packet together with the latter PATH_RESPONSE and PATH_CHALLENGE.
11996 const std::string data{"response body"};
11997 connection_.producer()->SaveStreamData(frame.stream_id, data);
11998 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11999 NO_FIN);
12000 }));
danzh4d58dae2023-06-06 11:13:10 -070012001 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040012002 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12003 ENCRYPTION_FORWARD_SECURE);
12004
12005 // Verify that this packet contains a STREAM_FRAME and a
12006 // PATH_RESPONSE_FRAME.
12007 EXPECT_EQ(1u, writer_->stream_frames().size());
12008 EXPECT_EQ(1u, writer_->path_response_frames().size());
danzh4d58dae2023-06-06 11:13:10 -070012009 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012010 // The final check is to ensure that the random data in the response
12011 // matches the random data from the challenge.
12012 EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
12013 &(writer_->path_response_frames().front().data_buffer),
12014 sizeof(path_frame_buffer)));
danzh4d58dae2023-06-06 11:13:10 -070012015 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012016 EXPECT_EQ(1u, writer_->padding_frames().size());
12017 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
danzh4d58dae2023-06-06 11:13:10 -070012018 EXPECT_TRUE(connection_.HasPendingPathValidation());
Bence Békybac04052022-04-07 15:44:29 -040012019}
12020
12021TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) {
12022 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12023 return;
12024 }
12025 PathProbeTestInit(Perspective::IS_SERVER);
12026
12027 QuicFrames frames;
12028 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012029 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012030 // PATH_RESPONSE should be flushed out before the rest packet is parsed.
12031 frames.push_back(QuicFrame(frame1_));
12032 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
12033 /*port=*/23456);
12034 QuicByteCount received_packet_size;
12035 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12036 .Times(AtLeast(1u))
12037 .WillOnce(Invoke([=, &received_packet_size]() {
12038 // Verify that this packet contains a PATH_RESPONSE_FRAME.
12039 EXPECT_EQ(0u, writer_->stream_frames().size());
12040 EXPECT_EQ(1u, writer_->path_response_frames().size());
12041 // The final check is to ensure that the random data in the response
12042 // matches the random data from the challenge.
12043 EXPECT_EQ(0,
12044 memcmp(path_frame_buffer.data(),
12045 &(writer_->path_response_frames().front().data_buffer),
12046 sizeof(path_frame_buffer)));
danzh4d58dae2023-06-06 11:13:10 -070012047 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012048 EXPECT_EQ(1u, writer_->padding_frames().size());
12049 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12050 received_packet_size =
12051 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_);
12052 }));
12053 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
danzh4d58dae2023-06-06 11:13:10 -070012054 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040012055 EXPECT_CALL(visitor_, OnStreamFrame(_))
12056 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
12057 // Send some data on the stream. The STREAM_FRAME should be built into a
12058 // new packet but throttled by anti-amplifciation limit.
12059 const std::string data{"response body"};
12060 connection_.producer()->SaveStreamData(frame.stream_id, data);
12061 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12062 NO_FIN);
12063 }));
12064
12065 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12066 ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040012067 EXPECT_TRUE(connection_.HasPendingPathValidation());
12068 EXPECT_EQ(0u,
12069 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
12070 EXPECT_EQ(
12071 received_packet_size,
12072 QuicConnectionPeer::BytesReceivedBeforeAddressValidation(&connection_));
12073}
12074
12075// Tests that a PATH_CHALLENGE is received in between other frames in an out of
12076// order packet.
12077TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) {
12078 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12079 return;
12080 }
12081 PathProbeTestInit(Perspective::IS_SERVER);
12082
12083 QuicFrames frames;
12084 frames.push_back(QuicFrame(frame1_));
12085 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012086 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012087 frames.push_back(QuicFrame(frame2_));
12088 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12089 /*port=*/23456);
12090
12091 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12092 EXPECT_CALL(visitor_, OnStreamFrame(_))
12093 .Times(2)
12094 .WillRepeatedly(Invoke([=](const QuicStreamFrame& frame) {
12095 // Send some data on the stream. The STREAM_FRAME should be built into
12096 // one packet together with the latter PATH_RESPONSE.
12097 const std::string data{"response body"};
12098 connection_.producer()->SaveStreamData(frame.stream_id, data);
12099 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12100 NO_FIN);
12101 }));
12102 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12103 .WillOnce(Invoke([=]() {
12104 // Verify that this packet contains a STREAM_FRAME and is sent to the
12105 // original peer address.
12106 EXPECT_EQ(1u, writer_->stream_frames().size());
12107 // No connection migration should happen because the packet is received
12108 // out of order.
12109 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12110 }))
12111 .WillOnce(Invoke([=]() {
12112 EXPECT_EQ(1u, writer_->path_response_frames().size());
12113 // The final check is to ensure that the random data in the response
12114 // matches the random data from the challenge.
12115 EXPECT_EQ(0,
12116 memcmp(path_frame_buffer.data(),
12117 &(writer_->path_response_frames().front().data_buffer),
12118 sizeof(path_frame_buffer)));
12119 EXPECT_EQ(1u, writer_->padding_frames().size());
12120 // PATH_RESPONSE should be sent in another packet to a different peer
12121 // address.
12122 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12123 }))
12124 .WillOnce(Invoke([=]() {
12125 // Verify that this packet contains a STREAM_FRAME and is sent to the
12126 // original peer address.
12127 EXPECT_EQ(1u, writer_->stream_frames().size());
12128 // No connection migration should happen because the packet is received
12129 // out of order.
12130 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12131 }));
12132 // Lower the packet number so that receiving this packet shouldn't trigger
12133 // peer migration.
12134 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12135 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12136 ENCRYPTION_FORWARD_SECURE);
12137}
12138
12139// Tests that a PATH_CHALLENGE is cached if its PATH_RESPONSE can't be sent.
danzh90315e82023-06-08 14:09:49 -070012140TEST_P(QuicConnectionTest, FailToWritePathResponseAtServer) {
Bence Békybac04052022-04-07 15:44:29 -040012141 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12142 return;
12143 }
12144 PathProbeTestInit(Perspective::IS_SERVER);
12145
12146 QuicFrames frames;
12147 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012148 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012149 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12150 /*port=*/23456);
12151
12152 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12153 // Lower the packet number so that receiving this packet shouldn't trigger
12154 // peer migration.
12155 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12156 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
12157 writer_->SetWriteBlocked();
12158 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12159 ENCRYPTION_FORWARD_SECURE);
12160}
12161
12162// Regression test for b/168101557.
12163TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) {
12164 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12165 return;
12166 }
12167 set_perspective(Perspective::IS_SERVER);
12168 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
12169 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12170 }
12171 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040012172 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12173 EXPECT_TRUE(connection_.HasPendingAcks());
12174
Bence Békybac04052022-04-07 15:44:29 -040012175 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12176 // Send INITIAL 1.
12177 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12178
martinduke9e0811c2022-12-08 20:35:57 -080012179 connection_.SetEncrypter(
12180 ENCRYPTION_HANDSHAKE,
12181 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012182 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12183 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080012184 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012185 // Send HANDSHAKE packets.
12186 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
12187 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12188
martinduke9e0811c2022-12-08 20:35:57 -080012189 connection_.SetEncrypter(
12190 ENCRYPTION_FORWARD_SECURE,
12191 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012192 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12193 // Send half RTT packet.
12194 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12195
12196 // Receives HANDSHAKE 1.
martinduke9e0811c2022-12-08 20:35:57 -080012197 peer_framer_.SetEncrypter(
12198 ENCRYPTION_HANDSHAKE,
12199 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012200 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
12201 // Discard INITIAL key.
12202 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12203 connection_.NeuterUnencryptedPackets();
12204 // Verify there is pending ACK.
12205 ASSERT_TRUE(connection_.HasPendingAcks());
12206 // Set the send alarm.
12207 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
12208
12209 // Fire ACK alarm.
12210 connection_.GetAckAlarm()->Fire();
12211 // Verify 1-RTT packet is coalesced with handshake packet.
12212 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12213 connection_.GetSendAlarm()->Fire();
12214
12215 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12216 connection_.GetRetransmissionAlarm()->Fire();
12217 // Verify a handshake packet gets PTOed and 1-RTT packet gets coalesced.
12218 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12219}
12220
12221// Regression test for b/168294218.
12222TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) {
12223 if (!connection_.version().CanSendCoalescedPackets()) {
12224 return;
12225 }
12226 SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true);
12227 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
12228 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12229 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12230 connection_.NeuterUnencryptedPackets();
12231 }));
12232 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12233
12234 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
12235 {
12236 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040012237 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
12238 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080012239 connection_.SetEncrypter(
12240 ENCRYPTION_HANDSHAKE,
12241 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012242 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12243 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
12244 // Verify this packet is on hold.
12245 EXPECT_EQ(0u, writer_->packets_write_attempts());
12246 }
12247 EXPECT_TRUE(connection_.connected());
12248}
12249
12250// Regresstion test for b/168294218
12251TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) {
12252 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12253 return;
12254 }
12255 // Not defer send in response to packet.
12256 connection_.set_defer_send_in_response_to_packets(false);
12257 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12258 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12259 connection_.NeuterUnencryptedPackets();
12260 }));
12261 EXPECT_CALL(visitor_, OnCryptoFrame(_))
12262 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
12263 if (frame.level == ENCRYPTION_HANDSHAKE) {
12264 // 0-RTT gets rejected.
12265 connection_.MarkZeroRttPacketsForRetransmission(0);
12266 // Send Crypto data.
martinduke9e0811c2022-12-08 20:35:57 -080012267 connection_.SetEncrypter(
12268 ENCRYPTION_HANDSHAKE,
12269 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012270 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12271 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080012272 connection_.SetEncrypter(
12273 ENCRYPTION_FORWARD_SECURE,
12274 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012275 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12276 // Advance INITIAL ack delay to trigger initial ACK to be sent AFTER
12277 // the retransmission of rejected 0-RTT packets while the HANDSHAKE
12278 // packet is still in the coalescer, such that the INITIAL key gets
12279 // dropped between SendAllPendingAcks and actually send the ack frame,
12280 // bummer.
12281 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12282 }
12283 }));
Bence Békybac04052022-04-07 15:44:29 -040012284 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12285 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080012286 connection_.SetEncrypter(
12287 ENCRYPTION_ZERO_RTT,
12288 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040012289 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12290 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12291
12292 QuicAckFrame frame1 = InitAckFrame(1);
12293 // Received ACK for packet 1.
martindukeba002452023-03-21 08:10:46 -070012294 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012295 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
12296 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12297
12298 // Fire retransmission alarm.
12299 connection_.GetRetransmissionAlarm()->Fire();
12300
12301 QuicFrames frames1;
12302 frames1.push_back(QuicFrame(&crypto_frame_));
12303 QuicFrames frames2;
12304 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12305 absl::string_view(data1));
12306 frames2.push_back(QuicFrame(&crypto_frame));
12307 ProcessCoalescedPacket(
12308 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
12309}
12310
12311TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) {
12312 if (!connection_.version().UsesTls()) {
12313 return;
12314 }
12315 MockQuicConnectionDebugVisitor debug_visitor;
12316 connection_.set_debug_visitor(&debug_visitor);
Bence Békybac04052022-04-07 15:44:29 -040012317 connection_.SendCryptoStreamData();
12318 // Send 0-RTT packet.
12319 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
12320 std::make_unique<TaggingEncrypter>(0x02));
12321 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12322 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12323 connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN);
12324 // Received ACK for packet 1, HANDSHAKE packet and 1-RTT ACK.
martindukeba002452023-03-21 08:10:46 -070012325 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040012326 .Times(AnyNumber());
12327 QuicFrames frames1;
12328 QuicAckFrame ack_frame1 = InitAckFrame(1);
12329 frames1.push_back(QuicFrame(&ack_frame1));
12330
12331 QuicFrames frames2;
12332 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12333 absl::string_view(data1));
12334 frames2.push_back(QuicFrame(&crypto_frame));
12335 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12336 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
12337 ProcessCoalescedPacket(
12338 {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}});
12339
12340 QuicFrames frames3;
12341 QuicAckFrame ack_frame2 =
12342 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
12343 frames3.push_back(QuicFrame(&ack_frame2));
12344 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1);
12345 ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}});
12346
12347 QuicFrames frames4;
12348 QuicAckFrame ack_frame3 =
12349 InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}});
12350 frames4.push_back(QuicFrame(&ack_frame3));
12351 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12352 ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}});
12353}
12354
12355TEST_P(QuicConnectionTest, InitiateKeyUpdate) {
12356 if (!connection_.version().UsesTls()) {
12357 return;
12358 }
12359
12360 TransportParameters params;
12361 QuicConfig config;
12362 std::string error_details;
12363 EXPECT_THAT(config.ProcessTransportParameters(
12364 params, /* is_resumption = */ false, &error_details),
12365 IsQuicNoError());
12366 QuicConfigPeer::SetNegotiated(&config, true);
12367 if (connection_.version().UsesTls()) {
12368 QuicConfigPeer::SetReceivedOriginalConnectionId(
12369 &config, connection_.connection_id());
12370 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12371 &config, connection_.connection_id());
12372 }
12373 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12374 connection_.SetFromConfig(config);
12375
12376 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12377
12378 MockFramerVisitor peer_framer_visitor_;
12379 peer_framer_.set_visitor(&peer_framer_visitor_);
12380
martinduke9e0811c2022-12-08 20:35:57 -080012381 uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012382 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12383 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012384 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012385 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012386 std::make_unique<StrictTaggingDecrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012387 EXPECT_CALL(visitor_, GetHandshakeState())
12388 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12389 connection_.OnHandshakeComplete();
12390
12391 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012392 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012393
12394 // Key update should still not be allowed, since no packet has been acked
12395 // from the current key phase.
12396 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12397 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12398
12399 // Send packet 1.
12400 QuicPacketNumber last_packet;
12401 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12402 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12403
12404 // Key update should still not be allowed, even though a packet was sent in
12405 // the current key phase it hasn't been acked yet.
12406 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12407 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12408
12409 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12410 // Receive ack for packet 1.
martindukeba002452023-03-21 08:10:46 -070012411 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012412 QuicAckFrame frame1 = InitAckFrame(1);
12413 ProcessAckPacket(&frame1);
12414
12415 // OnDecryptedFirstPacketInKeyPhase is called even on the first key phase,
12416 // so discard_previous_keys_alarm_ should be set now.
12417 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12418 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12419
martinduke9e0811c2022-12-08 20:35:57 -080012420 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012421 // Key update should now be allowed.
12422 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012423 .WillOnce([&correct_tag]() {
12424 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12425 });
12426 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12427 .WillOnce([&correct_tag]() {
12428 return std::make_unique<TaggingEncrypter>(correct_tag);
12429 });
Bence Békybac04052022-04-07 15:44:29 -040012430 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12431 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12432 // discard_previous_keys_alarm_ should not be set until a packet from the new
12433 // key phase has been received. (The alarm that was set above should be
12434 // cleared if it hasn't fired before the next key update happened.)
12435 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12436 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12437
12438 // Pretend that peer accepts the key update.
12439 EXPECT_CALL(peer_framer_visitor_,
12440 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012441 .WillOnce([&correct_tag]() {
12442 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12443 });
Bence Békybac04052022-04-07 15:44:29 -040012444 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012445 .WillOnce([&correct_tag]() {
12446 return std::make_unique<TaggingEncrypter>(correct_tag);
12447 });
Bence Békybac04052022-04-07 15:44:29 -040012448 peer_framer_.SetKeyUpdateSupportForConnection(true);
12449 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12450
12451 // Another key update should not be allowed yet.
12452 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12453
12454 // Send packet 2.
12455 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12456 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12457 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12458 // Receive ack for packet 2.
martindukeba002452023-03-21 08:10:46 -070012459 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012460 QuicAckFrame frame2 = InitAckFrame(2);
12461 ProcessAckPacket(&frame2);
12462 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12463 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12464
martinduke9e0811c2022-12-08 20:35:57 -080012465 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012466 // Key update should be allowed again now that a packet has been acked from
12467 // the current key phase.
12468 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012469 .WillOnce([&correct_tag]() {
12470 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12471 });
12472 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12473 .WillOnce([&correct_tag]() {
12474 return std::make_unique<TaggingEncrypter>(correct_tag);
12475 });
Bence Békybac04052022-04-07 15:44:29 -040012476 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12477 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12478
12479 // Pretend that peer accepts the key update.
12480 EXPECT_CALL(peer_framer_visitor_,
12481 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012482 .WillOnce([&correct_tag]() {
12483 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12484 });
Bence Békybac04052022-04-07 15:44:29 -040012485 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012486 .WillOnce([&correct_tag]() {
12487 return std::make_unique<TaggingEncrypter>(correct_tag);
12488 });
Bence Békybac04052022-04-07 15:44:29 -040012489 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12490
12491 // Another key update should not be allowed yet.
12492 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12493
12494 // Send packet 3.
12495 SendStreamDataToPeer(3, "baz", 0, NO_FIN, &last_packet);
12496 EXPECT_EQ(QuicPacketNumber(3u), last_packet);
12497
12498 // Another key update should not be allowed yet.
12499 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12500 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12501
12502 // Receive ack for packet 3.
martindukeba002452023-03-21 08:10:46 -070012503 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012504 QuicAckFrame frame3 = InitAckFrame(3);
12505 ProcessAckPacket(&frame3);
12506 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12507 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12508
martinduke9e0811c2022-12-08 20:35:57 -080012509 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012510 // Key update should be allowed now.
12511 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012512 .WillOnce([&correct_tag]() {
12513 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12514 });
12515 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12516 .WillOnce([&correct_tag]() {
12517 return std::make_unique<TaggingEncrypter>(correct_tag);
12518 });
Bence Békybac04052022-04-07 15:44:29 -040012519 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12520 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12521 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12522 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12523}
12524
12525TEST_P(QuicConnectionTest, InitiateKeyUpdateApproachingConfidentialityLimit) {
12526 if (!connection_.version().UsesTls()) {
12527 return;
12528 }
12529
birenroyef686222022-09-12 11:34:34 -070012530 SetQuicFlag(quic_key_update_confidentiality_limit, 3U);
Bence Békybac04052022-04-07 15:44:29 -040012531
12532 std::string error_details;
12533 TransportParameters params;
12534 // Key update is enabled.
12535 QuicConfig config;
12536 EXPECT_THAT(config.ProcessTransportParameters(
12537 params, /* is_resumption = */ false, &error_details),
12538 IsQuicNoError());
12539 QuicConfigPeer::SetNegotiated(&config, true);
12540 if (connection_.version().UsesTls()) {
12541 QuicConfigPeer::SetReceivedOriginalConnectionId(
12542 &config, connection_.connection_id());
12543 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12544 &config, connection_.connection_id());
12545 }
12546 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12547 connection_.SetFromConfig(config);
12548
12549 MockFramerVisitor peer_framer_visitor_;
12550 peer_framer_.set_visitor(&peer_framer_visitor_);
12551
martinduke9e0811c2022-12-08 20:35:57 -080012552 uint8_t current_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012553
12554 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12555 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12556 std::make_unique<TaggingEncrypter>(current_tag));
12557 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12558 std::make_unique<StrictTaggingDecrypter>(current_tag));
12559 EXPECT_CALL(visitor_, GetHandshakeState())
12560 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12561 connection_.OnHandshakeComplete();
12562
12563 peer_framer_.SetKeyUpdateSupportForConnection(true);
12564 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12565 std::make_unique<TaggingEncrypter>(current_tag));
12566
12567 const QuicConnectionStats& stats = connection_.GetStats();
12568
12569 for (int packet_num = 1; packet_num <= 8; ++packet_num) {
12570 if (packet_num == 3 || packet_num == 6) {
12571 current_tag++;
12572 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12573 .WillOnce([current_tag]() {
12574 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12575 });
12576 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12577 .WillOnce([current_tag]() {
12578 return std::make_unique<TaggingEncrypter>(current_tag);
12579 });
12580 EXPECT_CALL(visitor_,
12581 OnKeyUpdate(KeyUpdateReason::kLocalKeyUpdateLimitOverride));
12582 }
12583 // Send packet.
12584 QuicPacketNumber last_packet;
12585 SendStreamDataToPeer(packet_num, "foo", 0, NO_FIN, &last_packet);
12586 EXPECT_EQ(QuicPacketNumber(packet_num), last_packet);
12587 if (packet_num >= 6) {
12588 EXPECT_EQ(2U, stats.key_update_count);
12589 } else if (packet_num >= 3) {
12590 EXPECT_EQ(1U, stats.key_update_count);
12591 } else {
12592 EXPECT_EQ(0U, stats.key_update_count);
12593 }
12594
12595 if (packet_num == 4 || packet_num == 7) {
12596 // Pretend that peer accepts the key update.
12597 EXPECT_CALL(peer_framer_visitor_,
12598 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12599 .WillOnce([current_tag]() {
12600 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12601 });
12602 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12603 .WillOnce([current_tag]() {
12604 return std::make_unique<TaggingEncrypter>(current_tag);
12605 });
12606 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12607 }
12608 // Receive ack for packet.
martindukeba002452023-03-21 08:10:46 -070012609 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012610 QuicAckFrame frame1 = InitAckFrame(packet_num);
12611 ProcessAckPacket(&frame1);
12612 }
12613}
12614
12615TEST_P(QuicConnectionTest,
12616 CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed) {
12617 if (!connection_.version().UsesTls()) {
12618 return;
12619 }
12620
12621 // Set key update confidentiality limit to 1 packet.
birenroyef686222022-09-12 11:34:34 -070012622 SetQuicFlag(quic_key_update_confidentiality_limit, 1U);
Bence Békybac04052022-04-07 15:44:29 -040012623 // Use confidentiality limit for connection close of 3 packets.
12624 constexpr size_t kConfidentialityLimit = 3U;
12625
12626 std::string error_details;
12627 TransportParameters params;
12628 // Key update is enabled.
12629 QuicConfig config;
12630 EXPECT_THAT(config.ProcessTransportParameters(
12631 params, /* is_resumption = */ false, &error_details),
12632 IsQuicNoError());
12633 QuicConfigPeer::SetNegotiated(&config, true);
12634 if (connection_.version().UsesTls()) {
12635 QuicConfigPeer::SetReceivedOriginalConnectionId(
12636 &config, connection_.connection_id());
12637 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12638 &config, connection_.connection_id());
12639 }
12640 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12641 connection_.SetFromConfig(config);
12642
12643 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12644 connection_.SetEncrypter(
12645 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012646 std::make_unique<TaggingEncrypterWithConfidentialityLimit>(
12647 ENCRYPTION_FORWARD_SECURE, kConfidentialityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012648 EXPECT_CALL(visitor_, GetHandshakeState())
12649 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12650 connection_.OnHandshakeComplete();
12651
12652 QuicPacketNumber last_packet;
12653 // Send 3 packets without receiving acks for any of them. Key update will not
12654 // be allowed, so the confidentiality limit should be reached, forcing the
12655 // connection to be closed.
12656 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12657 EXPECT_TRUE(connection_.connected());
12658 SendStreamDataToPeer(2, "foo", 0, NO_FIN, &last_packet);
12659 EXPECT_TRUE(connection_.connected());
12660 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12661 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
12662 EXPECT_FALSE(connection_.connected());
12663 const QuicConnectionStats& stats = connection_.GetStats();
12664 EXPECT_EQ(0U, stats.key_update_count);
12665 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12666}
12667
12668TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitDuringHandshake) {
12669 if (!connection_.version().UsesTls()) {
12670 return;
12671 }
12672
martinduke9e0811c2022-12-08 20:35:57 -080012673 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012674 constexpr uint8_t wrong_tag = 0xFE;
12675 constexpr QuicPacketCount kIntegrityLimit = 3;
12676
12677 SetDecrypter(ENCRYPTION_HANDSHAKE,
12678 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12679 correct_tag, kIntegrityLimit));
12680 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12681 std::make_unique<TaggingEncrypter>(correct_tag));
12682 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12683 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12684 std::make_unique<TaggingEncrypter>(wrong_tag));
12685 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12686 EXPECT_TRUE(connection_.connected());
12687 if (i == kIntegrityLimit) {
12688 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12689 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
12690 }
12691 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12692 EXPECT_EQ(
12693 i, connection_.GetStats().num_failed_authentication_packets_received);
12694 }
12695 EXPECT_FALSE(connection_.connected());
12696 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12697}
12698
12699TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAfterHandshake) {
12700 if (!connection_.version().UsesTls()) {
12701 return;
12702 }
12703
martinduke9e0811c2022-12-08 20:35:57 -080012704 constexpr uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012705 constexpr uint8_t wrong_tag = 0xFE;
12706 constexpr QuicPacketCount kIntegrityLimit = 3;
12707
Bence Békybac04052022-04-07 15:44:29 -040012708 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12709 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12710 correct_tag, kIntegrityLimit));
12711 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12712 std::make_unique<TaggingEncrypter>(correct_tag));
12713 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12714 EXPECT_CALL(visitor_, GetHandshakeState())
12715 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12716 connection_.OnHandshakeComplete();
12717 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12718 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12719 std::make_unique<TaggingEncrypter>(wrong_tag));
12720 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12721 EXPECT_TRUE(connection_.connected());
12722 if (i == kIntegrityLimit) {
12723 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12724 }
12725 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12726 EXPECT_EQ(
12727 i, connection_.GetStats().num_failed_authentication_packets_received);
12728 }
12729 EXPECT_FALSE(connection_.connected());
12730 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12731}
12732
12733TEST_P(QuicConnectionTest,
12734 CloseConnectionOnIntegrityLimitAcrossEncryptionLevels) {
12735 if (!connection_.version().UsesTls()) {
12736 return;
12737 }
12738
martinduke9e0811c2022-12-08 20:35:57 -080012739 uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012740 constexpr uint8_t wrong_tag = 0xFE;
12741 constexpr QuicPacketCount kIntegrityLimit = 4;
12742
Bence Békybac04052022-04-07 15:44:29 -040012743 SetDecrypter(ENCRYPTION_HANDSHAKE,
12744 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12745 correct_tag, kIntegrityLimit));
12746 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12747 std::make_unique<TaggingEncrypter>(correct_tag));
12748 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12749 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12750 std::make_unique<TaggingEncrypter>(wrong_tag));
12751 for (uint64_t i = 1; i <= 2; ++i) {
12752 EXPECT_TRUE(connection_.connected());
12753 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12754 EXPECT_EQ(
12755 i, connection_.GetStats().num_failed_authentication_packets_received);
12756 }
12757
martinduke9e0811c2022-12-08 20:35:57 -080012758 correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012759 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12760 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12761 correct_tag, kIntegrityLimit));
12762 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12763 std::make_unique<TaggingEncrypter>(correct_tag));
12764 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12765 EXPECT_CALL(visitor_, GetHandshakeState())
12766 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12767 connection_.OnHandshakeComplete();
12768 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12769 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
12770 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12771 std::make_unique<TaggingEncrypter>(wrong_tag));
12772 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12773 EXPECT_TRUE(connection_.connected());
12774 if (i == kIntegrityLimit) {
12775 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12776 }
12777 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12778 EXPECT_EQ(
12779 i, connection_.GetStats().num_failed_authentication_packets_received);
12780 }
12781 EXPECT_FALSE(connection_.connected());
12782 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12783}
12784
12785TEST_P(QuicConnectionTest, IntegrityLimitDoesNotApplyWithoutDecryptionKey) {
12786 if (!connection_.version().UsesTls()) {
12787 return;
12788 }
12789
martinduke9e0811c2022-12-08 20:35:57 -080012790 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012791 constexpr uint8_t wrong_tag = 0xFE;
12792 constexpr QuicPacketCount kIntegrityLimit = 3;
12793
Bence Békybac04052022-04-07 15:44:29 -040012794 SetDecrypter(ENCRYPTION_HANDSHAKE,
12795 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12796 correct_tag, kIntegrityLimit));
12797 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12798 std::make_unique<TaggingEncrypter>(correct_tag));
12799 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12800 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
12801
12802 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12803 std::make_unique<TaggingEncrypter>(wrong_tag));
12804 for (uint64_t i = 1; i <= kIntegrityLimit * 2; ++i) {
12805 EXPECT_TRUE(connection_.connected());
12806 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12807 EXPECT_EQ(
12808 0u, connection_.GetStats().num_failed_authentication_packets_received);
12809 }
12810 EXPECT_TRUE(connection_.connected());
12811}
12812
12813TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossKeyPhases) {
12814 if (!connection_.version().UsesTls()) {
12815 return;
12816 }
12817
12818 constexpr QuicPacketCount kIntegrityLimit = 4;
12819
12820 TransportParameters params;
12821 QuicConfig config;
12822 std::string error_details;
12823 EXPECT_THAT(config.ProcessTransportParameters(
12824 params, /* is_resumption = */ false, &error_details),
12825 IsQuicNoError());
12826 QuicConfigPeer::SetNegotiated(&config, true);
12827 if (connection_.version().UsesTls()) {
12828 QuicConfigPeer::SetReceivedOriginalConnectionId(
12829 &config, connection_.connection_id());
12830 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12831 &config, connection_.connection_id());
12832 }
12833 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12834 connection_.SetFromConfig(config);
12835
12836 MockFramerVisitor peer_framer_visitor_;
12837 peer_framer_.set_visitor(&peer_framer_visitor_);
12838
Bence Békybac04052022-04-07 15:44:29 -040012839 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12840 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12841 std::make_unique<TaggingEncrypter>(0x01));
12842 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12843 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
martinduke9e0811c2022-12-08 20:35:57 -080012844 ENCRYPTION_FORWARD_SECURE, kIntegrityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012845 EXPECT_CALL(visitor_, GetHandshakeState())
12846 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12847 connection_.OnHandshakeComplete();
12848 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12849
12850 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12851 std::make_unique<TaggingEncrypter>(0xFF));
12852 for (uint64_t i = 1; i <= 2; ++i) {
12853 EXPECT_TRUE(connection_.connected());
12854 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12855 EXPECT_EQ(
12856 i, connection_.GetStats().num_failed_authentication_packets_received);
12857 }
12858
martinduke9e0811c2022-12-08 20:35:57 -080012859 peer_framer_.SetEncrypter(
12860 ENCRYPTION_FORWARD_SECURE,
12861 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012862 // Send packet 1.
12863 QuicPacketNumber last_packet;
12864 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12865 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12866 // Receive ack for packet 1.
martindukeba002452023-03-21 08:10:46 -070012867 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012868 QuicAckFrame frame1 = InitAckFrame(1);
12869 ProcessAckPacket(&frame1);
12870 // Key update should now be allowed, initiate it.
12871 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12872 .WillOnce([kIntegrityLimit]() {
12873 return std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12874 0x02, kIntegrityLimit);
12875 });
12876 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12877 return std::make_unique<TaggingEncrypter>(0x02);
12878 });
12879 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12880 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12881
12882 // Pretend that peer accepts the key update.
12883 EXPECT_CALL(peer_framer_visitor_,
12884 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12885 .WillOnce(
12886 []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
12887 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12888 .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); });
12889 peer_framer_.SetKeyUpdateSupportForConnection(true);
12890 peer_framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests);
12891
12892 // Send packet 2.
12893 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12894 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12895 // Receive ack for packet 2.
martindukeba002452023-03-21 08:10:46 -070012896 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012897 QuicAckFrame frame2 = InitAckFrame(2);
12898 ProcessAckPacket(&frame2);
12899
12900 EXPECT_EQ(2u,
12901 connection_.GetStats().num_failed_authentication_packets_received);
12902
12903 // Do two more undecryptable packets. Integrity limit should be reached.
12904 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12905 std::make_unique<TaggingEncrypter>(0xFF));
12906 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12907 EXPECT_TRUE(connection_.connected());
12908 if (i == kIntegrityLimit) {
12909 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12910 }
12911 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12912 EXPECT_EQ(
12913 i, connection_.GetStats().num_failed_authentication_packets_received);
12914 }
12915 EXPECT_FALSE(connection_.connected());
12916 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12917}
12918
12919TEST_P(QuicConnectionTest, SendAckFrequencyFrame) {
12920 if (!version().HasIetfQuicFrames()) {
12921 return;
12922 }
12923 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12924 set_perspective(Perspective::IS_SERVER);
martindukeba002452023-03-21 08:10:46 -070012925 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040012926 .Times(AnyNumber());
12927 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12928
12929 QuicConfig config;
12930 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
12931 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12932 connection_.SetFromConfig(config);
12933 QuicConnectionPeer::SetAddressValidated(&connection_);
12934 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12935 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
12936
12937 connection_.OnHandshakeComplete();
12938
12939 writer_->SetWritable();
12940 QuicPacketCreatorPeer::SetPacketNumber(creator_, 99);
12941 // Send packet 100
12942 SendStreamDataToPeer(/*id=*/1, "foo", /*offset=*/0, NO_FIN, nullptr);
12943
12944 QuicAckFrequencyFrame captured_frame;
12945 EXPECT_CALL(visitor_, SendAckFrequency(_))
12946 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
12947 captured_frame = frame;
12948 }));
12949 // Send packet 101.
12950 SendStreamDataToPeer(/*id=*/1, "bar", /*offset=*/3, NO_FIN, nullptr);
12951
12952 EXPECT_EQ(captured_frame.packet_tolerance, 10u);
12953 EXPECT_EQ(captured_frame.max_ack_delay,
wub349df3d2024-04-26 11:37:32 -070012954 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040012955
12956 // Sending packet 102 does not trigger sending another AckFrequencyFrame.
12957 SendStreamDataToPeer(/*id=*/1, "baz", /*offset=*/6, NO_FIN, nullptr);
12958}
12959
12960TEST_P(QuicConnectionTest, SendAckFrequencyFrameUponHandshakeCompletion) {
12961 if (!version().HasIetfQuicFrames()) {
12962 return;
12963 }
12964 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12965 set_perspective(Perspective::IS_SERVER);
martindukeba002452023-03-21 08:10:46 -070012966 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040012967 .Times(AnyNumber());
12968 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12969
12970 QuicConfig config;
12971 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
12972 QuicTagVector quic_tag_vector;
12973 // Enable sending AckFrequency upon handshake completion.
12974 quic_tag_vector.push_back(kAFF2);
12975 QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector);
12976 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12977 connection_.SetFromConfig(config);
12978 QuicConnectionPeer::SetAddressValidated(&connection_);
12979 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12980 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
12981
12982 QuicAckFrequencyFrame captured_frame;
12983 EXPECT_CALL(visitor_, SendAckFrequency(_))
12984 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
12985 captured_frame = frame;
12986 }));
12987
12988 connection_.OnHandshakeComplete();
12989
12990 EXPECT_EQ(captured_frame.packet_tolerance, 2u);
12991 EXPECT_EQ(captured_frame.max_ack_delay,
wub349df3d2024-04-26 11:37:32 -070012992 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040012993}
12994
12995TEST_P(QuicConnectionTest, FastRecoveryOfLostServerHello) {
12996 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12997 return;
12998 }
12999 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13000 QuicConfig config;
13001 connection_.SetFromConfig(config);
13002
Bence Békybac04052022-04-07 15:44:29 -040013003 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13004 connection_.SendCryptoStreamData();
13005 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13006
13007 // Assume ServerHello gets lost.
13008 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13009 std::make_unique<TaggingEncrypter>(0x02));
13010 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13011 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
13012 // Shorten PTO for fast recovery from lost ServerHello.
13013 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
13014 connection_.GetRetransmissionAlarm()->deadline());
13015}
13016
13017TEST_P(QuicConnectionTest, ServerHelloGetsReordered) {
13018 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
13019 return;
13020 }
13021 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13022 QuicConfig config;
13023 connection_.SetFromConfig(config);
13024 EXPECT_CALL(visitor_, OnCryptoFrame(_))
13025 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
13026 if (frame.level == ENCRYPTION_INITIAL) {
13027 // Install handshake read keys.
martinduke9e0811c2022-12-08 20:35:57 -080013028 SetDecrypter(
13029 ENCRYPTION_HANDSHAKE,
13030 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
13031 connection_.SetEncrypter(
13032 ENCRYPTION_HANDSHAKE,
13033 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040013034 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
13035 }
13036 }));
13037
Bence Békybac04052022-04-07 15:44:29 -040013038 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13039 connection_.SendCryptoStreamData();
13040 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13041
13042 // Assume ServerHello gets reordered.
13043 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13044 std::make_unique<TaggingEncrypter>(0x02));
13045 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13046 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
13047 // Verify fast recovery is not enabled.
13048 EXPECT_EQ(connection_.sent_packet_manager().GetRetransmissionTime(),
13049 connection_.GetRetransmissionAlarm()->deadline());
13050}
13051
13052TEST_P(QuicConnectionTest, MigratePath) {
danzh7c0ef5f2023-06-08 12:10:35 -070013053 connection_.CreateConnectionIdManager();
13054 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13055 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -040013056 EXPECT_CALL(visitor_, GetHandshakeState())
13057 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13058 EXPECT_CALL(visitor_, OnPathDegrading());
13059 connection_.OnPathDegradingDetected();
13060 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13061 EXPECT_NE(kNewSelfAddress, connection_.self_address());
13062
13063 // Buffer a packet.
13064 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
13065 writer_->SetWriteBlocked();
13066 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
13067 EXPECT_EQ(1u, connection_.NumQueuedPackets());
13068
danzh7c0ef5f2023-06-08 12:10:35 -070013069 if (version().HasIetfQuicFrames()) {
13070 QuicNewConnectionIdFrame frame;
13071 frame.connection_id = TestConnectionId(1234);
13072 ASSERT_NE(frame.connection_id, connection_.connection_id());
13073 frame.stateless_reset_token =
13074 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13075 frame.retire_prior_to = 0u;
13076 frame.sequence_number = 1u;
13077 connection_.OnNewConnectionIdFrame(frame);
13078 }
13079
Bence Békybac04052022-04-07 15:44:29 -040013080 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13081 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
danzh7c0ef5f2023-06-08 12:10:35 -070013082 EXPECT_TRUE(connection_.MigratePath(kNewSelfAddress,
13083 connection_.peer_address(), &new_writer,
13084 /*owns_writer=*/false));
Bence Békybac04052022-04-07 15:44:29 -040013085
13086 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13087 EXPECT_EQ(&new_writer, QuicConnectionPeer::GetWriter(&connection_));
13088 EXPECT_FALSE(connection_.IsPathDegrading());
13089 // Buffered packet on the old path should be discarded.
danzh7c0ef5f2023-06-08 12:10:35 -070013090 if (version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040013091 EXPECT_EQ(0u, connection_.NumQueuedPackets());
13092 } else {
13093 EXPECT_EQ(1u, connection_.NumQueuedPackets());
13094 }
13095}
13096
13097TEST_P(QuicConnectionTest, MigrateToNewPathDuringProbing) {
danzh87605712022-04-11 14:36:39 -070013098 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040013099 return;
13100 }
13101 PathProbeTestInit(Perspective::IS_CLIENT);
13102 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13103 EXPECT_NE(kNewSelfAddress, connection_.self_address());
13104 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13105 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13106 bool success = false;
13107 connection_.ValidatePath(
13108 std::make_unique<TestQuicPathValidationContext>(
13109 kNewSelfAddress, connection_.peer_address(), &new_writer),
13110 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080013111 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
13112 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040013113 EXPECT_TRUE(connection_.HasPendingPathValidation());
13114 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13115 &connection_, kNewSelfAddress, connection_.peer_address()));
13116
13117 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
13118 &new_writer, /*owns_writer=*/false);
13119 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13120 EXPECT_TRUE(connection_.HasPendingPathValidation());
13121 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13122 &connection_, kNewSelfAddress, connection_.peer_address()));
13123}
13124
renjietang89540a62022-12-01 14:46:26 -080013125TEST_P(QuicConnectionTest, MultiPortConnection) {
renjietangfca5c772022-08-25 13:48:21 -070013126 set_perspective(Perspective::IS_CLIENT);
13127 QuicConfig config;
renjietang89540a62022-12-01 14:46:26 -080013128 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
renjietangfca5c772022-08-25 13:48:21 -070013129 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13130 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013131 if (!version().HasIetfQuicFrames()) {
renjietangfca5c772022-08-25 13:48:21 -070013132 return;
13133 }
13134 connection_.CreateConnectionIdManager();
13135 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13136 connection_.OnHandshakeComplete();
13137
renjietang864fbda2022-09-08 10:50:07 -070013138 EXPECT_CALL(visitor_, OnPathDegrading());
13139 connection_.OnPathDegradingDetected();
13140
renjietangfca5c772022-08-25 13:48:21 -070013141 auto self_address = connection_.self_address();
13142 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13143 self_address.port() + 1);
13144 EXPECT_NE(kNewSelfAddress, self_address);
13145 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13146
renjietang89540a62022-12-01 14:46:26 -080013147 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
renjietangfca5c772022-08-25 13:48:21 -070013148 QuicNewConnectionIdFrame frame;
13149 frame.connection_id = TestConnectionId(1234);
13150 ASSERT_NE(frame.connection_id, connection_.connection_id());
13151 frame.stateless_reset_token =
13152 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13153 frame.retire_prior_to = 0u;
13154 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013155 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013156 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13157 observer->OnMultiPortPathContextAvailable(
13158 std::move(std::make_unique<TestQuicPathValidationContext>(
13159 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013160 }));
renjietangfca5c772022-08-25 13:48:21 -070013161 connection_.OnNewConnectionIdFrame(frame);
13162 EXPECT_TRUE(connection_.HasPendingPathValidation());
13163 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13164 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013165 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13166 EXPECT_FALSE(alt_path->validated);
renjietange499db42023-01-17 15:42:33 -080013167 EXPECT_EQ(PathValidationReason::kMultiPort,
13168 QuicConnectionPeer::path_validator(&connection_)
13169 ->GetPathValidationReason());
13170
13171 // Suppose the server retransmits the NEW_CID frame, the client will receive
13172 // the same frame again. It should be ignored.
13173 // Regression test of crbug.com/1406762
13174 connection_.OnNewConnectionIdFrame(frame);
renjietangfca5c772022-08-25 13:48:21 -070013175
renjietang864fbda2022-09-08 10:50:07 -070013176 // 30ms RTT.
13177 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13178 // Fake a response delay.
13179 clock_.AdvanceTime(kTestRTT);
13180
renjietangfca5c772022-08-25 13:48:21 -070013181 QuicFrames frames;
13182 frames.push_back(QuicFrame(QuicPathResponseFrame(
renjietang89540a62022-12-01 14:46:26 -080013183 99, new_writer.path_challenge_frames().back().data_buffer)));
renjietangfca5c772022-08-25 13:48:21 -070013184 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13185 ENCRYPTION_FORWARD_SECURE);
13186 // No migration should happen and the alternative path should still be alive.
13187 EXPECT_FALSE(connection_.HasPendingPathValidation());
13188 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13189 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013190 EXPECT_TRUE(alt_path->validated);
renjietang864fbda2022-09-08 10:50:07 -070013191 auto stats = connection_.multi_port_stats();
renjietang201bfa52023-04-24 18:12:27 -070013192 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietangbb4f6842024-02-12 14:25:06 -080013193 EXPECT_EQ(1, stats->num_successful_probes);
13194 EXPECT_EQ(1, stats->num_client_probing_attempts);
renjietang864fbda2022-09-08 10:50:07 -070013195 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13196 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13197 EXPECT_EQ(kTestRTT,
13198 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13199
renjietang785c7cb2023-08-21 09:10:25 -070013200 // Receiving the retransmitted NEW_CID frame now should still have no effect.
renjietang39a1add2023-10-26 12:51:57 -070013201 EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0);
13202 connection_.OnNewConnectionIdFrame(frame);
renjietang785c7cb2023-08-21 09:10:25 -070013203
renjietang89540a62022-12-01 14:46:26 -080013204 // When there's no active request, the probing shouldn't happen. But the
13205 // probing context should be saved.
13206 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
13207 connection_.GetMultiPortProbingAlarm()->Fire();
13208 EXPECT_FALSE(connection_.HasPendingPathValidation());
13209 EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13210
13211 // Simulate the situation where a new request stream is created.
13212 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13213 .WillRepeatedly(Return(true));
13214 random_generator_.ChangeValue();
13215 connection_.MaybeProbeMultiPortPath();
13216 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13217 &connection_, kNewSelfAddress, connection_.peer_address()));
13218 EXPECT_TRUE(alt_path->validated);
13219 // Fake a response delay.
13220 clock_.AdvanceTime(kTestRTT);
13221 QuicFrames frames2;
13222 frames2.push_back(QuicFrame(QuicPathResponseFrame(
13223 99, new_writer.path_challenge_frames().back().data_buffer)));
13224 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress, kPeerAddress,
13225 ENCRYPTION_FORWARD_SECURE);
13226 // No migration should happen and the alternative path should still be alive.
13227 EXPECT_FALSE(connection_.HasPendingPathValidation());
13228 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13229 &connection_, kNewSelfAddress, connection_.peer_address()));
13230 EXPECT_TRUE(alt_path->validated);
renjietang201bfa52023-04-24 18:12:27 -070013231 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013232 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13233 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13234 EXPECT_EQ(kTestRTT,
13235 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13236
renjietang546e3962023-09-01 10:51:19 -070013237 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
13238 QuicConnectionPeer::OnForwardProgressMade(&connection_);
13239
renjietang89540a62022-12-01 14:46:26 -080013240 EXPECT_TRUE(connection_.GetMultiPortProbingAlarm()->IsSet());
13241 // Since there's already a scheduled probing alarm, manual calls won't have
13242 // any effect.
13243 connection_.MaybeProbeMultiPortPath();
13244 EXPECT_FALSE(connection_.HasPendingPathValidation());
13245
renjietang546e3962023-09-01 10:51:19 -070013246 // Since kMPQM is not set, migration shouldn't happen
13247 EXPECT_CALL(visitor_, OnPathDegrading());
13248 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0);
13249 connection_.OnPathDegradingDetected();
13250 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13251 &connection_, kNewSelfAddress, connection_.peer_address()));
13252
renjietang89540a62022-12-01 14:46:26 -080013253 // Simulate the case where the path validation fails after retries.
renjietangfca5c772022-08-25 13:48:21 -070013254 connection_.GetMultiPortProbingAlarm()->Fire();
13255 EXPECT_TRUE(connection_.HasPendingPathValidation());
13256 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13257 &connection_, kNewSelfAddress, connection_.peer_address()));
13258 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13259 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13260 static_cast<TestAlarmFactory::TestAlarm*>(
13261 QuicPathValidatorPeer::retry_timer(
13262 QuicConnectionPeer::path_validator(&connection_)))
13263 ->Fire();
13264 }
13265
13266 EXPECT_FALSE(connection_.HasPendingPathValidation());
13267 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13268 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang546e3962023-09-01 10:51:19 -070013269 EXPECT_EQ(2, connection_.GetStats().num_path_degrading);
renjietang864fbda2022-09-08 10:50:07 -070013270 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13271 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_not_degrading);
renjietangfca5c772022-08-25 13:48:21 -070013272}
13273
renjietang89540a62022-12-01 14:46:26 -080013274TEST_P(QuicConnectionTest, TooManyMultiPortPathCreations) {
13275 set_perspective(Perspective::IS_CLIENT);
13276 QuicConfig config;
renjietang89540a62022-12-01 14:46:26 -080013277 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13278 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13279 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013280 if (!version().HasIetfQuicFrames()) {
renjietang89540a62022-12-01 14:46:26 -080013281 return;
13282 }
13283 connection_.CreateConnectionIdManager();
13284 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13285 connection_.OnHandshakeComplete();
13286
13287 EXPECT_CALL(visitor_, OnPathDegrading());
13288 connection_.OnPathDegradingDetected();
13289
13290 auto self_address = connection_.self_address();
13291 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13292 self_address.port() + 1);
13293 EXPECT_NE(kNewSelfAddress, self_address);
13294 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13295
13296 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13297 .WillRepeatedly(Return(true));
13298
QUICHE teame2a24ee2024-01-09 06:34:35 -080013299 {
13300 QuicNewConnectionIdFrame frame;
13301 frame.connection_id = TestConnectionId(1234);
13302 ASSERT_NE(frame.connection_id, connection_.connection_id());
13303 frame.stateless_reset_token =
13304 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13305 frame.retire_prior_to = 0u;
13306 frame.sequence_number = 1u;
13307 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13308 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13309 observer->OnMultiPortPathContextAvailable(
13310 std::move(std::make_unique<TestQuicPathValidationContext>(
13311 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13312 }));
13313 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13314 }
renjietang89540a62022-12-01 14:46:26 -080013315 EXPECT_TRUE(connection_.HasPendingPathValidation());
13316 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13317 &connection_, kNewSelfAddress, connection_.peer_address()));
13318 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13319 EXPECT_FALSE(alt_path->validated);
13320
13321 EXPECT_TRUE(connection_.HasPendingPathValidation());
13322 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13323 &connection_, kNewSelfAddress, connection_.peer_address()));
13324 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13325 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13326 static_cast<TestAlarmFactory::TestAlarm*>(
13327 QuicPathValidatorPeer::retry_timer(
13328 QuicConnectionPeer::path_validator(&connection_)))
13329 ->Fire();
13330 }
13331
13332 auto stats = connection_.multi_port_stats();
13333 EXPECT_FALSE(connection_.HasPendingPathValidation());
13334 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13335 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang201bfa52023-04-24 18:12:27 -070013336 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013337 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13338
13339 uint64_t connection_id = 1235;
13340 for (size_t i = 0; i < kMaxNumMultiPortPaths - 1; ++i) {
13341 QuicNewConnectionIdFrame frame;
13342 frame.connection_id = TestConnectionId(connection_id + i);
13343 ASSERT_NE(frame.connection_id, connection_.connection_id());
13344 frame.stateless_reset_token =
13345 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13346 frame.retire_prior_to = 0u;
13347 frame.sequence_number = i + 2;
QUICHE team107316f2023-05-03 09:04:11 -070013348 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013349 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13350 observer->OnMultiPortPathContextAvailable(
13351 std::move(std::make_unique<TestQuicPathValidationContext>(
13352 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013353 }));
renjietang89540a62022-12-01 14:46:26 -080013354 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13355 EXPECT_TRUE(connection_.HasPendingPathValidation());
13356 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13357 &connection_, kNewSelfAddress, connection_.peer_address()));
13358 EXPECT_FALSE(alt_path->validated);
13359
13360 for (size_t j = 0; j < QuicPathValidator::kMaxRetryTimes + 1; ++j) {
13361 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13362 static_cast<TestAlarmFactory::TestAlarm*>(
13363 QuicPathValidatorPeer::retry_timer(
13364 QuicConnectionPeer::path_validator(&connection_)))
13365 ->Fire();
13366 }
13367
13368 EXPECT_FALSE(connection_.HasPendingPathValidation());
13369 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13370 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang201bfa52023-04-24 18:12:27 -070013371 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013372 EXPECT_EQ(i + 2, stats->num_multi_port_probe_failures_when_path_degrading);
13373 }
13374
13375 // The 6th attemp should fail.
13376 QuicNewConnectionIdFrame frame2;
13377 frame2.connection_id = TestConnectionId(1239);
13378 ASSERT_NE(frame2.connection_id, connection_.connection_id());
13379 frame2.stateless_reset_token =
13380 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
13381 frame2.retire_prior_to = 0u;
13382 frame2.sequence_number = 6u;
13383 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame2));
13384 EXPECT_FALSE(connection_.HasPendingPathValidation());
13385 EXPECT_EQ(kMaxNumMultiPortPaths,
13386 stats->num_multi_port_probe_failures_when_path_degrading);
13387}
13388
renjietang4ca6b842023-06-05 08:00:57 -070013389TEST_P(QuicConnectionTest, MultiPortPathReceivesStatelessReset) {
13390 set_perspective(Perspective::IS_CLIENT);
13391 QuicConfig config;
13392 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
13393 kTestStatelessResetToken);
13394 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13395 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13396 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013397 if (!version().HasIetfQuicFrames()) {
renjietang4ca6b842023-06-05 08:00:57 -070013398 return;
13399 }
13400 connection_.CreateConnectionIdManager();
13401 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13402 connection_.OnHandshakeComplete();
13403
13404 EXPECT_CALL(visitor_, OnPathDegrading());
13405 connection_.OnPathDegradingDetected();
13406
13407 auto self_address = connection_.self_address();
13408 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13409 self_address.port() + 1);
13410 EXPECT_NE(kNewSelfAddress, self_address);
13411 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13412
13413 QuicNewConnectionIdFrame frame;
13414 frame.connection_id = TestConnectionId(1234);
13415 ASSERT_NE(frame.connection_id, connection_.connection_id());
13416 frame.stateless_reset_token =
13417 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13418 frame.retire_prior_to = 0u;
13419 frame.sequence_number = 1u;
13420 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13421 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13422 observer->OnMultiPortPathContextAvailable(
13423 std::move(std::make_unique<TestQuicPathValidationContext>(
13424 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13425 }));
13426 connection_.OnNewConnectionIdFrame(frame);
13427 EXPECT_TRUE(connection_.HasPendingPathValidation());
13428 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13429 &connection_, kNewSelfAddress, connection_.peer_address()));
13430 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13431 EXPECT_FALSE(alt_path->validated);
13432 EXPECT_EQ(PathValidationReason::kMultiPort,
13433 QuicConnectionPeer::path_validator(&connection_)
13434 ->GetPathValidationReason());
13435
13436 std::unique_ptr<QuicEncryptedPacket> packet(
13437 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
13438 /*received_packet_length=*/100,
13439 kTestStatelessResetToken));
13440 std::unique_ptr<QuicReceivedPacket> received(
13441 ConstructReceivedPacket(*packet, QuicTime::Zero()));
13442 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
13443 .Times(0);
13444 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
13445}
13446
renjietangc60dcb72023-06-06 13:00:51 -070013447// Test that if the client's active migration is disabled, multi-port will not
13448// be attempted.
13449TEST_P(QuicConnectionTest, MultiPortPathRespectsActiveMigrationConfig) {
danzh7c0ef5f2023-06-08 12:10:35 -070013450 if (!version().HasIetfQuicFrames()) {
13451 return;
13452 }
renjietangc60dcb72023-06-06 13:00:51 -070013453 set_perspective(Perspective::IS_CLIENT);
13454 QuicConfig config;
13455 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
13456 kTestStatelessResetToken);
13457 QuicConfigPeer::SetReceivedDisableConnectionMigration(&config);
13458 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13459 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13460 connection_.SetFromConfig(config);
renjietangc60dcb72023-06-06 13:00:51 -070013461 connection_.CreateConnectionIdManager();
13462 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13463 connection_.OnHandshakeComplete();
13464
13465 EXPECT_CALL(visitor_, OnPathDegrading());
13466 connection_.OnPathDegradingDetected();
13467
13468 QuicNewConnectionIdFrame frame;
13469 frame.connection_id = TestConnectionId(1234);
13470 ASSERT_NE(frame.connection_id, connection_.connection_id());
13471 frame.stateless_reset_token =
13472 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13473 frame.retire_prior_to = 0u;
13474 frame.sequence_number = 1u;
13475 EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0);
13476 connection_.OnNewConnectionIdFrame(frame);
13477 EXPECT_FALSE(connection_.HasPendingPathValidation());
13478}
13479
renjietang5ba0e1b2023-03-14 13:08:03 -070013480// Verify that when multi-port is enabled and path degrading is triggered, if
13481// the alt-path is not ready, nothing happens.
13482TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsNotReady) {
13483 set_perspective(Perspective::IS_CLIENT);
13484 QuicConfig config;
renjietang5ba0e1b2023-03-14 13:08:03 -070013485 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13486 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13487 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013488 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070013489 return;
13490 }
13491 connection_.CreateConnectionIdManager();
13492 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13493 connection_.OnHandshakeComplete();
13494
13495 auto self_address = connection_.self_address();
13496 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13497 self_address.port() + 1);
13498 EXPECT_NE(kNewSelfAddress, self_address);
13499 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13500
13501 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13502 .WillRepeatedly(Return(true));
13503
13504 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 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070013517 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13518 EXPECT_TRUE(connection_.HasPendingPathValidation());
13519 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13520 &connection_, kNewSelfAddress, connection_.peer_address()));
13521 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13522 EXPECT_FALSE(alt_path->validated);
13523
13524 // The alt path is not ready, path degrading doesn't do anything.
13525 EXPECT_CALL(visitor_, OnPathDegrading());
13526 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0);
13527 connection_.OnPathDegradingDetected();
13528
13529 // 30ms RTT.
13530 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13531 // Fake a response delay.
13532 clock_.AdvanceTime(kTestRTT);
13533
13534 // Even if the alt path is validated after path degrading, nothing should
13535 // happen.
13536 QuicFrames frames;
13537 frames.push_back(QuicFrame(QuicPathResponseFrame(
13538 99, new_writer.path_challenge_frames().back().data_buffer)));
13539 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13540 ENCRYPTION_FORWARD_SECURE);
13541 // No migration should happen and the alternative path should still be alive.
13542 EXPECT_FALSE(connection_.HasPendingPathValidation());
13543 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13544 &connection_, kNewSelfAddress, connection_.peer_address()));
13545 EXPECT_TRUE(alt_path->validated);
13546}
13547
13548// Verify that when multi-port is enabled and path degrading is triggered, if
13549// the alt-path is ready and not probing, it should be migrated.
13550TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndNotProbing) {
13551 EXPECT_CALL(visitor_, GetHandshakeState())
13552 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13553 set_perspective(Perspective::IS_CLIENT);
13554 QuicConfig config;
renjietang546e3962023-09-01 10:51:19 -070013555 config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
renjietang5ba0e1b2023-03-14 13:08:03 -070013556 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13557 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013558 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070013559 return;
13560 }
13561 connection_.CreateConnectionIdManager();
13562 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13563 connection_.OnHandshakeComplete();
13564
13565 auto self_address = connection_.self_address();
13566 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13567 self_address.port() + 1);
13568 EXPECT_NE(kNewSelfAddress, self_address);
13569 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13570
13571 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13572 .WillRepeatedly(Return(true));
13573
13574 QuicNewConnectionIdFrame frame;
13575 frame.connection_id = TestConnectionId(1234);
13576 ASSERT_NE(frame.connection_id, connection_.connection_id());
13577 frame.stateless_reset_token =
13578 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13579 frame.retire_prior_to = 0u;
13580 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013581 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013582 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13583 observer->OnMultiPortPathContextAvailable(
13584 std::move(std::make_unique<TestQuicPathValidationContext>(
13585 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013586 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070013587 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13588 EXPECT_TRUE(connection_.HasPendingPathValidation());
13589 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13590 &connection_, kNewSelfAddress, connection_.peer_address()));
13591 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13592 EXPECT_FALSE(alt_path->validated);
13593
13594 // 30ms RTT.
13595 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13596 // Fake a response delay.
13597 clock_.AdvanceTime(kTestRTT);
13598
13599 // Even if the alt path is validated after path degrading, nothing should
13600 // happen.
13601 QuicFrames frames;
13602 frames.push_back(QuicFrame(QuicPathResponseFrame(
13603 99, new_writer.path_challenge_frames().back().data_buffer)));
13604 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13605 ENCRYPTION_FORWARD_SECURE);
13606 // No migration should happen and the alternative path should still be alive.
13607 EXPECT_FALSE(connection_.HasPendingPathValidation());
13608 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13609 &connection_, kNewSelfAddress, connection_.peer_address()));
13610 EXPECT_TRUE(alt_path->validated);
13611
13612 // Trigger path degrading and the connection should attempt to migrate.
13613 EXPECT_CALL(visitor_, OnPathDegrading());
13614 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0);
13615 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_))
13616 .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) {
13617 EXPECT_EQ(context->self_address(), kNewSelfAddress);
13618 connection_.MigratePath(context->self_address(),
13619 context->peer_address(), context->WriterToUse(),
13620 /*owns_writer=*/false);
13621 }));
13622 connection_.OnPathDegradingDetected();
13623}
13624
13625// Verify that when multi-port is enabled and path degrading is triggered, if
13626// the alt-path is probing, the probing should be cancelled and the path should
13627// be migrated.
13628TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndProbing) {
13629 EXPECT_CALL(visitor_, GetHandshakeState())
13630 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13631 set_perspective(Perspective::IS_CLIENT);
13632 QuicConfig config;
renjietang546e3962023-09-01 10:51:19 -070013633 config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
renjietang5ba0e1b2023-03-14 13:08:03 -070013634 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13635 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013636 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070013637 return;
13638 }
13639 connection_.CreateConnectionIdManager();
13640 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13641 connection_.OnHandshakeComplete();
13642
13643 auto self_address = connection_.self_address();
13644 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13645 self_address.port() + 1);
13646 EXPECT_NE(kNewSelfAddress, self_address);
13647 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13648
13649 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13650 .WillRepeatedly(Return(true));
13651
13652 QuicNewConnectionIdFrame frame;
13653 frame.connection_id = TestConnectionId(1234);
13654 ASSERT_NE(frame.connection_id, connection_.connection_id());
13655 frame.stateless_reset_token =
13656 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13657 frame.retire_prior_to = 0u;
13658 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013659 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013660 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13661 observer->OnMultiPortPathContextAvailable(
13662 std::move(std::make_unique<TestQuicPathValidationContext>(
13663 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013664 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070013665 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13666 EXPECT_TRUE(connection_.HasPendingPathValidation());
13667 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13668 &connection_, kNewSelfAddress, connection_.peer_address()));
13669 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13670 EXPECT_FALSE(alt_path->validated);
13671
13672 // 30ms RTT.
13673 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13674 // Fake a response delay.
13675 clock_.AdvanceTime(kTestRTT);
13676
13677 // Even if the alt path is validated after path degrading, nothing should
13678 // happen.
13679 QuicFrames frames;
13680 frames.push_back(QuicFrame(QuicPathResponseFrame(
13681 99, new_writer.path_challenge_frames().back().data_buffer)));
13682 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13683 ENCRYPTION_FORWARD_SECURE);
13684 // No migration should happen and the alternative path should still be alive.
13685 EXPECT_FALSE(connection_.HasPendingPathValidation());
13686 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13687 &connection_, kNewSelfAddress, connection_.peer_address()));
13688 EXPECT_TRUE(alt_path->validated);
13689
13690 random_generator_.ChangeValue();
13691 connection_.GetMultiPortProbingAlarm()->Fire();
13692 EXPECT_TRUE(connection_.HasPendingPathValidation());
13693 EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13694
13695 // Trigger path degrading and the connection should attempt to migrate.
13696 EXPECT_CALL(visitor_, OnPathDegrading());
13697 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0);
13698 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_))
13699 .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) {
13700 EXPECT_EQ(context->self_address(), kNewSelfAddress);
13701 connection_.MigratePath(context->self_address(),
13702 context->peer_address(), context->WriterToUse(),
13703 /*owns_writer=*/false);
13704 }));
13705 connection_.OnPathDegradingDetected();
13706 EXPECT_FALSE(connection_.HasPendingPathValidation());
13707 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
13708 EXPECT_FALSE(QuicPathValidatorPeer::retry_timer(path_validator)->IsSet());
13709}
13710
Bence Békybac04052022-04-07 15:44:29 -040013711TEST_P(QuicConnectionTest, SingleAckInPacket) {
13712 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13713 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13714 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13715 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13716 connection_.NeuterUnencryptedPackets();
13717 connection_.OnHandshakeComplete();
13718 EXPECT_CALL(visitor_, GetHandshakeState())
13719 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13720
13721 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13722 connection_.SendStreamData3();
13723 connection_.CloseConnection(
13724 QUIC_INTERNAL_ERROR, "error",
13725 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
13726 }));
13727 QuicFrames frames;
13728 frames.push_back(QuicFrame(frame1_));
13729 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
13730 ENCRYPTION_FORWARD_SECURE);
13731 ASSERT_FALSE(writer_->ack_frames().empty());
13732 EXPECT_EQ(1u, writer_->ack_frames().size());
13733}
13734
13735TEST_P(QuicConnectionTest,
13736 ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey) {
13737 if (!connection_.version().UsesTls()) {
13738 return;
13739 }
13740
13741 set_perspective(Perspective::IS_SERVER);
13742 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080013743 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040013744
13745 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13746 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13747
13748 // Finish handshake.
13749 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13750 notifier_.NeuterUnencryptedData();
13751 connection_.NeuterUnencryptedPackets();
13752 connection_.OnHandshakeComplete();
13753 EXPECT_CALL(visitor_, GetHandshakeState())
13754 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13755
13756 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13757 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13758 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13759
13760 // 0-RTT packet received out of order should be decoded since the decrypter
13761 // is temporarily retained.
13762 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13763 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13764 EXPECT_EQ(
13765 0u,
13766 connection_.GetStats()
13767 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13768
13769 // Simulate the timeout for discarding 0-RTT keys passing.
13770 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
13771
13772 // Another 0-RTT packet received now should not be decoded.
13773 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13774 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
13775 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13776 EXPECT_EQ(
13777 1u,
13778 connection_.GetStats()
13779 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13780
13781 // The |discard_zero_rtt_decryption_keys_alarm_| should only be set on the
13782 // first 1-RTT packet received.
13783 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13784 ProcessDataPacketAtLevel(5, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13785 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13786}
13787
13788TEST_P(QuicConnectionTest, NewTokenFrameInstigateAcks) {
13789 if (!version().HasIetfQuicFrames()) {
13790 return;
13791 }
13792 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13793
13794 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13795 EXPECT_CALL(visitor_, OnNewTokenReceived(_));
13796 ProcessFramePacket(QuicFrame(new_token));
13797
13798 // Ensure that this has caused the ACK alarm to be set.
13799 EXPECT_TRUE(connection_.HasPendingAcks());
13800}
13801
13802TEST_P(QuicConnectionTest, ServerClosesConnectionOnNewTokenFrame) {
13803 if (!version().HasIetfQuicFrames()) {
13804 return;
13805 }
13806 set_perspective(Perspective::IS_SERVER);
13807 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13808 EXPECT_CALL(visitor_, OnNewTokenReceived(_)).Times(0);
13809 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13810 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13811 ProcessFramePacket(QuicFrame(new_token));
13812 EXPECT_FALSE(connection_.connected());
13813}
13814
13815TEST_P(QuicConnectionTest, OverrideRetryTokenWithRetryPacket) {
13816 if (!version().HasIetfQuicFrames()) {
13817 return;
13818 }
13819 std::string address_token = "TestAddressToken";
13820 connection_.SetSourceAddressTokenToSend(address_token);
13821 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13822 QuicConnectionPeer::GetPacketCreator(&connection_)),
13823 address_token);
13824 // Passes valid retry and verify token gets overridden.
13825 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13826 /*missing_original_id_in_config=*/false,
13827 /*wrong_original_id_in_config=*/false,
13828 /*missing_retry_id_in_config=*/false,
13829 /*wrong_retry_id_in_config=*/false);
13830}
13831
13832TEST_P(QuicConnectionTest, DonotOverrideRetryTokenWithAddressToken) {
13833 if (!version().HasIetfQuicFrames()) {
13834 return;
13835 }
13836 // Passes valid retry and verify token gets overridden.
13837 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13838 /*missing_original_id_in_config=*/false,
13839 /*wrong_original_id_in_config=*/false,
13840 /*missing_retry_id_in_config=*/false,
13841 /*wrong_retry_id_in_config=*/false);
13842 std::string retry_token = QuicPacketCreatorPeer::GetRetryToken(
13843 QuicConnectionPeer::GetPacketCreator(&connection_));
13844
13845 std::string address_token = "TestAddressToken";
13846 connection_.SetSourceAddressTokenToSend(address_token);
13847 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13848 QuicConnectionPeer::GetPacketCreator(&connection_)),
13849 retry_token);
13850}
13851
13852TEST_P(QuicConnectionTest,
13853 ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt) {
13854 if (!connection_.version().UsesTls()) {
13855 return;
13856 }
13857
13858 // The code that checks for this error piggybacks on some book-keeping state
13859 // kept for key update, so enable key update for the test.
13860 std::string error_details;
13861 TransportParameters params;
13862 QuicConfig config;
13863 EXPECT_THAT(config.ProcessTransportParameters(
13864 params, /* is_resumption = */ false, &error_details),
13865 IsQuicNoError());
13866 QuicConfigPeer::SetNegotiated(&config, true);
13867 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
13868 connection_.connection_id());
13869 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
13870 &config, connection_.connection_id());
13871 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13872 connection_.SetFromConfig(config);
13873
13874 set_perspective(Perspective::IS_SERVER);
13875 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080013876 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040013877
13878 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13879 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13880
13881 // Finish handshake.
13882 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13883 notifier_.NeuterUnencryptedData();
13884 connection_.NeuterUnencryptedPackets();
13885 connection_.OnHandshakeComplete();
13886 EXPECT_CALL(visitor_, GetHandshakeState())
13887 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13888
13889 // Decrypt a 1-RTT packet.
13890 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13891 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13892 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13893
13894 // 0-RTT packet with higher packet number than a 1-RTT packet is invalid and
13895 // should cause the connection to be closed.
13896 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13897 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13898 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13899 EXPECT_FALSE(connection_.connected());
13900 TestConnectionCloseQuicErrorCode(
13901 QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
13902}
13903
13904// Regression test for b/177312785
13905TEST_P(QuicConnectionTest, PeerMigrateBeforeHandshakeConfirm) {
13906 if (!VersionHasIetfQuicFrames(version().transport_version)) {
13907 return;
13908 }
13909 set_perspective(Perspective::IS_SERVER);
13910 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
13911 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
13912 EXPECT_CALL(visitor_, GetHandshakeState())
13913 .WillRepeatedly(Return(HANDSHAKE_START));
13914
13915 // Clear direct_peer_address.
13916 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
13917 // Clear effective_peer_address, it is the same as direct_peer_address for
13918 // this test.
13919 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
13920 QuicSocketAddress());
13921 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
13922
13923 const QuicSocketAddress kNewPeerAddress =
13924 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
13925 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
13926 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
13927 ENCRYPTION_INITIAL);
13928 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13929 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13930
13931 // Process another packet with a different peer address on server side will
13932 // close connection.
13933 QuicAckFrame frame = InitAckFrame(1);
13934 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13935 EXPECT_CALL(visitor_,
13936 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
13937 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
13938
martindukeba002452023-03-21 08:10:46 -070013939 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
13940 .Times(0);
Bence Békybac04052022-04-07 15:44:29 -040013941 ProcessFramePacketWithAddresses(QuicFrame(&frame), kSelfAddress,
13942 kNewPeerAddress, ENCRYPTION_INITIAL);
13943 EXPECT_FALSE(connection_.connected());
13944}
13945
13946// Regresstion test for b/175685916
13947TEST_P(QuicConnectionTest, TryToFlushAckWithAckQueued) {
13948 if (!version().HasIetfQuicFrames()) {
13949 return;
13950 }
13951 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13952 set_perspective(Perspective::IS_SERVER);
13953
13954 QuicConfig config;
13955 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13956 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13957 connection_.SetFromConfig(config);
13958 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13959 connection_.OnHandshakeComplete();
13960 QuicPacketCreatorPeer::SetPacketNumber(creator_, 200);
13961
13962 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13963 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13964 // Sending ACK_FREQUENCY bundles ACK. QuicConnectionPeer::SendPing
13965 // will try to bundle ACK but there is no pending ACK.
13966 EXPECT_CALL(visitor_, SendAckFrequency(_))
13967 .WillOnce(Invoke(&notifier_,
13968 &SimpleSessionNotifier::WriteOrBufferAckFrequency));
13969 QuicConnectionPeer::SendPing(&connection_);
13970}
13971
13972TEST_P(QuicConnectionTest, PathChallengeBeforePeerIpAddressChangeAtServer) {
13973 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070013974 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040013975 return;
13976 }
13977 PathProbeTestInit(Perspective::IS_SERVER);
13978 SetClientConnectionId(TestConnectionId(1));
13979 connection_.CreateConnectionIdManager();
13980
13981 QuicConnectionId server_cid0 = connection_.connection_id();
13982 QuicConnectionId client_cid0 = connection_.client_connection_id();
13983 QuicConnectionId client_cid1 = TestConnectionId(2);
13984 QuicConnectionId server_cid1;
13985 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013986 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013987 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13988 .WillOnce(Return(TestConnectionId(456)));
13989 }
haoyuewangada6b822022-06-23 13:41:18 -070013990 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13991 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13992 server_cid1 = cid;
13993 return true;
13994 }));
Bence Békybac04052022-04-07 15:44:29 -040013995 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13996 connection_.MaybeSendConnectionIdToClient();
13997 // Receives new client CID from client.
13998 QuicNewConnectionIdFrame new_cid_frame;
13999 new_cid_frame.connection_id = client_cid1;
14000 new_cid_frame.sequence_number = 1u;
14001 new_cid_frame.retire_prior_to = 0u;
14002 connection_.OnNewConnectionIdFrame(new_cid_frame);
14003 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14004 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14005 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14006
14007 peer_creator_.SetServerConnectionId(server_cid1);
14008 const QuicSocketAddress kNewPeerAddress =
14009 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
14010 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14011 QuicFrames frames1;
14012 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014013 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014014 QuicPathFrameBuffer payload;
14015 EXPECT_CALL(*send_algorithm_,
14016 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14017 .Times(AtLeast(1))
14018 .WillOnce(Invoke([&]() {
14019 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14020 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14021 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14022 EXPECT_FALSE(writer_->path_response_frames().empty());
14023 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14024 payload = writer_->path_challenge_frames().front().data_buffer;
awillia202240c2024-07-08 09:47:00 -070014025 }))
14026 .WillRepeatedly(DoDefault());
14027 ;
Bence Békybac04052022-04-07 15:44:29 -040014028 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14029 ENCRYPTION_FORWARD_SECURE);
14030 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14031 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14032 EXPECT_TRUE(connection_.HasPendingPathValidation());
14033 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14034 const auto* alternative_path =
14035 QuicConnectionPeer::GetAlternativePath(&connection_);
14036 EXPECT_EQ(default_path->client_connection_id, client_cid0);
14037 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14038 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14039 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14040 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14041 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14042
14043 // Process another packet with a different peer address on server side will
14044 // start connection migration.
14045 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14046 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
14047 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14048 }));
14049 // IETF QUIC send algorithm should be changed to a different object, so no
14050 // OnPacketSent() called on the old send algorithm.
14051 EXPECT_CALL(*send_algorithm_,
14052 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14053 .Times(0);
14054 QuicFrames frames2;
14055 frames2.push_back(QuicFrame(frame2_));
14056 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14057 ENCRYPTION_FORWARD_SECURE);
14058 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14059 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14060 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
14061 connection_.active_effective_peer_migration_type());
14062 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14063 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
14064 send_algorithm_);
14065 // Switch to use the mock send algorithm.
14066 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14067 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14068 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14069 .WillRepeatedly(Return(kDefaultTCPMSS));
14070 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14071 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14072 .Times(AnyNumber())
14073 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14074 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14075 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14076 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14077 connection_.SetSendAlgorithm(send_algorithm_);
14078 EXPECT_EQ(default_path->client_connection_id, client_cid1);
14079 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14080 // The previous default path is kept as alternative path before reverse path
14081 // validation finishes.
14082 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
14083 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
14084 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
14085 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
14086
14087 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14088 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14089 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
14090 connection_.active_effective_peer_migration_type());
14091 EXPECT_EQ(1u, connection_.GetStats()
14092 .num_peer_migration_to_proactively_validated_address);
14093
14094 // The PATH_CHALLENGE and PATH_RESPONSE is expanded upto the max packet size
14095 // which may exceeds the anti-amplification limit. Verify server is throttled
14096 // by anti-amplification limit.
14097 connection_.SendCryptoDataWithString("foo", 0);
14098 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
14099
14100 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
14101 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070014102 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040014103 EXPECT_CALL(visitor_, MaybeSendAddressToken());
14104 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14105 .Times(testing::AtLeast(1u));
14106 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
14107 ENCRYPTION_FORWARD_SECURE);
14108 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
14109 // Verify that alternative_path_ is cleared and the peer CID is retired.
14110 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14111 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14112 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14113 auto* retire_peer_issued_cid_alarm =
14114 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14115 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14116 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14117 retire_peer_issued_cid_alarm->Fire();
14118
14119 // Verify the anti-amplification limit is lifted by sending a packet larger
14120 // than the anti-amplification limit.
14121 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
14122 EXPECT_CALL(*send_algorithm_, PacingRate(_))
14123 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14124 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
14125 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -070014126 EXPECT_EQ(1u, connection_.num_unlinkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -040014127}
14128
14129TEST_P(QuicConnectionTest,
14130 PathValidationSucceedsBeforePeerIpAddressChangeAtServer) {
14131 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070014132 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014133 return;
14134 }
14135 PathProbeTestInit(Perspective::IS_SERVER);
14136 connection_.CreateConnectionIdManager();
14137
14138 QuicConnectionId server_cid0 = connection_.connection_id();
14139 QuicConnectionId server_cid1;
14140 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014141 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014142 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14143 .WillOnce(Return(TestConnectionId(456)));
14144 }
haoyuewangada6b822022-06-23 13:41:18 -070014145 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14146 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14147 server_cid1 = cid;
14148 return true;
14149 }));
Bence Békybac04052022-04-07 15:44:29 -040014150 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14151 connection_.MaybeSendConnectionIdToClient();
14152 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14153 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14154
14155 // Receive probing packet with new peer address.
14156 peer_creator_.SetServerConnectionId(server_cid1);
14157 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14158 /*port=*/23456);
14159 QuicPathFrameBuffer payload;
14160 EXPECT_CALL(*send_algorithm_,
14161 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14162 .WillOnce(Invoke([&]() {
14163 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14164 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14165 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14166 EXPECT_FALSE(writer_->path_response_frames().empty());
14167 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14168 payload = writer_->path_challenge_frames().front().data_buffer;
14169 }))
14170 .WillRepeatedly(Invoke([&]() {
14171 // Only start reverse path validation once.
14172 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14173 }));
14174 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14175 QuicFrames frames1;
14176 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014177 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014178 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14179 ENCRYPTION_FORWARD_SECURE);
14180 EXPECT_TRUE(connection_.HasPendingPathValidation());
14181 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14182 const auto* alternative_path =
14183 QuicConnectionPeer::GetAlternativePath(&connection_);
14184 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14185 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14186 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14187
14188 // Receive PATH_RESPONSE should mark the new peer address validated.
14189 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070014190 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040014191 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
14192 ENCRYPTION_FORWARD_SECURE);
14193
14194 // Process another packet with a newer peer address with the same port will
14195 // start connection migration.
14196 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14197 // IETF QUIC send algorithm should be changed to a different object, so no
14198 // OnPacketSent() called on the old send algorithm.
14199 EXPECT_CALL(*send_algorithm_,
14200 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14201 .Times(0);
14202 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14203 /*port=*/34567);
14204 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
14205 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
14206 }));
14207 EXPECT_CALL(visitor_, MaybeSendAddressToken());
14208 QuicFrames frames2;
14209 frames2.push_back(QuicFrame(frame2_));
14210 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewerPeerAddress,
14211 ENCRYPTION_FORWARD_SECURE);
14212 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
14213 EXPECT_EQ(kNewerPeerAddress, connection_.effective_peer_address());
14214 // Since the newer address has the same IP as the previously validated probing
14215 // address. The peer migration becomes validated immediately.
14216 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
14217 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14218 EXPECT_EQ(1u, connection_.GetStats()
14219 .num_peer_migration_to_proactively_validated_address);
14220 EXPECT_FALSE(connection_.HasPendingPathValidation());
14221 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
14222 send_algorithm_);
14223
14224 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14225 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
14226 // Verify that alternative_path_ is cleared.
14227 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14228 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14229
14230 // Switch to use the mock send algorithm.
14231 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14232 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14233 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14234 .WillRepeatedly(Return(kDefaultTCPMSS));
14235 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14236 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14237 .Times(AnyNumber())
14238 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14239 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14240 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14241 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14242 connection_.SetSendAlgorithm(send_algorithm_);
14243
14244 // Verify the server is not throttled by the anti-amplification limit by
14245 // sending a packet larger than the anti-amplification limit.
14246 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
14247 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
14248 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
14249}
14250
danzhb37451f2022-04-19 08:18:54 -070014251// Regression test of b/228645208.
14252TEST_P(QuicConnectionTest, NoNonProbingFrameOnAlternativePath) {
danzh7c0ef5f2023-06-08 12:10:35 -070014253 if (!version().HasIetfQuicFrames()) {
danzhb37451f2022-04-19 08:18:54 -070014254 return;
14255 }
14256
14257 PathProbeTestInit(Perspective::IS_SERVER);
14258 SetClientConnectionId(TestConnectionId(1));
14259 connection_.CreateConnectionIdManager();
14260
14261 QuicConnectionId server_cid0 = connection_.connection_id();
14262 QuicConnectionId client_cid0 = connection_.client_connection_id();
14263 QuicConnectionId client_cid1 = TestConnectionId(2);
14264 QuicConnectionId server_cid1;
14265 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014266 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014267 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14268 .WillOnce(Return(TestConnectionId(456)));
14269 }
haoyuewangada6b822022-06-23 13:41:18 -070014270 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14271 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14272 server_cid1 = cid;
14273 return true;
14274 }));
danzhb37451f2022-04-19 08:18:54 -070014275 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14276 connection_.MaybeSendConnectionIdToClient();
14277 // Receives new client CID from client.
14278 QuicNewConnectionIdFrame new_cid_frame;
14279 new_cid_frame.connection_id = client_cid1;
14280 new_cid_frame.sequence_number = 1u;
14281 new_cid_frame.retire_prior_to = 0u;
14282 connection_.OnNewConnectionIdFrame(new_cid_frame);
14283 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14284 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14285 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14286
14287 peer_creator_.SetServerConnectionId(server_cid1);
14288 const QuicSocketAddress kNewPeerAddress =
14289 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
14290 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14291 QuicFrames frames1;
14292 frames1.push_back(
14293 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
danzhb37451f2022-04-19 08:18:54 -070014294 EXPECT_CALL(*send_algorithm_,
14295 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14296 .Times(AtLeast(1))
14297 .WillOnce(Invoke([&]() {
14298 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14299 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14300 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14301 EXPECT_FALSE(writer_->path_response_frames().empty());
14302 EXPECT_FALSE(writer_->path_challenge_frames().empty());
awillia202240c2024-07-08 09:47:00 -070014303 }))
14304 .WillRepeatedly(DoDefault());
danzhb37451f2022-04-19 08:18:54 -070014305 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14306 ENCRYPTION_FORWARD_SECURE);
14307 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14308 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14309 EXPECT_TRUE(connection_.HasPendingPathValidation());
14310 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14311 const auto* alternative_path =
14312 QuicConnectionPeer::GetAlternativePath(&connection_);
14313 EXPECT_EQ(default_path->client_connection_id, client_cid0);
14314 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14315 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14316 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14317 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14318 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14319
14320 // Process non-probing packets on the default path.
14321 peer_creator_.SetServerConnectionId(server_cid0);
14322 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillRepeatedly(Invoke([=]() {
14323 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14324 }));
14325 // Receives packets 3 - 39 to send 19 ACK-only packets, which will force the
14326 // connection to reach |kMaxConsecutiveNonRetransmittablePackets| while
14327 // sending the next ACK.
14328 for (size_t i = 3; i <= 39; ++i) {
14329 ProcessDataPacket(i);
14330 }
14331 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14332 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14333
14334 EXPECT_TRUE(connection_.HasPendingAcks());
14335 QuicTime ack_time = connection_.GetAckAlarm()->deadline();
14336 QuicTime path_validation_retry_time =
14337 connection_.GetRetryTimeout(kNewPeerAddress, writer_.get());
14338 // Advance time to simultaneously fire path validation retry and ACK alarms.
14339 clock_.AdvanceTime(std::max(ack_time, path_validation_retry_time) -
14340 clock_.ApproximateNow());
14341
14342 // The 20th ACK should bundle with a WINDOW_UPDATE frame.
14343 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
14344 .WillOnce(Invoke([this]() {
14345 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
14346 }));
martindukee6444ef2022-09-23 12:32:23 -070014347 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14348 .WillOnce(Invoke([&]() {
14349 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14350 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14351 // Retry path validation shouldn't bundle ACK.
14352 EXPECT_TRUE(writer_->ack_frames().empty());
14353 }))
14354 .WillOnce(Invoke([&]() {
14355 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
14356 EXPECT_FALSE(writer_->ack_frames().empty());
14357 EXPECT_FALSE(writer_->window_update_frames().empty());
14358 }));
14359 static_cast<TestAlarmFactory::TestAlarm*>(
14360 QuicPathValidatorPeer::retry_timer(
14361 QuicConnectionPeer::path_validator(&connection_)))
14362 ->Fire();
danzhb37451f2022-04-19 08:18:54 -070014363}
14364
haoyuewangada6b822022-06-23 13:41:18 -070014365TEST_P(QuicConnectionTest, DoNotIssueNewCidIfVisitorSaysNo) {
14366 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070014367 if (!version().HasIetfQuicFrames()) {
haoyuewangada6b822022-06-23 13:41:18 -070014368 return;
14369 }
14370
14371 connection_.CreateConnectionIdManager();
14372
14373 QuicConnectionId server_cid0 = connection_.connection_id();
14374 QuicConnectionId client_cid1 = TestConnectionId(2);
14375 QuicConnectionId server_cid1;
14376 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014377 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014378 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14379 .WillOnce(Return(TestConnectionId(456)));
14380 }
haoyuewangada6b822022-06-23 13:41:18 -070014381 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(false));
haoyuewangc0d96f52023-06-08 11:24:28 -070014382 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(0);
haoyuewangada6b822022-06-23 13:41:18 -070014383 connection_.MaybeSendConnectionIdToClient();
14384}
14385
Bence Békybac04052022-04-07 15:44:29 -040014386TEST_P(QuicConnectionTest,
14387 ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer) {
14388 PathProbeTestInit(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -070014389 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014390 return;
14391 }
14392
14393 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14394 /*port=*/23456);
14395
14396 // Process a packet with a new peer address will start connection migration.
14397 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14398 // IETF QUIC send algorithm should be changed to a different object, so no
14399 // OnPacketSent() called on the old send algorithm.
14400 EXPECT_CALL(*send_algorithm_,
14401 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14402 .Times(0);
14403 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
14404 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14405 }));
14406 QuicFrames frames2;
14407 frames2.push_back(QuicFrame(frame2_));
14408 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14409 ENCRYPTION_FORWARD_SECURE);
14410 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14411 EXPECT_TRUE(connection_.HasPendingPathValidation());
14412
14413 // Switch to use the mock send algorithm.
14414 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14415 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14416 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14417 .WillRepeatedly(Return(kDefaultTCPMSS));
14418 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14419 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14420 .Times(AnyNumber())
14421 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14422 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14423 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14424 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14425 connection_.SetSendAlgorithm(send_algorithm_);
14426
14427 // Receive probing packet with a newer peer address shouldn't override the
14428 // on-going path validation.
14429 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14430 /*port=*/34567);
14431 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14432 .WillOnce(Invoke([&]() {
14433 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14434 EXPECT_FALSE(writer_->path_response_frames().empty());
14435 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14436 }));
14437 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14438 QuicFrames frames1;
14439 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014440 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014441 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewerPeerAddress,
14442 ENCRYPTION_FORWARD_SECURE);
14443 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14444 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14445 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14446 EXPECT_TRUE(connection_.HasPendingPathValidation());
14447}
14448
14449TEST_P(QuicConnectionTest,
14450 PathValidationFailedOnClientDueToLackOfServerConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070014451 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014452 return;
14453 }
14454 PathProbeTestInit(Perspective::IS_CLIENT,
14455 /*receive_new_server_connection_id=*/false);
14456
14457 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14458 /*port=*/34567);
14459
14460 bool success;
14461 connection_.ValidatePath(
14462 std::make_unique<TestQuicPathValidationContext>(
14463 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14464 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014465 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
14466 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014467
14468 EXPECT_FALSE(success);
14469}
14470
14471TEST_P(QuicConnectionTest,
14472 PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime) {
danzh7c0ef5f2023-06-08 12:10:35 -070014473 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014474 return;
14475 }
14476 PathProbeTestInit(Perspective::IS_CLIENT,
14477 /*receive_new_server_connection_id=*/false);
14478 SetClientConnectionId(TestConnectionId(1));
14479
14480 // Make sure server connection ID is available for the 1st validation.
14481 QuicConnectionId server_cid0 = connection_.connection_id();
14482 QuicConnectionId server_cid1 = TestConnectionId(2);
14483 QuicConnectionId server_cid2 = TestConnectionId(4);
14484 QuicConnectionId client_cid1;
14485 QuicNewConnectionIdFrame frame1;
14486 frame1.connection_id = server_cid1;
14487 frame1.sequence_number = 1u;
14488 frame1.retire_prior_to = 0u;
14489 frame1.stateless_reset_token =
14490 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14491 connection_.OnNewConnectionIdFrame(frame1);
14492 const auto* packet_creator =
14493 QuicConnectionPeer::GetPacketCreator(&connection_);
14494 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid0);
14495
14496 // Client will issue a new client connection ID to server.
martinduke08e3ff82022-10-18 09:06:26 -070014497 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14498 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014499 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14500 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14501 client_cid1 = frame.connection_id;
14502 }));
14503
14504 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14505 ASSERT_NE(kSelfAddress1, connection_.self_address());
14506 bool success1;
14507 connection_.ValidatePath(
14508 std::make_unique<TestQuicPathValidationContext>(
14509 kSelfAddress1, connection_.peer_address(), writer_.get()),
14510 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014511 &connection_, kSelfAddress1, connection_.peer_address(), &success1),
14512 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014513
14514 // Migrate upon 1st validation success.
14515 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14516 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14517 &new_writer, /*owns_writer=*/false));
14518 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14519 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14520 EXPECT_EQ(default_path->client_connection_id, client_cid1);
14521 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14522 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14523 const auto* alternative_path =
14524 QuicConnectionPeer::GetAlternativePath(&connection_);
14525 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14526 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14527 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14528 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid1);
14529
14530 // Client will retire server connection ID on old default_path.
14531 auto* retire_peer_issued_cid_alarm =
14532 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14533 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14534 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14535 retire_peer_issued_cid_alarm->Fire();
14536
14537 // Another server connection ID is available to client.
14538 QuicNewConnectionIdFrame frame2;
14539 frame2.connection_id = server_cid2;
14540 frame2.sequence_number = 2u;
14541 frame2.retire_prior_to = 1u;
14542 frame2.stateless_reset_token =
14543 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14544 connection_.OnNewConnectionIdFrame(frame2);
14545
14546 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14547 /*port=*/45678);
14548 bool success2;
14549 connection_.ValidatePath(
14550 std::make_unique<TestQuicPathValidationContext>(
14551 kSelfAddress2, connection_.peer_address(), writer_.get()),
14552 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014553 &connection_, kSelfAddress2, connection_.peer_address(), &success2),
14554 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014555 // Since server does not retire any client connection ID yet, 2nd validation
14556 // would fail due to lack of client connection ID.
14557 EXPECT_FALSE(success2);
14558}
14559
14560TEST_P(QuicConnectionTest, ServerConnectionIdRetiredUponPathValidationFailure) {
danzh7c0ef5f2023-06-08 12:10:35 -070014561 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014562 return;
14563 }
14564 PathProbeTestInit(Perspective::IS_CLIENT);
14565
14566 // Make sure server connection ID is available for validation.
14567 QuicNewConnectionIdFrame frame;
14568 frame.connection_id = TestConnectionId(2);
14569 frame.sequence_number = 1u;
14570 frame.retire_prior_to = 0u;
14571 frame.stateless_reset_token =
14572 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14573 connection_.OnNewConnectionIdFrame(frame);
14574
14575 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14576 /*port=*/34567);
14577 bool success;
14578 connection_.ValidatePath(
14579 std::make_unique<TestQuicPathValidationContext>(
14580 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14581 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014582 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
14583 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014584
14585 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
14586 path_validator->CancelPathValidation();
14587 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14588 EXPECT_FALSE(success);
14589 const auto* alternative_path =
14590 QuicConnectionPeer::GetAlternativePath(&connection_);
14591 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14592 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14593 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14594
14595 // Client will retire server connection ID on alternative_path.
14596 auto* retire_peer_issued_cid_alarm =
14597 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14598 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14599 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
14600 retire_peer_issued_cid_alarm->Fire();
14601}
14602
14603TEST_P(QuicConnectionTest,
14604 MigratePathDirectlyFailedDueToLackOfServerConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070014605 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014606 return;
14607 }
14608 PathProbeTestInit(Perspective::IS_CLIENT,
14609 /*receive_new_server_connection_id=*/false);
14610 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14611 ASSERT_NE(kSelfAddress1, connection_.self_address());
14612
14613 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14614 ASSERT_FALSE(connection_.MigratePath(kSelfAddress1,
14615 connection_.peer_address(), &new_writer,
14616 /*owns_writer=*/false));
14617}
14618
14619TEST_P(QuicConnectionTest,
14620 MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime) {
danzh7c0ef5f2023-06-08 12:10:35 -070014621 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014622 return;
14623 }
14624 PathProbeTestInit(Perspective::IS_CLIENT,
14625 /*receive_new_server_connection_id=*/false);
14626 SetClientConnectionId(TestConnectionId(1));
14627
14628 // Make sure server connection ID is available for the 1st migration.
14629 QuicNewConnectionIdFrame frame1;
14630 frame1.connection_id = TestConnectionId(2);
14631 frame1.sequence_number = 1u;
14632 frame1.retire_prior_to = 0u;
14633 frame1.stateless_reset_token =
14634 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14635 connection_.OnNewConnectionIdFrame(frame1);
14636
14637 // Client will issue a new client connection ID to server.
14638 QuicConnectionId new_client_connection_id;
martinduke08e3ff82022-10-18 09:06:26 -070014639 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14640 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014641 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14642 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14643 new_client_connection_id = frame.connection_id;
14644 }));
14645
14646 // 1st migration is successful.
14647 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14648 ASSERT_NE(kSelfAddress1, connection_.self_address());
14649 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14650 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14651 &new_writer,
14652 /*owns_writer=*/false));
14653 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14654 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14655 EXPECT_EQ(default_path->client_connection_id, new_client_connection_id);
14656 EXPECT_EQ(default_path->server_connection_id, frame1.connection_id);
14657 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14658
14659 // Client will retire server connection ID on old default_path.
14660 auto* retire_peer_issued_cid_alarm =
14661 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14662 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14663 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14664 retire_peer_issued_cid_alarm->Fire();
14665
14666 // Another server connection ID is available to client.
14667 QuicNewConnectionIdFrame frame2;
14668 frame2.connection_id = TestConnectionId(4);
14669 frame2.sequence_number = 2u;
14670 frame2.retire_prior_to = 1u;
14671 frame2.stateless_reset_token =
14672 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14673 connection_.OnNewConnectionIdFrame(frame2);
14674
14675 // Since server does not retire any client connection ID yet, 2nd migration
14676 // would fail due to lack of client connection ID.
14677 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14678 /*port=*/45678);
14679 auto new_writer2 = std::make_unique<TestPacketWriter>(version(), &clock_,
14680 Perspective::IS_CLIENT);
14681 ASSERT_FALSE(connection_.MigratePath(
14682 kSelfAddress2, connection_.peer_address(), new_writer2.release(),
14683 /*owns_writer=*/true));
14684}
14685
14686TEST_P(QuicConnectionTest,
14687 CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID) {
14688 if (!version().HasIetfQuicFrames()) {
14689 return;
14690 }
14691 set_perspective(Perspective::IS_SERVER);
14692 ASSERT_TRUE(connection_.client_connection_id().IsEmpty());
14693
14694 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14695 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14696 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14697 QuicNewConnectionIdFrame frame;
14698 frame.sequence_number = 1u;
14699 frame.connection_id = TestConnectionId(1);
14700 frame.stateless_reset_token =
14701 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14702 frame.retire_prior_to = 0u;
14703
14704 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14705
14706 EXPECT_FALSE(connection_.connected());
14707 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14708 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14709}
14710
14711TEST_P(QuicConnectionTest, NewConnectionIdFrameResultsInError) {
14712 if (!version().HasIetfQuicFrames()) {
14713 return;
14714 }
14715 connection_.CreateConnectionIdManager();
14716 ASSERT_FALSE(connection_.connection_id().IsEmpty());
14717
14718 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14719 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14720 QuicNewConnectionIdFrame frame;
14721 frame.sequence_number = 1u;
14722 frame.connection_id = connection_id_; // Reuses connection ID casuing error.
14723 frame.stateless_reset_token =
14724 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14725 frame.retire_prior_to = 0u;
14726
14727 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14728
14729 EXPECT_FALSE(connection_.connected());
14730 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14731 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14732}
14733
14734TEST_P(QuicConnectionTest,
14735 ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14736 if (!version().HasIetfQuicFrames()) {
14737 return;
14738 }
14739 connection_.CreateConnectionIdManager();
14740
14741 QuicNewConnectionIdFrame frame;
14742 frame.sequence_number = 1u;
14743 frame.connection_id = TestConnectionId(1);
14744 frame.stateless_reset_token =
14745 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14746 frame.retire_prior_to = 0u;
14747
14748 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14749 auto* retire_peer_issued_cid_alarm =
14750 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14751 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14752
14753 frame.sequence_number = 2u;
14754 frame.connection_id = TestConnectionId(2);
14755 frame.stateless_reset_token =
14756 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14757 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14758
14759 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14760 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14761 EXPECT_EQ(connection_.connection_id(), connection_id_);
14762
14763 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14764 retire_peer_issued_cid_alarm->Fire();
14765 EXPECT_EQ(connection_.connection_id(), TestConnectionId(2));
14766 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14767 TestConnectionId(2));
14768}
14769
14770TEST_P(QuicConnectionTest,
14771 ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14772 if (!version().HasIetfQuicFrames()) {
14773 return;
14774 }
14775 set_perspective(Perspective::IS_SERVER);
14776 SetClientConnectionId(TestConnectionId(0));
14777
14778 QuicNewConnectionIdFrame frame;
14779 frame.sequence_number = 1u;
14780 frame.connection_id = TestConnectionId(1);
14781 frame.stateless_reset_token =
14782 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14783 frame.retire_prior_to = 0u;
14784
14785 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14786 auto* retire_peer_issued_cid_alarm =
14787 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14788 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14789
14790 frame.sequence_number = 2u;
14791 frame.connection_id = TestConnectionId(2);
14792 frame.stateless_reset_token =
14793 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14794 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14795
14796 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14797 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14798 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14799
14800 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14801 retire_peer_issued_cid_alarm->Fire();
14802 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14803 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14804 TestConnectionId(2));
14805}
14806
14807TEST_P(
14808 QuicConnectionTest,
14809 ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame) {
danzhaf2e52a2022-04-20 07:37:03 -070014810 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014811 return;
14812 }
14813 PathProbeTestInit(Perspective::IS_SERVER);
14814 SetClientConnectionId(TestConnectionId(0));
14815
14816 // Populate alternative_path_ with probing packet.
14817 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
14818
14819 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
14820 QuicEncryptedPacket(probing_packet->encrypted_buffer,
14821 probing_packet->encrypted_length),
14822 clock_.Now()));
14823 QuicIpAddress new_host;
14824 new_host.FromString("1.1.1.1");
14825 ProcessReceivedPacket(kSelfAddress,
14826 QuicSocketAddress(new_host, /*port=*/23456), *received);
14827
14828 EXPECT_EQ(
14829 TestConnectionId(0),
14830 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14831
14832 QuicNewConnectionIdFrame frame;
14833 frame.sequence_number = 1u;
14834 frame.connection_id = TestConnectionId(1);
14835 frame.stateless_reset_token =
14836 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14837 frame.retire_prior_to = 0u;
14838
14839 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14840 auto* retire_peer_issued_cid_alarm =
14841 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14842 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14843
14844 frame.sequence_number = 2u;
14845 frame.connection_id = TestConnectionId(2);
14846 frame.stateless_reset_token =
14847 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14848 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14849
14850 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14851 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14852 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14853
14854 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14855 retire_peer_issued_cid_alarm->Fire();
14856 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14857 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14858 TestConnectionId(2));
14859 // Clean up alternative path connection ID.
14860 EXPECT_EQ(
14861 TestConnectionId(2),
14862 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14863}
14864
14865TEST_P(QuicConnectionTest,
14866 CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued) {
danzh7c0ef5f2023-06-08 12:10:35 -070014867 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014868 return;
14869 }
14870 set_perspective(Perspective::IS_SERVER);
14871
14872 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14873 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14874 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14875 QuicRetireConnectionIdFrame frame;
14876 frame.sequence_number = 1u;
14877
14878 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14879
14880 EXPECT_FALSE(connection_.connected());
14881 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14882 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14883}
14884
14885TEST_P(QuicConnectionTest, RetireConnectionIdFrameResultsInError) {
danzh7c0ef5f2023-06-08 12:10:35 -070014886 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014887 return;
14888 }
14889 set_perspective(Perspective::IS_SERVER);
14890 connection_.CreateConnectionIdManager();
14891
martinduke08e3ff82022-10-18 09:06:26 -070014892 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014893 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14894 .WillOnce(Return(TestConnectionId(456)));
14895 }
danzh7c0ef5f2023-06-08 12:10:35 -070014896 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
Bence Békybac04052022-04-07 15:44:29 -040014897 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14898 connection_.MaybeSendConnectionIdToClient();
14899
14900 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14901 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14902 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14903 QuicRetireConnectionIdFrame frame;
14904 frame.sequence_number = 2u; // The corresponding ID is never issued.
14905
14906 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14907
14908 EXPECT_FALSE(connection_.connected());
14909 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14910 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14911}
14912
14913TEST_P(QuicConnectionTest,
14914 ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore) {
14915 if (!version().HasIetfQuicFrames()) {
14916 return;
14917 }
14918 set_perspective(Perspective::IS_SERVER);
14919 connection_.CreateConnectionIdManager();
14920
14921 auto* retire_self_issued_cid_alarm =
14922 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14923 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14924
14925 QuicConnectionId cid0 = connection_id_;
14926 QuicRetireConnectionIdFrame frame;
14927 frame.sequence_number = 0u;
danzh7c0ef5f2023-06-08 12:10:35 -070014928
14929 if (!connection_.connection_id().IsEmpty()) {
14930 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(cid0))
14931 .WillOnce(Return(TestConnectionId(456)));
14932 EXPECT_CALL(connection_id_generator_,
14933 GenerateNextConnectionId(TestConnectionId(456)))
14934 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040014935 }
danzh7c0ef5f2023-06-08 12:10:35 -070014936 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14937 .Times(2)
14938 .WillRepeatedly(Return(true));
14939 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -040014940 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(frame));
14941}
14942
14943TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070014944 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014945 return;
14946 }
14947 set_perspective(Perspective::IS_SERVER);
14948 connection_.CreateConnectionIdManager();
14949 QuicConnectionId recorded_cid;
haoyuewangada6b822022-06-23 13:41:18 -070014950 auto cid_recorder = [&recorded_cid](const QuicConnectionId& cid) -> bool {
Bence Békybac04052022-04-07 15:44:29 -040014951 recorded_cid = cid;
haoyuewangada6b822022-06-23 13:41:18 -070014952 return true;
Bence Békybac04052022-04-07 15:44:29 -040014953 };
14954 QuicConnectionId cid0 = connection_id_;
14955 QuicConnectionId cid1;
14956 QuicConnectionId cid2;
14957 EXPECT_EQ(connection_.connection_id(), cid0);
14958 EXPECT_EQ(connection_.GetOneActiveServerConnectionId(), cid0);
14959
14960 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke08e3ff82022-10-18 09:06:26 -070014961 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014962 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14963 .WillOnce(Return(TestConnectionId(456)));
14964 }
haoyuewangada6b822022-06-23 13:41:18 -070014965 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040014966 .WillOnce(Invoke(cid_recorder));
14967 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14968 connection_.MaybeSendConnectionIdToClient();
14969 cid1 = recorded_cid;
14970
14971 auto* retire_self_issued_cid_alarm =
14972 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14973 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14974
14975 // Generate three packets with different connection IDs that will arrive out
14976 // of order (2, 1, 3) later.
14977 char buffers[3][kMaxOutgoingPacketSize];
14978 // Destination connection ID of packet1 is cid0.
14979 auto packet1 =
14980 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14981 buffers[0], kMaxOutgoingPacketSize);
14982 peer_creator_.SetServerConnectionId(cid1);
14983 auto retire_cid_frame = std::make_unique<QuicRetireConnectionIdFrame>();
14984 retire_cid_frame->sequence_number = 0u;
14985 // Destination connection ID of packet2 is cid1.
14986 auto packet2 = ConstructPacket({QuicFrame(retire_cid_frame.release())},
14987 ENCRYPTION_FORWARD_SECURE, buffers[1],
14988 kMaxOutgoingPacketSize);
14989 // Destination connection ID of packet3 is cid1.
14990 auto packet3 =
14991 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14992 buffers[2], kMaxOutgoingPacketSize);
14993
14994 // Packet2 with RetireConnectionId frame trigers sending NewConnectionId
14995 // immediately.
martinduke08e3ff82022-10-18 09:06:26 -070014996 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014997 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14998 .WillOnce(Return(TestConnectionId(456)));
14999 }
haoyuewangada6b822022-06-23 13:41:18 -070015000 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040015001 .WillOnce(Invoke(cid_recorder));
15002 EXPECT_CALL(visitor_, SendNewConnectionId(_));
15003 peer_creator_.SetServerConnectionId(cid1);
15004 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet2);
15005 cid2 = recorded_cid;
15006 // cid0 is not retired immediately.
15007 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
15008 ElementsAre(cid0, cid1, cid2));
15009 ASSERT_TRUE(retire_self_issued_cid_alarm->IsSet());
15010 EXPECT_EQ(connection_.connection_id(), cid1);
15011 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
15012 connection_.GetOneActiveServerConnectionId() == cid1 ||
15013 connection_.GetOneActiveServerConnectionId() == cid2);
15014
15015 // Packet1 updates the connection ID on the default path but not the active
15016 // connection ID.
15017 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet1);
15018 EXPECT_EQ(connection_.connection_id(), cid0);
15019 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
15020 connection_.GetOneActiveServerConnectionId() == cid1 ||
15021 connection_.GetOneActiveServerConnectionId() == cid2);
15022
15023 // cid0 is retired when the retire CID alarm fires.
15024 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(cid0));
15025 retire_self_issued_cid_alarm->Fire();
15026 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
15027 ElementsAre(cid1, cid2));
15028 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
15029 connection_.GetOneActiveServerConnectionId() == cid2);
15030
15031 // Packet3 updates the connection ID on the default path.
15032 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet3);
15033 EXPECT_EQ(connection_.connection_id(), cid1);
15034 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
15035 connection_.GetOneActiveServerConnectionId() == cid2);
15036}
15037
15038TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoAlternativePath) {
15039 if (!version().HasIetfQuicFrames()) {
15040 return;
15041 }
15042 set_perspective(Perspective::IS_SERVER);
15043 connection_.CreateConnectionIdManager();
15044 connection_.set_client_connection_id(TestConnectionId(1));
15045
15046 // Set up the state after path probing.
15047 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15048 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
15049 QuicIpAddress new_host;
15050 new_host.FromString("12.12.12.12");
15051 alternative_path->self_address = default_path->self_address;
15052 alternative_path->peer_address = QuicSocketAddress(new_host, 12345);
15053 alternative_path->server_connection_id = TestConnectionId(3);
15054 ASSERT_TRUE(alternative_path->client_connection_id.IsEmpty());
15055 ASSERT_FALSE(alternative_path->stateless_reset_token.has_value());
15056
15057 QuicNewConnectionIdFrame frame;
15058 frame.sequence_number = 1u;
15059 frame.connection_id = TestConnectionId(5);
15060 frame.stateless_reset_token =
15061 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15062 frame.retire_prior_to = 0u;
15063 // New ID is patched onto the alternative path when the needed
15064 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
15065 connection_.OnNewConnectionIdFrame(frame);
15066
15067 ASSERT_EQ(alternative_path->client_connection_id, frame.connection_id);
15068 ASSERT_EQ(alternative_path->stateless_reset_token,
15069 frame.stateless_reset_token);
15070}
15071
15072TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoDefaultPath) {
15073 if (!version().HasIetfQuicFrames()) {
15074 return;
15075 }
15076 set_perspective(Perspective::IS_SERVER);
15077 connection_.CreateConnectionIdManager();
15078 connection_.set_client_connection_id(TestConnectionId(1));
15079
15080 // Set up the state after peer migration without probing.
15081 auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15082 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
15083 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
15084 *alternative_path = std::move(*default_path);
15085 QuicIpAddress new_host;
15086 new_host.FromString("12.12.12.12");
15087 default_path->self_address = default_path->self_address;
15088 default_path->peer_address = QuicSocketAddress(new_host, 12345);
15089 default_path->server_connection_id = TestConnectionId(3);
15090 packet_creator->SetDefaultPeerAddress(default_path->peer_address);
15091 packet_creator->SetServerConnectionId(default_path->server_connection_id);
15092 packet_creator->SetClientConnectionId(default_path->client_connection_id);
15093
15094 ASSERT_FALSE(default_path->validated);
15095 ASSERT_TRUE(default_path->client_connection_id.IsEmpty());
15096 ASSERT_FALSE(default_path->stateless_reset_token.has_value());
15097
15098 QuicNewConnectionIdFrame frame;
15099 frame.sequence_number = 1u;
15100 frame.connection_id = TestConnectionId(5);
15101 frame.stateless_reset_token =
15102 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15103 frame.retire_prior_to = 0u;
15104 // New ID is patched onto the default path when the needed
15105 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
15106 connection_.OnNewConnectionIdFrame(frame);
15107
15108 ASSERT_EQ(default_path->client_connection_id, frame.connection_id);
15109 ASSERT_EQ(default_path->stateless_reset_token, frame.stateless_reset_token);
15110 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), frame.connection_id);
15111}
15112
15113TEST_P(QuicConnectionTest, ShouldGeneratePacketBlockedByMissingConnectionId) {
15114 if (!version().HasIetfQuicFrames()) {
15115 return;
15116 }
15117 set_perspective(Perspective::IS_SERVER);
15118 connection_.set_client_connection_id(TestConnectionId(1));
15119 connection_.CreateConnectionIdManager();
15120 if (version().SupportsAntiAmplificationLimit()) {
15121 QuicConnectionPeer::SetAddressValidated(&connection_);
15122 }
15123
15124 ASSERT_TRUE(
15125 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
15126
15127 QuicPacketCreator* packet_creator =
15128 QuicConnectionPeer::GetPacketCreator(&connection_);
15129 QuicIpAddress peer_host1;
15130 peer_host1.FromString("12.12.12.12");
15131 QuicSocketAddress peer_address1(peer_host1, 1235);
15132
15133 {
15134 // No connection ID is available as context is created without any.
15135 QuicPacketCreator::ScopedPeerAddressContext context(
15136 packet_creator, peer_address1, EmptyQuicConnectionId(),
danzh7c0ef5f2023-06-08 12:10:35 -070015137 EmptyQuicConnectionId());
Bence Békybac04052022-04-07 15:44:29 -040015138 ASSERT_FALSE(connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
15139 NOT_HANDSHAKE));
15140 }
15141 ASSERT_TRUE(
15142 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
15143}
15144
15145// Regression test for b/182571515
15146TEST_P(QuicConnectionTest, LostDataThenGetAcknowledged) {
15147 set_perspective(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -070015148 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -070015149 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040015150 return;
15151 }
15152
15153 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
15154 if (version().SupportsAntiAmplificationLimit()) {
15155 QuicConnectionPeer::SetAddressValidated(&connection_);
15156 }
15157 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15158 // Discard INITIAL key.
15159 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15160 connection_.NeuterUnencryptedPackets();
15161 EXPECT_CALL(visitor_, GetHandshakeState())
15162 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
15163
15164 QuicPacketNumber last_packet;
15165 // Send packets 1 to 4.
15166 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
15167 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 2
15168 SendStreamDataToPeer(3, "foo", 6, NO_FIN, &last_packet); // Packet 3
15169 SendStreamDataToPeer(3, "foo", 9, NO_FIN, &last_packet); // Packet 4
15170
15171 // Process a PING packet to set peer address.
15172 ProcessFramePacket(QuicFrame(QuicPingFrame()));
15173
15174 // Process a packet containing a STREAM_FRAME and an ACK with changed peer
15175 // address.
15176 QuicFrames frames;
15177 frames.push_back(QuicFrame(frame1_));
15178 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}});
15179 frames.push_back(QuicFrame(&ack));
15180
Bence Békybac04052022-04-07 15:44:29 -040015181 // Invoke OnCanWrite.
Bence Békybac04052022-04-07 15:44:29 -040015182 QuicIpAddress ip_address;
15183 ASSERT_TRUE(ip_address.FromString("127.0.52.223"));
vasilvvac2e30d2022-06-02 14:26:59 -070015184 EXPECT_QUIC_BUG(
15185 {
15186 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(1);
15187 EXPECT_CALL(visitor_, OnStreamFrame(_))
15188 .WillOnce(InvokeWithoutArgs(&notifier_,
15189 &SimpleSessionNotifier::OnCanWrite));
15190 ProcessFramesPacketWithAddresses(frames, kSelfAddress,
15191 QuicSocketAddress(ip_address, 1000),
15192 ENCRYPTION_FORWARD_SECURE);
15193 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
15194
15195 // Verify stream frame will not be retransmitted.
15196 EXPECT_TRUE(writer_->stream_frames().empty());
15197 },
15198 "Try to write mid packet processing");
Bence Békybac04052022-04-07 15:44:29 -040015199}
15200
15201TEST_P(QuicConnectionTest, PtoSendStreamData) {
15202 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15203 return;
15204 }
15205 set_perspective(Perspective::IS_SERVER);
15206 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
15207 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15208 }
15209 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015210 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15211 EXPECT_TRUE(connection_.HasPendingAcks());
15212
Bence Békybac04052022-04-07 15:44:29 -040015213 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15214 // Send INITIAL 1.
15215 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15216
martinduke9e0811c2022-12-08 20:35:57 -080015217 connection_.SetEncrypter(
15218 ENCRYPTION_HANDSHAKE,
15219 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015220 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15221 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015222 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015223 // Send HANDSHAKE packets.
15224 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15225 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15226
martinduke9e0811c2022-12-08 20:35:57 -080015227 connection_.SetEncrypter(
15228 ENCRYPTION_FORWARD_SECURE,
15229 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015230 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15231
15232 // Send half RTT packet with congestion control blocked.
15233 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
15234 connection_.SendStreamDataWithString(2, std::string(1500, 'a'), 0, NO_FIN);
15235
15236 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15237 connection_.GetRetransmissionAlarm()->Fire();
15238 // Verify INITIAL and HANDSHAKE get retransmitted.
martinduke9e0811c2022-12-08 20:35:57 -080015239 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015240}
15241
15242TEST_P(QuicConnectionTest, SendingZeroRttPacketsDoesNotPostponePTO) {
15243 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15244 return;
15245 }
Bence Békybac04052022-04-07 15:44:29 -040015246 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15247 // Send CHLO.
15248 connection_.SendCryptoStreamData();
15249 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15250 // Install 0-RTT keys.
15251 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15252 std::make_unique<TaggingEncrypter>(0x02));
15253 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15254
15255 // CHLO gets acknowledged after 10ms.
15256 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15257 QuicAckFrame frame1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070015258 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015259 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15260 // Verify PTO is still armed since address validation is not finished yet.
15261 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15262 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15263
15264 // Send 0-RTT packet.
15265 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15266 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15267 std::make_unique<TaggingEncrypter>(0x02));
15268 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15269 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15270 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15271 // PTO deadline should be unchanged.
15272 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15273}
15274
15275TEST_P(QuicConnectionTest, QueueingUndecryptablePacketsDoesntPostponePTO) {
15276 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15277 return;
15278 }
15279 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15280 QuicConfig config;
15281 config.set_max_undecryptable_packets(3);
15282 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040015283 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15284 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15285 // Send CHLO.
15286 connection_.SendCryptoStreamData();
15287
15288 // Send 0-RTT packet.
15289 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15290 std::make_unique<TaggingEncrypter>(0x02));
15291 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15292 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15293
15294 // CHLO gets acknowledged after 10ms.
15295 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15296 QuicAckFrame frame1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070015297 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015298 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15299 // Verify PTO is still armed since address validation is not finished yet.
15300 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15301 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15302
15303 // Receive an undecryptable packets.
15304 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15305 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15306 std::make_unique<TaggingEncrypter>(0xFF));
15307 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15308 // Verify PTO deadline is sooner.
15309 EXPECT_GT(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15310 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15311
15312 // PTO fires.
15313 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15314 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15315 connection_.GetRetransmissionAlarm()->Fire();
15316 // Verify PTO is still armed since address validation is not finished yet.
15317 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15318 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15319
15320 // Verify PTO deadline does not change.
15321 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15322 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15323}
15324
15325TEST_P(QuicConnectionTest, QueueUndecryptableHandshakePackets) {
15326 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15327 return;
15328 }
15329 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15330 QuicConfig config;
15331 config.set_max_undecryptable_packets(3);
15332 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040015333 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15334 connection_.RemoveDecrypter(ENCRYPTION_HANDSHAKE);
15335 // Send CHLO.
15336 connection_.SendCryptoStreamData();
15337
15338 // Send 0-RTT packet.
15339 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15340 std::make_unique<TaggingEncrypter>(0x02));
15341 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15342 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15343 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15344
15345 // Receive an undecryptable handshake packet.
15346 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15347 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15348 std::make_unique<TaggingEncrypter>(0xFF));
15349 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
15350 // Verify this handshake packet gets queued.
15351 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15352}
15353
15354TEST_P(QuicConnectionTest, PingNotSentAt0RTTLevelWhenInitialAvailable) {
15355 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15356 return;
15357 }
Bence Békybac04052022-04-07 15:44:29 -040015358 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15359 // Send CHLO.
15360 connection_.SendCryptoStreamData();
15361 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080015362 connection_.SetEncrypter(
15363 ENCRYPTION_ZERO_RTT,
15364 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015365 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15366 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15367
15368 // CHLO gets acknowledged after 10ms.
15369 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15370 QuicAckFrame frame1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070015371 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015372 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15373 // Verify PTO is still armed since address validation is not finished yet.
15374 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15375 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15376
15377 // PTO fires.
15378 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15379 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15380 connection_.GetRetransmissionAlarm()->Fire();
15381 // Verify the PING gets sent in ENCRYPTION_INITIAL.
martinduke9e0811c2022-12-08 20:35:57 -080015382 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015383}
15384
15385TEST_P(QuicConnectionTest, AckElicitingFrames) {
danzh7c0ef5f2023-06-08 12:10:35 -070015386 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040015387 return;
15388 }
martinduke08e3ff82022-10-18 09:06:26 -070015389 EXPECT_CALL(connection_id_generator_,
15390 GenerateNextConnectionId(TestConnectionId(12)))
15391 .WillOnce(Return(TestConnectionId(456)));
15392 EXPECT_CALL(connection_id_generator_,
15393 GenerateNextConnectionId(TestConnectionId(456)))
15394 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040015395 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
15396 EXPECT_CALL(visitor_, OnRstStream(_));
15397 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
15398 EXPECT_CALL(visitor_, OnBlockedFrame(_));
15399 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
15400 EXPECT_CALL(visitor_, OnStreamFrame(_));
martindukeba002452023-03-21 08:10:46 -070015401 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015402 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_));
15403 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_));
15404 EXPECT_CALL(visitor_, OnStopSendingFrame(_));
15405 EXPECT_CALL(visitor_, OnMessageReceived(""));
15406 EXPECT_CALL(visitor_, OnNewTokenReceived(""));
15407
15408 SetClientConnectionId(TestConnectionId(12));
15409 connection_.CreateConnectionIdManager();
15410 QuicConnectionPeer::GetSelfIssuedConnectionIdManager(&connection_)
15411 ->MaybeSendNewConnectionIds();
15412 connection_.set_can_receive_ack_frequency_frame();
15413
15414 QuicAckFrame ack_frame = InitAckFrame(1);
15415 QuicRstStreamFrame rst_stream_frame;
15416 QuicWindowUpdateFrame window_update_frame;
15417 QuicPathChallengeFrame path_challenge_frame;
15418 QuicNewConnectionIdFrame new_connection_id_frame;
renjietang785c7cb2023-08-21 09:10:25 -070015419 new_connection_id_frame.sequence_number = 1u;
Bence Békybac04052022-04-07 15:44:29 -040015420 QuicRetireConnectionIdFrame retire_connection_id_frame;
15421 retire_connection_id_frame.sequence_number = 1u;
15422 QuicStopSendingFrame stop_sending_frame;
15423 QuicPathResponseFrame path_response_frame;
15424 QuicMessageFrame message_frame;
15425 QuicNewTokenFrame new_token_frame;
15426 QuicAckFrequencyFrame ack_frequency_frame;
vasilvv60a22a62024-02-05 08:26:22 -080015427 QuicResetStreamAtFrame reset_stream_at_frame;
Bence Békybac04052022-04-07 15:44:29 -040015428 QuicBlockedFrame blocked_frame;
15429 size_t packet_number = 1;
15430
15431 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
vasilvv60a22a62024-02-05 08:26:22 -080015432 QuicFramer* framer = const_cast<QuicFramer*>(&connection_.framer());
15433 framer->set_process_reset_stream_at(true);
15434 peer_framer_.set_process_reset_stream_at(true);
Bence Békybac04052022-04-07 15:44:29 -040015435
15436 for (uint8_t i = 0; i < NUM_FRAME_TYPES; ++i) {
15437 QuicFrameType frame_type = static_cast<QuicFrameType>(i);
15438 bool skipped = false;
15439 QuicFrame frame;
15440 QuicFrames frames;
15441 // Add some padding to fullfill the min size requirement of header
15442 // protection.
15443 frames.push_back(QuicFrame(QuicPaddingFrame(10)));
15444 switch (frame_type) {
15445 case PADDING_FRAME:
15446 frame = QuicFrame(QuicPaddingFrame(10));
15447 break;
15448 case MTU_DISCOVERY_FRAME:
15449 frame = QuicFrame(QuicMtuDiscoveryFrame());
15450 break;
15451 case PING_FRAME:
15452 frame = QuicFrame(QuicPingFrame());
15453 break;
15454 case MAX_STREAMS_FRAME:
15455 frame = QuicFrame(QuicMaxStreamsFrame());
15456 break;
15457 case STOP_WAITING_FRAME:
15458 // Not supported.
15459 skipped = true;
15460 break;
15461 case STREAMS_BLOCKED_FRAME:
15462 frame = QuicFrame(QuicStreamsBlockedFrame());
15463 break;
15464 case STREAM_FRAME:
15465 frame = QuicFrame(QuicStreamFrame());
15466 break;
15467 case HANDSHAKE_DONE_FRAME:
15468 frame = QuicFrame(QuicHandshakeDoneFrame());
15469 break;
15470 case ACK_FRAME:
15471 frame = QuicFrame(&ack_frame);
15472 break;
15473 case RST_STREAM_FRAME:
15474 frame = QuicFrame(&rst_stream_frame);
15475 break;
15476 case CONNECTION_CLOSE_FRAME:
15477 // Do not test connection close.
15478 skipped = true;
15479 break;
15480 case GOAWAY_FRAME:
15481 // Does not exist in IETF QUIC.
15482 skipped = true;
15483 break;
15484 case BLOCKED_FRAME:
15485 frame = QuicFrame(blocked_frame);
15486 break;
15487 case WINDOW_UPDATE_FRAME:
15488 frame = QuicFrame(window_update_frame);
15489 break;
15490 case PATH_CHALLENGE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015491 frame = QuicFrame(path_challenge_frame);
Bence Békybac04052022-04-07 15:44:29 -040015492 break;
15493 case STOP_SENDING_FRAME:
15494 frame = QuicFrame(stop_sending_frame);
15495 break;
15496 case NEW_CONNECTION_ID_FRAME:
15497 frame = QuicFrame(&new_connection_id_frame);
15498 break;
15499 case RETIRE_CONNECTION_ID_FRAME:
15500 frame = QuicFrame(&retire_connection_id_frame);
15501 break;
15502 case PATH_RESPONSE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015503 frame = QuicFrame(path_response_frame);
Bence Békybac04052022-04-07 15:44:29 -040015504 break;
15505 case MESSAGE_FRAME:
15506 frame = QuicFrame(&message_frame);
15507 break;
15508 case CRYPTO_FRAME:
15509 // CRYPTO_FRAME is ack eliciting is covered by other tests.
15510 skipped = true;
15511 break;
15512 case NEW_TOKEN_FRAME:
15513 frame = QuicFrame(&new_token_frame);
15514 break;
15515 case ACK_FREQUENCY_FRAME:
15516 frame = QuicFrame(&ack_frequency_frame);
15517 break;
vasilvv60a22a62024-02-05 08:26:22 -080015518 case RESET_STREAM_AT_FRAME:
15519 frame = QuicFrame(&reset_stream_at_frame);
15520 break;
Bence Békybac04052022-04-07 15:44:29 -040015521 case NUM_FRAME_TYPES:
15522 skipped = true;
15523 break;
15524 }
15525 if (skipped) {
15526 continue;
15527 }
15528 ASSERT_EQ(frame_type, frame.type);
15529 frames.push_back(frame);
15530 EXPECT_FALSE(connection_.HasPendingAcks());
15531 // Process frame.
15532 ProcessFramesPacketAtLevel(packet_number++, frames,
15533 ENCRYPTION_FORWARD_SECURE);
15534 if (QuicUtils::IsAckElicitingFrame(frame_type)) {
15535 ASSERT_TRUE(connection_.HasPendingAcks()) << frame;
15536 // Flush ACK.
15537 clock_.AdvanceTime(DefaultDelayedAckTime());
15538 connection_.GetAckAlarm()->Fire();
15539 }
15540 EXPECT_FALSE(connection_.HasPendingAcks());
15541 ASSERT_TRUE(connection_.connected());
15542 }
15543}
15544
15545TEST_P(QuicConnectionTest, ReceivedChloAndAck) {
15546 if (!version().HasIetfQuicFrames()) {
15547 return;
15548 }
15549 set_perspective(Perspective::IS_SERVER);
15550 QuicFrames frames;
15551 QuicAckFrame ack_frame = InitAckFrame(1);
15552 frames.push_back(MakeCryptoFrame());
15553 frames.push_back(QuicFrame(&ack_frame));
15554
15555 EXPECT_CALL(visitor_, OnCryptoFrame(_))
15556 .WillOnce(IgnoreResult(InvokeWithoutArgs(
15557 &connection_, &TestConnection::SendCryptoStreamData)));
15558 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15559 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15560 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
15561 ENCRYPTION_INITIAL);
15562}
15563
15564// Regression test for b/201643321.
15565TEST_P(QuicConnectionTest, FailedToRetransmitShlo) {
danzh4d58dae2023-06-06 11:13:10 -070015566 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -070015567 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040015568 return;
15569 }
15570 set_perspective(Perspective::IS_SERVER);
15571 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15572 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015573 // Received INITIAL 1.
15574 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15575 EXPECT_TRUE(connection_.HasPendingAcks());
15576
martinduke9e0811c2022-12-08 20:35:57 -080015577 peer_framer_.SetEncrypter(
15578 ENCRYPTION_ZERO_RTT,
15579 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015580
martinduke9e0811c2022-12-08 20:35:57 -080015581 connection_.SetEncrypter(
15582 ENCRYPTION_HANDSHAKE,
15583 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015584 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015585 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015586 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015587 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15588 connection_.SetEncrypter(
15589 ENCRYPTION_FORWARD_SECURE,
15590 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015591 // Received ENCRYPTION_ZERO_RTT 1.
15592 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15593 {
15594 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15595 // Send INITIAL 1.
15596 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15597 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15598 // Send HANDSHAKE 2.
15599 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15600 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15601 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15602 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15603 // Send half RTT data to exhaust amplification credit.
15604 connection_.SendStreamDataWithString(0, std::string(100 * 1024, 'a'), 0,
15605 NO_FIN);
15606 }
15607 // Received INITIAL 2.
15608 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
15609 ASSERT_TRUE(connection_.HasPendingAcks());
15610 // Verify ACK delay is 1ms.
15611 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
15612 connection_.GetAckAlarm()->deadline());
15613 // ACK is not throttled by amplification limit, and SHLO is bundled. Also
15614 // HANDSHAKE + 1RTT packets get coalesced.
fayange9753892022-05-17 03:57:11 -070015615 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -040015616 // ACK alarm fires.
15617 clock_.AdvanceTime(kAlarmGranularity);
15618 connection_.GetAckAlarm()->Fire();
fayange9753892022-05-17 03:57:11 -070015619 // Verify 1-RTT packet is coalesced.
martinduke9e0811c2022-12-08 20:35:57 -080015620 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015621 // Only the first packet in the coalesced packet has been processed,
15622 // verify SHLO is bundled with INITIAL ACK.
15623 EXPECT_EQ(1u, writer_->ack_frames().size());
15624 EXPECT_EQ(1u, writer_->crypto_frames().size());
15625 // Process the coalesced HANDSHAKE packet.
15626 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15627 auto packet = writer_->coalesced_packet()->Clone();
15628 writer_->framer()->ProcessPacket(*packet);
15629 EXPECT_EQ(0u, writer_->ack_frames().size());
15630 EXPECT_EQ(1u, writer_->crypto_frames().size());
fayange9753892022-05-17 03:57:11 -070015631 // Process the coalesced 1-RTT packet.
15632 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15633 packet = writer_->coalesced_packet()->Clone();
15634 writer_->framer()->ProcessPacket(*packet);
15635 EXPECT_EQ(0u, writer_->crypto_frames().size());
15636 EXPECT_EQ(1u, writer_->stream_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040015637
15638 // Received INITIAL 3.
15639 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
15640 ProcessCryptoPacketAtLevel(3, ENCRYPTION_INITIAL);
15641 EXPECT_TRUE(connection_.HasPendingAcks());
15642}
15643
15644// Regression test for b/216133388.
15645TEST_P(QuicConnectionTest, FailedToConsumeCryptoData) {
15646 if (!version().HasIetfQuicFrames()) {
15647 return;
15648 }
15649 set_perspective(Perspective::IS_SERVER);
15650 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15651 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015652 // Received INITIAL 1.
15653 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15654 EXPECT_TRUE(connection_.HasPendingAcks());
15655
martinduke9e0811c2022-12-08 20:35:57 -080015656 peer_framer_.SetEncrypter(
15657 ENCRYPTION_ZERO_RTT,
15658 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15659 connection_.SetEncrypter(
15660 ENCRYPTION_HANDSHAKE,
15661 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015662 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015663 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015664 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015665 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15666 connection_.SetEncrypter(
15667 ENCRYPTION_FORWARD_SECURE,
15668 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015669 // Received ENCRYPTION_ZERO_RTT 1.
15670 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15671 {
15672 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15673 // Send INITIAL 1.
15674 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15675 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15676 // Send HANDSHAKE 2.
15677 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15678 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15679 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15680 ENCRYPTION_HANDSHAKE);
15681 // Send 1-RTT 3.
15682 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15683 connection_.SendStreamDataWithString(0, std::string(40, 'a'), 0, NO_FIN);
15684 }
15685 // Received HANDSHAKE Ping, hence discard INITIAL keys.
15686 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15687 std::make_unique<TaggingEncrypter>(0x03));
15688 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15689 connection_.NeuterUnencryptedPackets();
15690 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
15691 clock_.AdvanceTime(kAlarmGranularity);
15692 {
15693 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15694 // Sending this 1-RTT data would leave the coalescer only have space to
15695 // accommodate the HANDSHAKE ACK. The crypto data cannot be bundled with the
15696 // ACK.
15697 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15698 connection_.SendStreamDataWithString(0, std::string(1395, 'a'), 40, NO_FIN);
15699 }
15700 // Verify retransmission alarm is armed.
15701 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15702 const QuicTime retransmission_time =
15703 connection_.GetRetransmissionAlarm()->deadline();
15704 clock_.AdvanceTime(retransmission_time - clock_.Now());
15705 connection_.GetRetransmissionAlarm()->Fire();
15706
fayang43294412022-04-21 09:22:12 -070015707 // Verify the retransmission is a coalesced packet with HANDSHAKE 2 and
15708 // 1-RTT 3.
martinduke9e0811c2022-12-08 20:35:57 -080015709 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
fayang43294412022-04-21 09:22:12 -070015710 // Only the first packet in the coalesced packet has been processed.
15711 EXPECT_EQ(1u, writer_->crypto_frames().size());
15712 // Process the coalesced 1-RTT packet.
15713 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15714 auto packet = writer_->coalesced_packet()->Clone();
15715 writer_->framer()->ProcessPacket(*packet);
15716 EXPECT_EQ(1u, writer_->stream_frames().size());
15717 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
Bence Békybac04052022-04-07 15:44:29 -040015718 // Verify retransmission alarm is still armed.
15719 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15720}
15721
15722TEST_P(QuicConnectionTest,
15723 RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing) {
15724 // An endpoint might postpone the processing of ACK when the corresponding
15725 // decryption key is not available. This test makes sure the RTT sample does
15726 // not include the queuing delay.
15727 if (!version().HasIetfQuicFrames()) {
15728 return;
15729 }
15730 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15731 QuicConfig config;
15732 config.set_max_undecryptable_packets(3);
15733 connection_.SetFromConfig(config);
15734
15735 // 30ms RTT.
15736 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
15737 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
15738 rtt_stats->UpdateRtt(kTestRTT, QuicTime::Delta::Zero(), QuicTime::Zero());
Bence Békybac04052022-04-07 15:44:29 -040015739
15740 // Send 0-RTT packet.
15741 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
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(0, std::string(10, 'a'), 0, FIN);
15747
15748 // Receives 1-RTT ACK for 0-RTT packet after RTT + ack_delay.
wub349df3d2024-04-26 11:37:32 -070015749 clock_.AdvanceTime(kTestRTT + QuicTime::Delta::FromMilliseconds(
15750 GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040015751 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
martinduke9e0811c2022-12-08 20:35:57 -080015752 peer_framer_.SetEncrypter(
15753 ENCRYPTION_FORWARD_SECURE,
15754 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015755 QuicAckFrame ack_frame = InitAckFrame(1);
15756 // Peer reported ACK delay.
15757 ack_frame.ack_delay_time =
wub349df3d2024-04-26 11:37:32 -070015758 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
Bence Békybac04052022-04-07 15:44:29 -040015759 QuicFrames frames;
15760 frames.push_back(QuicFrame(&ack_frame));
15761 QuicPacketHeader header =
15762 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15763 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15764
15765 char buffer[kMaxOutgoingPacketSize];
15766 size_t encrypted_length = peer_framer_.EncryptPayload(
15767 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15768 kMaxOutgoingPacketSize);
15769 connection_.ProcessUdpPacket(
15770 kSelfAddress, kPeerAddress,
15771 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15772 if (connection_.GetSendAlarm()->IsSet()) {
15773 connection_.GetSendAlarm()->Fire();
15774 }
15775 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15776
15777 // Assume 1-RTT decrypter is available after 10ms.
15778 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15779 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080015780 SetDecrypter(
15781 ENCRYPTION_FORWARD_SECURE,
15782 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015783 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15784
martindukeba002452023-03-21 08:10:46 -070015785 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015786 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15787 // Verify RTT sample does not include queueing delay.
15788 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
15789}
15790
15791// Regression test for b/112480134.
15792TEST_P(QuicConnectionTest, NoExtraPaddingInReserializedInitial) {
15793 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
15794 if (!IsDefaultTestConfiguration() ||
15795 !connection_.version().CanSendCoalescedPackets()) {
15796 return;
15797 }
15798
15799 set_perspective(Perspective::IS_SERVER);
15800 MockQuicConnectionDebugVisitor debug_visitor;
15801 connection_.set_debug_visitor(&debug_visitor);
15802
15803 uint64_t debug_visitor_sent_count = 0;
wub92727922023-07-13 08:47:39 -070015804 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040015805 .WillRepeatedly([&]() { debug_visitor_sent_count++; });
15806
15807 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15808 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015809
15810 // Received INITIAL 1.
15811 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15812
martinduke9e0811c2022-12-08 20:35:57 -080015813 peer_framer_.SetEncrypter(
15814 ENCRYPTION_ZERO_RTT,
15815 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15816 connection_.SetEncrypter(
15817 ENCRYPTION_HANDSHAKE,
15818 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015819 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015820 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015821 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015822 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15823 connection_.SetEncrypter(
15824 ENCRYPTION_FORWARD_SECURE,
15825 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015826
15827 // Received ENCRYPTION_ZERO_RTT 2.
15828 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15829
15830 {
15831 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15832 // Send INITIAL 1.
15833 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15834 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15835 // Send HANDSHAKE 2.
15836 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15837 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15838 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15839 ENCRYPTION_HANDSHAKE);
15840 // Send 1-RTT 3.
15841 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15842 connection_.SendStreamDataWithString(0, std::string(400, 'b'), 0, NO_FIN);
15843 }
15844
15845 // Arrange the stream data to be sent in response to ENCRYPTION_INITIAL 3.
15846 const std::string data4(1000, '4'); // Data to send in stream id 4
15847 const std::string data8(3000, '8'); // Data to send in stream id 8
15848 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce([&]() {
15849 connection_.producer()->SaveStreamData(4, data4);
15850 connection_.producer()->SaveStreamData(8, data8);
15851
15852 notifier_.WriteOrBufferData(4, data4.size(), FIN_AND_PADDING);
15853
15854 // This should trigger FlushCoalescedPacket.
15855 notifier_.WriteOrBufferData(8, data8.size(), FIN);
15856 });
15857
15858 QuicByteCount pending_padding_after_serialize_2nd_1rtt_packet = 0;
15859 QuicPacketCount num_1rtt_packets_serialized = 0;
15860 EXPECT_CALL(connection_, OnSerializedPacket(_))
15861 .WillRepeatedly([&](SerializedPacket packet) {
15862 if (packet.encryption_level == ENCRYPTION_FORWARD_SECURE) {
15863 num_1rtt_packets_serialized++;
15864 if (num_1rtt_packets_serialized == 2) {
15865 pending_padding_after_serialize_2nd_1rtt_packet =
15866 connection_.packet_creator().pending_padding_bytes();
15867 }
15868 }
15869 connection_.QuicConnection::OnSerializedPacket(std::move(packet));
15870 });
15871
15872 // Server receives INITIAL 3, this will serialzie FS 7 (stream 4, stream 8),
15873 // which will trigger a flush of a coalesced packet consists of INITIAL 4,
15874 // HS 5 and FS 6 (stream 4).
wub08efde42022-05-09 12:25:02 -070015875
15876 // Expect no QUIC_BUG.
15877 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15878 EXPECT_EQ(
15879 debug_visitor_sent_count,
15880 connection_.sent_packet_manager().GetLargestSentPacket().ToUint64());
Bence Békybac04052022-04-07 15:44:29 -040015881
15882 // The error only happens if after serializing the second 1RTT packet(pkt #7),
15883 // the pending padding bytes is non zero.
15884 EXPECT_GT(pending_padding_after_serialize_2nd_1rtt_packet, 0u);
15885 EXPECT_TRUE(connection_.connected());
15886}
15887
15888TEST_P(QuicConnectionTest, ReportedAckDelayIncludesQueuingDelay) {
15889 if (!version().HasIetfQuicFrames()) {
15890 return;
15891 }
15892 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15893 QuicConfig config;
15894 config.set_max_undecryptable_packets(3);
15895 connection_.SetFromConfig(config);
15896
15897 // Receive 1-RTT ack-eliciting packet while keys are not available.
15898 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015899 peer_framer_.SetEncrypter(
15900 ENCRYPTION_FORWARD_SECURE,
15901 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015902 QuicFrames frames;
15903 frames.push_back(QuicFrame(QuicPingFrame()));
15904 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
15905 QuicPacketHeader header =
15906 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15907 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15908
15909 char buffer[kMaxOutgoingPacketSize];
15910 size_t encrypted_length = peer_framer_.EncryptPayload(
15911 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15912 kMaxOutgoingPacketSize);
15913 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15914 const QuicTime packet_receipt_time = clock_.Now();
15915 connection_.ProcessUdpPacket(
15916 kSelfAddress, kPeerAddress,
15917 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15918 if (connection_.GetSendAlarm()->IsSet()) {
15919 connection_.GetSendAlarm()->Fire();
15920 }
15921 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15922 // 1-RTT keys become available after 10ms.
15923 const QuicTime::Delta kQueuingDelay = QuicTime::Delta::FromMilliseconds(10);
15924 clock_.AdvanceTime(kQueuingDelay);
15925 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15926 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015927 SetDecrypter(
15928 ENCRYPTION_FORWARD_SECURE,
15929 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015930 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15931
15932 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15933 ASSERT_TRUE(connection_.HasPendingAcks());
fayangfea655c2022-05-17 08:19:12 -070015934 EXPECT_EQ(packet_receipt_time + DefaultDelayedAckTime(),
15935 connection_.GetAckAlarm()->deadline());
15936 clock_.AdvanceTime(packet_receipt_time + DefaultDelayedAckTime() -
15937 clock_.Now());
Bence Békybac04052022-04-07 15:44:29 -040015938 // Fire ACK alarm.
15939 connection_.GetAckAlarm()->Fire();
15940 ASSERT_EQ(1u, writer_->ack_frames().size());
fayangfea655c2022-05-17 08:19:12 -070015941 // Verify ACK delay time does not include queuing delay.
15942 EXPECT_EQ(DefaultDelayedAckTime(), writer_->ack_frames()[0].ack_delay_time);
Bence Békybac04052022-04-07 15:44:29 -040015943}
15944
15945TEST_P(QuicConnectionTest, CoalesceOneRTTPacketWithInitialAndHandshakePackets) {
15946 if (!version().HasIetfQuicFrames()) {
15947 return;
15948 }
15949 set_perspective(Perspective::IS_SERVER);
15950 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15951 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015952
15953 // Received INITIAL 1.
15954 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15955
martinduke9e0811c2022-12-08 20:35:57 -080015956 peer_framer_.SetEncrypter(
15957 ENCRYPTION_ZERO_RTT,
15958 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015959
martinduke9e0811c2022-12-08 20:35:57 -080015960 connection_.SetEncrypter(
15961 ENCRYPTION_HANDSHAKE,
15962 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015963 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015964 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015965 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015966 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15967 connection_.SetEncrypter(
15968 ENCRYPTION_FORWARD_SECURE,
15969 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015970
15971 // Received ENCRYPTION_ZERO_RTT 2.
15972 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15973
15974 {
15975 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15976 // Send INITIAL 1.
15977 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15978 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15979 // Send HANDSHAKE 2.
15980 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15981 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15982 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15983 ENCRYPTION_HANDSHAKE);
15984 // Send 1-RTT data.
15985 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15986 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
15987 }
15988 // Verify coalesced packet [INITIAL 1 + HANDSHAKE 2 + part of 1-RTT data] +
15989 // rest of 1-RTT data get sent.
15990 EXPECT_EQ(2u, writer_->packets_write_attempts());
15991
15992 // Received ENCRYPTION_INITIAL 3.
15993 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15994
15995 // Verify a coalesced packet gets sent.
15996 EXPECT_EQ(3u, writer_->packets_write_attempts());
15997
15998 // Only the first INITIAL packet has been processed yet.
15999 EXPECT_EQ(1u, writer_->ack_frames().size());
16000 EXPECT_EQ(1u, writer_->crypto_frames().size());
16001
16002 // Process HANDSHAKE packet.
16003 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16004 auto packet = writer_->coalesced_packet()->Clone();
16005 writer_->framer()->ProcessPacket(*packet);
16006 EXPECT_EQ(1u, writer_->crypto_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040016007 // Process 1-RTT packet.
16008 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16009 packet = writer_->coalesced_packet()->Clone();
16010 writer_->framer()->ProcessPacket(*packet);
16011 EXPECT_EQ(1u, writer_->stream_frames().size());
16012}
16013
16014// Regression test for b/180103273
16015TEST_P(QuicConnectionTest, SendMultipleConnectionCloses) {
16016 if (!version().HasIetfQuicFrames() ||
16017 !GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
16018 return;
16019 }
16020 set_perspective(Perspective::IS_SERVER);
16021 // Finish handshake.
16022 QuicConnectionPeer::SetAddressValidated(&connection_);
16023 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16024 notifier_.NeuterUnencryptedData();
16025 connection_.NeuterUnencryptedPackets();
16026 connection_.OnHandshakeComplete();
16027 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
16028 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
16029 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080016030 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040016031
16032 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
16033 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
bnc3000cba2022-04-18 12:19:14 -070016034 // Verify that BeforeConnectionCloseSent() gets called twice,
16035 // while OnConnectionClosed() is called only once.
Bence Békybac04052022-04-07 15:44:29 -040016036 EXPECT_CALL(visitor_, BeforeConnectionCloseSent()).Times(2);
16037 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
16038 // Send connection close w/o closing connection.
16039 QuicConnectionPeer::SendConnectionClosePacket(
16040 &connection_, INTERNAL_ERROR, QUIC_INTERNAL_ERROR, "internal error");
bnc3000cba2022-04-18 12:19:14 -070016041 // Fire blackhole detection alarm. This will invoke
16042 // SendConnectionClosePacket() a second time.
16043 connection_.GetBlackholeDetectorAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -040016044}
16045
16046// Regression test for b/157895910.
16047TEST_P(QuicConnectionTest, EarliestSentTimeNotInitializedWhenPtoFires) {
16048 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
16049 return;
16050 }
16051 set_perspective(Perspective::IS_SERVER);
16052 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
16053 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040016054
16055 // Received INITIAL 1.
16056 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080016057 connection_.SetEncrypter(
16058 ENCRYPTION_HANDSHAKE,
16059 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016060 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080016061 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
16062 connection_.SetEncrypter(
16063 ENCRYPTION_FORWARD_SECURE,
16064 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016065 {
16066 QuicConnection::ScopedPacketFlusher flusher(&connection_);
16067 // Send INITIAL 1.
16068 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16069 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
16070 // Send HANDSHAKE 2.
16071 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
16072 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
16073 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
16074 ENCRYPTION_HANDSHAKE);
16075 // Send half RTT data.
16076 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16077 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
16078 }
16079
16080 // Received ACKs for both INITIAL and HANDSHAKE packets.
martindukeba002452023-03-21 08:10:46 -070016081 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040016082 .Times(AnyNumber());
16083 QuicFrames frames1;
16084 QuicAckFrame ack_frame1 = InitAckFrame(1);
16085 frames1.push_back(QuicFrame(&ack_frame1));
16086
16087 QuicFrames frames2;
16088 QuicAckFrame ack_frame2 =
16089 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
16090 frames2.push_back(QuicFrame(&ack_frame2));
16091 ProcessCoalescedPacket(
16092 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
16093 // Verify PTO is not armed given the only outstanding data is half RTT data.
16094 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16095}
16096
wub47bb7282022-06-14 09:40:33 -070016097TEST_P(QuicConnectionTest, CalculateNetworkBlackholeDelay) {
16098 if (!IsDefaultTestConfiguration()) {
16099 return;
16100 }
16101
16102 const QuicTime::Delta kOneSec = QuicTime::Delta::FromSeconds(1);
16103 const QuicTime::Delta kTwoSec = QuicTime::Delta::FromSeconds(2);
16104 const QuicTime::Delta kFourSec = QuicTime::Delta::FromSeconds(4);
16105
16106 // Normal case: blackhole_delay longer than path_degrading_delay +
16107 // 2*pto_delay.
16108 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
16109 kOneSec),
16110 kFourSec);
16111
16112 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
16113 kTwoSec),
16114 QuicTime::Delta::FromSeconds(5));
16115}
16116
fayangb225e172022-06-27 17:45:38 -070016117TEST_P(QuicConnectionTest, FixBytesAccountingForBufferedCoalescedPackets) {
16118 if (!connection_.version().CanSendCoalescedPackets()) {
16119 return;
16120 }
fayangb225e172022-06-27 17:45:38 -070016121 // Write is blocked.
16122 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
16123 writer_->SetWriteBlocked();
16124 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16125 QuicConnectionPeer::SendPing(&connection_);
16126 const QuicConnectionStats& stats = connection_.GetStats();
fayang4e283832022-09-01 12:47:07 -070016127 // Verify padding is accounted.
16128 EXPECT_EQ(stats.bytes_sent, connection_.max_packet_length());
fayangb225e172022-06-27 17:45:38 -070016129}
16130
fayang161ce6e2022-07-01 18:02:11 -070016131TEST_P(QuicConnectionTest, StrictAntiAmplificationLimit) {
16132 if (!connection_.version().SupportsAntiAmplificationLimit()) {
16133 return;
16134 }
16135 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
16136 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -070016137 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16138 // Verify no data can be sent at the beginning because bytes received is 0.
16139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
16140 connection_.SendCryptoDataWithString("foo", 0);
16141 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
16142 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
16143 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16144
16145 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -070016146 GetQuicFlag(quic_anti_amplification_factor);
fayang161ce6e2022-07-01 18:02:11 -070016147 // Receives packet 1.
16148 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
16149 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16150 .Times(anti_amplification_factor);
wubc9fd4292023-08-14 13:00:21 -070016151 ForceWillingAndAbleToWriteOnceForDeferSending();
fayang161ce6e2022-07-01 18:02:11 -070016152 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16153 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16154 std::make_unique<TaggingEncrypter>(0x02));
16155 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16156 std::make_unique<TaggingEncrypter>(0x03));
16157
16158 for (size_t i = 1; i < anti_amplification_factor - 1; ++i) {
16159 connection_.SendCryptoDataWithString("foo", i * 3);
16160 }
16161 // Send an addtion packet with max_packet_size - 1.
16162 connection_.SetMaxPacketLength(connection_.max_packet_length() - 1);
16163 connection_.SendCryptoDataWithString("bar",
16164 (anti_amplification_factor - 1) * 3);
16165 EXPECT_LT(writer_->total_bytes_written(),
16166 anti_amplification_factor *
16167 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
birenroyef686222022-09-12 11:34:34 -070016168 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070016169 // 3 connection closes which will be buffered.
16170 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
16171 // Verify retransmission alarm is not set.
16172 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16173 } else {
16174 // Crypto + 3 connection closes.
16175 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
16176 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
16177 }
16178 // Try to send another packet with max_packet_size.
16179 connection_.SetMaxPacketLength(connection_.max_packet_length() + 1);
16180 connection_.SendCryptoDataWithString("bar", anti_amplification_factor * 3);
16181 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16182 // Close connection.
16183 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
16184 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
16185 connection_.CloseConnection(
16186 QUIC_INTERNAL_ERROR, "error",
16187 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
16188 EXPECT_EQ(0u, connection_.NumQueuedPackets());
birenroyef686222022-09-12 11:34:34 -070016189 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070016190 EXPECT_LT(writer_->total_bytes_written(),
16191 anti_amplification_factor *
16192 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16193 } else {
16194 EXPECT_LT(writer_->total_bytes_written(),
16195 (anti_amplification_factor + 2) *
16196 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16197 EXPECT_GT(writer_->total_bytes_written(),
16198 (anti_amplification_factor + 1) *
16199 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16200 }
16201}
16202
martinduke96840a02022-07-14 07:09:06 -070016203TEST_P(QuicConnectionTest, OriginalConnectionId) {
16204 set_perspective(Perspective::IS_SERVER);
16205 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
16206 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
16207 connection_.connection_id());
16208 QuicConnectionId original({0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
16209 connection_.SetOriginalDestinationConnectionId(original);
16210 EXPECT_EQ(original, connection_.GetOriginalDestinationConnectionId());
16211 // Send a 1-RTT packet to start the DiscardZeroRttDecryptionKeys timer.
16212 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16213 ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE);
martindukee6444ef2022-09-23 12:32:23 -070016214 if (connection_.version().UsesTls()) {
martinduke96840a02022-07-14 07:09:06 -070016215 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
16216 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(original));
16217 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
16218 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
16219 connection_.connection_id());
16220 } else {
16221 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), original);
16222 }
16223}
16224
martindukebae24052022-10-06 15:27:46 -070016225ACTION_P2(InstallKeys, conn, level) {
16226 uint8_t crypto_input = (level == ENCRYPTION_FORWARD_SECURE) ? 0x03 : 0x02;
16227 conn->SetEncrypter(level, std::make_unique<TaggingEncrypter>(crypto_input));
16228 conn->InstallDecrypter(
16229 level, std::make_unique<StrictTaggingDecrypter>(crypto_input));
16230 conn->SetDefaultEncryptionLevel(level);
martindukec2a33062022-09-30 16:04:13 -070016231}
16232
martindukebae24052022-10-06 15:27:46 -070016233TEST_P(QuicConnectionTest, ServerConnectionIdChangeWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070016234 if (!connection_.version().HasIetfQuicFrames()) {
16235 return;
16236 }
16237 // Call SetFromConfig so that the undecrypted packet buffer size is
16238 // initialized above zero.
16239 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
16240 QuicConfig config;
16241 connection_.SetFromConfig(config);
martindukebae24052022-10-06 15:27:46 -070016242 connection_.RemoveEncrypter(ENCRYPTION_FORWARD_SECURE);
16243 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martindukec2a33062022-09-30 16:04:13 -070016244
16245 // Send Client Initial.
16246 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16247 connection_.SendCryptoStreamData();
16248
16249 EXPECT_EQ(1u, writer_->packets_write_attempts());
martindukebae24052022-10-06 15:27:46 -070016250 // Server Handshake packet with new connection ID is buffered.
martindukec2a33062022-09-30 16:04:13 -070016251 QuicConnectionId old_id = connection_id_;
16252 connection_id_ = TestConnectionId(2);
16253 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16254 std::make_unique<TaggingEncrypter>(0x02));
16255 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
martindukec2a33062022-09-30 16:04:13 -070016256 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16257 EXPECT_EQ(connection_.connection_id(), old_id);
16258
martindukebae24052022-10-06 15:27:46 -070016259 // Server 1-RTT Packet is buffered.
16260 peer_creator_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16261 std::make_unique<TaggingEncrypter>(0x03));
16262 ProcessDataPacket(0);
16263 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 2u);
16264
martindukec2a33062022-09-30 16:04:13 -070016265 // Pretend the server Initial packet will yield the Handshake keys.
16266 EXPECT_CALL(visitor_, OnCryptoFrame(_))
16267 .Times(2)
martindukebae24052022-10-06 15:27:46 -070016268 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE))
16269 .WillOnce(InstallKeys(&connection_, ENCRYPTION_FORWARD_SECURE));
16270 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martindukec2a33062022-09-30 16:04:13 -070016271 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16272 // Two packets processed, connection ID changed.
16273 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16274 EXPECT_EQ(connection_.connection_id(), connection_id_);
16275}
16276
martindukebae24052022-10-06 15:27:46 -070016277TEST_P(QuicConnectionTest, ServerConnectionIdChangeTwiceWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070016278 if (!connection_.version().HasIetfQuicFrames()) {
16279 return;
16280 }
16281 // Call SetFromConfig so that the undecrypted packet buffer size is
16282 // initialized above zero.
16283 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
16284 QuicConfig config;
16285 connection_.SetFromConfig(config);
16286
16287 // Send Client Initial.
16288 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16289 connection_.SendCryptoStreamData();
16290
16291 EXPECT_EQ(1u, writer_->packets_write_attempts());
16292 // Server Handshake Packet Arrives with new connection ID.
16293 QuicConnectionId old_id = connection_id_;
16294 connection_id_ = TestConnectionId(2);
16295 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16296 std::make_unique<TaggingEncrypter>(0x02));
16297 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
16298 // Packet is buffered.
16299 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16300 EXPECT_EQ(connection_.connection_id(), old_id);
16301
16302 // Pretend the server Initial packet will yield the Handshake keys.
16303 EXPECT_CALL(visitor_, OnCryptoFrame(_))
martindukebae24052022-10-06 15:27:46 -070016304 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE));
martindukec2a33062022-09-30 16:04:13 -070016305 connection_id_ = TestConnectionId(1);
16306 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16307 // Handshake packet discarded because there's a different connection ID.
16308 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16309 EXPECT_EQ(connection_.connection_id(), connection_id_);
16310}
16311
fayangdbd6a302022-12-21 16:24:27 -080016312TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress) {
16313 // Test the scenario where the client validates server preferred address by
16314 // receiving PATH_RESPONSE from server preferred address.
16315 if (!connection_.version().HasIetfQuicFrames()) {
16316 return;
16317 }
fayanga0618a62022-12-28 19:31:24 -080016318 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016319 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016320 const QuicSocketAddress kNewSelfAddress =
16321 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16322 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016323 const StatelessResetToken kNewStatelessResetToken =
16324 QuicUtils::GenerateStatelessResetToken(TestConnectionId(17));
16325 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16326 EXPECT_CALL(visitor_, GetHandshakeState())
16327 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16328 // Kick off path validation of server preferred address on handshake
16329 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016330 EXPECT_CALL(visitor_,
16331 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16332 .WillOnce(Invoke([&]() {
16333 connection_.ValidatePath(
16334 std::make_unique<TestQuicPathValidationContext>(
16335 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16336 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016337 &connection_),
16338 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016339 }));
fayangdbd6a302022-12-21 16:24:27 -080016340 connection_.OnHandshakeComplete();
16341 EXPECT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016342 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16343 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016344 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016345 new_writer.last_packet_header().destination_connection_id);
16346 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016347
fayang37765f62022-12-27 17:49:13 -080016348 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016349 QuicPathFrameBuffer payload =
fayang37765f62022-12-27 17:49:13 -080016350 new_writer.path_challenge_frames().front().data_buffer;
fayangdbd6a302022-12-21 16:24:27 -080016351 // Send data packet while path validation is pending.
16352 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016353 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016354 // While path validation is pending, packet is sent on default path.
16355 EXPECT_EQ(TestConnectionId(),
16356 writer_->last_packet_header().destination_connection_id);
16357 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16358 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16359 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16360
danzh8fdee2e2023-01-05 15:33:02 -080016361 // Receive path response from server preferred address.
fayangdbd6a302022-12-21 16:24:27 -080016362 QuicFrames frames;
16363 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16364 // Verify send_algorithm gets reset after migration (new sent packet is not
16365 // updated to exsting send_algorithm_).
16366 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang37765f62022-12-27 17:49:13 -080016367 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
16368 kServerPreferredAddress,
16369 ENCRYPTION_FORWARD_SECURE);
fayangdbd6a302022-12-21 16:24:27 -080016370 ASSERT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016371 EXPECT_TRUE(QuicConnectionPeer::IsDefaultPath(&connection_, kNewSelfAddress,
16372 kServerPreferredAddress));
16373 ASSERT_FALSE(new_writer.stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016374 // Verify stream data is retransmitted on new path.
16375 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016376 new_writer.last_packet_header().destination_connection_id);
16377 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016378 // Verify stateless reset token gets changed.
16379 EXPECT_FALSE(
16380 connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16381 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16382
16383 auto* retire_peer_issued_cid_alarm =
16384 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16385 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16386 // Verify client retires connection ID with sequence number 0.
16387 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16388 retire_peer_issued_cid_alarm->Fire();
fayang37765f62022-12-27 17:49:13 -080016389 EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16390 EXPECT_FALSE(
16391 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016392}
16393
16394TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress2) {
16395 // Test the scenario where the client validates server preferred address by
16396 // receiving PATH_RESPONSE from original server address.
16397 if (!connection_.version().HasIetfQuicFrames()) {
16398 return;
16399 }
fayanga0618a62022-12-28 19:31:24 -080016400 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016401 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016402 const QuicSocketAddress kNewSelfAddress =
16403 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16404 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016405 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16406 EXPECT_CALL(visitor_, GetHandshakeState())
16407 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16408 // Kick off path validation of server preferred address on handshake
16409 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016410 EXPECT_CALL(visitor_,
16411 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16412 .WillOnce(Invoke([&]() {
16413 connection_.ValidatePath(
16414 std::make_unique<TestQuicPathValidationContext>(
16415 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16416 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016417 &connection_),
16418 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016419 }));
fayangdbd6a302022-12-21 16:24:27 -080016420 connection_.OnHandshakeComplete();
16421 EXPECT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016422 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016423 QuicPathFrameBuffer payload =
fayang37765f62022-12-27 17:49:13 -080016424 new_writer.path_challenge_frames().front().data_buffer;
fayangdbd6a302022-12-21 16:24:27 -080016425 // Send data packet while path validation is pending.
16426 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016427 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016428 EXPECT_EQ(TestConnectionId(),
16429 writer_->last_packet_header().destination_connection_id);
16430 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16431
danzh8fdee2e2023-01-05 15:33:02 -080016432 // Receive path response from original server address.
fayangdbd6a302022-12-21 16:24:27 -080016433 QuicFrames frames;
16434 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
fayang37765f62022-12-27 17:49:13 -080016435 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
fayangdbd6a302022-12-21 16:24:27 -080016436 ENCRYPTION_FORWARD_SECURE);
16437 ASSERT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016438 ASSERT_FALSE(new_writer.stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016439 // Verify stream data is retransmitted on new path.
16440 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016441 new_writer.last_packet_header().destination_connection_id);
16442 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016443
16444 auto* retire_peer_issued_cid_alarm =
16445 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16446 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16447 // Verify client retires connection ID with sequence number 0.
16448 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16449 retire_peer_issued_cid_alarm->Fire();
16450
16451 // Verify another packet from original server address gets processed.
16452 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16453 frames.clear();
16454 frames.push_back(QuicFrame(frame1_));
16455 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
16456 ENCRYPTION_FORWARD_SECURE);
fayang37765f62022-12-27 17:49:13 -080016457 EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16458 EXPECT_FALSE(
16459 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016460}
16461
16462TEST_P(QuicConnectionTest, ClientFailedToValidateServerPreferredAddress) {
16463 // Test the scenario where the client fails to validate server preferred
16464 // address.
16465 if (!connection_.version().HasIetfQuicFrames()) {
16466 return;
16467 }
fayanga0618a62022-12-28 19:31:24 -080016468 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016469 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016470 const QuicSocketAddress kNewSelfAddress =
16471 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16472 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016473 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16474 EXPECT_CALL(visitor_, GetHandshakeState())
16475 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16476 // Kick off path validation of server preferred address on handshake
16477 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016478 EXPECT_CALL(visitor_,
16479 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16480 .WillOnce(Invoke([&]() {
16481 connection_.ValidatePath(
16482 std::make_unique<TestQuicPathValidationContext>(
16483 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16484 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016485 &connection_),
16486 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016487 }));
fayangdbd6a302022-12-21 16:24:27 -080016488 connection_.OnHandshakeComplete();
danzh8fdee2e2023-01-05 15:33:02 -080016489 EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
fayang37765f62022-12-27 17:49:13 -080016490 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16491 &connection_, kNewSelfAddress, kServerPreferredAddress));
16492 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016493
16494 // Receive mismatched path challenge from original server address.
16495 QuicFrames frames;
16496 frames.push_back(
16497 QuicFrame(QuicPathResponseFrame(99, {0, 1, 2, 3, 4, 5, 6, 7})));
fayang37765f62022-12-27 17:49:13 -080016498 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
fayangdbd6a302022-12-21 16:24:27 -080016499 ENCRYPTION_FORWARD_SECURE);
16500 ASSERT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016501 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16502 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016503
16504 // Simluate path validation times out.
16505 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16506 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16507 static_cast<TestAlarmFactory::TestAlarm*>(
16508 QuicPathValidatorPeer::retry_timer(
16509 QuicConnectionPeer::path_validator(&connection_)))
16510 ->Fire();
16511 }
16512 EXPECT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016513 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
16514 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016515 // Verify stream data is sent on the default path.
16516 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016517 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016518 EXPECT_EQ(TestConnectionId(),
16519 writer_->last_packet_header().destination_connection_id);
16520 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16521
16522 auto* retire_peer_issued_cid_alarm =
16523 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16524 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16525 // Verify client retires connection ID with sequence number 1.
16526 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
16527 retire_peer_issued_cid_alarm->Fire();
16528 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
fayang37765f62022-12-27 17:49:13 -080016529 EXPECT_FALSE(connection_.GetStats().server_preferred_address_validated);
16530 EXPECT_TRUE(
16531 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016532}
16533
fayanga0618a62022-12-28 19:31:24 -080016534TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress) {
16535 if (!connection_.version().HasIetfQuicFrames()) {
16536 return;
16537 }
fayanga0618a62022-12-28 19:31:24 -080016538 const QuicSocketAddress kNewSelfAddress =
16539 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16540 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016541 EXPECT_CALL(visitor_,
16542 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16543 .WillOnce(Invoke([&]() {
16544 connection_.ValidatePath(
16545 std::make_unique<TestQuicPathValidationContext>(
16546 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16547 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016548 &connection_),
16549 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016550 }));
fayanga0618a62022-12-28 19:31:24 -080016551 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016552 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080016553 ServerPreferredAddressInit(config);
16554 EXPECT_TRUE(connection_.HasPendingPathValidation());
16555 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16556
16557 // Send data packet while path validation is pending.
16558 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16559 // Verify the packet is sent on both paths.
16560 EXPECT_FALSE(writer_->stream_frames().empty());
16561 EXPECT_FALSE(new_writer.stream_frames().empty());
16562
16563 // Verify packet duplication stops on handshake confirmed.
16564 EXPECT_CALL(visitor_, GetHandshakeState())
16565 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16566 connection_.OnHandshakeComplete();
16567 SendPing();
16568 EXPECT_FALSE(writer_->ping_frames().empty());
16569 EXPECT_TRUE(new_writer.ping_frames().empty());
16570}
16571
16572TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress2) {
16573 if (!connection_.version().HasIetfQuicFrames()) {
16574 return;
16575 }
fayanga0618a62022-12-28 19:31:24 -080016576 const QuicSocketAddress kNewSelfAddress =
16577 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16578 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016579 EXPECT_CALL(visitor_,
16580 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16581 .WillOnce(Invoke([&]() {
16582 connection_.ValidatePath(
16583 std::make_unique<TestQuicPathValidationContext>(
16584 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16585 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016586 &connection_),
16587 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016588 }));
fayanga0618a62022-12-28 19:31:24 -080016589 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016590 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080016591 ServerPreferredAddressInit(config);
16592 EXPECT_TRUE(connection_.HasPendingPathValidation());
16593 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16594
16595 // Send data packet while path validation is pending.
16596 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16597 // Verify the packet is sent on both paths.
16598 EXPECT_FALSE(writer_->stream_frames().empty());
16599 EXPECT_FALSE(new_writer.stream_frames().empty());
16600
16601 // Simluate path validation times out.
16602 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16603 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16604 static_cast<TestAlarmFactory::TestAlarm*>(
16605 QuicPathValidatorPeer::retry_timer(
16606 QuicConnectionPeer::path_validator(&connection_)))
16607 ->Fire();
16608 }
16609 EXPECT_FALSE(connection_.HasPendingPathValidation());
16610 // Verify packet duplication stops if there is no pending validation.
16611 SendPing();
16612 EXPECT_FALSE(writer_->ping_frames().empty());
16613 EXPECT_TRUE(new_writer.ping_frames().empty());
16614}
16615
16616TEST_P(QuicConnectionTest, MaxDuplicatedPacketsSentToServerPreferredAddress) {
16617 if (!connection_.version().HasIetfQuicFrames()) {
16618 return;
16619 }
fayanga0618a62022-12-28 19:31:24 -080016620 const QuicSocketAddress kNewSelfAddress =
16621 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16622 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016623 EXPECT_CALL(visitor_,
16624 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16625 .WillOnce(Invoke([&]() {
16626 connection_.ValidatePath(
16627 std::make_unique<TestQuicPathValidationContext>(
16628 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16629 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016630 &connection_),
16631 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016632 }));
fayanga0618a62022-12-28 19:31:24 -080016633 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016634 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080016635 ServerPreferredAddressInit(config);
16636 EXPECT_TRUE(connection_.HasPendingPathValidation());
16637 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16638
16639 // Send data packet while path validation is pending.
16640 size_t write_limit = writer_->packets_write_attempts();
16641 size_t new_write_limit = new_writer.packets_write_attempts();
16642 for (size_t i = 0; i < kMaxDuplicatedPacketsSentToServerPreferredAddress;
16643 ++i) {
16644 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
16645 // Verify the packet is sent on both paths.
16646 ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
16647 ASSERT_EQ(new_write_limit + 1, new_writer.packets_write_attempts());
16648 ++write_limit;
16649 ++new_write_limit;
16650 EXPECT_FALSE(writer_->stream_frames().empty());
16651 EXPECT_FALSE(new_writer.stream_frames().empty());
16652 }
16653
16654 // Verify packet duplication stops if duplication limit is hit.
16655 SendPing();
16656 ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
16657 ASSERT_EQ(new_write_limit, new_writer.packets_write_attempts());
16658 EXPECT_FALSE(writer_->ping_frames().empty());
16659 EXPECT_TRUE(new_writer.ping_frames().empty());
16660}
16661
danzh8fdee2e2023-01-05 15:33:02 -080016662TEST_P(QuicConnectionTest, MultiPortCreationAfterServerMigration) {
16663 if (!GetParam().version.HasIetfQuicFrames()) {
16664 return;
16665 }
16666 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016667 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
danzh8fdee2e2023-01-05 15:33:02 -080016668 ServerPreferredAddressInit(config);
danzh8fdee2e2023-01-05 15:33:02 -080016669 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16670 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16671 const QuicSocketAddress kNewSelfAddress =
16672 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16673 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16674 EXPECT_CALL(visitor_,
16675 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16676 .WillOnce(Invoke([&]() {
16677 connection_.ValidatePath(
16678 std::make_unique<TestQuicPathValidationContext>(
16679 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16680 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016681 &connection_),
16682 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016683 }));
16684 // The connection should start probing the preferred address after handshake
16685 // confirmed.
16686 QuicPathFrameBuffer payload;
16687 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16688 .Times(testing::AtLeast(1u))
16689 .WillOnce(Invoke([&]() {
16690 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
16691 payload = new_writer.path_challenge_frames().front().data_buffer;
16692 EXPECT_EQ(kServerPreferredAddress,
16693 new_writer.last_write_peer_address());
16694 }));
16695 EXPECT_CALL(visitor_, GetHandshakeState())
16696 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16697 connection_.OnHandshakeComplete();
16698 EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
16699
16700 // Receiving PATH_RESPONSE should cause the connection to migrate to the
16701 // preferred address.
16702 QuicFrames frames;
16703 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16704 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
16705 ENCRYPTION_FORWARD_SECURE);
16706 EXPECT_FALSE(connection_.IsValidatingServerPreferredAddress());
16707 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16708 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16709 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16710
16711 // As the default path changed, the server issued CID 1 should be retired.
16712 auto* retire_peer_issued_cid_alarm =
16713 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16714 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16715 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16716 retire_peer_issued_cid_alarm->Fire();
16717
16718 const QuicSocketAddress kNewSelfAddress2(kNewSelfAddress.host(),
16719 kNewSelfAddress.port() + 1);
16720 EXPECT_NE(kNewSelfAddress2, kNewSelfAddress);
16721 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
16722 QuicNewConnectionIdFrame frame;
16723 frame.connection_id = TestConnectionId(789);
16724 ASSERT_NE(frame.connection_id, connection_.connection_id());
16725 frame.stateless_reset_token =
16726 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
16727 frame.retire_prior_to = 0u;
16728 frame.sequence_number = 2u;
QUICHE team107316f2023-05-03 09:04:11 -070016729 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070016730 .WillOnce(testing::WithArgs<0>([&](auto&& observer) {
16731 observer->OnMultiPortPathContextAvailable(
16732 std::move(std::make_unique<TestQuicPathValidationContext>(
16733 kNewSelfAddress2, connection_.peer_address(), &new_writer2)));
QUICHE team107316f2023-05-03 09:04:11 -070016734 }));
danzh8fdee2e2023-01-05 15:33:02 -080016735 connection_.OnNewConnectionIdFrame(frame);
16736 EXPECT_TRUE(connection_.HasPendingPathValidation());
16737 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
16738 payload = new_writer.path_challenge_frames().front().data_buffer;
16739 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
16740 EXPECT_EQ(kNewSelfAddress2.host(), new_writer.last_write_source_address());
16741 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16742 &connection_, kNewSelfAddress2, connection_.peer_address()));
16743 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
16744 EXPECT_FALSE(alt_path->validated);
16745 QuicFrames frames2;
16746 frames2.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16747 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress2, kPeerAddress,
16748 ENCRYPTION_FORWARD_SECURE);
16749 EXPECT_TRUE(alt_path->validated);
16750}
16751
danzh72225ae2023-01-13 14:57:42 -080016752// Tests that after half-way server migration, the client should be able to
16753// respond to any reverse path validation from the original server address.
16754TEST_P(QuicConnectionTest, ClientReceivePathChallengeAfterServerMigration) {
16755 if (!GetParam().version.HasIetfQuicFrames()) {
16756 return;
16757 }
16758 QuicConfig config;
16759 ServerPreferredAddressInit(config);
16760 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16761 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16762 EXPECT_CALL(visitor_,
16763 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16764 .WillOnce(Invoke([&]() {
16765 connection_.AddKnownServerAddress(kServerPreferredAddress);
16766 }));
16767 EXPECT_CALL(visitor_, GetHandshakeState())
16768 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16769 connection_.OnHandshakeComplete();
16770
16771 const QuicSocketAddress kNewSelfAddress =
16772 QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1);
16773 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16774 auto context = std::make_unique<TestQuicPathValidationContext>(
16775 kNewSelfAddress, kServerPreferredAddress, &new_writer);
16776 // Pretend that the validation already succeeded. And start to use the server
16777 // preferred address.
16778 connection_.OnServerPreferredAddressValidated(*context, false);
16779 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16780 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16781 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16782 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16783 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
16784 send_algorithm_);
16785 // Switch to use a mock send algorithm.
16786 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
16787 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
16788 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
16789 .WillRepeatedly(Return(kDefaultTCPMSS));
16790 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
16791 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
16792 .Times(AnyNumber())
16793 .WillRepeatedly(Return(QuicBandwidth::Zero()));
16794 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
16795 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
16796 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
16797 connection_.SetSendAlgorithm(send_algorithm_);
16798
16799 // As the default path changed, the server issued CID 123 should be retired.
16800 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
16801 auto* retire_peer_issued_cid_alarm =
16802 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16803 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16804 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16805 retire_peer_issued_cid_alarm->Fire();
16806
16807 // Receive PATH_CHALLENGE from the original server
16808 // address. The client connection responds it on the default path.
16809 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
16810 QuicFrames frames1;
16811 frames1.push_back(
16812 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
16813 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16814 .Times(AtLeast(1))
16815 .WillOnce(Invoke([&]() {
16816 ASSERT_FALSE(new_writer.path_response_frames().empty());
16817 EXPECT_EQ(
16818 0, memcmp(&path_challenge_payload,
16819 &(new_writer.path_response_frames().front().data_buffer),
16820 sizeof(path_challenge_payload)));
16821 EXPECT_EQ(kServerPreferredAddress,
16822 new_writer.last_write_peer_address());
16823 EXPECT_EQ(kNewSelfAddress.host(),
16824 new_writer.last_write_source_address());
16825 }));
16826 ProcessFramesPacketWithAddresses(frames1, kNewSelfAddress, kPeerAddress,
16827 ENCRYPTION_FORWARD_SECURE);
16828}
16829
16830// Tests that after half-way server migration, the client should be able to
16831// probe with a different socket and respond to reverse path validation.
16832TEST_P(QuicConnectionTest, ClientProbesAfterServerMigration) {
16833 if (!GetParam().version.HasIetfQuicFrames()) {
16834 return;
16835 }
16836 QuicConfig config;
16837 ServerPreferredAddressInit(config);
16838 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16839 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16840
16841 // The connection should start probing the preferred address after handshake
16842 // confirmed.
16843 EXPECT_CALL(visitor_,
16844 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16845 .WillOnce(Invoke([&]() {
16846 connection_.AddKnownServerAddress(kServerPreferredAddress);
16847 }));
16848 EXPECT_CALL(visitor_, GetHandshakeState())
16849 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16850 connection_.OnHandshakeComplete();
16851
16852 const QuicSocketAddress kNewSelfAddress =
16853 QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1);
16854 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16855 auto context = std::make_unique<TestQuicPathValidationContext>(
16856 kNewSelfAddress, kServerPreferredAddress, &new_writer);
16857 // Pretend that the validation already succeeded.
16858 connection_.OnServerPreferredAddressValidated(*context, false);
16859 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16860 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16861 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16862 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16863 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
16864 send_algorithm_);
16865 // Switch to use a mock send algorithm.
16866 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
16867 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
16868 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
16869 .WillRepeatedly(Return(kDefaultTCPMSS));
16870 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
16871 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
16872 .Times(AnyNumber())
16873 .WillRepeatedly(Return(QuicBandwidth::Zero()));
16874 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
16875 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
16876 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
16877 connection_.SetSendAlgorithm(send_algorithm_);
16878
16879 // Receiving data from the original server address should not change the peer
16880 // address.
16881 EXPECT_CALL(visitor_, OnCryptoFrame(_));
16882 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kNewSelfAddress,
16883 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
16884 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16885 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16886
16887 // As the default path changed, the server issued CID 123 should be retired.
16888 auto* retire_peer_issued_cid_alarm =
16889 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16890 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16891 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16892 retire_peer_issued_cid_alarm->Fire();
16893
16894 // Receiving a new CID from the server.
16895 QuicNewConnectionIdFrame new_cid_frame1;
16896 new_cid_frame1.connection_id = TestConnectionId(456);
16897 ASSERT_NE(new_cid_frame1.connection_id, connection_.connection_id());
16898 new_cid_frame1.stateless_reset_token =
16899 QuicUtils::GenerateStatelessResetToken(new_cid_frame1.connection_id);
16900 new_cid_frame1.retire_prior_to = 0u;
16901 new_cid_frame1.sequence_number = 2u;
16902 connection_.OnNewConnectionIdFrame(new_cid_frame1);
16903
16904 // Probe from a new socket.
16905 const QuicSocketAddress kNewSelfAddress2 =
16906 QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort + 2);
16907 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
16908 bool success;
16909 QuicPathFrameBuffer payload;
16910 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16911 .Times(testing::AtLeast(1u))
16912 .WillOnce(Invoke([&]() {
16913 EXPECT_EQ(1u, new_writer2.path_challenge_frames().size());
16914 payload = new_writer2.path_challenge_frames().front().data_buffer;
16915 EXPECT_EQ(kServerPreferredAddress,
16916 new_writer2.last_write_peer_address());
16917 EXPECT_EQ(kNewSelfAddress2.host(),
16918 new_writer2.last_write_source_address());
16919 }));
16920 connection_.ValidatePath(
16921 std::make_unique<TestQuicPathValidationContext>(
16922 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
16923 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016924 &connection_, kNewSelfAddress2, connection_.peer_address(), &success),
16925 PathValidationReason::kServerPreferredAddressMigration);
danzh72225ae2023-01-13 14:57:42 -080016926 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16927 &connection_, kNewSelfAddress2, kServerPreferredAddress));
16928
16929 // Our server implementation will send PATH_CHALLENGE from the original server
16930 // address. The client connection send PATH_RESPONSE to the default peer
16931 // address.
16932 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
16933 QuicFrames frames;
16934 frames.push_back(
16935 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
16936 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16937 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16938 .Times(AtLeast(1))
16939 .WillOnce(Invoke([&]() {
16940 EXPECT_FALSE(new_writer2.path_response_frames().empty());
16941 EXPECT_EQ(
16942 0, memcmp(&path_challenge_payload,
16943 &(new_writer2.path_response_frames().front().data_buffer),
16944 sizeof(path_challenge_payload)));
16945 EXPECT_EQ(kServerPreferredAddress,
16946 new_writer2.last_write_peer_address());
16947 EXPECT_EQ(kNewSelfAddress2.host(),
16948 new_writer2.last_write_source_address());
16949 }));
16950 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress2, kPeerAddress,
16951 ENCRYPTION_FORWARD_SECURE);
16952 EXPECT_TRUE(success);
16953}
16954
martindukefcfa32a2023-01-12 10:04:44 -080016955TEST_P(QuicConnectionTest, EcnMarksCorrectlyRecorded) {
16956 set_perspective(Perspective::IS_SERVER);
martindukefcfa32a2023-01-12 10:04:44 -080016957 QuicFrames frames;
martindukef33b1da2023-01-12 14:14:29 -080016958 frames.push_back(QuicFrame(QuicPingFrame()));
16959 frames.push_back(QuicFrame(QuicPaddingFrame(7)));
16960 QuicAckFrame ack_frame =
16961 connection_.SupportsMultiplePacketNumberSpaces()
16962 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
16963 : connection_.received_packet_manager().ack_frame();
16964 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
16965
16966 ProcessFramesPacketAtLevelWithEcn(1, frames, ENCRYPTION_FORWARD_SECURE,
16967 ECN_ECT0);
16968 ack_frame =
16969 connection_.SupportsMultiplePacketNumberSpaces()
16970 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
16971 : connection_.received_packet_manager().ack_frame();
martinduke01ee3222023-03-08 17:08:09 -080016972 // Send two PINGs so that the ACK goes too. The second packet should not
16973 // include an ACK, which checks that the packet state is cleared properly.
16974 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16975 if (connection_.version().HasIetfQuicFrames()) {
16976 QuicConnectionPeer::SendPing(&connection_);
16977 QuicConnectionPeer::SendPing(&connection_);
16978 }
16979 QuicConnectionStats stats = connection_.GetStats();
martindukef8b97fc2024-02-06 12:11:57 -080016980 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
16981 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
16982 EXPECT_EQ(stats.num_ack_frames_sent_with_ecn,
16983 connection_.version().HasIetfQuicFrames() ? 1 : 0);
martinduke01ee3222023-03-08 17:08:09 -080016984 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 1);
16985 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
16986 EXPECT_EQ(stats.num_ecn_marks_received.ce, 0);
martindukefcfa32a2023-01-12 10:04:44 -080016987}
16988
martindukef33b1da2023-01-12 14:14:29 -080016989TEST_P(QuicConnectionTest, EcnMarksCoalescedPacket) {
martindukef8b97fc2024-02-06 12:11:57 -080016990 if (!connection_.version().CanSendCoalescedPackets()) {
martindukef33b1da2023-01-12 14:14:29 -080016991 return;
16992 }
16993 QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"};
16994 QuicFrames frames1;
16995 frames1.push_back(QuicFrame(&crypto_frame1));
16996 QuicFrames frames2;
16997 QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"};
16998 frames2.push_back(QuicFrame(&crypto_frame2));
16999 std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE},
17000 {3, frames2, ENCRYPTION_FORWARD_SECURE}};
17001 QuicAckFrame ack_frame =
17002 connection_.SupportsMultiplePacketNumberSpaces()
17003 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17004 : connection_.received_packet_manager().ack_frame();
17005 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17006 ack_frame =
17007 connection_.SupportsMultiplePacketNumberSpaces()
17008 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17009 : connection_.received_packet_manager().ack_frame();
17010 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17011 // Deliver packets.
17012 connection_.SetEncrypter(
17013 ENCRYPTION_HANDSHAKE,
17014 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
17015 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
17016 ProcessCoalescedPacket(packets, ECN_ECT0);
martinduke01ee3222023-03-08 17:08:09 -080017017 // Send two PINGs so that the ACKs go too.
17018 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17019 if (connection_.version().HasIetfQuicFrames()) {
17020 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
17021 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
17022 QuicConnectionPeer::SendPing(&connection_);
17023 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17024 QuicConnectionPeer::SendPing(&connection_);
17025 }
17026 QuicConnectionStats stats = connection_.GetStats();
martindukef33b1da2023-01-12 14:14:29 -080017027 ack_frame =
17028 connection_.SupportsMultiplePacketNumberSpaces()
17029 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17030 : connection_.received_packet_manager().ack_frame();
17031 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17032 EXPECT_EQ(ack_frame.ecn_counters->ect0,
17033 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2);
17034 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17035 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17036 ? connection_.received_packet_manager().GetAckFrame(
17037 APPLICATION_DATA)
17038 : connection_.received_packet_manager().ack_frame();
17039 EXPECT_TRUE(ack_frame.ecn_counters.has_value());
17040 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17041 }
martindukef8b97fc2024-02-06 12:11:57 -080017042 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2);
17043 EXPECT_EQ(stats.num_ack_frames_sent_with_ecn,
17044 connection_.version().HasIetfQuicFrames() ? 2 : 0);
martinduke01ee3222023-03-08 17:08:09 -080017045 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
17046 EXPECT_EQ(stats.num_ecn_marks_received.ce, 0);
martindukef33b1da2023-01-12 14:14:29 -080017047}
17048
17049TEST_P(QuicConnectionTest, EcnMarksUndecryptableCoalescedPacket) {
martindukef8b97fc2024-02-06 12:11:57 -080017050 if (!connection_.version().CanSendCoalescedPackets()) {
martindukef33b1da2023-01-12 14:14:29 -080017051 return;
17052 }
17053 // SetFromConfig is always called after construction from InitializeSession.
17054 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
17055 QuicConfig config;
17056 config.set_max_undecryptable_packets(100);
17057 connection_.SetFromConfig(config);
17058 QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"};
17059 QuicFrames frames1;
17060 frames1.push_back(QuicFrame(&crypto_frame1));
17061 QuicFrames frames2;
17062 QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"};
17063 frames2.push_back(QuicFrame(&crypto_frame2));
17064 std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE},
17065 {3, frames2, ENCRYPTION_FORWARD_SECURE}};
17066 char coalesced_buffer[kMaxOutgoingPacketSize];
17067 size_t coalesced_size = 0;
17068 for (const auto& packet : packets) {
17069 QuicPacketHeader header =
17070 ConstructPacketHeader(packet.packet_number, packet.level);
17071 // Set the correct encryption level and encrypter on peer_creator and
17072 // peer_framer, respectively.
17073 peer_creator_.set_encryption_level(packet.level);
17074 peer_framer_.SetEncrypter(packet.level,
17075 std::make_unique<TaggingEncrypter>(packet.level));
17076 // Set the corresponding decrypter.
17077 if (packet.level == ENCRYPTION_HANDSHAKE) {
17078 connection_.SetEncrypter(
17079 packet.level, std::make_unique<TaggingEncrypter>(packet.level));
17080 connection_.SetDefaultEncryptionLevel(packet.level);
17081 SetDecrypter(packet.level,
17082 std::make_unique<StrictTaggingDecrypter>(packet.level));
17083 }
17084 // Forward Secure packet is undecryptable.
17085 std::unique_ptr<QuicPacket> constructed_packet(
17086 ConstructPacket(header, packet.frames));
17087
17088 char buffer[kMaxOutgoingPacketSize];
17089 size_t encrypted_length = peer_framer_.EncryptPayload(
17090 packet.level, QuicPacketNumber(packet.packet_number),
17091 *constructed_packet, buffer, kMaxOutgoingPacketSize);
17092 QUICHE_DCHECK_LE(coalesced_size + encrypted_length, kMaxOutgoingPacketSize);
17093 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
17094 coalesced_size += encrypted_length;
17095 }
17096 QuicAckFrame ack_frame =
17097 connection_.SupportsMultiplePacketNumberSpaces()
17098 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17099 : connection_.received_packet_manager().ack_frame();
17100 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17101 ack_frame =
17102 connection_.SupportsMultiplePacketNumberSpaces()
17103 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17104 : connection_.received_packet_manager().ack_frame();
17105 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17106 // Deliver packets, but first remove the Forward Secure decrypter so that
17107 // packet has to be buffered.
17108 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
17109 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
17110 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
17111 connection_.ProcessUdpPacket(
17112 kSelfAddress, kPeerAddress,
17113 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(), false,
17114 0, true, nullptr, 0, true, ECN_ECT0));
17115 if (connection_.GetSendAlarm()->IsSet()) {
17116 connection_.GetSendAlarm()->Fire();
17117 }
17118 ack_frame =
17119 connection_.SupportsMultiplePacketNumberSpaces()
17120 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17121 : connection_.received_packet_manager().ack_frame();
17122 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17123 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17124 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17125 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17126 ? connection_.received_packet_manager().GetAckFrame(
17127 APPLICATION_DATA)
17128 : connection_.received_packet_manager().ack_frame();
17129 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17130 }
17131 // Send PING packet with ECN_CE, which will change the ECN codepoint in
17132 // last_received_packet_info_.
17133 ProcessFramePacketAtLevelWithEcn(4, QuicFrame(QuicPingFrame()),
17134 ENCRYPTION_HANDSHAKE, ECN_CE);
17135 ack_frame =
17136 connection_.SupportsMultiplePacketNumberSpaces()
17137 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17138 : connection_.received_packet_manager().ack_frame();
17139 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17140 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17141 EXPECT_EQ(ack_frame.ecn_counters->ce, 1);
17142 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17143 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17144 ? connection_.received_packet_manager().GetAckFrame(
17145 APPLICATION_DATA)
17146 : connection_.received_packet_manager().ack_frame();
17147 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17148 }
17149 // Install decrypter for ENCRYPTION_FORWARD_SECURE. Make sure the original
17150 // ECN codepoint is incremented.
17151 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
17152 SetDecrypter(
17153 ENCRYPTION_FORWARD_SECURE,
17154 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
17155 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
17156 ack_frame =
17157 connection_.SupportsMultiplePacketNumberSpaces()
17158 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17159 : connection_.received_packet_manager().ack_frame();
17160 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17161 // Should be recorded as ECT(0), not CE.
17162 EXPECT_EQ(ack_frame.ecn_counters->ect0,
17163 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2);
martinduke01ee3222023-03-08 17:08:09 -080017164 QuicConnectionStats stats = connection_.GetStats();
martindukef8b97fc2024-02-06 12:11:57 -080017165 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2);
martinduke01ee3222023-03-08 17:08:09 -080017166 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
martindukef8b97fc2024-02-06 12:11:57 -080017167 EXPECT_EQ(stats.num_ecn_marks_received.ce, 1);
martindukef33b1da2023-01-12 14:14:29 -080017168}
17169
martinduke0bfe7322023-01-18 07:36:34 -080017170TEST_P(QuicConnectionTest, ReceivedPacketInfoDefaults) {
martinduke74528e52023-01-13 12:24:21 -080017171 EXPECT_TRUE(QuicConnectionPeer::TestLastReceivedPacketInfoDefaults());
17172}
17173
danzhb159ab02023-01-30 10:58:46 -080017174TEST_P(QuicConnectionTest, DetectMigrationToPreferredAddress) {
17175 if (!GetParam().version.HasIetfQuicFrames()) {
17176 return;
17177 }
17178 ServerHandlePreferredAddressInit();
17179
17180 // Issue a new server CID associated with the preferred address.
17181 QuicConnectionId server_issued_cid_for_preferred_address =
17182 TestConnectionId(17);
17183 EXPECT_CALL(connection_id_generator_,
17184 GenerateNextConnectionId(connection_id_))
17185 .WillOnce(Return(server_issued_cid_for_preferred_address));
17186 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
vasilvv243b2622023-11-07 17:01:30 -080017187 std::optional<QuicNewConnectionIdFrame> frame =
danzhb159ab02023-01-30 10:58:46 -080017188 connection_.MaybeIssueNewConnectionIdForPreferredAddress();
17189 ASSERT_TRUE(frame.has_value());
17190
17191 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
17192 ASSERT_EQ(packet_creator->GetDestinationConnectionId(),
17193 connection_.client_connection_id());
17194 ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_);
17195
17196 // Process a packet received at the preferred Address.
17197 peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address);
17198 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17199 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17200 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17201 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17202 // The server migrates half-way with the default path unchanged, and
17203 // continuing with the client issued CID 1.
17204 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17205 EXPECT_EQ(kSelfAddress, connection_.self_address());
17206
17207 // The peer retires CID 123.
17208 QuicRetireConnectionIdFrame retire_cid_frame;
17209 retire_cid_frame.sequence_number = 0u;
17210 EXPECT_CALL(connection_id_generator_,
17211 GenerateNextConnectionId(server_issued_cid_for_preferred_address))
17212 .WillOnce(Return(TestConnectionId(456)));
17213 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
17214 EXPECT_CALL(visitor_, SendNewConnectionId(_));
17215 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(retire_cid_frame));
17216
17217 // Process another packet received at Preferred Address.
17218 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17219 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17220 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17221 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17222 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17223 EXPECT_EQ(kSelfAddress, connection_.self_address());
17224}
17225
17226TEST_P(QuicConnectionTest,
17227 DetectSimutanuousServerAndClientAddressChangeWithProbe) {
17228 if (!GetParam().version.HasIetfQuicFrames()) {
17229 return;
17230 }
17231 ServerHandlePreferredAddressInit();
17232
17233 // Issue a new server CID associated with the preferred address.
17234 QuicConnectionId server_issued_cid_for_preferred_address =
17235 TestConnectionId(17);
17236 EXPECT_CALL(connection_id_generator_,
17237 GenerateNextConnectionId(connection_id_))
17238 .WillOnce(Return(server_issued_cid_for_preferred_address));
17239 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
vasilvv243b2622023-11-07 17:01:30 -080017240 std::optional<QuicNewConnectionIdFrame> frame =
danzhb159ab02023-01-30 10:58:46 -080017241 connection_.MaybeIssueNewConnectionIdForPreferredAddress();
17242 ASSERT_TRUE(frame.has_value());
17243
17244 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
17245 ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_);
17246 ASSERT_EQ(packet_creator->GetDestinationConnectionId(),
17247 connection_.client_connection_id());
17248
17249 // Receiving a probing packet from a new client address to the preferred
17250 // address.
17251 peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address);
17252 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
17253 /*port=*/34567);
17254 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
17255 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
17256 QuicEncryptedPacket(probing_packet->encrypted_buffer,
17257 probing_packet->encrypted_length),
17258 clock_.Now()));
17259 uint64_t num_probing_received =
17260 connection_.GetStats().num_connectivity_probing_received;
17261 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17262 .Times(AtLeast(1u))
17263 .WillOnce(Invoke([&]() {
17264 EXPECT_EQ(1u, writer_->path_response_frames().size());
17265 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
fayang1f578d32023-03-20 11:36:15 -070017266 // The responses should be sent from preferred address given server
17267 // has not received packet on original address from the new client
17268 // address.
17269 EXPECT_EQ(kServerPreferredAddress.host(),
17270 writer_->last_write_source_address());
danzhb159ab02023-01-30 10:58:46 -080017271 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
awillia202240c2024-07-08 09:47:00 -070017272 }))
17273 .WillRepeatedly(DoDefault());
danzhb159ab02023-01-30 10:58:46 -080017274 ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received);
17275 EXPECT_EQ(num_probing_received + 1,
17276 connection_.GetStats().num_connectivity_probing_received);
17277 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
17278 kNewPeerAddress));
17279 EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
17280 EXPECT_EQ(received->length(),
17281 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
17282 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17283 EXPECT_EQ(kSelfAddress, connection_.self_address());
17284
17285 // Process a data packet received at the preferred Address from the new client
17286 // address.
17287 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
17288 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17289 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17290 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
17291 // The server migrates half-way with the new peer address but the same default
17292 // self address.
17293 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17294 EXPECT_EQ(kSelfAddress, connection_.self_address());
17295 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
17296 EXPECT_TRUE(connection_.HasPendingPathValidation());
17297 EXPECT_FALSE(QuicConnectionPeer::GetDefaultPath(&connection_)->validated);
17298 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
17299 kPeerAddress));
17300 EXPECT_EQ(packet_creator->GetSourceConnectionId(),
17301 server_issued_cid_for_preferred_address);
17302
17303 // Process another packet received at the preferred Address.
17304 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17305 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17306 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
17307 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
fayang1f578d32023-03-20 11:36:15 -070017308 EXPECT_EQ(kServerPreferredAddress.host(),
17309 writer_->last_write_source_address());
danzhb159ab02023-01-30 10:58:46 -080017310 EXPECT_EQ(kSelfAddress, connection_.self_address());
17311}
17312
martinduke007b2ca2023-04-10 10:43:38 -070017313TEST_P(QuicConnectionTest, EcnCodepointsRejected) {
martinduke0643ea92023-12-06 13:16:20 -080017314 SetQuicRestartFlag(quic_support_ect1, true);
martinduke007b2ca2023-04-10 10:43:38 -070017315 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke007b2ca2023-04-10 10:43:38 -070017316 if (ecn == ECN_ECT0) {
martinduke57c456d2023-12-01 12:34:18 -080017317 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martinduke007b2ca2023-04-10 10:43:38 -070017318 } else if (ecn == ECN_ECT1) {
martinduke57c456d2023-12-01 12:34:18 -080017319 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
martinduke007b2ca2023-04-10 10:43:38 -070017320 }
martinduke039c1552023-05-23 16:10:57 -070017321 if (ecn == ECN_NOT_ECT) {
17322 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17323 } else {
17324 EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17325 }
17326 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduke007b2ca2023-04-10 10:43:38 -070017327 EXPECT_CALL(connection_, OnSerializedPacket(_));
17328 SendPing();
martinduke007b2ca2023-04-10 10:43:38 -070017329 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17330 }
17331}
17332
17333TEST_P(QuicConnectionTest, EcnCodepointsAccepted) {
martinduke0643ea92023-12-06 13:16:20 -080017334 SetQuicRestartFlag(quic_support_ect1, true);
martinduke007b2ca2023-04-10 10:43:38 -070017335 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke007b2ca2023-04-10 10:43:38 -070017336 if (ecn == ECN_ECT0) {
martinduke57c456d2023-12-01 12:34:18 -080017337 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martinduke007b2ca2023-04-10 10:43:38 -070017338 } else if (ecn == ECN_ECT1) {
martinduke57c456d2023-12-01 12:34:18 -080017339 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke007b2ca2023-04-10 10:43:38 -070017340 }
martinduke039c1552023-05-23 16:10:57 -070017341 if (ecn == ECN_CE) {
17342 EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17343 } else {
17344 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17345 }
martinduke007b2ca2023-04-10 10:43:38 -070017346 EXPECT_CALL(connection_, OnSerializedPacket(_));
17347 SendPing();
17348 QuicEcnCodepoint expected_codepoint = ecn;
17349 if (ecn == ECN_CE) {
martinduke039c1552023-05-23 16:10:57 -070017350 expected_codepoint = ECN_ECT1;
martinduke007b2ca2023-04-10 10:43:38 -070017351 }
martinduke039c1552023-05-23 16:10:57 -070017352 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
martinduke007b2ca2023-04-10 10:43:38 -070017353 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
17354 }
17355}
17356
martinduked2d9e7b2023-04-20 14:13:01 -070017357TEST_P(QuicConnectionTest, EcnCodepointsRejectedIfFlagIsFalse) {
martinduke0643ea92023-12-06 13:16:20 -080017358 SetQuicRestartFlag(quic_support_ect1, false);
martinduked2d9e7b2023-04-20 14:13:01 -070017359 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke039c1552023-05-23 16:10:57 -070017360 EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
martinduked2d9e7b2023-04-20 14:13:01 -070017361 EXPECT_CALL(connection_, OnSerializedPacket(_));
17362 SendPing();
martindukeacfdb392023-05-23 15:23:55 -070017363 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduked2d9e7b2023-04-20 14:13:01 -070017364 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17365 }
17366}
17367
martinduke007b2ca2023-04-10 10:43:38 -070017368TEST_P(QuicConnectionTest, EcnValidationDisabled) {
martinduke0643ea92023-12-06 13:16:20 -080017369 SetQuicRestartFlag(quic_support_ect1, true);
martinduke007b2ca2023-04-10 10:43:38 -070017370 QuicConnectionPeer::DisableEcnCodepointValidation(&connection_);
17371 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke039c1552023-05-23 16:10:57 -070017372 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
martinduke007b2ca2023-04-10 10:43:38 -070017373 EXPECT_CALL(connection_, OnSerializedPacket(_));
17374 SendPing();
martindukeacfdb392023-05-23 15:23:55 -070017375 EXPECT_EQ(connection_.ecn_codepoint(), ecn);
martinduke007b2ca2023-04-10 10:43:38 -070017376 EXPECT_EQ(writer_->last_ecn_sent(), ecn);
17377 }
17378}
17379
martinduked2d9e7b2023-04-20 14:13:01 -070017380TEST_P(QuicConnectionTest, RtoDisablesEcnMarking) {
martinduke0643ea92023-12-06 13:16:20 -080017381 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017382 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017383 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martinduked2d9e7b2023-04-20 14:13:01 -070017384 QuicPacketCreatorPeer::SetPacketNumber(
17385 QuicConnectionPeer::GetPacketCreator(&connection_), 1);
17386 SendPing();
vasilvva7d7d442024-05-31 09:42:40 -070017387 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017388 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
martindukeacfdb392023-05-23 15:23:55 -070017389 EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1);
martinduked2d9e7b2023-04-20 14:13:01 -070017390 // On 2nd RTO, QUIC abandons ECN.
vasilvva7d7d442024-05-31 09:42:40 -070017391 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017392 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
martindukeacfdb392023-05-23 15:23:55 -070017393 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduked2d9e7b2023-04-20 14:13:01 -070017394}
17395
17396TEST_P(QuicConnectionTest, RtoDoesntDisableEcnMarkingIfEcnAcked) {
martinduke0643ea92023-12-06 13:16:20 -080017397 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017398 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017399 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martinduked2d9e7b2023-04-20 14:13:01 -070017400 QuicPacketCreatorPeer::SetPacketNumber(
17401 QuicConnectionPeer::GetPacketCreator(&connection_), 1);
martinduke0643ea92023-12-06 13:16:20 -080017402 connection_.OnInFlightEcnPacketAcked();
martinduked2d9e7b2023-04-20 14:13:01 -070017403 SendPing();
17404 // Because an ECN packet was acked, PTOs have no effect on ECN settings.
vasilvva7d7d442024-05-31 09:42:40 -070017405 connection_.OnRetransmissionAlarm();
martinduke0643ea92023-12-06 13:16:20 -080017406 QuicEcnCodepoint expected_codepoint = ECN_ECT1;
martinduked2d9e7b2023-04-20 14:13:01 -070017407 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
martindukeacfdb392023-05-23 15:23:55 -070017408 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
vasilvva7d7d442024-05-31 09:42:40 -070017409 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017410 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
martindukeacfdb392023-05-23 15:23:55 -070017411 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
martinduked2d9e7b2023-04-20 14:13:01 -070017412}
17413
17414TEST_P(QuicConnectionTest, InvalidFeedbackCancelsEcn) {
martinduke0643ea92023-12-06 13:16:20 -080017415 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017416 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017417 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukeacfdb392023-05-23 15:23:55 -070017418 EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1);
martinduke0643ea92023-12-06 13:16:20 -080017419 connection_.OnInvalidEcnFeedback();
martindukeacfdb392023-05-23 15:23:55 -070017420 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduked2d9e7b2023-04-20 14:13:01 -070017421}
17422
martindukec0da7642023-05-04 17:23:22 -070017423TEST_P(QuicConnectionTest, StateMatchesSentEcn) {
martinduke0643ea92023-12-06 13:16:20 -080017424 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017425 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017426 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017427 SendPing();
17428 QuicSentPacketManager* sent_packet_manager =
17429 QuicConnectionPeer::GetSentPacketManager(&connection_);
17430 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1);
17431 EXPECT_EQ(
17432 QuicSentPacketManagerPeer::GetEct1Sent(sent_packet_manager, INITIAL_DATA),
17433 1);
17434}
17435
17436TEST_P(QuicConnectionTest, CoalescedPacketSplitsEcn) {
17437 if (!connection_.version().CanSendCoalescedPackets()) {
17438 return;
17439 }
martinduke0643ea92023-12-06 13:16:20 -080017440 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017441 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017442 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017443 // All these steps are necessary to send an INITIAL ping and save it to be
17444 // coalesced, instead of just calling SendPing() and sending it immediately.
17445 char buffer[1000];
17446 creator_->set_encryption_level(ENCRYPTION_INITIAL);
17447 QuicFrames frames;
17448 QuicPingFrame ping;
17449 frames.emplace_back(QuicFrame(ping));
17450 SerializedPacket packet1 = QuicPacketCreatorPeer::SerializeAllFrames(
17451 creator_, frames, buffer, sizeof(buffer));
17452 connection_.SendOrQueuePacket(std::move(packet1));
17453 creator_->set_encryption_level(ENCRYPTION_FORWARD_SECURE);
martinduke57c456d2023-12-01 12:34:18 -080017454 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martindukec0da7642023-05-04 17:23:22 -070017455 // If not for the line below, these packets would coalesce.
martinduke039c1552023-05-23 16:10:57 -070017456 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0));
martindukec0da7642023-05-04 17:23:22 -070017457 EXPECT_EQ(writer_->packets_write_attempts(), 0);
17458 SendPing();
17459 EXPECT_EQ(writer_->packets_write_attempts(), 2);
17460 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT0);
17461}
17462
17463TEST_P(QuicConnectionTest, BufferedPacketRetainsOldEcn) {
martinduke0643ea92023-12-06 13:16:20 -080017464 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017465 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017466 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017467 writer_->SetWriteBlocked();
17468 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(2);
17469 SendPing();
martinduke57c456d2023-12-01 12:34:18 -080017470 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017471 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0));
martindukec0da7642023-05-04 17:23:22 -070017472 writer_->SetWritable();
17473 connection_.OnCanWrite();
17474 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1);
17475}
17476
martinduke514a2742023-05-23 16:58:05 -070017477TEST_P(QuicConnectionTest, RejectEcnIfWriterDoesNotSupport) {
martinduke0643ea92023-12-06 13:16:20 -080017478 SetQuicRestartFlag(quic_support_ect1, true);
martinduke514a2742023-05-23 16:58:05 -070017479 MockPacketWriter mock_writer;
17480 QuicConnectionPeer::SetWriter(&connection_, &mock_writer, false);
17481 EXPECT_CALL(mock_writer, SupportsEcn()).WillOnce(Return(false));
17482 EXPECT_FALSE(connection_.set_ecn_codepoint(ECN_ECT1));
17483 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
17484}
17485
Bence Békybac04052022-04-07 15:44:29 -040017486} // namespace
17487} // namespace test
17488} // namespace quic