blob: b4f67c51d37092755ffe929034122e8f7478a8a6 [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());
wub2e302c82024-07-16 18:21:36 -0700707 EXPECT_CALL(visitor_, MaybeBundleOpportunistically()).Times(AnyNumber());
708 EXPECT_CALL(visitor_, GetFlowControlSendWindowSize(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -0400709 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
710 .Times(testing::AtMost(1));
711 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
712 .WillRepeatedly(Return(QuicTime::Zero()));
713 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
714 .Times(AnyNumber());
715 EXPECT_CALL(visitor_, GetHandshakeState())
716 .WillRepeatedly(Return(HANDSHAKE_START));
717 if (connection_.version().KnowsWhichDecrypterToUse()) {
718 connection_.InstallDecrypter(
719 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800720 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
721 } else {
722 connection_.SetAlternativeDecrypter(
723 ENCRYPTION_FORWARD_SECURE,
724 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE),
725 false);
Bence Békybac04052022-04-07 15:44:29 -0400726 }
727 peer_creator_.SetDefaultPeerAddress(kSelfAddress);
728 }
729
730 QuicConnectionTest(const QuicConnectionTest&) = delete;
731 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
732
733 ParsedQuicVersion version() { return GetParam().version; }
734
Bence Békybac04052022-04-07 15:44:29 -0400735 void SetClientConnectionId(const QuicConnectionId& client_connection_id) {
736 connection_.set_client_connection_id(client_connection_id);
737 writer_->framer()->framer()->SetExpectedClientConnectionIdLength(
738 client_connection_id.length());
739 }
740
741 void SetDecrypter(EncryptionLevel level,
742 std::unique_ptr<QuicDecrypter> decrypter) {
743 if (connection_.version().KnowsWhichDecrypterToUse()) {
744 connection_.InstallDecrypter(level, std::move(decrypter));
745 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800746 connection_.SetAlternativeDecrypter(level, std::move(decrypter), false);
Bence Békybac04052022-04-07 15:44:29 -0400747 }
748 }
749
750 void ProcessPacket(uint64_t number) {
751 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
752 ProcessDataPacket(number);
753 if (connection_.GetSendAlarm()->IsSet()) {
754 connection_.GetSendAlarm()->Fire();
755 }
756 }
757
758 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
759 const QuicSocketAddress& peer_address,
760 const QuicReceivedPacket& packet) {
761 connection_.ProcessUdpPacket(self_address, peer_address, packet);
762 if (connection_.GetSendAlarm()->IsSet()) {
763 connection_.GetSendAlarm()->Fire();
764 }
765 }
766
767 QuicFrame MakeCryptoFrame() const {
768 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
769 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
770 }
771 return QuicFrame(QuicStreamFrame(
772 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
773 0u, absl::string_view()));
774 }
775
776 void ProcessFramePacket(QuicFrame frame) {
777 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress,
778 ENCRYPTION_FORWARD_SECURE);
779 }
780
781 void ProcessFramePacketWithAddresses(QuicFrame frame,
782 QuicSocketAddress self_address,
783 QuicSocketAddress peer_address,
784 EncryptionLevel level) {
785 QuicFrames frames;
786 frames.push_back(QuicFrame(frame));
787 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address,
788 level);
789 }
790
791 std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames,
792 EncryptionLevel level,
793 char* buffer,
794 size_t buffer_len) {
795 QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level));
796 peer_creator_.set_encryption_level(level);
797 QuicPacketCreatorPeer::SetSendVersionInPacket(
798 &peer_creator_,
799 level < ENCRYPTION_FORWARD_SECURE &&
800 connection_.perspective() == Perspective::IS_SERVER);
801
802 SerializedPacket serialized_packet =
803 QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
804 buffer, buffer_len);
805 return std::make_unique<QuicReceivedPacket>(
806 serialized_packet.encrypted_buffer, serialized_packet.encrypted_length,
807 clock_.Now());
808 }
809
810 void ProcessFramesPacketWithAddresses(QuicFrames frames,
811 QuicSocketAddress self_address,
812 QuicSocketAddress peer_address,
813 EncryptionLevel level) {
814 char buffer[kMaxOutgoingPacketSize];
815 connection_.ProcessUdpPacket(
816 self_address, peer_address,
817 *ConstructPacket(std::move(frames), level, buffer,
818 kMaxOutgoingPacketSize));
819 if (connection_.GetSendAlarm()->IsSet()) {
820 connection_.GetSendAlarm()->Fire();
821 }
822 }
823
824 // Bypassing the packet creator is unrealistic, but allows us to process
825 // packets the QuicPacketCreator won't allow us to create.
826 void ForceProcessFramePacket(QuicFrame frame) {
827 QuicFrames frames;
828 frames.push_back(QuicFrame(frame));
829 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
830 if (connection_.version().KnowsWhichDecrypterToUse()) {
831 send_version = true;
832 }
833 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
834 QuicPacketHeader header;
835 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
836 char encrypted_buffer[kMaxOutgoingPacketSize];
837 size_t length = peer_framer_.BuildDataPacket(
838 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
839 ENCRYPTION_INITIAL);
840 QUICHE_DCHECK_GT(length, 0u);
841
842 const size_t encrypted_length = peer_framer_.EncryptInPlace(
843 ENCRYPTION_INITIAL, header.packet_number,
844 GetStartOfEncryptedData(peer_framer_.version().transport_version,
845 header),
846 length, kMaxOutgoingPacketSize, encrypted_buffer);
847 QUICHE_DCHECK_GT(encrypted_length, 0u);
848
849 connection_.ProcessUdpPacket(
850 kSelfAddress, kPeerAddress,
851 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
852 }
853
854 size_t ProcessFramePacketAtLevel(uint64_t number, QuicFrame frame,
855 EncryptionLevel level) {
martindukef33b1da2023-01-12 14:14:29 -0800856 return ProcessFramePacketAtLevelWithEcn(number, frame, level, ECN_NOT_ECT);
Bence Békybac04052022-04-07 15:44:29 -0400857 }
858
martindukef33b1da2023-01-12 14:14:29 -0800859 size_t ProcessFramePacketAtLevelWithEcn(uint64_t number, QuicFrame frame,
860 EncryptionLevel level,
861 QuicEcnCodepoint ecn_codepoint) {
862 QuicFrames frames;
863 frames.push_back(frame);
864 return ProcessFramesPacketAtLevelWithEcn(number, frames, level,
865 ecn_codepoint);
866 }
867
868 size_t ProcessFramesPacketAtLevel(uint64_t number, QuicFrames frames,
Bence Békybac04052022-04-07 15:44:29 -0400869 EncryptionLevel level) {
martindukef33b1da2023-01-12 14:14:29 -0800870 return ProcessFramesPacketAtLevelWithEcn(number, frames, level,
871 ECN_NOT_ECT);
872 }
873
874 size_t ProcessFramesPacketAtLevelWithEcn(uint64_t number,
875 const QuicFrames& frames,
876 EncryptionLevel level,
877 QuicEcnCodepoint ecn_codepoint) {
Bence Békybac04052022-04-07 15:44:29 -0400878 QuicPacketHeader header = ConstructPacketHeader(number, level);
879 // Set the correct encryption level and encrypter on peer_creator and
880 // peer_framer, respectively.
881 peer_creator_.set_encryption_level(level);
martinduke9e0811c2022-12-08 20:35:57 -0800882 if (level > ENCRYPTION_INITIAL) {
883 peer_framer_.SetEncrypter(level,
884 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400885 // Set the corresponding decrypter.
886 if (connection_.version().KnowsWhichDecrypterToUse()) {
887 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800888 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400889 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800890 connection_.SetAlternativeDecrypter(
891 level, std::make_unique<StrictTaggingDecrypter>(level), false);
Bence Békybac04052022-04-07 15:44:29 -0400892 }
893 }
894 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
895
896 char buffer[kMaxOutgoingPacketSize];
897 size_t encrypted_length =
898 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
899 buffer, kMaxOutgoingPacketSize);
900 connection_.ProcessUdpPacket(
901 kSelfAddress, kPeerAddress,
martindukef33b1da2023-01-12 14:14:29 -0800902 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false, 0,
903 true, nullptr, 0, false, ecn_codepoint));
Bence Békybac04052022-04-07 15:44:29 -0400904 if (connection_.GetSendAlarm()->IsSet()) {
905 connection_.GetSendAlarm()->Fire();
906 }
907 return encrypted_length;
908 }
909
910 struct PacketInfo {
911 PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level)
912 : packet_number(packet_number), frames(frames), level(level) {}
913
914 uint64_t packet_number;
915 QuicFrames frames;
916 EncryptionLevel level;
917 };
918
919 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) {
martindukef33b1da2023-01-12 14:14:29 -0800920 return ProcessCoalescedPacket(packets, ECN_NOT_ECT);
921 }
922
923 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets,
924 QuicEcnCodepoint ecn_codepoint) {
Bence Békybac04052022-04-07 15:44:29 -0400925 char coalesced_buffer[kMaxOutgoingPacketSize];
926 size_t coalesced_size = 0;
927 bool contains_initial = false;
928 for (const auto& packet : packets) {
929 QuicPacketHeader header =
930 ConstructPacketHeader(packet.packet_number, packet.level);
931 // Set the correct encryption level and encrypter on peer_creator and
932 // peer_framer, respectively.
933 peer_creator_.set_encryption_level(packet.level);
934 if (packet.level == ENCRYPTION_INITIAL) {
935 contains_initial = true;
936 }
martinduke9e0811c2022-12-08 20:35:57 -0800937 EncryptionLevel level =
938 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_);
939 if (level > ENCRYPTION_INITIAL) {
940 peer_framer_.SetEncrypter(level,
941 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400942 // Set the corresponding decrypter.
943 if (connection_.version().KnowsWhichDecrypterToUse()) {
944 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800945 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400946 } else {
947 connection_.SetDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800948 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400949 }
950 }
951 std::unique_ptr<QuicPacket> constructed_packet(
952 ConstructPacket(header, packet.frames));
953
954 char buffer[kMaxOutgoingPacketSize];
955 size_t encrypted_length = peer_framer_.EncryptPayload(
956 packet.level, QuicPacketNumber(packet.packet_number),
957 *constructed_packet, buffer, kMaxOutgoingPacketSize);
958 QUICHE_DCHECK_LE(coalesced_size + encrypted_length,
959 kMaxOutgoingPacketSize);
960 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
961 coalesced_size += encrypted_length;
962 }
963 if (contains_initial) {
964 // Padded coalesced packet to full if it contains initial packet.
965 memset(coalesced_buffer + coalesced_size, '0',
966 kMaxOutgoingPacketSize - coalesced_size);
967 }
968 connection_.ProcessUdpPacket(
969 kSelfAddress, kPeerAddress,
970 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(),
martindukef33b1da2023-01-12 14:14:29 -0800971 false, 0, true, nullptr, 0, false, ecn_codepoint));
Bence Békybac04052022-04-07 15:44:29 -0400972 if (connection_.GetSendAlarm()->IsSet()) {
973 connection_.GetSendAlarm()->Fire();
974 }
975 return coalesced_size;
976 }
977
978 size_t ProcessDataPacket(uint64_t number) {
979 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
980 }
981
982 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
983 return ProcessDataPacketAtLevel(packet_number, false,
984 ENCRYPTION_FORWARD_SECURE);
985 }
986
987 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
988 bool has_stop_waiting,
989 EncryptionLevel level) {
990 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
991 level);
992 }
993
994 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
995 QuicPacketHeader header = ConstructPacketHeader(number, level);
996 QuicFrames frames;
997 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
998 frames.push_back(QuicFrame(&crypto_frame_));
999 } else {
1000 frames.push_back(QuicFrame(frame1_));
1001 }
1002 if (level == ENCRYPTION_INITIAL) {
1003 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
1004 }
1005 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1006 char buffer[kMaxOutgoingPacketSize];
1007 peer_creator_.set_encryption_level(level);
1008 size_t encrypted_length =
1009 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1010 buffer, kMaxOutgoingPacketSize);
1011 connection_.ProcessUdpPacket(
1012 kSelfAddress, kPeerAddress,
1013 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1014 if (connection_.GetSendAlarm()->IsSet()) {
1015 connection_.GetSendAlarm()->Fire();
1016 }
1017 return encrypted_length;
1018 }
1019
1020 size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting,
1021 EncryptionLevel level) {
1022 std::unique_ptr<QuicPacket> packet(
1023 ConstructDataPacket(number, has_stop_waiting, level));
1024 char buffer[kMaxOutgoingPacketSize];
1025 peer_creator_.set_encryption_level(level);
1026 size_t encrypted_length =
1027 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1028 buffer, kMaxOutgoingPacketSize);
1029 connection_.ProcessUdpPacket(
1030 kSelfAddress, kPeerAddress,
1031 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1032 if (connection_.GetSendAlarm()->IsSet()) {
1033 connection_.GetSendAlarm()->Fire();
1034 }
1035 return encrypted_length;
1036 }
1037
1038 void ProcessClosePacket(uint64_t number) {
1039 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
1040 char buffer[kMaxOutgoingPacketSize];
1041 size_t encrypted_length = peer_framer_.EncryptPayload(
1042 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
1043 kMaxOutgoingPacketSize);
1044 connection_.ProcessUdpPacket(
1045 kSelfAddress, kPeerAddress,
1046 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1047 }
1048
1049 QuicByteCount SendStreamDataToPeer(QuicStreamId id, absl::string_view data,
1050 QuicStreamOffset offset,
1051 StreamSendingState state,
1052 QuicPacketNumber* last_packet) {
QUICHE team24a23852022-10-31 18:03:52 -07001053 QuicByteCount packet_size = 0;
Bence Békybac04052022-04-07 15:44:29 -04001054 // Save the last packet's size.
1055 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1056 .Times(AnyNumber())
1057 .WillRepeatedly(SaveArg<3>(&packet_size));
1058 connection_.SendStreamDataWithString(id, data, offset, state);
1059 if (last_packet != nullptr) {
1060 *last_packet = creator_->packet_number();
1061 }
1062 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1063 .Times(AnyNumber());
1064 return packet_size;
1065 }
1066
1067 void SendAckPacketToPeer() {
1068 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1069 {
1070 QuicConnection::ScopedPacketFlusher flusher(&connection_);
1071 connection_.SendAck();
1072 }
1073 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1074 .Times(AnyNumber());
1075 }
1076
1077 void SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error,
1078 QuicStreamOffset bytes_written) {
1079 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1080 connection_.OnStreamReset(id, error);
1081 }
1082
1083 void SendPing() { notifier_.WriteOrBufferPing(); }
1084
1085 MessageStatus SendMessage(absl::string_view message) {
1086 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1087 quiche::QuicheMemSlice slice(quiche::QuicheBuffer::Copy(
1088 connection_.helper()->GetStreamSendBufferAllocator(), message));
1089 return connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false);
1090 }
1091
1092 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1093 if (packet_number > 1) {
1094 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1095 } else {
1096 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1097 }
1098 ProcessFramePacket(QuicFrame(frame));
1099 }
1100
1101 void ProcessAckPacket(QuicAckFrame* frame) {
1102 ProcessFramePacket(QuicFrame(frame));
1103 }
1104
1105 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1106 ProcessFramePacket(QuicFrame(frame));
1107 }
1108
1109 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1110 QuicStopWaitingFrame frame,
1111 EncryptionLevel /*level*/) {
1112 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1113 ENCRYPTION_ZERO_RTT);
1114 }
1115
1116 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1117 ProcessFramePacket(QuicFrame(frame));
1118 }
1119
1120 bool IsMissing(uint64_t number) {
1121 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
1122 QuicPacketNumber());
1123 }
1124
1125 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1126 const QuicFrames& frames) {
1127 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1128 EXPECT_NE(nullptr, packet.get());
1129 return packet;
1130 }
1131
1132 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1133 EncryptionLevel level) {
1134 QuicPacketHeader header;
fayangfc04b8a2023-05-18 09:26:25 -07001135 if (level < ENCRYPTION_FORWARD_SECURE) {
Bence Békybac04052022-04-07 15:44:29 -04001136 // Set long header type accordingly.
1137 header.version_flag = true;
1138 header.form = IETF_QUIC_LONG_HEADER_PACKET;
1139 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1140 if (QuicVersionHasLongHeaderLengths(
1141 peer_framer_.version().transport_version)) {
dschinazi35c0ff72022-08-16 12:10:06 -07001142 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04001143 if (header.long_packet_type == INITIAL) {
dschinazi35c0ff72022-08-16 12:10:06 -07001144 header.retry_token_length_length =
1145 quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
Bence Békybac04052022-04-07 15:44:29 -04001146 }
1147 }
1148 }
1149 // Set connection_id to peer's in memory representation as this data packet
1150 // is created by peer_framer.
1151 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1152 header.source_connection_id = connection_id_;
1153 header.source_connection_id_included = connection_id_included_;
1154 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1155 } else {
1156 header.destination_connection_id = connection_id_;
1157 header.destination_connection_id_included = connection_id_included_;
1158 }
fayangfc04b8a2023-05-18 09:26:25 -07001159 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
Bence Békybac04052022-04-07 15:44:29 -04001160 if (!connection_.client_connection_id().IsEmpty()) {
1161 header.destination_connection_id = connection_.client_connection_id();
1162 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
1163 } else {
1164 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1165 }
1166 if (header.version_flag) {
1167 header.source_connection_id = connection_id_;
1168 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1169 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1170 header.long_packet_type == ZERO_RTT_PROTECTED) {
1171 header.nonce = &kTestDiversificationNonce;
1172 }
1173 }
1174 }
1175 header.packet_number_length = packet_number_length_;
1176 header.packet_number = QuicPacketNumber(number);
1177 return header;
1178 }
1179
1180 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1181 bool has_stop_waiting,
1182 EncryptionLevel level) {
1183 QuicPacketHeader header = ConstructPacketHeader(number, level);
1184 QuicFrames frames;
1185 if (VersionHasIetfQuicFrames(version().transport_version) &&
1186 (level == ENCRYPTION_INITIAL || level == ENCRYPTION_HANDSHAKE)) {
1187 frames.push_back(QuicFrame(QuicPingFrame()));
1188 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
1189 } else {
1190 frames.push_back(QuicFrame(frame1_));
1191 if (has_stop_waiting) {
1192 frames.push_back(QuicFrame(stop_waiting_));
1193 }
1194 }
1195 return ConstructPacket(header, frames);
1196 }
1197
1198 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
1199 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1200 if (VersionHasIetfQuicFrames(version().transport_version)) {
1201 QuicPathFrameBuffer payload = {
1202 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1203 return QuicPacketCreatorPeer::
1204 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1205 payload);
1206 }
danzh65153092023-06-16 10:59:32 -07001207 QUICHE_DCHECK(!GetQuicReloadableFlag(quic_ignore_gquic_probing));
Bence Békybac04052022-04-07 15:44:29 -04001208 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1209 &peer_creator_);
1210 }
1211
1212 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1213 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1214 QuicPacketHeader header;
1215 // Set connection_id to peer's in memory representation as this connection
1216 // close packet is created by peer_framer.
1217 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1218 header.source_connection_id = connection_id_;
1219 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04001220 } else {
1221 header.destination_connection_id = connection_id_;
fayangfc04b8a2023-05-18 09:26:25 -07001222 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04001223 }
1224
1225 header.packet_number = QuicPacketNumber(number);
1226
1227 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
1228 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1229 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
1230 /*transport_close_frame_type=*/0);
1231 QuicFrames frames;
1232 frames.push_back(QuicFrame(&qccf));
1233 return ConstructPacket(header, frames);
1234 }
1235
1236 QuicTime::Delta DefaultRetransmissionTime() {
1237 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1238 }
1239
1240 QuicTime::Delta DefaultDelayedAckTime() {
wub349df3d2024-04-26 11:37:32 -07001241 return QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
Bence Békybac04052022-04-07 15:44:29 -04001242 }
1243
1244 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1245 QuicStopWaitingFrame frame;
1246 frame.least_unacked = QuicPacketNumber(least_unacked);
1247 return frame;
1248 }
1249
1250 // Construct a ack_frame that acks all packet numbers between 1 and
1251 // |largest_acked|, except |missing|.
1252 // REQUIRES: 1 <= |missing| < |largest_acked|
1253 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1254 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1255 QuicPacketNumber(missing));
1256 }
1257
1258 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1259 QuicPacketNumber missing) {
1260 if (missing == QuicPacketNumber(1)) {
1261 return InitAckFrame({{missing + 1, largest_acked + 1}});
1262 }
1263 return InitAckFrame(
1264 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1265 }
1266
1267 // Undo nacking a packet within the frame.
1268 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1269 EXPECT_FALSE(frame->packets.Contains(arrived));
1270 frame->packets.Add(arrived);
1271 }
1272
1273 void TriggerConnectionClose() {
1274 // Send an erroneous packet to close the connection.
1275 EXPECT_CALL(visitor_,
1276 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1277 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1278
1279 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1280 // Triggers a connection by receiving ACK of unsent packet.
1281 QuicAckFrame frame = InitAckFrame(10000);
1282 ProcessAckPacket(1, &frame);
1283 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1284 nullptr);
1285 EXPECT_EQ(1, connection_close_frame_count_);
1286 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1287 IsError(QUIC_INVALID_ACK_DATA));
1288 }
1289
1290 void BlockOnNextWrite() {
1291 writer_->BlockOnNextWrite();
1292 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1293 }
1294
1295 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1296
fayangf6607db2022-04-21 18:10:41 -07001297 void ExpectNextPacketUnprocessable() {
1298 writer_->ExpectNextPacketUnprocessable();
1299 }
1300
Bence Békybac04052022-04-07 15:44:29 -04001301 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1302
1303 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1304 writer_->SetWritePauseTimeDelta(delta);
1305 }
1306
1307 void CongestionBlockWrites() {
1308 EXPECT_CALL(*send_algorithm_, CanSend(_))
1309 .WillRepeatedly(testing::Return(false));
1310 }
1311
1312 void CongestionUnblockWrites() {
1313 EXPECT_CALL(*send_algorithm_, CanSend(_))
1314 .WillRepeatedly(testing::Return(true));
1315 }
1316
1317 void set_perspective(Perspective perspective) {
1318 connection_.set_perspective(perspective);
1319 if (perspective == Perspective::IS_SERVER) {
Bence Békybac04052022-04-07 15:44:29 -04001320 connection_.set_can_truncate_connection_ids(true);
1321 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
1322 connection_.OnSuccessfulVersionNegotiation();
1323 }
1324 QuicFramerPeer::SetPerspective(&peer_framer_,
1325 QuicUtils::InvertPerspective(perspective));
1326 peer_framer_.SetInitialObfuscators(TestConnectionId());
1327 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
1328 ENCRYPTION_FORWARD_SECURE}) {
1329 if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) {
martinduke9e0811c2022-12-08 20:35:57 -08001330 peer_creator_.SetEncrypter(level,
1331 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -04001332 }
1333 }
1334 }
1335
1336 void set_packets_between_probes_base(
1337 const QuicPacketCount packets_between_probes_base) {
1338 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1339 &connection_, packets_between_probes_base,
1340 QuicPacketNumber(packets_between_probes_base));
1341 }
1342
1343 bool IsDefaultTestConfiguration() {
1344 TestParams p = GetParam();
1345 return p.ack_response == AckResponse::kImmediate &&
fayangfc04b8a2023-05-18 09:26:25 -07001346 p.version == AllSupportedVersions()[0];
Bence Békybac04052022-04-07 15:44:29 -04001347 }
1348
1349 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1350 // Not strictly needed for this test, but is commonly done.
1351 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1352 nullptr);
1353 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1354 writer_->connection_close_frames();
1355 ASSERT_EQ(1u, connection_close_frames.size());
1356
1357 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1358 IsError(expected_code));
1359
1360 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1361 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1362 IsError(expected_code));
1363 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1364 connection_close_frames[0].close_type);
1365 return;
1366 }
1367
1368 QuicErrorCodeToIetfMapping mapping =
1369 QuicErrorCodeToTransportErrorCode(expected_code);
1370
1371 if (mapping.is_transport_close) {
1372 // This Google QUIC Error Code maps to a transport close,
1373 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1374 connection_close_frames[0].close_type);
1375 } else {
1376 // This maps to an application close.
1377 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1378 connection_close_frames[0].close_type);
1379 }
1380 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
1381 }
1382
1383 void MtuDiscoveryTestInit() {
1384 set_perspective(Perspective::IS_SERVER);
1385 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1386 if (version().SupportsAntiAmplificationLimit()) {
1387 QuicConnectionPeer::SetAddressValidated(&connection_);
1388 }
1389 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1390 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04001391 // Prevent packets from being coalesced.
1392 EXPECT_CALL(visitor_, GetHandshakeState())
1393 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1394 EXPECT_TRUE(connection_.connected());
1395 }
1396
1397 void PathProbeTestInit(Perspective perspective,
1398 bool receive_new_server_connection_id = true) {
1399 set_perspective(perspective);
1400 connection_.CreateConnectionIdManager();
1401 EXPECT_EQ(connection_.perspective(), perspective);
1402 if (perspective == Perspective::IS_SERVER) {
1403 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1404 }
1405 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1406 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1407 // Discard INITIAL key.
1408 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1409 connection_.NeuterUnencryptedPackets();
1410 // Prevent packets from being coalesced.
1411 EXPECT_CALL(visitor_, GetHandshakeState())
1412 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1413 if (version().SupportsAntiAmplificationLimit() &&
1414 perspective == Perspective::IS_SERVER) {
1415 QuicConnectionPeer::SetAddressValidated(&connection_);
1416 }
1417 // Clear direct_peer_address.
1418 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1419 // Clear effective_peer_address, it is the same as direct_peer_address for
1420 // this test.
1421 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1422 QuicSocketAddress());
1423 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1424
1425 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1426 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1427 } else {
1428 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1429 }
1430 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1431 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1432 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1433 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1434 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1435 if (perspective == Perspective::IS_CLIENT &&
1436 receive_new_server_connection_id && version().HasIetfQuicFrames()) {
1437 QuicNewConnectionIdFrame frame;
1438 frame.connection_id = TestConnectionId(1234);
1439 ASSERT_NE(frame.connection_id, connection_.connection_id());
1440 frame.stateless_reset_token =
1441 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
1442 frame.retire_prior_to = 0u;
1443 frame.sequence_number = 1u;
1444 connection_.OnNewConnectionIdFrame(frame);
1445 }
1446 }
1447
danzhb159ab02023-01-30 10:58:46 -08001448 void ServerHandlePreferredAddressInit() {
1449 ASSERT_TRUE(GetParam().version.HasIetfQuicFrames());
1450 set_perspective(Perspective::IS_SERVER);
1451 connection_.CreateConnectionIdManager();
1452 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang1f578d32023-03-20 11:36:15 -07001453 SetQuicReloadableFlag(quic_use_received_client_addresses_cache, true);
danzhb159ab02023-01-30 10:58:46 -08001454 EXPECT_CALL(visitor_, AllowSelfAddressChange())
1455 .WillRepeatedly(Return(true));
1456
1457 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1458 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1459 // Discard INITIAL key.
1460 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1461 connection_.NeuterUnencryptedPackets();
1462 // Prevent packets from being coalesced.
1463 EXPECT_CALL(visitor_, GetHandshakeState())
1464 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1465 if (version().SupportsAntiAmplificationLimit()) {
1466 QuicConnectionPeer::SetAddressValidated(&connection_);
1467 }
1468 // Clear direct_peer_address.
1469 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1470 // Clear effective_peer_address, it is the same as direct_peer_address for
1471 // this test.
1472 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1473 QuicSocketAddress());
1474 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1475
1476 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1477 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1478 } else {
1479 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1480 }
1481 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1482 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1483 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1484 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1485 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1486 QuicConfig config;
danzhb159ab02023-01-30 10:58:46 -08001487 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1488 connection_.SetFromConfig(config);
rchacbdda42024-04-08 13:35:17 -07001489 connection_.set_expected_server_preferred_address(kServerPreferredAddress);
danzhb159ab02023-01-30 10:58:46 -08001490 }
1491
fayangdbd6a302022-12-21 16:24:27 -08001492 // Receive server preferred address.
fayanga0618a62022-12-28 19:31:24 -08001493 void ServerPreferredAddressInit(QuicConfig& config) {
fayangdbd6a302022-12-21 16:24:27 -08001494 ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1495 ASSERT_TRUE(version().HasIetfQuicFrames());
1496 ASSERT_TRUE(connection_.self_address().host().IsIPv6());
fayangdbd6a302022-12-21 16:24:27 -08001497 const QuicConnectionId connection_id = TestConnectionId(17);
1498 const StatelessResetToken reset_token =
1499 QuicUtils::GenerateStatelessResetToken(connection_id);
1500
1501 connection_.CreateConnectionIdManager();
1502
1503 connection_.SendCryptoStreamData();
1504 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07001505 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangdbd6a302022-12-21 16:24:27 -08001506 QuicAckFrame frame = InitAckFrame(1);
1507 // Received ACK for packet 1.
1508 ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
fayang37765f62022-12-27 17:49:13 -08001509 // Discard INITIAL key.
1510 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
fayanga0618a62022-12-28 19:31:24 -08001511 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangdbd6a302022-12-21 16:24:27 -08001512
danzhc251e142023-06-02 11:53:11 -07001513 config.SetConnectionOptionsToSend(QuicTagVector{kSPAD});
fayangdbd6a302022-12-21 16:24:27 -08001514 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
1515 kTestStatelessResetToken);
1516 QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
danzh8fdee2e2023-01-05 15:33:02 -08001517 kServerPreferredAddress);
fayangdbd6a302022-12-21 16:24:27 -08001518 QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
1519 &config, connection_id, reset_token);
1520 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1521 connection_.SetFromConfig(config);
1522
danzhb159ab02023-01-30 10:58:46 -08001523 ASSERT_TRUE(
1524 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)
1525 .IsInitialized());
1526 EXPECT_EQ(
1527 kServerPreferredAddress,
1528 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_));
fayangdbd6a302022-12-21 16:24:27 -08001529 }
1530
wubc9fd4292023-08-14 13:00:21 -07001531 // If defer sending is enabled, tell |visitor_| to return true on the next
1532 // call to WillingAndAbleToWrite().
1533 // This function can be used before a call to ProcessXxxPacket, to allow the
1534 // process function to schedule and fire the send alarm at the end.
1535 void ForceWillingAndAbleToWriteOnceForDeferSending() {
1536 if (GetParam().ack_response == AckResponse::kDefer) {
1537 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
1538 .WillOnce(Return(true))
1539 .RetiresOnSaturation();
1540 }
1541 }
1542
Bence Békybac04052022-04-07 15:44:29 -04001543 void TestClientRetryHandling(bool invalid_retry_tag,
1544 bool missing_original_id_in_config,
1545 bool wrong_original_id_in_config,
1546 bool missing_retry_id_in_config,
1547 bool wrong_retry_id_in_config);
1548
1549 void TestReplaceConnectionIdFromInitial();
1550
1551 QuicConnectionId connection_id_;
1552 QuicFramer framer_;
1553
1554 MockSendAlgorithm* send_algorithm_;
1555 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1556 MockClock clock_;
1557 MockRandom random_generator_;
1558 quiche::SimpleBufferAllocator buffer_allocator_;
1559 std::unique_ptr<TestConnectionHelper> helper_;
1560 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1561 QuicFramer peer_framer_;
1562 QuicPacketCreator peer_creator_;
1563 std::unique_ptr<TestPacketWriter> writer_;
1564 TestConnection connection_;
1565 QuicPacketCreator* creator_;
1566 QuicSentPacketManager* manager_;
1567 StrictMock<MockQuicConnectionVisitor> visitor_;
1568
1569 QuicStreamFrame frame1_;
1570 QuicStreamFrame frame2_;
1571 QuicCryptoFrame crypto_frame_;
1572 QuicAckFrame ack_;
1573 QuicStopWaitingFrame stop_waiting_;
1574 QuicPacketNumberLength packet_number_length_;
1575 QuicConnectionIdIncluded connection_id_included_;
1576
1577 SimpleSessionNotifier notifier_;
1578
1579 QuicConnectionCloseFrame saved_connection_close_frame_;
1580 int connection_close_frame_count_;
martinduke605dca22022-09-01 10:40:19 -07001581 MockConnectionIdGenerator connection_id_generator_;
Bence Békybac04052022-04-07 15:44:29 -04001582};
1583
1584// Run all end to end tests with all supported versions.
1585INSTANTIATE_TEST_SUITE_P(QuicConnectionTests, QuicConnectionTest,
1586 ::testing::ValuesIn(GetTestParams()),
1587 ::testing::PrintToStringParamName());
1588
1589// These two tests ensure that the QuicErrorCode mapping works correctly.
1590// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1591// If running IETF QUIC, the first will generate a transport connection
1592// close, the second an application connection close.
1593// The connection close codes for the two tests are manually chosen;
1594// they are expected to always map to transport- and application-
1595// closes, respectively. If that changes, new codes should be chosen.
1596TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1597 EXPECT_TRUE(connection_.connected());
1598 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1599 connection_.CloseConnection(
1600 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1601 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1602 EXPECT_FALSE(connection_.connected());
1603 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1604}
1605
1606// Test that the IETF QUIC Error code mapping function works
1607// properly for application connection close codes.
1608TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1609 EXPECT_TRUE(connection_.connected());
1610 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1611 connection_.CloseConnection(
1612 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1613 "Should be application close",
1614 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1615 EXPECT_FALSE(connection_.connected());
1616 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1617}
1618
1619TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1620 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1621
1622 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1623 EXPECT_TRUE(connection_.connected());
1624
1625 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1626 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1627 } else {
1628 EXPECT_CALL(visitor_, OnStreamFrame(_));
1629 }
1630 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1631 ENCRYPTION_INITIAL);
1632 // Cause change in self_address.
1633 QuicIpAddress host;
1634 host.FromString("1.1.1.1");
1635 QuicSocketAddress self_address(host, 123);
1636 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1637 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1638 } else {
1639 EXPECT_CALL(visitor_, OnStreamFrame(_));
1640 }
1641 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1642 ENCRYPTION_INITIAL);
1643 EXPECT_TRUE(connection_.connected());
danzh65153092023-06-16 10:59:32 -07001644 EXPECT_NE(connection_.self_address(), self_address);
Bence Békybac04052022-04-07 15:44:29 -04001645}
1646
1647TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1648 set_perspective(Perspective::IS_SERVER);
1649 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1650
1651 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1652 EXPECT_TRUE(connection_.connected());
1653
1654 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1655 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1656 } else {
1657 EXPECT_CALL(visitor_, OnStreamFrame(_));
1658 }
1659 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1660 ENCRYPTION_INITIAL);
1661 // Cause change in self_address.
1662 QuicIpAddress host;
1663 host.FromString("1.1.1.1");
1664 QuicSocketAddress self_address(host, 123);
1665 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
1666 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fayang19027942022-05-16 10:29:29 -07001667 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1668 ENCRYPTION_INITIAL);
1669 EXPECT_TRUE(connection_.connected());
Bence Békybac04052022-04-07 15:44:29 -04001670 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
1671}
1672
1673TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1674 set_perspective(Perspective::IS_SERVER);
1675 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1676
1677 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1678 EXPECT_TRUE(connection_.connected());
1679
1680 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1681 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1682 } else {
1683 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1684 }
1685 QuicIpAddress host;
1686 host.FromString("1.1.1.1");
1687 QuicSocketAddress self_address1(host, 443);
1688 connection_.SetSelfAddress(self_address1);
1689 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1690 kPeerAddress, ENCRYPTION_INITIAL);
1691 // Cause self_address change to mapped Ipv4 address.
1692 QuicIpAddress host2;
1693 host2.FromString(
1694 absl::StrCat("::ffff:", connection_.self_address().host().ToString()));
1695 QuicSocketAddress self_address2(host2, connection_.self_address().port());
1696 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1697 kPeerAddress, ENCRYPTION_INITIAL);
1698 EXPECT_TRUE(connection_.connected());
1699 // self_address change back to Ipv4 address.
1700 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1701 kPeerAddress, ENCRYPTION_INITIAL);
1702 EXPECT_TRUE(connection_.connected());
1703}
1704
1705TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1706 set_perspective(Perspective::IS_SERVER);
1707 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1708 EXPECT_CALL(visitor_, GetHandshakeState())
1709 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1710
1711 // Clear direct_peer_address.
1712 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1713 // Clear effective_peer_address, it is the same as direct_peer_address for
1714 // this test.
1715 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1716 QuicSocketAddress());
1717
1718 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1719 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1720 } else {
1721 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1722 }
1723 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1724 const QuicSocketAddress kNewPeerAddress =
1725 QuicSocketAddress(QuicIpAddress::Loopback6(),
1726 /*port=*/23456);
1727 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1728 kNewPeerAddress, ENCRYPTION_INITIAL);
1729 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1730 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1731
1732 // Decrease packet number to simulate out-of-order packets.
1733 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1734 // This is an old packet, do not migrate.
1735 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1736 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1737 ENCRYPTION_INITIAL);
1738 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1739 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1740}
1741
1742TEST_P(QuicConnectionTest, PeerPortChangeAtServer) {
1743 set_perspective(Perspective::IS_SERVER);
1744 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1745 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1746 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1747 // Prevent packets from being coalesced.
1748 EXPECT_CALL(visitor_, GetHandshakeState())
1749 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1750 if (version().SupportsAntiAmplificationLimit()) {
1751 QuicConnectionPeer::SetAddressValidated(&connection_);
1752 }
1753
1754 // Clear direct_peer_address.
1755 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1756 // Clear effective_peer_address, it is the same as direct_peer_address for
1757 // this test.
1758 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1759 QuicSocketAddress());
1760 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1761
1762 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
1763 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
1764 rtt_stats->set_initial_rtt(default_init_rtt * 2);
1765 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
1766
fayang339f0c82022-04-30 14:20:02 -07001767 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
1768 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001769
1770 const QuicSocketAddress kNewPeerAddress =
1771 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1772 EXPECT_CALL(visitor_, OnStreamFrame(_))
1773 .WillOnce(Invoke(
QUICHE teamf8ca4ff2024-07-17 12:06:18 -07001774 [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1775 .WillOnce(Invoke([=, this]() {
1776 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1777 }));
Bence Békybac04052022-04-07 15:44:29 -04001778 QuicFrames frames;
1779 frames.push_back(QuicFrame(frame1_));
1780 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1781 ENCRYPTION_FORWARD_SECURE);
1782 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1783 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1784
1785 // Process another packet with a different peer address on server side will
1786 // start connection migration.
1787 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1788 QuicFrames frames2;
1789 frames2.push_back(QuicFrame(frame2_));
1790 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1791 ENCRYPTION_FORWARD_SECURE);
1792 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1793 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1794 // PORT_CHANGE shouldn't state change in sent packet manager.
1795 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07001796 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001797 EXPECT_EQ(manager_->GetSendAlgorithm(), send_algorithm_);
danzh4d58dae2023-06-06 11:13:10 -07001798 if (version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04001799 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1800 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001801 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001802 }
1803}
1804
1805TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServer) {
1806 set_perspective(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -07001807 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07001808 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04001809 return;
1810 }
1811 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1812 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1813 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1814 // Discard INITIAL key.
1815 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1816 connection_.NeuterUnencryptedPackets();
1817 // Prevent packets from being coalesced.
1818 EXPECT_CALL(visitor_, GetHandshakeState())
1819 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1820 QuicConnectionPeer::SetAddressValidated(&connection_);
1821 connection_.OnHandshakeComplete();
1822
1823 // Enable 5 RTO
1824 QuicConfig config;
1825 QuicTagVector connection_options;
1826 connection_options.push_back(k5RTO);
1827 config.SetInitialReceivedConnectionOptions(connection_options);
1828 QuicConfigPeer::SetNegotiated(&config, true);
1829 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
1830 connection_.connection_id());
1831 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
1832 QuicConnectionId());
1833 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1834 connection_.SetFromConfig(config);
1835
1836 // Clear direct_peer_address.
1837 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1838 // Clear effective_peer_address, it is the same as direct_peer_address for
1839 // this test.
1840 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1841 QuicSocketAddress());
1842 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1843
1844 const QuicSocketAddress kNewPeerAddress =
1845 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1846 EXPECT_CALL(visitor_, OnStreamFrame(_))
1847 .WillOnce(Invoke(
QUICHE teamf8ca4ff2024-07-17 12:06:18 -07001848 [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1849 .WillOnce(Invoke([=, this]() {
1850 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1851 }));
Bence Békybac04052022-04-07 15:44:29 -04001852 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(
QUICHE teamf8ca4ff2024-07-17 12:06:18 -07002330 [=, this]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
2331 .WillOnce(Invoke([=, this]() {
2332 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2333 }));
Bence Békybac04052022-04-07 15:44:29 -04002334 QuicFrames frames;
2335 frames.push_back(QuicFrame(frame1_));
2336 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
2337 ENCRYPTION_FORWARD_SECURE);
2338 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2339 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2340
2341 // Process another packet with a different peer address on server side will
2342 // start connection migration.
2343 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2344 // IETF QUIC send algorithm should be changed to a different object, so no
2345 // OnPacketSent() called on the old send algorithm.
2346 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0);
2347
2348 QuicFrames frames2;
2349 frames2.push_back(QuicFrame(frame2_));
2350 QuicPaddingFrame padding;
2351 frames2.push_back(QuicFrame(padding));
2352 peer_creator_.SetServerConnectionId(server_cid1);
2353 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2354 ENCRYPTION_FORWARD_SECURE);
2355 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2356 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2357 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2358 connection_.active_effective_peer_migration_type());
2359 EXPECT_LT(0u, writer_->packets_write_attempts());
2360 EXPECT_TRUE(connection_.HasPendingPathValidation());
2361 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
2362 send_algorithm_);
2363 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2364 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2365 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2366 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
2367 const auto* alternative_path =
2368 QuicConnectionPeer::GetAlternativePath(&connection_);
2369 EXPECT_EQ(default_path->client_connection_id, client_cid1);
2370 EXPECT_EQ(default_path->server_connection_id, server_cid1);
2371 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
2372 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
2373 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
2374 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
2375
2376 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes; ++i) {
2377 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2378 static_cast<TestAlarmFactory::TestAlarm*>(
2379 QuicPathValidatorPeer::retry_timer(
2380 QuicConnectionPeer::path_validator(&connection_)))
2381 ->Fire();
2382 }
2383 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2384 connection_.active_effective_peer_migration_type());
2385
2386 // Make sure anti-amplification limit is not reached.
2387 ProcessFramesPacketWithAddresses(
2388 {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
2389 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2390 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2391 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2392
2393 // Advance the time so that the reverse path validation times out.
2394 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2395 static_cast<TestAlarmFactory::TestAlarm*>(
2396 QuicPathValidatorPeer::retry_timer(
2397 QuicConnectionPeer::path_validator(&connection_)))
2398 ->Fire();
2399 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2400 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2401 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2402 EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
2403 send_algorithm_);
2404 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2405
2406 // Verify that default_path_ is reverted and alternative_path_ is cleared.
2407 EXPECT_EQ(default_path->client_connection_id, client_cid0);
2408 EXPECT_EQ(default_path->server_connection_id, server_cid0);
2409 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
2410 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
2411 auto* retire_peer_issued_cid_alarm =
2412 connection_.GetRetirePeerIssuedConnectionIdAlarm();
2413 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
2414 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
2415 retire_peer_issued_cid_alarm->Fire();
2416 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2417 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2418}
2419
2420TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
danzh65153092023-06-16 10:59:32 -07002421 if (!version().HasIetfQuicFrames() &&
2422 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2423 return;
2424 }
Bence Békybac04052022-04-07 15:44:29 -04002425 PathProbeTestInit(Perspective::IS_SERVER);
2426
2427 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2428 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
2429
2430 // Process a padded PING packet with no peer address change on server side
2431 // will be ignored. But a PATH CHALLENGE packet with no peer address change
2432 // will be considered as path probing.
2433 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2434
2435 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2436 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2437 probing_packet->encrypted_length),
2438 clock_.Now()));
2439
2440 uint64_t num_probing_received =
2441 connection_.GetStats().num_connectivity_probing_received;
2442 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2443
2444 EXPECT_EQ(
2445 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2446 connection_.GetStats().num_connectivity_probing_received);
2447 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2448 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2449}
2450
2451// Regression test for b/150161358.
2452TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
2453 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2454 writer_->SetWriteBlocked();
2455
2456 // Send a MTU packet while blocked. It should be buffered.
2457 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2458 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2459 EXPECT_TRUE(writer_->IsWriteBlocked());
2460
2461 writer_->AlwaysGetPacketTooLarge();
2462 writer_->SetWritable();
2463 connection_.OnCanWrite();
2464}
2465
2466TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2467 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2468 if (!IsDefaultTestConfiguration()) {
2469 return;
2470 }
2471
2472 set_perspective(Perspective::IS_CLIENT);
2473
2474 BlockOnNextWrite();
2475
2476 QuicStreamId stream_id = 2;
2477 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2478
2479 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2480
2481 writer_->SetWritable();
2482 connection_.SendConnectivityProbingPacket(writer_.get(),
2483 connection_.peer_address());
2484 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2485 connection_.OnCanWrite();
2486}
2487
2488TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2489 // Regression test for b/74073386.
2490 {
2491 InSequence seq;
2492 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2493 .Times(AtLeast(1));
2494 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
2495 }
2496
2497 set_perspective(Perspective::IS_CLIENT);
2498
2499 writer_->SimulateNextPacketTooLarge();
2500
2501 // This packet write should fail, which should cause the connection to close
2502 // after sending a connection close packet, then the failed packet should be
2503 // queued.
2504 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2505
2506 EXPECT_FALSE(connection_.connected());
2507 // No need to buffer packets.
2508 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2509
2510 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2511 connection_.OnCanWrite();
2512 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2513}
2514
2515class TestQuicPathValidationContext : public QuicPathValidationContext {
2516 public:
2517 TestQuicPathValidationContext(const QuicSocketAddress& self_address,
2518 const QuicSocketAddress& peer_address,
2519
2520 QuicPacketWriter* writer)
2521 : QuicPathValidationContext(self_address, peer_address),
2522 writer_(writer) {}
2523
2524 QuicPacketWriter* WriterToUse() override { return writer_; }
2525
2526 private:
2527 QuicPacketWriter* writer_;
2528};
2529
2530class TestValidationResultDelegate : public QuicPathValidator::ResultDelegate {
2531 public:
2532 TestValidationResultDelegate(QuicConnection* connection,
2533 const QuicSocketAddress& expected_self_address,
2534 const QuicSocketAddress& expected_peer_address,
2535 bool* success)
2536 : QuicPathValidator::ResultDelegate(),
2537 connection_(connection),
2538 expected_self_address_(expected_self_address),
2539 expected_peer_address_(expected_peer_address),
2540 success_(success) {}
2541 void OnPathValidationSuccess(
wub130bde92022-08-01 14:33:14 -07002542 std::unique_ptr<QuicPathValidationContext> context,
2543 QuicTime /*start_time*/) override {
Bence Békybac04052022-04-07 15:44:29 -04002544 EXPECT_EQ(expected_self_address_, context->self_address());
2545 EXPECT_EQ(expected_peer_address_, context->peer_address());
2546 *success_ = true;
2547 }
2548
2549 void OnPathValidationFailure(
2550 std::unique_ptr<QuicPathValidationContext> context) override {
2551 EXPECT_EQ(expected_self_address_, context->self_address());
2552 EXPECT_EQ(expected_peer_address_, context->peer_address());
2553 if (connection_->perspective() == Perspective::IS_CLIENT) {
danzh8fdee2e2023-01-05 15:33:02 -08002554 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2555 *context);
Bence Békybac04052022-04-07 15:44:29 -04002556 }
2557 *success_ = false;
2558 }
2559
2560 private:
2561 QuicConnection* connection_;
2562 QuicSocketAddress expected_self_address_;
2563 QuicSocketAddress expected_peer_address_;
2564 bool* success_;
2565};
2566
danzh8fdee2e2023-01-05 15:33:02 -08002567// A test implementation which migrates to server preferred address
2568// on path validation suceeds. Otherwise, client cleans up alternative path.
fayang5c6e7012023-01-08 20:06:01 -08002569class ServerPreferredAddressTestResultDelegate
danzh8fdee2e2023-01-05 15:33:02 -08002570 : public QuicPathValidator::ResultDelegate {
2571 public:
2572 explicit ServerPreferredAddressTestResultDelegate(QuicConnection* connection)
2573 : connection_(connection) {}
2574 void OnPathValidationSuccess(
2575 std::unique_ptr<QuicPathValidationContext> context,
2576 QuicTime /*start_time*/) override {
2577 connection_->OnServerPreferredAddressValidated(*context, false);
2578 }
2579
2580 void OnPathValidationFailure(
2581 std::unique_ptr<QuicPathValidationContext> context) override {
2582 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2583 *context);
2584 }
2585
2586 protected:
2587 QuicConnection* connection() { return connection_; }
2588
2589 private:
2590 QuicConnection* connection_;
2591};
2592
danzh65153092023-06-16 10:59:32 -07002593// Receive a path probe request at the server side, in IETF version: receive a
2594// packet contains PATH CHALLENGE with peer address change.
danzhb159ab02023-01-30 10:58:46 -08002595TEST_P(QuicConnectionTest, ReceivePathProbingFromNewPeerAddressAtServer) {
danzh65153092023-06-16 10:59:32 -07002596 if (!version().HasIetfQuicFrames() &&
2597 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2598 return;
2599 }
Bence Békybac04052022-04-07 15:44:29 -04002600 PathProbeTestInit(Perspective::IS_SERVER);
2601
2602 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2603 QuicPathFrameBuffer payload;
2604 if (!GetParam().version.HasIetfQuicFrames()) {
2605 EXPECT_CALL(visitor_,
2606 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2607 .Times(1);
2608 } else {
2609 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
danzh4d58dae2023-06-06 11:13:10 -07002610 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2611 .Times(AtLeast(1u))
2612 .WillOnce(Invoke([&]() {
2613 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2614 EXPECT_EQ(1u, writer_->path_response_frames().size());
2615 payload = writer_->path_challenge_frames().front().data_buffer;
awillia202240c2024-07-08 09:47:00 -07002616 }))
2617 .WillRepeatedly(DoDefault());
Bence Békybac04052022-04-07 15:44:29 -04002618 }
2619 // Process a probing packet from a new peer address on server side
2620 // is effectively receiving a connectivity probing.
2621 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2622 /*port=*/23456);
2623
2624 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2625 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2626 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2627 probing_packet->encrypted_length),
2628 clock_.Now()));
2629 uint64_t num_probing_received =
2630 connection_.GetStats().num_connectivity_probing_received;
2631 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2632
2633 EXPECT_EQ(num_probing_received + 1,
2634 connection_.GetStats().num_connectivity_probing_received);
2635 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2636 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhaf2e52a2022-04-20 07:37:03 -07002637 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002638 QuicByteCount bytes_sent =
2639 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_);
2640 EXPECT_LT(0u, bytes_sent);
2641 EXPECT_EQ(received->length(),
2642 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2643
2644 // Receiving one more probing packet should update the bytes count.
2645 probing_packet = ConstructProbingPacket();
2646 received.reset(ConstructReceivedPacket(
2647 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2648 probing_packet->encrypted_length),
2649 clock_.Now()));
2650 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2651
2652 EXPECT_EQ(num_probing_received + 2,
2653 connection_.GetStats().num_connectivity_probing_received);
2654 EXPECT_EQ(2 * bytes_sent,
2655 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2656 EXPECT_EQ(2 * received->length(),
2657 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2658
danzh4d58dae2023-06-06 11:13:10 -07002659 EXPECT_EQ(2 * bytes_sent,
Bence Békybac04052022-04-07 15:44:29 -04002660 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2661 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -07002662 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04002663 ProcessFramesPacketWithAddresses(frames, connection_.self_address(),
2664 kNewPeerAddress,
2665 ENCRYPTION_FORWARD_SECURE);
2666 EXPECT_LT(2 * received->length(),
2667 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
danzh4d58dae2023-06-06 11:13:10 -07002668 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
Bence Békybac04052022-04-07 15:44:29 -04002669 // Receiving another probing packet from a newer address with a different
2670 // port shouldn't trigger another reverse path validation.
2671 QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
2672 /*port=*/34567);
2673 probing_packet = ConstructProbingPacket();
2674 received.reset(ConstructReceivedPacket(
2675 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2676 probing_packet->encrypted_length),
2677 clock_.Now()));
2678 ProcessReceivedPacket(kSelfAddress, kNewerPeerAddress, *received);
2679 EXPECT_FALSE(connection_.HasPendingPathValidation());
danzh4d58dae2023-06-06 11:13:10 -07002680 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
Bence Békybac04052022-04-07 15:44:29 -04002681 }
2682
2683 // Process another packet with the old peer address on server side will not
2684 // start peer migration.
2685 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2686 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2687 ENCRYPTION_INITIAL);
2688 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2689 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2690}
2691
danzhb159ab02023-01-30 10:58:46 -08002692// Receive a packet contains PATH CHALLENGE with self address change.
2693TEST_P(QuicConnectionTest, ReceivePathProbingToPreferredAddressAtServer) {
2694 if (!GetParam().version.HasIetfQuicFrames()) {
2695 return;
2696 }
2697 ServerHandlePreferredAddressInit();
2698
2699 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2700 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2701
2702 // Process a probing packet to the server preferred address.
2703 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2704 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2705 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2706 probing_packet->encrypted_length),
2707 clock_.Now()));
2708 uint64_t num_probing_received =
2709 connection_.GetStats().num_connectivity_probing_received;
2710 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2711 .Times(AtLeast(1u))
2712 .WillOnce(Invoke([&]() {
2713 EXPECT_EQ(1u, writer_->path_response_frames().size());
2714 // Verify that the PATH_RESPONSE is sent from the original self address.
2715 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
2716 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
2717 }));
2718 ProcessReceivedPacket(kServerPreferredAddress, kPeerAddress, *received);
2719
2720 EXPECT_EQ(num_probing_received + 1,
2721 connection_.GetStats().num_connectivity_probing_received);
2722 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
2723 &connection_, kServerPreferredAddress, kPeerAddress));
2724 EXPECT_NE(kServerPreferredAddress, connection_.self_address());
2725
2726 // Receiving another probing packet from a new client address.
2727 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2728 /*port=*/34567);
2729 probing_packet = ConstructProbingPacket();
2730 received.reset(ConstructReceivedPacket(
2731 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2732 probing_packet->encrypted_length),
2733 clock_.Now()));
2734 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2735 .Times(AtLeast(1u))
2736 .WillOnce(Invoke([&]() {
2737 EXPECT_EQ(1u, writer_->path_response_frames().size());
2738 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
fayang1f578d32023-03-20 11:36:15 -07002739 EXPECT_EQ(kServerPreferredAddress.host(),
2740 writer_->last_write_source_address());
2741 // The responses should be sent from preferred address given server
2742 // has not received packet on original address from the new client
2743 // address.
danzhb159ab02023-01-30 10:58:46 -08002744 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2745 }));
2746 ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received);
2747
2748 EXPECT_EQ(num_probing_received + 2,
2749 connection_.GetStats().num_connectivity_probing_received);
2750 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
2751 kNewPeerAddress));
2752 EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2753 EXPECT_EQ(received->length(),
2754 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2755}
2756
Bence Békybac04052022-04-07 15:44:29 -04002757// Receive a padded PING packet with a port change on server side.
2758TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2759 set_perspective(Perspective::IS_SERVER);
2760 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2761 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2762 if (version().SupportsAntiAmplificationLimit()) {
2763 QuicConnectionPeer::SetAddressValidated(&connection_);
2764 }
2765
2766 // Clear direct_peer_address.
2767 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2768 // Clear effective_peer_address, it is the same as direct_peer_address for
2769 // this test.
2770 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2771 QuicSocketAddress());
2772 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2773
2774 if (GetParam().version.UsesCryptoFrames()) {
2775 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2776 } else {
2777 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2778 }
2779 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2780 ENCRYPTION_INITIAL);
2781 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2782 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2783
danzh65153092023-06-16 10:59:32 -07002784 if (GetParam().version.HasIetfQuicFrames() ||
2785 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002786 // In IETF version, a padded PING packet with port change is not taken as
2787 // connectivity probe.
2788 EXPECT_CALL(visitor_, GetHandshakeState())
2789 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2790 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2791 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2792 } else {
2793 // In non-IETF version, process a padded PING packet from a new peer
2794 // address on server side is effectively receiving a connectivity probing.
2795 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2796 EXPECT_CALL(visitor_,
2797 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2798 .Times(1);
2799 }
2800 const QuicSocketAddress kNewPeerAddress =
2801 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2802
2803 QuicFrames frames;
2804 // Write a PING frame, which has no data payload.
2805 QuicPingFrame ping_frame;
2806 frames.push_back(QuicFrame(ping_frame));
2807
2808 // Add padding to the rest of the packet.
2809 QuicPaddingFrame padding_frame;
2810 frames.push_back(QuicFrame(padding_frame));
2811
2812 uint64_t num_probing_received =
2813 connection_.GetStats().num_connectivity_probing_received;
2814
2815 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
2816 ENCRYPTION_INITIAL);
2817
danzh65153092023-06-16 10:59:32 -07002818 if (GetParam().version.HasIetfQuicFrames() ||
2819 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002820 // Padded PING with port changen is not considered as connectivity probe but
2821 // a PORT CHANGE.
2822 EXPECT_EQ(num_probing_received,
2823 connection_.GetStats().num_connectivity_probing_received);
2824 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2825 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2826 } else {
2827 EXPECT_EQ(num_probing_received + 1,
2828 connection_.GetStats().num_connectivity_probing_received);
2829 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2830 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2831 }
2832
danzh65153092023-06-16 10:59:32 -07002833 if (GetParam().version.HasIetfQuicFrames() ||
2834 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002835 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2836 }
danzh65153092023-06-16 10:59:32 -07002837 // Process another packet with the old peer address on server side.
Bence Békybac04052022-04-07 15:44:29 -04002838 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2839 ENCRYPTION_INITIAL);
2840 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2841 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2842}
2843
2844TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
danzh65153092023-06-16 10:59:32 -07002845 if (!GetParam().version.HasIetfQuicFrames() &&
2846 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2847 return;
2848 }
Bence Békybac04052022-04-07 15:44:29 -04002849 PathProbeTestInit(Perspective::IS_SERVER);
2850
2851 // Decrease packet number to simulate out-of-order packets.
2852 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2853
2854 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2855 if (!GetParam().version.HasIetfQuicFrames()) {
2856 EXPECT_CALL(visitor_,
2857 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2858 .Times(1);
2859 } else {
2860 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2861 }
2862
2863 // Process a padded PING packet from a new peer address on server side
2864 // is effectively receiving a connectivity probing, even if a newer packet has
2865 // been received before this one.
2866 const QuicSocketAddress kNewPeerAddress =
2867 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2868
2869 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2870 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2871 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2872 probing_packet->encrypted_length),
2873 clock_.Now()));
2874
2875 uint64_t num_probing_received =
2876 connection_.GetStats().num_connectivity_probing_received;
2877 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2878
danzh65153092023-06-16 10:59:32 -07002879 EXPECT_EQ(num_probing_received +
2880 (!version().HasIetfQuicFrames() &&
2881 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2882 ? 0u
2883 : 1u),
Bence Békybac04052022-04-07 15:44:29 -04002884 connection_.GetStats().num_connectivity_probing_received);
danzh65153092023-06-16 10:59:32 -07002885 EXPECT_EQ((!version().HasIetfQuicFrames() &&
2886 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2887 ? kNewPeerAddress
2888 : kPeerAddress),
2889 connection_.peer_address());
2890 EXPECT_EQ((!version().HasIetfQuicFrames() &&
2891 GetQuicReloadableFlag(quic_ignore_gquic_probing)
2892 ? kNewPeerAddress
2893 : kPeerAddress),
2894 connection_.effective_peer_address());
Bence Békybac04052022-04-07 15:44:29 -04002895}
2896
2897TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
danzh65153092023-06-16 10:59:32 -07002898 if (!GetParam().version.HasIetfQuicFrames() &&
2899 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2900 return;
2901 }
Bence Békybac04052022-04-07 15:44:29 -04002902 PathProbeTestInit(Perspective::IS_SERVER);
2903
2904 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2905 if (!GetParam().version.HasIetfQuicFrames()) {
2906 EXPECT_CALL(visitor_,
2907 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2908 .Times(1);
2909 } else {
2910 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2911 }
2912
2913 // Process a padded PING packet from a new peer address on server side
2914 // is effectively receiving a connectivity probing.
2915 const QuicSocketAddress kNewPeerAddress =
2916 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2917
2918 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2919 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2920 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2921 probing_packet->encrypted_length),
2922 clock_.Now()));
2923 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2924 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2925 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2926
2927 // Process another non-probing packet with the new peer address on server
2928 // side will start peer migration.
2929 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2930
2931 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2932 kNewPeerAddress, ENCRYPTION_INITIAL);
2933 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2934 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2935}
2936
2937TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) {
danzh65153092023-06-16 10:59:32 -07002938 if (!version().HasIetfQuicFrames() &&
2939 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
2940 return;
2941 }
Bence Békybac04052022-04-07 15:44:29 -04002942 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2943 PathProbeTestInit(Perspective::IS_CLIENT);
2944
2945 // Client takes all padded PING packet as speculative connectivity
2946 // probing packet, and reports to visitor.
2947 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2948
2949 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2950 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2951 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2952 probing_packet->encrypted_length),
2953 clock_.Now()));
2954 uint64_t num_probing_received =
2955 connection_.GetStats().num_connectivity_probing_received;
2956 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2957
2958 EXPECT_EQ(
2959 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2960 connection_.GetStats().num_connectivity_probing_received);
2961 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2962 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2963}
2964
2965TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
danzh65153092023-06-16 10:59:32 -07002966 if (GetParam().version.HasIetfQuicFrames() ||
2967 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
Bence Békybac04052022-04-07 15:44:29 -04002968 return;
2969 }
2970 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2971 PathProbeTestInit(Perspective::IS_CLIENT);
2972
2973 // Process a padded PING packet with a different self address on client side
2974 // is effectively receiving a connectivity probing.
2975 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2976 if (!GetParam().version.HasIetfQuicFrames()) {
2977 EXPECT_CALL(visitor_,
2978 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2979 .Times(1);
2980 } else {
2981 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2982 }
2983
2984 const QuicSocketAddress kNewSelfAddress =
2985 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2986
2987 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2988 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2989 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2990 probing_packet->encrypted_length),
2991 clock_.Now()));
2992 uint64_t num_probing_received =
2993 connection_.GetStats().num_connectivity_probing_received;
2994 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2995
2996 EXPECT_EQ(num_probing_received + 1,
2997 connection_.GetStats().num_connectivity_probing_received);
2998 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2999 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3000}
3001
3002TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
3003 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3004 set_perspective(Perspective::IS_CLIENT);
3005 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3006
3007 // Clear direct_peer_address.
3008 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
3009 // Clear effective_peer_address, it is the same as direct_peer_address for
3010 // this test.
3011 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
3012 QuicSocketAddress());
3013 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
3014
fayangd1f2c992022-12-21 10:34:55 -08003015 if (connection_.version().HasIetfQuicFrames()) {
3016 // Verify the 2nd packet from unknown server address gets dropped.
3017 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3018 } else if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3019 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -04003020 } else {
fayangd1f2c992022-12-21 10:34:55 -08003021 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -04003022 }
3023 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3024 ENCRYPTION_INITIAL);
3025 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3026 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
Bence Békybac04052022-04-07 15:44:29 -04003027 const QuicSocketAddress kNewPeerAddress =
3028 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3029 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
3030 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3031 kNewPeerAddress, ENCRYPTION_INITIAL);
3032 if (connection_.version().HasIetfQuicFrames()) {
3033 // IETF QUIC disallows server initiated address change.
3034 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3035 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3036 } else {
3037 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
3038 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
3039 }
3040}
3041
wub3cab5622024-02-20 08:30:32 -08003042TEST_P(QuicConnectionTest, NoNormalizedPeerAddressChangeAtClient) {
3043 if (!version().HasIetfQuicFrames()) {
3044 return;
3045 }
3046 QuicIpAddress peer_ip;
3047 peer_ip.FromString("1.1.1.1");
3048
3049 QuicSocketAddress peer_addr = QuicSocketAddress(peer_ip, /*port=*/443);
3050 QuicSocketAddress dualstack_peer_addr =
3051 QuicSocketAddress(peer_addr.host().DualStacked(), peer_addr.port());
3052
3053 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
3054 set_perspective(Perspective::IS_CLIENT);
3055 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3056
3057 QuicConnectionPeer::SetDirectPeerAddress(&connection_, dualstack_peer_addr);
3058
3059 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
3060 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
3061 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, peer_addr,
3062 ENCRYPTION_INITIAL);
3063 EXPECT_TRUE(connection_.connected());
3064
3065 if (GetQuicReloadableFlag(quic_test_peer_addr_change_after_normalize)) {
3066 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
3067 } else {
3068 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
3069 }
3070}
3071
fayangd1f2c992022-12-21 10:34:55 -08003072TEST_P(QuicConnectionTest, ServerAddressChangesToKnownAddress) {
3073 if (!connection_.version().HasIetfQuicFrames()) {
3074 return;
3075 }
3076 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3077 set_perspective(Perspective::IS_CLIENT);
3078 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3079
3080 // Clear direct_peer_address.
3081 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
3082 // Clear effective_peer_address, it is the same as direct_peer_address for
3083 // this test.
3084 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
3085 QuicSocketAddress());
3086 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
3087
3088 // Verify all 3 packets get processed.
3089 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
3090 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3091 ENCRYPTION_INITIAL);
3092 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3093 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3094
3095 // Process another packet with a different but known server address.
3096 const QuicSocketAddress kNewPeerAddress =
3097 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
3098 connection_.AddKnownServerAddress(kNewPeerAddress);
3099 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(0);
3100 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3101 kNewPeerAddress, ENCRYPTION_INITIAL);
3102 // Verify peer address does not change.
3103 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3104 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3105
3106 // Process 3rd packet from previous server address.
3107 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
3108 ENCRYPTION_INITIAL);
3109 // Verify peer address does not change.
3110 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3111 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3112}
3113
danzh8fdee2e2023-01-05 15:33:02 -08003114TEST_P(QuicConnectionTest,
3115 PeerAddressChangesToPreferredAddressBeforeClientInitiates) {
3116 if (!version().HasIetfQuicFrames()) {
3117 return;
3118 }
3119 ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3120 ASSERT_TRUE(connection_.self_address().host().IsIPv6());
danzh8fdee2e2023-01-05 15:33:02 -08003121 const QuicConnectionId connection_id = TestConnectionId(17);
3122 const StatelessResetToken reset_token =
3123 QuicUtils::GenerateStatelessResetToken(connection_id);
3124
3125 connection_.CreateConnectionIdManager();
3126
3127 connection_.SendCryptoStreamData();
3128 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07003129 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
danzh8fdee2e2023-01-05 15:33:02 -08003130 QuicAckFrame frame = InitAckFrame(1);
3131 // Received ACK for packet 1.
3132 ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
3133 // Discard INITIAL key.
3134 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
3135 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3136
3137 QuicConfig config;
danzhc251e142023-06-02 11:53:11 -07003138 config.SetConnectionOptionsToSend(QuicTagVector{kSPAD});
danzh8fdee2e2023-01-05 15:33:02 -08003139 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
3140 kTestStatelessResetToken);
3141 QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
3142 kServerPreferredAddress);
3143 QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
3144 &config, connection_id, reset_token);
3145 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3146 connection_.SetFromConfig(config);
3147 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3148 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhb159ab02023-01-30 10:58:46 -08003149 ASSERT_TRUE(
3150 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_)
3151 .IsInitialized());
3152 EXPECT_EQ(
3153 kServerPreferredAddress,
3154 QuicConnectionPeer::GetReceivedServerPreferredAddress(&connection_));
danzh8fdee2e2023-01-05 15:33:02 -08003155
3156 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(0);
3157 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3158 kServerPreferredAddress, ENCRYPTION_INITIAL);
3159}
3160
Bence Békybac04052022-04-07 15:44:29 -04003161TEST_P(QuicConnectionTest, MaxPacketSize) {
3162 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3163 EXPECT_EQ(1250u, connection_.max_packet_length());
3164}
3165
3166TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
3167 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3168
3169 // SetFromConfig is always called after construction from InitializeSession.
3170 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3171 constexpr uint32_t kTestMaxPacketSize = 1233u;
3172 QuicConfig config;
3173 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3174 connection_.SetFromConfig(config);
3175
3176 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
3177}
3178
3179TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
3180 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3181
3182 // SetFromConfig is always called after construction from InitializeSession.
3183 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3184 constexpr uint32_t kTestMaxPacketSize = 1450u;
3185 QuicConfig config;
3186 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3187 connection_.SetFromConfig(config);
3188
3189 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3190}
3191
3192TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
3193 TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress,
3194 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003195 Perspective::IS_SERVER, version(),
3196 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003197 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
3198 EXPECT_EQ(1000u, connection.max_packet_length());
3199}
3200
3201TEST_P(QuicConnectionTest, LowerServerResponseMtuTest) {
3202 set_perspective(Perspective::IS_SERVER);
3203 connection_.SetMaxPacketLength(1000);
3204 EXPECT_EQ(1000u, connection_.max_packet_length());
3205
birenroyef686222022-09-12 11:34:34 -07003206 SetQuicFlag(quic_use_lower_server_response_mtu_for_test, true);
Bence Békybac04052022-04-07 15:44:29 -04003207 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(::testing::AtMost(1));
3208 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(::testing::AtMost(1));
3209 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3210 EXPECT_EQ(1250u, connection_.max_packet_length());
3211}
3212
3213TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
3214 set_perspective(Perspective::IS_SERVER);
3215 connection_.SetMaxPacketLength(1000);
3216
3217 QuicPacketHeader header;
3218 header.destination_connection_id = connection_id_;
3219 header.version_flag = true;
3220 header.packet_number = QuicPacketNumber(12);
3221
3222 if (QuicVersionHasLongHeaderLengths(
3223 peer_framer_.version().transport_version)) {
3224 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07003225 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3226 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04003227 }
3228
3229 QuicFrames frames;
3230 QuicPaddingFrame padding;
3231 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3232 frames.push_back(QuicFrame(&crypto_frame_));
3233 } else {
3234 frames.push_back(QuicFrame(frame1_));
3235 }
3236 frames.push_back(QuicFrame(padding));
3237 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3238 char buffer[kMaxOutgoingPacketSize];
3239 size_t encrypted_length =
3240 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3241 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08003242 EXPECT_EQ(kMaxOutgoingPacketSize,
3243 encrypted_length +
3244 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003245
3246 framer_.set_version(version());
3247 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3248 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3249 } else {
3250 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3251 }
3252 connection_.ProcessUdpPacket(
3253 kSelfAddress, kPeerAddress,
3254 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3255 false));
3256
martinduke9e0811c2022-12-08 20:35:57 -08003257 EXPECT_EQ(kMaxOutgoingPacketSize,
3258 connection_.max_packet_length() +
3259 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003260}
3261
3262TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
3263 const QuicByteCount lower_max_packet_size = 1240;
3264 writer_->set_max_packet_size(lower_max_packet_size);
3265 set_perspective(Perspective::IS_SERVER);
3266 connection_.SetMaxPacketLength(1000);
3267 EXPECT_EQ(1000u, connection_.max_packet_length());
3268
3269 QuicPacketHeader header;
3270 header.destination_connection_id = connection_id_;
3271 header.version_flag = true;
3272 header.packet_number = QuicPacketNumber(12);
3273
3274 if (QuicVersionHasLongHeaderLengths(
3275 peer_framer_.version().transport_version)) {
3276 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07003277 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3278 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04003279 }
3280
3281 QuicFrames frames;
3282 QuicPaddingFrame padding;
3283 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3284 frames.push_back(QuicFrame(&crypto_frame_));
3285 } else {
3286 frames.push_back(QuicFrame(frame1_));
3287 }
3288 frames.push_back(QuicFrame(padding));
3289 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3290 char buffer[kMaxOutgoingPacketSize];
3291 size_t encrypted_length =
3292 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3293 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08003294 EXPECT_EQ(kMaxOutgoingPacketSize,
3295 encrypted_length +
3296 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003297
3298 framer_.set_version(version());
3299 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3300 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3301 } else {
3302 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3303 }
3304 connection_.ProcessUdpPacket(
3305 kSelfAddress, kPeerAddress,
3306 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3307 false));
3308
3309 // Here, the limit imposed by the writer is lower than the size of the packet
3310 // received, so the writer max packet size is used.
3311 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3312}
3313
3314TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
3315 const QuicByteCount lower_max_packet_size = 1240;
3316 writer_->set_max_packet_size(lower_max_packet_size);
3317
3318 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
3319 "Default maximum packet size is too low");
3320 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
3321
3322 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3323}
3324
3325TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
3326 const QuicConnectionId connection_id = TestConnectionId(17);
3327 const QuicByteCount lower_max_packet_size = 1240;
3328 writer_->set_max_packet_size(lower_max_packet_size);
3329 TestConnection connection(connection_id, kSelfAddress, kPeerAddress,
3330 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003331 Perspective::IS_CLIENT, version(),
3332 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003333 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
3334 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
3335}
3336
3337TEST_P(QuicConnectionTest, PacketsInOrder) {
3338 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3339
3340 ProcessPacket(1);
3341 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
3342 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3343
3344 ProcessPacket(2);
3345 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
3346 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3347
3348 ProcessPacket(3);
3349 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3350 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3351}
3352
3353TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
3354 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3355
3356 ProcessPacket(3);
3357 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3358 EXPECT_TRUE(IsMissing(2));
3359 EXPECT_TRUE(IsMissing(1));
3360
3361 ProcessPacket(2);
3362 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3363 EXPECT_FALSE(IsMissing(2));
3364 EXPECT_TRUE(IsMissing(1));
3365
3366 ProcessPacket(1);
3367 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3368 EXPECT_FALSE(IsMissing(2));
3369 EXPECT_FALSE(IsMissing(1));
3370}
3371
3372TEST_P(QuicConnectionTest, DuplicatePacket) {
3373 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3374
3375 ProcessPacket(3);
3376 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3377 EXPECT_TRUE(IsMissing(2));
3378 EXPECT_TRUE(IsMissing(1));
3379
3380 // Send packet 3 again, but do not set the expectation that
3381 // the visitor OnStreamFrame() will be called.
3382 ProcessDataPacket(3);
3383 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3384 EXPECT_TRUE(IsMissing(2));
3385 EXPECT_TRUE(IsMissing(1));
3386}
3387
3388TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
3389 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3390 return;
3391 }
3392 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3393
3394 ProcessPacket(3);
3395 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3396 EXPECT_TRUE(IsMissing(2));
3397 EXPECT_TRUE(IsMissing(1));
3398
3399 ProcessPacket(2);
3400 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3401 EXPECT_TRUE(IsMissing(1));
3402
3403 ProcessPacket(5);
3404 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
3405 EXPECT_TRUE(IsMissing(1));
3406 EXPECT_TRUE(IsMissing(4));
3407
3408 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
3409 // packet the peer will not retransmit. It indicates this by sending 'least
3410 // awaiting' is 4. The connection should then realize 1 will not be
3411 // retransmitted, and will remove it from the missing list.
3412 QuicAckFrame frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07003413 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003414 ProcessAckPacket(6, &frame);
3415
3416 // Force an ack to be sent.
3417 SendAckPacketToPeer();
3418 EXPECT_TRUE(IsMissing(4));
3419}
3420
3421TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
3422 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
3423 if (!IsDefaultTestConfiguration() ||
3424 VersionHasIetfQuicFrames(version().transport_version)) {
3425 return;
3426 }
3427
3428 // Process an unencrypted packet from the non-crypto stream.
3429 frame1_.stream_id = 3;
3430 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3431 EXPECT_CALL(visitor_,
3432 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3433 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
3434 "");
3435 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
3436}
3437
3438TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
3439 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3440
3441 ProcessPacket(3);
3442 // Should not cause an ack.
3443 EXPECT_EQ(0u, writer_->packets_write_attempts());
3444
3445 ProcessPacket(2);
3446 // Should ack immediately, since this fills the last hole.
3447 EXPECT_EQ(1u, writer_->packets_write_attempts());
3448
3449 ProcessPacket(1);
3450 // Should ack immediately, since this fills the last hole.
3451 EXPECT_EQ(2u, writer_->packets_write_attempts());
3452
3453 ProcessPacket(4);
3454 // Should not cause an ack.
3455 EXPECT_EQ(2u, writer_->packets_write_attempts());
3456}
3457
3458TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
3459 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3460
3461 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3462 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3463 EXPECT_EQ(2u, writer_->packets_write_attempts());
3464
3465 QuicAckFrame ack1 = InitAckFrame(1);
3466 QuicAckFrame ack2 = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07003467 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003468 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3469 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
3470 }
3471 ProcessAckPacket(2, &ack2);
3472 // Should ack immediately since we have missing packets.
3473 EXPECT_EQ(2u, writer_->packets_write_attempts());
3474
3475 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3476 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
3477 }
3478 ProcessAckPacket(1, &ack1);
3479 // Should not ack an ack filling a missing packet.
3480 EXPECT_EQ(2u, writer_->packets_write_attempts());
3481}
3482
3483TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
3484 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3485 QuicPacketNumber original, second;
3486
3487 QuicByteCount packet_size =
3488 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3489 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3490
3491 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3492 // First nack triggers early retransmit.
3493 LostPacketVector lost_packets;
3494 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
3495 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3496 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3497 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07003498 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003499 QuicPacketNumber retransmission;
3500 // Packet 1 is short header for IETF QUIC because the encryption level
3501 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangfc04b8a2023-05-18 09:26:25 -07003502 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _))
Bence Békybac04052022-04-07 15:44:29 -04003503 .WillOnce(SaveArg<2>(&retransmission));
3504
3505 ProcessAckPacket(&frame);
3506
3507 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
martindukeba002452023-03-21 08:10:46 -07003508 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003509 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3510 ProcessAckPacket(&frame2);
3511
3512 // Now if the peer sends an ack which still reports the retransmitted packet
3513 // as missing, that will bundle an ack with data after two acks in a row
3514 // indicate the high water mark needs to be raised.
3515 EXPECT_CALL(*send_algorithm_,
3516 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3517 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
3518 // No ack sent.
3519 size_t padding_frame_count = writer_->padding_frames().size();
3520 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3521 EXPECT_EQ(1u, writer_->stream_frames().size());
3522
3523 // No more packet loss for the rest of the test.
3524 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3525 .Times(AnyNumber());
3526 ProcessAckPacket(&frame2);
3527 EXPECT_CALL(*send_algorithm_,
3528 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3529 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
3530 // Ack bundled.
fayangfc04b8a2023-05-18 09:26:25 -07003531 // Do not ACK acks.
3532 EXPECT_EQ(1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04003533 EXPECT_EQ(1u, writer_->stream_frames().size());
fayangfc04b8a2023-05-18 09:26:25 -07003534 EXPECT_TRUE(writer_->ack_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04003535
3536 // But an ack with no missing packets will not send an ack.
3537 AckPacket(original, &frame2);
3538 ProcessAckPacket(&frame2);
3539 ProcessAckPacket(&frame2);
3540}
3541
3542TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) {
3543 if (!GetParam().version.HasIetfQuicFrames()) {
3544 return;
3545 }
3546 connection_.set_can_receive_ack_frequency_frame();
3547
3548 // Expect 13 acks, every 3rd packet including the first packet with
3549 // AckFrequencyFrame.
3550 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
3551 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3552
3553 QuicAckFrequencyFrame ack_frequency_frame;
3554 ack_frequency_frame.packet_tolerance = 3;
3555 ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
3556 ENCRYPTION_FORWARD_SECURE);
3557
3558 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38);
3559 // Receives packets 2 - 39.
3560 for (size_t i = 2; i <= 39; ++i) {
3561 ProcessDataPacket(i);
3562 }
3563}
3564
3565TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
3566 const size_t kMinRttMs = 40;
3567 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
3568 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
3569 QuicTime::Delta::Zero(), QuicTime::Zero());
3570 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
3571
3572 // Start ack decimation from 10th packet.
3573 connection_.set_min_received_before_ack_decimation(10);
3574
3575 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3576 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
3577
3578 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
3579 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
3580 // Receives packets 1 - 29.
3581 for (size_t i = 1; i <= 29; ++i) {
3582 ProcessDataPacket(i);
3583 }
3584
3585 // We now receive the 30th packet, and so we send an ack.
3586 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3587 ProcessDataPacket(30);
3588}
3589
3590TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
3591 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3592 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3593 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3594
3595 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3596 // Receives packets 1 - 39.
3597 for (size_t i = 1; i <= 39; ++i) {
3598 ProcessDataPacket(i);
3599 }
3600 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3601 // WINDOW_UPDATE.
3602 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3603 .WillOnce(Invoke([this]() {
3604 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3605 }));
3606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3607 EXPECT_EQ(0u, writer_->window_update_frames().size());
3608 ProcessDataPacket(40);
3609 EXPECT_EQ(1u, writer_->window_update_frames().size());
3610
3611 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3612 // Receives packets 41 - 59.
3613 for (size_t i = 41; i <= 59; ++i) {
3614 ProcessDataPacket(i);
3615 }
3616 // Send a packet containing stream frame.
3617 SendStreamDataToPeer(
3618 QuicUtils::GetFirstBidirectionalStreamId(
3619 connection_.version().transport_version, Perspective::IS_CLIENT),
3620 "bar", 0, NO_FIN, nullptr);
3621
3622 // Session will not be informed until receiving another 20 packets.
3623 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3624 for (size_t i = 60; i <= 98; ++i) {
3625 ProcessDataPacket(i);
3626 EXPECT_EQ(0u, writer_->window_update_frames().size());
3627 }
3628 // Session does not add a retransmittable frame.
3629 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3630 .WillOnce(Invoke([this]() {
3631 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3632 }));
3633 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3634 EXPECT_EQ(0u, writer_->ping_frames().size());
3635 ProcessDataPacket(99);
3636 EXPECT_EQ(0u, writer_->window_update_frames().size());
3637 // A ping frame will be added.
3638 EXPECT_EQ(1u, writer_->ping_frames().size());
3639}
3640
3641TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
Bence Békybac04052022-04-07 15:44:29 -04003642 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3643 QuicConfig config;
3644 QuicTagVector connection_options;
3645 connection_options.push_back(kEACK);
3646 config.SetConnectionOptionsToSend(connection_options);
3647 connection_.SetFromConfig(config);
3648
3649 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3650 connection_.OnHandshakeComplete();
3651
3652 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3653 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3654
3655 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3656 // Receive packets 1 - 9.
3657 for (size_t i = 1; i <= 9; ++i) {
3658 ProcessDataPacket(i);
3659 }
3660
3661 // Send a ping and fire the retransmission alarm.
3662 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3663 SendPing();
3664 QuicTime retransmission_time =
3665 connection_.GetRetransmissionAlarm()->deadline();
3666 clock_.AdvanceTime(retransmission_time - clock_.Now());
3667 connection_.GetRetransmissionAlarm()->Fire();
fayang339f0c82022-04-30 14:20:02 -07003668 ASSERT_LT(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04003669
3670 // Process a packet, which requests a retransmittable frame be bundled
3671 // with the ACK.
3672 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3673 .WillOnce(Invoke([this]() {
3674 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3675 }));
3676 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3677 ProcessDataPacket(11);
3678 EXPECT_EQ(1u, writer_->window_update_frames().size());
3679}
3680
Bence Békybac04052022-04-07 15:44:29 -04003681TEST_P(QuicConnectionTest, TooManySentPackets) {
3682 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3683
3684 QuicPacketCount max_tracked_packets = 50;
3685 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3686
3687 const int num_packets = max_tracked_packets + 5;
3688
3689 for (int i = 0; i < num_packets; ++i) {
3690 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3691 }
3692
3693 EXPECT_CALL(visitor_,
3694 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3695
3696 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3697
3698 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
3699}
3700
3701TEST_P(QuicConnectionTest, LargestObservedLower) {
3702 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3703
3704 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3705 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3706 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
martindukeba002452023-03-21 08:10:46 -07003707 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003708
3709 // Start out saying the largest observed is 2.
3710 QuicAckFrame frame1 = InitAckFrame(1);
3711 QuicAckFrame frame2 = InitAckFrame(2);
3712 ProcessAckPacket(&frame2);
3713
wubc9fd4292023-08-14 13:00:21 -07003714 EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04003715 ProcessAckPacket(&frame1);
3716}
3717
3718TEST_P(QuicConnectionTest, AckUnsentData) {
3719 // Ack a packet which has not been sent.
3720 EXPECT_CALL(visitor_,
3721 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3722 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3723 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3724 QuicAckFrame frame = InitAckFrame(1);
3725 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3726 ProcessAckPacket(&frame);
3727 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
3728}
3729
3730TEST_P(QuicConnectionTest, BasicSending) {
3731 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3732 return;
3733 }
3734 const QuicConnectionStats& stats = connection_.GetStats();
3735 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
3736 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3737 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3738 ProcessDataPacket(1);
3739 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3740 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3741 QuicPacketNumber last_packet;
3742 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3743 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3744 SendAckPacketToPeer(); // Packet 2
3745
Bence Békybac04052022-04-07 15:44:29 -04003746 SendAckPacketToPeer(); // Packet 3
Bence Békybac04052022-04-07 15:44:29 -04003747
3748 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3749 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3750 SendAckPacketToPeer(); // Packet 5
Bence Békybac04052022-04-07 15:44:29 -04003751
martindukeba002452023-03-21 08:10:46 -07003752 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003753
3754 // Peer acks up to packet 3.
3755 QuicAckFrame frame = InitAckFrame(3);
3756 ProcessAckPacket(&frame);
3757 SendAckPacketToPeer(); // Packet 6
3758
martindukeba002452023-03-21 08:10:46 -07003759 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04003760
3761 // Peer acks up to packet 4, the last packet.
3762 QuicAckFrame frame2 = InitAckFrame(6);
3763 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3764
3765 // Verify that we did not send an ack.
3766 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3767
Bence Békybac04052022-04-07 15:44:29 -04003768 // If we force an ack, we shouldn't change our retransmit state.
3769 SendAckPacketToPeer(); // Packet 7
Bence Békybac04052022-04-07 15:44:29 -04003770
3771 // But if we send more data it should.
3772 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3773 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3774 SendAckPacketToPeer(); // Packet 9
Bence Békybac04052022-04-07 15:44:29 -04003775 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3776}
3777
3778// QuicConnection should record the packet sent-time prior to sending the
3779// packet.
3780TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3781 // We're using a MockClock for the tests, so we have complete control over the
3782 // time.
3783 // Our recorded timestamp for the last packet sent time will be passed in to
3784 // the send_algorithm. Make sure that it is set to the correct value.
3785 QuicTime actual_recorded_send_time = QuicTime::Zero();
3786 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3787 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3788
3789 // First send without any pause and check the result.
3790 QuicTime expected_recorded_send_time = clock_.Now();
3791 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3792 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3793 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3794 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3795
3796 // Now pause during the write, and check the results.
3797 actual_recorded_send_time = QuicTime::Zero();
3798 const QuicTime::Delta write_pause_time_delta =
3799 QuicTime::Delta::FromMilliseconds(5000);
3800 SetWritePauseTimeDelta(write_pause_time_delta);
3801 expected_recorded_send_time = clock_.Now();
3802
3803 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3804 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3805 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3806 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3807 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3808 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3809}
3810
QUICHE teamac0a8082022-06-13 09:17:05 -07003811TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithRetransmissions) {
3812 // Send two stream frames in 1 packet by queueing them.
3813 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3814
3815 {
3816 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3817 connection_.SaveAndSendStreamData(
3818 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3819 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3820 connection_.SaveAndSendStreamData(
3821 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3822 "helloworld", 0, NO_FIN, LOSS_RETRANSMISSION);
3823 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3824 }
3825
3826 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3827 EXPECT_FALSE(connection_.HasQueuedData());
3828
3829 EXPECT_EQ(2u, writer_->frame_count());
3830 for (auto& frame : writer_->stream_frames()) {
3831 EXPECT_EQ(frame->data_length, 10u);
3832 }
3833
3834 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3835 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 20u);
3836}
3837
3838TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithMixedFrames) {
3839 // Send two stream frames in 1 packet by queueing them.
3840 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3841
3842 {
3843 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3844 // First frame is retransmission. Second is NOT_RETRANSMISSION but the
3845 // packet retains the PTO_RETRANSMISSION type.
3846 connection_.SaveAndSendStreamData(
3847 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3848 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3849 connection_.SaveAndSendStreamData(
3850 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3851 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3852 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3853 }
3854
3855 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3856 EXPECT_FALSE(connection_.HasQueuedData());
3857
3858 EXPECT_EQ(2u, writer_->frame_count());
3859 for (auto& frame : writer_->stream_frames()) {
3860 EXPECT_EQ(frame->data_length, 10u);
3861 }
3862
3863 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3864 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 10u);
3865}
3866
3867TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_NoRetransmission) {
3868 // Send two stream frames in 1 packet by queueing them.
3869 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3870
3871 {
3872 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3873 // Both frames are NOT_RETRANSMISSION
3874 connection_.SaveAndSendStreamData(
3875 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3876 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3877 connection_.SaveAndSendStreamData(
3878 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3879 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3880 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3881 }
3882
3883 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3884 EXPECT_FALSE(connection_.HasQueuedData());
3885
3886 EXPECT_EQ(2u, writer_->frame_count());
3887 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 0u);
3888 ASSERT_EQ(connection_.GetStats().bytes_retransmitted, 0u);
3889}
3890
Bence Békybac04052022-04-07 15:44:29 -04003891TEST_P(QuicConnectionTest, FramePacking) {
3892 // Send two stream frames in 1 packet by queueing them.
3893 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3894 {
3895 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3896 connection_.SendStreamData3();
3897 connection_.SendStreamData5();
3898 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3899 }
3900 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3901 EXPECT_FALSE(connection_.HasQueuedData());
3902
3903 // Parse the last packet and ensure it's an ack and two stream frames from
3904 // two different streams.
fayangfc04b8a2023-05-18 09:26:25 -07003905 EXPECT_EQ(2u, writer_->frame_count());
3906 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04003907
3908 EXPECT_TRUE(writer_->ack_frames().empty());
3909
3910 ASSERT_EQ(2u, writer_->stream_frames().size());
3911 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3912 writer_->stream_frames()[0]->stream_id);
3913 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3914 writer_->stream_frames()[1]->stream_id);
3915}
3916
3917TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3918 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3919 // queueing them.
3920 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3921 {
3922 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3923 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3924 connection_.SendStreamData3();
3925 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08003926 // Set the crypters for INITIAL packets in the TestPacketWriter.
3927 if (!connection_.version().KnowsWhichDecrypterToUse()) {
3928 writer_->framer()->framer()->SetAlternativeDecrypter(
3929 ENCRYPTION_INITIAL,
3930 std::make_unique<NullDecrypter>(Perspective::IS_SERVER), false);
3931 }
Bence Békybac04052022-04-07 15:44:29 -04003932 connection_.SendCryptoStreamData();
3933 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3934 }
3935 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3936 EXPECT_FALSE(connection_.HasQueuedData());
3937
3938 // Parse the last packet and ensure it contains a crypto stream frame.
3939 EXPECT_LE(2u, writer_->frame_count());
3940 ASSERT_LE(1u, writer_->padding_frames().size());
3941 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3942 ASSERT_EQ(1u, writer_->stream_frames().size());
3943 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3944 writer_->stream_frames()[0]->stream_id);
3945 } else {
3946 EXPECT_LE(1u, writer_->crypto_frames().size());
3947 }
3948}
3949
3950TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3951 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3952 // queueing them.
3953 {
3954 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3955 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3956 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3957 connection_.SendCryptoStreamData();
3958 connection_.SendStreamData3();
3959 }
3960 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3961 EXPECT_FALSE(connection_.HasQueuedData());
3962
3963 // Parse the last packet and ensure it's the stream frame from stream 3.
3964 size_t padding_frame_count = writer_->padding_frames().size();
3965 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3966 ASSERT_EQ(1u, writer_->stream_frames().size());
3967 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3968 writer_->stream_frames()[0]->stream_id);
3969}
3970
3971TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3972 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3973 // Process a data packet to queue up a pending ack.
3974 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3975 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3976 } else {
3977 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3978 }
3979 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3980
3981 QuicPacketNumber last_packet;
3982 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3983 connection_.SendCryptoDataWithString("foo", 0);
3984 } else {
3985 SendStreamDataToPeer(
3986 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3987 NO_FIN, &last_packet);
3988 }
3989 // Verify ack is bundled with outging packet.
3990 EXPECT_FALSE(writer_->ack_frames().empty());
3991
3992 EXPECT_CALL(visitor_, OnCanWrite())
3993 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3994 &connection_, &TestConnection::SendStreamData3)),
3995 IgnoreResult(InvokeWithoutArgs(
3996 &connection_, &TestConnection::SendStreamData5))));
3997
3998 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3999
4000 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
4001 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martinduke9e0811c2022-12-08 20:35:57 -08004002 peer_framer_.SetEncrypter(
4003 ENCRYPTION_FORWARD_SECURE,
4004 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
4005 SetDecrypter(
4006 ENCRYPTION_FORWARD_SECURE,
4007 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
wubc9fd4292023-08-14 13:00:21 -07004008 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04004009 ProcessDataPacket(2);
4010
4011 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4012 EXPECT_FALSE(connection_.HasQueuedData());
4013
4014 // Parse the last packet and ensure it's an ack and two stream frames from
4015 // two different streams.
fayangfc04b8a2023-05-18 09:26:25 -07004016 EXPECT_EQ(3u, writer_->frame_count());
4017 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04004018 EXPECT_FALSE(writer_->ack_frames().empty());
4019 ASSERT_EQ(2u, writer_->stream_frames().size());
4020 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4021 writer_->stream_frames()[0]->stream_id);
4022 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4023 writer_->stream_frames()[1]->stream_id);
4024}
4025
4026TEST_P(QuicConnectionTest, FramePackingSendv) {
4027 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4028 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4029
4030 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4031 connection_.transport_version(), Perspective::IS_CLIENT);
4032 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4033
4034 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4035 EXPECT_FALSE(connection_.HasQueuedData());
4036
4037 // Parse the last packet and ensure multiple iovector blocks have
4038 // been packed into a single stream frame from one stream.
4039 EXPECT_EQ(1u, writer_->frame_count());
4040 EXPECT_EQ(1u, writer_->stream_frames().size());
4041 EXPECT_EQ(0u, writer_->padding_frames().size());
4042 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4043 EXPECT_EQ(stream_id, frame->stream_id);
4044 EXPECT_EQ("ABCDEF",
4045 absl::string_view(frame->data_buffer, frame->data_length));
4046}
4047
4048TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
4049 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4051
4052 BlockOnNextWrite();
4053 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4054 connection_.transport_version(), Perspective::IS_CLIENT);
4055 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4056
4057 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4058 EXPECT_TRUE(connection_.HasQueuedData());
4059
4060 // Unblock the writes and actually send.
4061 writer_->SetWritable();
4062 connection_.OnCanWrite();
4063 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4064
4065 // Parse the last packet and ensure it's one stream frame from one stream.
4066 EXPECT_EQ(1u, writer_->frame_count());
4067 EXPECT_EQ(1u, writer_->stream_frames().size());
4068 EXPECT_EQ(0u, writer_->padding_frames().size());
4069 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4070 EXPECT_EQ(stream_id, frame->stream_id);
4071 EXPECT_EQ("ABCDEF",
4072 absl::string_view(frame->data_buffer, frame->data_length));
4073}
4074
4075TEST_P(QuicConnectionTest, SendingZeroBytes) {
4076 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4077 // Send a zero byte write with a fin using writev.
4078 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4079 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4080 connection_.transport_version(), Perspective::IS_CLIENT);
4081 connection_.SaveAndSendStreamData(stream_id, {}, 0, FIN);
4082
4083 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4084 EXPECT_FALSE(connection_.HasQueuedData());
4085
4086 // Padding frames are added by v99 to ensure a minimum packet size.
4087 size_t extra_padding_frames = 0;
4088 if (GetParam().version.HasHeaderProtection()) {
4089 extra_padding_frames = 1;
4090 }
4091
4092 // Parse the last packet and ensure it's one stream frame from one stream.
4093 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
4094 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
4095 ASSERT_EQ(1u, writer_->stream_frames().size());
4096 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
4097 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4098}
4099
4100TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
4101 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4102 EXPECT_CALL(visitor_, GetHandshakeState())
4103 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
4104 // Set the ack alarm by processing a ping frame.
4105 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4106
4107 // Processs a PING frame.
4108 ProcessFramePacket(QuicFrame(QuicPingFrame()));
4109 // Ensure that this has caused the ACK alarm to be set.
4110 EXPECT_TRUE(connection_.HasPendingAcks());
4111
4112 // Send data and ensure the ack is bundled.
4113 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
4114 const std::string data(10000, '?');
4115 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
4116 GetNthClientInitiatedStreamId(0, connection_.transport_version()), data,
4117 0, FIN);
4118 EXPECT_EQ(data.length(), consumed.bytes_consumed);
4119 EXPECT_TRUE(consumed.fin_consumed);
4120 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4121 EXPECT_FALSE(connection_.HasQueuedData());
4122
4123 // Parse the last packet and ensure it's one stream frame with a fin.
4124 EXPECT_EQ(1u, writer_->frame_count());
4125 ASSERT_EQ(1u, writer_->stream_frames().size());
4126 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4127 writer_->stream_frames()[0]->stream_id);
4128 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4129 // Ensure the ack alarm was cancelled when the ack was sent.
4130 EXPECT_FALSE(connection_.HasPendingAcks());
4131}
4132
4133TEST_P(QuicConnectionTest, OnCanWrite) {
4134 // Visitor's OnCanWrite will send data, but will have more pending writes.
4135 EXPECT_CALL(visitor_, OnCanWrite())
4136 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
4137 &connection_, &TestConnection::SendStreamData3)),
4138 IgnoreResult(InvokeWithoutArgs(
4139 &connection_, &TestConnection::SendStreamData5))));
4140 {
4141 InSequence seq;
4142 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
4143 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
4144 .WillRepeatedly(Return(false));
4145 }
4146
4147 EXPECT_CALL(*send_algorithm_, CanSend(_))
4148 .WillRepeatedly(testing::Return(true));
4149
4150 connection_.OnCanWrite();
4151
4152 // Parse the last packet and ensure it's the two stream frames from
4153 // two different streams.
4154 EXPECT_EQ(2u, writer_->frame_count());
4155 EXPECT_EQ(2u, writer_->stream_frames().size());
4156 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4157 writer_->stream_frames()[0]->stream_id);
4158 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4159 writer_->stream_frames()[1]->stream_id);
4160}
4161
4162TEST_P(QuicConnectionTest, RetransmitOnNack) {
4163 QuicPacketNumber last_packet;
4164 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
4165 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet);
4166 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet);
4167
4168 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4169
4170 // Don't lose a packet on an ack, and nothing is retransmitted.
martindukeba002452023-03-21 08:10:46 -07004171 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004172 QuicAckFrame ack_one = InitAckFrame(1);
4173 ProcessAckPacket(&ack_one);
4174
4175 // Lose a packet and ensure it triggers retransmission.
4176 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4177 LostPacketVector lost_packets;
4178 lost_packets.push_back(
4179 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4180 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4181 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4182 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004183 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004184 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4185 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4186 ProcessAckPacket(&nack_two);
4187}
4188
4189TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
4190 // Block the connection to queue the packet.
4191 BlockOnNextWrite();
4192
4193 QuicStreamId stream_id = 2;
4194 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4195
4196 // Now that there is a queued packet, reset the stream.
4197 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4198
4199 // Unblock the connection and verify that only the RST_STREAM is sent.
4200 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4201 writer_->SetWritable();
4202 connection_.OnCanWrite();
4203 size_t padding_frame_count = writer_->padding_frames().size();
4204 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4205 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4206}
4207
4208TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
4209 // Block the connection to queue the packet.
4210 BlockOnNextWrite();
4211
4212 QuicStreamId stream_id = 2;
4213 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4214 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4215
4216 // Now that there is a queued packet, reset the stream.
4217 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4218
4219 // Unblock the connection and verify that the RST_STREAM is sent and the data
4220 // packet is sent.
4221 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4222 writer_->SetWritable();
4223 connection_.OnCanWrite();
4224 size_t padding_frame_count = writer_->padding_frames().size();
4225 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4226 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4227}
4228
4229TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
4230 QuicStreamId stream_id = 2;
4231 QuicPacketNumber last_packet;
4232 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4233 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4234 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4235
4236 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4237 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4238
4239 // Lose a packet and ensure it does not trigger retransmission.
4240 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4241 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4242 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004243 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004244 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4245 ProcessAckPacket(&nack_two);
4246}
4247
4248TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
4249 QuicStreamId stream_id = 2;
4250 QuicPacketNumber last_packet;
4251 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4252 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4253 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4254
4255 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4256 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4257
4258 // Lose a packet, ensure it triggers retransmission.
4259 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4261 LostPacketVector lost_packets;
4262 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4263 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4264 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4265 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004266 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004267 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4268 ProcessAckPacket(&nack_two);
4269}
4270
4271TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
4272 QuicStreamId stream_id = 2;
4273 QuicPacketNumber last_packet;
4274 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4275
4276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4277 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4278
4279 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
4280 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4281 clock_.AdvanceTime(DefaultRetransmissionTime());
4282 connection_.GetRetransmissionAlarm()->Fire();
4283 size_t padding_frame_count = writer_->padding_frames().size();
4284 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4285 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4286 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4287}
4288
4289// Ensure that if the only data in flight is non-retransmittable, the
4290// retransmission alarm is not set.
4291TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
4292 QuicStreamId stream_id = 2;
4293 QuicPacketNumber last_data_packet;
4294 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
4295
4296 // Cancel the stream.
4297 const QuicPacketNumber rst_packet = last_data_packet + 1;
4298 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
4299 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4300
4301 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
4302 // packet, which is no longer retransmittable since the stream was cancelled.
4303 QuicAckFrame nack_stream_data =
4304 ConstructAckFrame(rst_packet, last_data_packet);
4305 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07004306 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004307 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4308 ProcessAckPacket(&nack_stream_data);
4309
4310 // Ensure that the data is still in flight, but the retransmission alarm is no
4311 // longer set.
4312 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
4313 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4314}
4315
fayang339f0c82022-04-30 14:20:02 -07004316TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnPTO) {
Bence Békybac04052022-04-07 15:44:29 -04004317 QuicStreamId stream_id = 2;
4318 QuicPacketNumber last_packet;
4319 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4320
4321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4322 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4323
4324 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
4325 // is sent.
fayang339f0c82022-04-30 14:20:02 -07004326 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
Bence Békybac04052022-04-07 15:44:29 -04004327 clock_.AdvanceTime(DefaultRetransmissionTime());
4328 connection_.GetRetransmissionAlarm()->Fire();
4329 size_t padding_frame_count = writer_->padding_frames().size();
4330 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04004331}
4332
4333TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
4334 QuicStreamId stream_id = 2;
4335 QuicPacketNumber last_packet;
4336 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4337 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4338 BlockOnNextWrite();
4339 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4340
4341 // Lose a packet which will trigger a pending retransmission.
4342 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4343 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4344 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004345 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004346 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4347 ProcessAckPacket(&ack);
4348
4349 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4350
4351 // Unblock the connection and verify that the RST_STREAM is sent but not the
4352 // second data packet nor a retransmit.
4353 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4354 writer_->SetWritable();
4355 connection_.OnCanWrite();
4356 size_t padding_frame_count = writer_->padding_frames().size();
4357 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4358 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
4359 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4360}
4361
4362TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
4363 QuicStreamId stream_id = 2;
4364 QuicPacketNumber last_packet;
4365 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4366 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4367 BlockOnNextWrite();
4368 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4369
4370 // Lose a packet which will trigger a pending retransmission.
4371 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4372 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4373 LostPacketVector lost_packets;
4374 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4375 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4376 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4377 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004378 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004379 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4380 ProcessAckPacket(&ack);
4381
4382 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4383
4384 // Unblock the connection and verify that the RST_STREAM is sent and the
4385 // second data packet or a retransmit is sent.
4386 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
4387 writer_->SetWritable();
4388 connection_.OnCanWrite();
4389 // The RST_STREAM_FRAME is sent after queued packets and pending
4390 // retransmission.
4391 connection_.SendControlFrame(QuicFrame(
4392 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
4393 size_t padding_frame_count = writer_->padding_frames().size();
4394 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4395 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4396}
4397
4398TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
4399 QuicPacketNumber last_packet;
4400 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4401 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
4402 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
4403
4404 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4405
4406 // Instigate a loss with an ack.
4407 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4408 // The first nack should trigger a fast retransmission, but we'll be
4409 // write blocked, so the packet will be queued.
4410 BlockOnNextWrite();
4411
4412 LostPacketVector lost_packets;
4413 lost_packets.push_back(
4414 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4415 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4416 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4417 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004418 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004419 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4420 .Times(1);
4421 ProcessAckPacket(&nack_two);
4422 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4423
4424 // Now, ack the previous transmission.
4425 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07004426 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004427 QuicAckFrame ack_all = InitAckFrame(3);
4428 ProcessAckPacket(&ack_all);
4429
4430 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4431 .Times(0);
4432
4433 writer_->SetWritable();
4434 connection_.OnCanWrite();
4435
4436 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4437 // We do not store retransmittable frames of this retransmission.
4438 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
4439}
4440
4441TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
4442 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4443 QuicPacketNumber original, second;
4444
4445 QuicByteCount packet_size =
4446 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
4447 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
4448
4449 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
4450 // The first nack should retransmit the largest observed packet.
4451 LostPacketVector lost_packets;
4452 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
4453 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4454 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4455 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004456 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004457 // Packet 1 is short header for IETF QUIC because the encryption level
4458 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
fayangfc04b8a2023-05-18 09:26:25 -07004459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, packet_size, _));
Bence Békybac04052022-04-07 15:44:29 -04004460 ProcessAckPacket(&frame);
4461}
4462
Bence Békybac04052022-04-07 15:44:29 -04004463TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
4464 BlockOnNextWrite();
4465 writer_->set_is_write_blocked_data_buffered(true);
4466 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4467 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4468 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4469
4470 writer_->SetWritable();
4471 connection_.OnCanWrite();
4472 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4473}
4474
4475TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
4476 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4477 BlockOnNextWrite();
4478 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4479 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4480 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4481 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4482
4483 // The second packet should also be queued, in order to ensure packets are
4484 // never sent out of order.
4485 writer_->SetWritable();
4486 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4487 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4488 EXPECT_EQ(2u, connection_.NumQueuedPackets());
4489
4490 // Now both are sent in order when we unblock.
4491 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4492 connection_.OnCanWrite();
4493 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4494 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4495}
4496
4497TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
4498 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4499 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4500 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4501
4502 BlockOnNextWrite();
4503 writer_->set_is_write_blocked_data_buffered(true);
4504 // Simulate the retransmission alarm firing.
4505 clock_.AdvanceTime(DefaultRetransmissionTime());
4506 connection_.GetRetransmissionAlarm()->Fire();
4507
4508 // Ack the sent packet before the callback returns, which happens in
4509 // rare circumstances with write blocked sockets.
4510 QuicAckFrame ack = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07004511 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004512 ProcessAckPacket(&ack);
4513
4514 writer_->SetWritable();
4515 connection_.OnCanWrite();
4516 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang339f0c82022-04-30 14:20:02 -07004517 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 3));
Bence Békybac04052022-04-07 15:44:29 -04004518}
4519
4520TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4521 // Block the connection.
4522 BlockOnNextWrite();
4523 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4524 EXPECT_EQ(1u, writer_->packets_write_attempts());
4525 EXPECT_TRUE(writer_->IsWriteBlocked());
4526
4527 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4528 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4529 connection_.GetSendAlarm()->Fire();
4530 EXPECT_TRUE(writer_->IsWriteBlocked());
4531 EXPECT_EQ(1u, writer_->packets_write_attempts());
4532}
4533
4534TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4535 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4536
4537 // Block the connection.
4538 BlockOnNextWrite();
4539 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4540 EXPECT_TRUE(writer_->IsWriteBlocked());
4541 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4542 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4543
4544 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4545 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4546 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4547 // is returned.
4548 const uint64_t received_packet_num = 1;
4549 const bool has_stop_waiting = false;
4550 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4551 std::unique_ptr<QuicPacket> packet(
4552 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4553 char buffer[kMaxOutgoingPacketSize];
4554 size_t encrypted_length =
4555 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4556 *packet, buffer, kMaxOutgoingPacketSize);
4557 connection_.ProcessUdpPacket(
4558 kSelfAddress, kPeerAddress,
4559 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4560
4561 EXPECT_TRUE(writer_->IsWriteBlocked());
4562 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4563}
4564
QUICHE team32d62792023-04-27 11:47:01 -07004565TEST_P(QuicConnectionTest, SendAlarmNonZeroDelay) {
4566 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4567 // Set a 10 ms send alarm delay. The send alarm after processing the packet
4568 // should fire after waiting 10ms, not immediately.
4569 connection_.set_defer_send_in_response_to_packets(true);
4570 connection_.sent_packet_manager().SetDeferredSendAlarmDelay(
4571 QuicTime::Delta::FromMilliseconds(10));
4572 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4573
4574 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4575 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4576 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4577 // is returned.
4578 const uint64_t received_packet_num = 1;
4579 const bool has_stop_waiting = false;
4580 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4581 std::unique_ptr<QuicPacket> packet(
4582 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4583 char buffer[kMaxOutgoingPacketSize];
4584 size_t encrypted_length =
4585 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4586 *packet, buffer, kMaxOutgoingPacketSize);
wubc9fd4292023-08-14 13:00:21 -07004587 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
QUICHE team32d62792023-04-27 11:47:01 -07004588 connection_.ProcessUdpPacket(
4589 kSelfAddress, kPeerAddress,
4590 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4591
4592 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
4593 // It was set to be 10 ms in the future, so it should at the least be greater
4594 // than now + 5 ms.
4595 EXPECT_TRUE(connection_.GetSendAlarm()->deadline() >
4596 clock_.ApproximateNow() + QuicTime::Delta::FromMilliseconds(5));
4597}
4598
Bence Békybac04052022-04-07 15:44:29 -04004599TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4600 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4601 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4602
4603 // Simulate the case where a shared writer gets blocked by another connection.
4604 writer_->SetWriteBlocked();
4605
4606 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4607 QuicAckFrame ack1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07004608 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004609 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4610 ProcessAckPacket(1, &ack1);
4611}
4612
4613TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4614 writer_->SetBatchMode(true);
4615 EXPECT_TRUE(connection_.connected());
4616 // Have to explicitly grab the OnConnectionClosed frame and check
4617 // its parameters because this is a silent connection close and the
4618 // frame is not also transmitted to the peer.
4619 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4620 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4621
4622 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4623
4624 {
4625 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4626 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4627 ConnectionCloseBehavior::SILENT_CLOSE);
4628
4629 EXPECT_FALSE(connection_.connected());
4630 writer_->SetWriteBlocked();
4631 }
4632 EXPECT_EQ(1, connection_close_frame_count_);
4633 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4634 IsError(QUIC_PEER_GOING_AWAY));
4635}
4636
4637TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4638 writer_->SetBatchMode(true);
4639 writer_->BlockOnNextFlush();
4640
4641 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4642 {
4643 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4644 // flusher's destructor will call connection_.FlushPackets, which should add
4645 // the connection to the write blocked list.
4646 }
4647}
4648
4649TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4650 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4651 int offset = 0;
4652 // Send packets 1 to 15.
4653 for (int i = 0; i < 15; ++i) {
4654 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4655 offset += 3;
4656 }
4657
4658 // Ack 15, nack 1-14.
4659
4660 QuicAckFrame nack =
4661 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4662
4663 // 14 packets have been NACK'd and lost.
4664 LostPacketVector lost_packets;
4665 for (int i = 1; i < 15; ++i) {
4666 lost_packets.push_back(
4667 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
4668 }
4669 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4670 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4671 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07004672 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004673 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4674 ProcessAckPacket(&nack);
4675}
4676
4677// Test sending multiple acks from the connection to the session.
4678TEST_P(QuicConnectionTest, MultipleAcks) {
4679 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4680 return;
4681 }
4682 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4683 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4684 ProcessDataPacket(1);
4685 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4686 QuicPacketNumber last_packet;
4687 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4688 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4689 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4690 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4691 SendAckPacketToPeer(); // Packet 3
4692 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4693 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4694 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4695 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4696 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4697 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4698
4699 // Client will ack packets 1, 2, [!3], 4, 5.
martindukeba002452023-03-21 08:10:46 -07004700 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004701 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4702 ProcessAckPacket(&frame1);
4703
4704 // Now the client implicitly acks 3, and explicitly acks 6.
martindukeba002452023-03-21 08:10:46 -07004705 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004706 QuicAckFrame frame2 = InitAckFrame(6);
4707 ProcessAckPacket(&frame2);
4708}
4709
4710TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
4711 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4712 return;
4713 }
4714 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4715 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4716 ProcessDataPacket(1);
4717 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4718 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4719 // From now on, we send acks, so the send algorithm won't mark them pending.
4720 SendAckPacketToPeer(); // Packet 2
4721
martindukeba002452023-03-21 08:10:46 -07004722 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004723 QuicAckFrame frame = InitAckFrame(1);
4724 ProcessAckPacket(&frame);
4725
martindukeba002452023-03-21 08:10:46 -07004726 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004727 frame = InitAckFrame(2);
4728 ProcessAckPacket(&frame);
Bence Békybac04052022-04-07 15:44:29 -04004729
4730 // When we send an ack, we make sure our least-unacked makes sense. In this
4731 // case since we're not waiting on an ack for 2 and all packets are acked, we
4732 // set it to 3.
4733 SendAckPacketToPeer(); // Packet 3
Bence Békybac04052022-04-07 15:44:29 -04004734
4735 // Ack the ack, which updates the rtt and raises the least unacked.
martindukeba002452023-03-21 08:10:46 -07004736 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004737 frame = InitAckFrame(3);
4738 ProcessAckPacket(&frame);
4739
4740 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
haoyuewang16f86e82023-07-26 14:13:26 -07004741 SendAckPacketToPeer(); // Packet 5
Bence Békybac04052022-04-07 15:44:29 -04004742
4743 // Send two data packets at the end, and ensure if the last one is acked,
4744 // the least unacked is raised above the ack packets.
4745 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4746 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4747
martindukeba002452023-03-21 08:10:46 -07004748 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04004749 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4750 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4751 ProcessAckPacket(&frame);
Bence Békybac04052022-04-07 15:44:29 -04004752}
4753
Bence Békybac04052022-04-07 15:44:29 -04004754TEST_P(QuicConnectionTest, SendHandshakeMessages) {
Bence Békybac04052022-04-07 15:44:29 -04004755 // Attempt to send a handshake message and have the socket block.
4756 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4757 BlockOnNextWrite();
4758 connection_.SendCryptoDataWithString("foo", 0);
4759 // The packet should be serialized, but not queued.
4760 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4761
4762 // Switch to the new encrypter.
martinduke9e0811c2022-12-08 20:35:57 -08004763 connection_.SetEncrypter(
4764 ENCRYPTION_ZERO_RTT,
4765 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004766 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4767
4768 // Now become writeable and flush the packets.
4769 writer_->SetWritable();
4770 EXPECT_CALL(visitor_, OnCanWrite());
4771 connection_.OnCanWrite();
4772 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4773
martinduke9e0811c2022-12-08 20:35:57 -08004774 // Verify that the handshake packet went out with Initial encryption.
4775 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -04004776}
4777
martinduke9e0811c2022-12-08 20:35:57 -08004778TEST_P(QuicConnectionTest, DropRetransmitsForInitialPacketAfterForwardSecure) {
Bence Békybac04052022-04-07 15:44:29 -04004779 connection_.SendCryptoStreamData();
Bence Békybac04052022-04-07 15:44:29 -04004780 // Simulate the retransmission alarm firing and the socket blocking.
4781 BlockOnNextWrite();
4782 clock_.AdvanceTime(DefaultRetransmissionTime());
4783 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4784 connection_.GetRetransmissionAlarm()->Fire();
4785 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4786
4787 // Go forward secure.
4788 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4789 std::make_unique<TaggingEncrypter>(0x02));
4790 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4791 notifier_.NeuterUnencryptedData();
4792 connection_.NeuterUnencryptedPackets();
4793 connection_.OnHandshakeComplete();
4794
4795 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4796 // Unblock the socket and ensure that no packets are sent.
4797 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4798 writer_->SetWritable();
4799 connection_.OnCanWrite();
4800}
4801
4802TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
Bence Békybac04052022-04-07 15:44:29 -04004803 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
4804
4805 connection_.SendCryptoDataWithString("foo", 0);
4806
martinduke9e0811c2022-12-08 20:35:57 -08004807 connection_.SetEncrypter(
4808 ENCRYPTION_ZERO_RTT,
4809 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004810 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -08004811 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4812 writer_->framer()->framer()->SetAlternativeDecrypter(
4813 ENCRYPTION_ZERO_RTT,
4814 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT), false);
4815 }
Bence Békybac04052022-04-07 15:44:29 -04004816
4817 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4818 EXPECT_FALSE(notifier_.HasLostStreamData());
4819 connection_.MarkZeroRttPacketsForRetransmission(0);
4820 EXPECT_TRUE(notifier_.HasLostStreamData());
4821}
4822
4823TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
4824 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4825 return;
4826 }
4827 // SetFromConfig is always called after construction from InitializeSession.
4828 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4829 QuicConfig config;
4830 connection_.SetFromConfig(config);
4831 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004832
martinduke9e0811c2022-12-08 20:35:57 -08004833 peer_framer_.SetEncrypter(
4834 ENCRYPTION_ZERO_RTT,
4835 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4836 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4837 writer_->framer()->framer()->SetDecrypter(
4838 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4839 }
Bence Békybac04052022-04-07 15:44:29 -04004840
4841 // Process an encrypted packet which can not yet be decrypted which should
4842 // result in the packet being buffered.
4843 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4844
4845 // Transition to the new encryption state and process another encrypted packet
4846 // which should result in the original packet being processed.
4847 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004848 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
4849 connection_.SetEncrypter(
4850 ENCRYPTION_ZERO_RTT,
4851 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004852 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4853 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4854 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4855
4856 // Finally, process a third packet and note that we do not reprocess the
4857 // buffered packet.
4858 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4859 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4860}
4861
Bence Békybac04052022-04-07 15:44:29 -04004862TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
4863 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4864 return;
4865 }
4866 // SetFromConfig is always called after construction from InitializeSession.
4867 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4868 QuicConfig config;
4869 config.set_max_undecryptable_packets(100);
4870 connection_.SetFromConfig(config);
4871 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004872
martinduke9e0811c2022-12-08 20:35:57 -08004873 peer_framer_.SetEncrypter(
4874 ENCRYPTION_ZERO_RTT,
4875 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004876
4877 // Process an encrypted packet which can not yet be decrypted which should
4878 // result in the packet being buffered.
4879 for (uint64_t i = 1; i <= 100; ++i) {
4880 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4881 }
4882
4883 // Transition to the new encryption state and process another encrypted packet
4884 // which should result in the original packets being processed.
4885 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4886 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004887 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004888 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -08004889 connection_.SetEncrypter(
4890 ENCRYPTION_ZERO_RTT,
4891 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004892 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4893
4894 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
martinduke9e0811c2022-12-08 20:35:57 -08004895 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4896 writer_->framer()->framer()->SetDecrypter(
4897 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4898 }
Bence Békybac04052022-04-07 15:44:29 -04004899 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4900
4901 // Finally, process a third packet and note that we do not reprocess the
4902 // buffered packet.
4903 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4904 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4905}
4906
4907TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4908 BlockOnNextWrite();
4909 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4910 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4911 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4912
4913 // Test that RTO is started once we write to the socket.
4914 writer_->SetWritable();
4915 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4916 connection_.OnCanWrite();
4917 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4918}
4919
Bence Békybac04052022-04-07 15:44:29 -04004920TEST_P(QuicConnectionTest, TestQueued) {
Bence Békybac04052022-04-07 15:44:29 -04004921 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4922 BlockOnNextWrite();
4923 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4924 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4925
4926 // Unblock the writes and actually send.
4927 writer_->SetWritable();
4928 connection_.OnCanWrite();
4929 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4930}
4931
4932TEST_P(QuicConnectionTest, InitialTimeout) {
4933 EXPECT_TRUE(connection_.connected());
4934 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4935 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4936
4937 // SetFromConfig sets the initial timeouts before negotiation.
4938 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4939 QuicConfig config;
4940 connection_.SetFromConfig(config);
4941 // Subtract a second from the idle timeout on the client side.
4942 QuicTime default_timeout =
4943 clock_.ApproximateNow() +
4944 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4945 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4946
4947 EXPECT_CALL(visitor_,
4948 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4949 // Simulate the timeout alarm firing.
4950 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4951 connection_.GetTimeoutAlarm()->Fire();
4952
4953 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4954 EXPECT_FALSE(connection_.connected());
4955
4956 EXPECT_FALSE(connection_.HasPendingAcks());
4957 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4958 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4959 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4960 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4961 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4962 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4963}
4964
4965TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4966 EXPECT_TRUE(connection_.connected());
4967 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4968 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4969
4970 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4971 QuicConfig config;
4972 connection_.SetFromConfig(config);
4973 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4974 QuicTime initial_ddl =
4975 clock_.ApproximateNow() +
4976 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4977 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4978 EXPECT_TRUE(connection_.connected());
4979
4980 // Advance the time and send the first packet to the peer.
4981 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4982 QuicPacketNumber last_packet;
4983 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4984 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4985 // This will be the updated deadline for the connection to idle time out.
4986 QuicTime new_ddl = clock_.ApproximateNow() +
4987 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4988
4989 // Simulate the timeout alarm firing, the connection should not be closed as
4990 // a new packet has been sent.
4991 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
4992 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4993 clock_.AdvanceTime(delay);
4994 // Verify the timeout alarm deadline is updated.
4995 EXPECT_TRUE(connection_.connected());
4996 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4997 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4998
4999 // Simulate the timeout alarm firing again, the connection now should be
5000 // closed.
5001 EXPECT_CALL(visitor_,
5002 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5003 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
5004 connection_.GetTimeoutAlarm()->Fire();
5005 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5006 EXPECT_FALSE(connection_.connected());
5007
5008 EXPECT_FALSE(connection_.HasPendingAcks());
5009 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5010 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5011 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5012 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5013 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5014}
5015
5016TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
5017 EXPECT_TRUE(connection_.connected());
5018 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5019 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5020
5021 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5022 QuicConfig config;
5023 connection_.SetFromConfig(config);
5024 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5025 QuicTime initial_ddl =
5026 clock_.ApproximateNow() +
5027 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5028 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
5029 EXPECT_TRUE(connection_.connected());
5030
5031 // Immediately send the first packet, this is a rare case but test code will
5032 // hit this issue often as MockClock used for tests doesn't move with code
5033 // execution until manually adjusted.
5034 QuicPacketNumber last_packet;
5035 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5036 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
5037
5038 // Advance the time and send the second packet to the peer.
5039 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
5040 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5041 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
5042
5043 // Simulate the timeout alarm firing, the connection will be closed.
5044 EXPECT_CALL(visitor_,
5045 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5046 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
5047 connection_.GetTimeoutAlarm()->Fire();
5048
5049 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5050 EXPECT_FALSE(connection_.connected());
5051
5052 EXPECT_FALSE(connection_.HasPendingAcks());
5053 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5054 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5055 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5056 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5057 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5058}
5059
5060TEST_P(QuicConnectionTest, HandshakeTimeout) {
5061 // Use a shorter handshake timeout than idle timeout for this test.
5062 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
5063 connection_.SetNetworkTimeouts(timeout, timeout);
5064 EXPECT_TRUE(connection_.connected());
5065 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5066
5067 QuicTime handshake_timeout =
5068 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
5069 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
5070 EXPECT_TRUE(connection_.connected());
5071
5072 // Send and ack new data 3 seconds later to lengthen the idle timeout.
5073 SendStreamDataToPeer(
5074 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5075 "GET /", 0, FIN, nullptr);
5076 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
5077 QuicAckFrame frame = InitAckFrame(1);
5078 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005079 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005080 ProcessAckPacket(&frame);
5081
5082 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5083 EXPECT_TRUE(connection_.connected());
5084
5085 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
5086
5087 EXPECT_CALL(visitor_,
5088 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5089 // Simulate the timeout alarm firing.
5090 connection_.GetTimeoutAlarm()->Fire();
5091
5092 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5093 EXPECT_FALSE(connection_.connected());
5094
5095 EXPECT_FALSE(connection_.HasPendingAcks());
5096 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5097 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5098 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5099 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
5100}
5101
5102TEST_P(QuicConnectionTest, PingAfterSend) {
5103 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5104 return;
5105 }
5106 EXPECT_TRUE(connection_.connected());
5107 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5108 .WillRepeatedly(Return(true));
5109 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5110
5111 // Advance to 5ms, and send a packet to the peer, which will set
5112 // the ping alarm.
5113 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5114 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5115 SendStreamDataToPeer(
5116 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5117 "GET /", 0, FIN, nullptr);
5118 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5119 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
5120 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5121
5122 // Now recevie an ACK of the previous packet, which will move the
5123 // ping alarm forward.
5124 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5125 QuicAckFrame frame = InitAckFrame(1);
5126 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005127 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005128 ProcessAckPacket(&frame);
5129 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5130 // The ping timer is set slightly less than 15 seconds in the future, because
5131 // of the 1s ping timer alarm granularity.
5132 EXPECT_EQ(
5133 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
5134 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5135
5136 writer_->Reset();
5137 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
5138 connection_.GetPingAlarm()->Fire();
5139 size_t padding_frame_count = writer_->padding_frames().size();
5140 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5141 ASSERT_EQ(1u, writer_->ping_frames().size());
5142 writer_->Reset();
5143
5144 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5145 .WillRepeatedly(Return(false));
5146 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5147 SendAckPacketToPeer();
5148
5149 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5150}
5151
5152TEST_P(QuicConnectionTest, ReducedPingTimeout) {
5153 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5154 return;
5155 }
5156 EXPECT_TRUE(connection_.connected());
5157 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5158 .WillRepeatedly(Return(true));
5159 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5160
5161 // Use a reduced ping timeout for this connection.
fayang5d393332022-04-18 13:34:54 -07005162 connection_.set_keep_alive_ping_timeout(QuicTime::Delta::FromSeconds(10));
Bence Békybac04052022-04-07 15:44:29 -04005163
5164 // Advance to 5ms, and send a packet to the peer, which will set
5165 // the ping alarm.
5166 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5167 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5168 SendStreamDataToPeer(
5169 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5170 "GET /", 0, FIN, nullptr);
5171 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5172 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
5173 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5174
5175 // Now recevie an ACK of the previous packet, which will move the
5176 // ping alarm forward.
5177 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5178 QuicAckFrame frame = InitAckFrame(1);
5179 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07005180 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005181 ProcessAckPacket(&frame);
5182 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5183 // The ping timer is set slightly less than 10 seconds in the future, because
5184 // of the 1s ping timer alarm granularity.
5185 EXPECT_EQ(
5186 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5187 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5188
5189 writer_->Reset();
5190 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5191 connection_.GetPingAlarm()->Fire();
5192 size_t padding_frame_count = writer_->padding_frames().size();
5193 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5194 ASSERT_EQ(1u, writer_->ping_frames().size());
5195 writer_->Reset();
5196
5197 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5198 .WillRepeatedly(Return(false));
5199 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5200 SendAckPacketToPeer();
5201
5202 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5203}
5204
5205// Tests whether sending an MTU discovery packet to peer successfully causes the
5206// maximum packet size to increase.
5207TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
5208 MtuDiscoveryTestInit();
5209
5210 // Send an MTU probe.
5211 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5212 QuicByteCount mtu_probe_size;
5213 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5214 .WillOnce(SaveArg<3>(&mtu_probe_size));
5215 connection_.SendMtuDiscoveryPacket(new_mtu);
5216 EXPECT_EQ(new_mtu, mtu_probe_size);
5217 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5218
5219 // Send more than MTU worth of data. No acknowledgement was received so far,
5220 // so the MTU should be at its old value.
5221 const std::string data(kDefaultMaxPacketSize + 1, '.');
5222 QuicByteCount size_before_mtu_change;
5223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5224 .Times(2)
5225 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5226 .WillOnce(Return());
5227 connection_.SendStreamDataWithString(3, data, 0, FIN);
5228 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5229 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5230
5231 // Acknowledge all packets so far.
5232 QuicAckFrame probe_ack = InitAckFrame(3);
martindukeba002452023-03-21 08:10:46 -07005233 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005234 ProcessAckPacket(&probe_ack);
5235 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5236
5237 // Send the same data again. Check that it fits into a single packet now.
5238 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5239 connection_.SendStreamDataWithString(3, data, 0, FIN);
5240 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5241}
5242
5243// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5244// the writer is flushed immediately.
5245TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5246 writer_->SetBatchMode(true);
5247 MtuDiscoveryTestInit();
5248
5249 // Send an MTU probe.
5250 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5251 QuicByteCount mtu_probe_size;
5252 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5253 .WillOnce(SaveArg<3>(&mtu_probe_size));
5254 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5255 connection_.SendMtuDiscoveryPacket(target_mtu);
5256 EXPECT_EQ(target_mtu, mtu_probe_size);
5257 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
5258}
5259
5260// Tests whether MTU discovery does not happen when it is not explicitly enabled
5261// by the connection options.
5262TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
5263 MtuDiscoveryTestInit();
5264
5265 const QuicPacketCount packets_between_probes_base = 10;
5266 set_packets_between_probes_base(packets_between_probes_base);
5267
5268 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5269 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5270 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5271 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5272 EXPECT_EQ(0u, connection_.mtu_probe_count());
5273 }
5274}
5275
5276// Tests whether MTU discovery works when all probes are acknowledged on the
5277// first try.
5278TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
5279 MtuDiscoveryTestInit();
5280
5281 const QuicPacketCount packets_between_probes_base = 5;
5282 set_packets_between_probes_base(packets_between_probes_base);
5283
5284 connection_.EnablePathMtuDiscovery(send_algorithm_);
5285
5286 // Send enough packets so that the next one triggers path MTU discovery.
5287 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5288 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5289 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5290 }
5291
5292 // Trigger the probe.
5293 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5294 nullptr);
5295 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5296 QuicByteCount probe_size;
5297 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5298 .WillOnce(SaveArg<3>(&probe_size));
5299 connection_.GetMtuDiscoveryAlarm()->Fire();
5300
5301 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5302 kMtuDiscoveryTargetPacketSizeHigh));
5303
5304 const QuicPacketNumber probe_packet_number =
5305 FirstSendingPacketNumber() + packets_between_probes_base;
5306 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5307
5308 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005309 {
5310 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5311 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5312 .Times(AnyNumber());
5313 ProcessAckPacket(&probe_ack);
5314 EXPECT_EQ(probe_size, connection_.max_packet_length());
5315 EXPECT_EQ(0u, connection_.GetBytesInFlight());
Bence Békybac04052022-04-07 15:44:29 -04005316
QUICHE teame2a24ee2024-01-09 06:34:35 -08005317 EXPECT_EQ(1u, connection_.mtu_probe_count());
5318 }
Bence Békybac04052022-04-07 15:44:29 -04005319
5320 QuicStreamOffset stream_offset = packets_between_probes_base;
5321 QuicByteCount last_probe_size = 0;
5322 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5323 ++num_probes) {
5324 // Send just enough packets without triggering the next probe.
5325 for (QuicPacketCount i = 0;
5326 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5327 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5328 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5329 }
5330
5331 // Trigger the next probe.
5332 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5333 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5334 QuicByteCount new_probe_size;
5335 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5336 .WillOnce(SaveArg<3>(&new_probe_size));
5337 connection_.GetMtuDiscoveryAlarm()->Fire();
5338 EXPECT_THAT(new_probe_size,
5339 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5340 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5341
5342 // Acknowledge all packets sent so far.
5343 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5344 ProcessAckPacket(&probe_ack);
5345 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5346 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5347
5348 last_probe_size = probe_size;
5349 probe_size = new_probe_size;
5350 }
5351
5352 // The last probe size should be equal to the target.
5353 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
5354
5355 writer_->SetShouldWriteFail();
5356
5357 // Ignore PACKET_WRITE_ERROR once.
5358 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5359 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5360 EXPECT_TRUE(connection_.connected());
5361
5362 // Close connection on another PACKET_WRITE_ERROR.
5363 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5364 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5365 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5366 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5367 EXPECT_FALSE(connection_.connected());
5368 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5369 IsError(QUIC_PACKET_WRITE_ERROR));
5370}
5371
5372// After a successful MTU probe, one and only one write error should be ignored
5373// if it happened in QuicConnection::FlushPacket.
5374TEST_P(QuicConnectionTest,
5375 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5376 MtuDiscoveryTestInit();
5377 writer_->SetBatchMode(true);
5378
5379 const QuicPacketCount packets_between_probes_base = 5;
5380 set_packets_between_probes_base(packets_between_probes_base);
5381
5382 connection_.EnablePathMtuDiscovery(send_algorithm_);
5383
5384 const QuicByteCount original_max_packet_length =
5385 connection_.max_packet_length();
5386 // Send enough packets so that the next one triggers path MTU discovery.
5387 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5388 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5389 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5390 }
5391
5392 // Trigger the probe.
5393 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5394 nullptr);
5395 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5396 QuicByteCount probe_size;
5397 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5398 .WillOnce(SaveArg<3>(&probe_size));
5399 connection_.GetMtuDiscoveryAlarm()->Fire();
5400
5401 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5402 kMtuDiscoveryTargetPacketSizeHigh));
5403
5404 const QuicPacketNumber probe_packet_number =
5405 FirstSendingPacketNumber() + packets_between_probes_base;
5406 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5407
5408 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005409 {
5410 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5411 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5412 .Times(AnyNumber());
5413 ProcessAckPacket(&probe_ack);
5414 EXPECT_EQ(probe_size, connection_.max_packet_length());
5415 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5416 }
Bence Békybac04052022-04-07 15:44:29 -04005417
5418 EXPECT_EQ(1u, connection_.mtu_probe_count());
5419
5420 writer_->SetShouldWriteFail();
5421
5422 // Ignore PACKET_WRITE_ERROR once.
5423 {
5424 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5425 // flusher's destructor will call connection_.FlushPackets, which should
5426 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5427 }
5428 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5429 EXPECT_TRUE(connection_.connected());
5430
5431 // Close connection on another PACKET_WRITE_ERROR.
5432 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5433 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5434 {
5435 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5436 // flusher's destructor will call connection_.FlushPackets, which should
5437 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5438 }
5439 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5440 EXPECT_FALSE(connection_.connected());
5441 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5442 IsError(QUIC_PACKET_WRITE_ERROR));
5443}
5444
5445// Simulate the case where the first attempt to send a probe is write blocked,
5446// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5447TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
5448 MtuDiscoveryTestInit();
5449
5450 const QuicPacketCount packets_between_probes_base = 5;
5451 set_packets_between_probes_base(packets_between_probes_base);
5452
5453 connection_.EnablePathMtuDiscovery(send_algorithm_);
5454
5455 // Send enough packets so that the next one triggers path MTU discovery.
5456 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5457 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5458 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5459 }
5460
5461 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5462
5463 // Trigger the probe.
5464 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5465 nullptr);
5466 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5468 BlockOnNextWrite();
5469 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5470 connection_.GetMtuDiscoveryAlarm()->Fire();
5471 EXPECT_EQ(1u, connection_.mtu_probe_count());
5472 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5473 ASSERT_TRUE(connection_.connected());
5474
5475 writer_->SetWritable();
5476 SimulateNextPacketTooLarge();
5477 connection_.OnCanWrite();
5478 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5479 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5480 EXPECT_TRUE(connection_.connected());
5481}
5482
5483// Tests whether MTU discovery works correctly when the probes never get
5484// acknowledged.
5485TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5486 MtuDiscoveryTestInit();
5487
5488 // Lower the number of probes between packets in order to make the test go
5489 // much faster.
5490 const QuicPacketCount packets_between_probes_base = 5;
5491 set_packets_between_probes_base(packets_between_probes_base);
5492
5493 connection_.EnablePathMtuDiscovery(send_algorithm_);
5494
5495 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5496
5497 EXPECT_EQ(packets_between_probes_base,
5498 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5499
5500 // This tests sends more packets than strictly necessary to make sure that if
5501 // the connection was to send more discovery packets than needed, those would
5502 // get caught as well.
5503 const QuicPacketCount number_of_packets =
5504 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5505 std::vector<QuicPacketNumber> mtu_discovery_packets;
5506 // Called on many acks.
martindukeba002452023-03-21 08:10:46 -07005507 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04005508 .Times(AnyNumber());
5509 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5510 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5511 clock_.AdvanceTime(rtt);
5512
5513 // Receive an ACK, which marks all data packets as received, and all MTU
5514 // discovery packets as missing.
5515
5516 QuicAckFrame ack;
5517
5518 if (!mtu_discovery_packets.empty()) {
5519 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5520 mtu_discovery_packets.end());
5521 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5522 mtu_discovery_packets.end());
5523 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5524 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5525 creator_->packet_number() + 1);
5526 ack.largest_acked = creator_->packet_number();
5527
5528 } else {
5529 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5530 ack.largest_acked = creator_->packet_number();
5531 }
5532
5533 ProcessAckPacket(&ack);
5534
5535 // Trigger MTU probe if it would be scheduled now.
5536 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5537 continue;
5538 }
5539
5540 // Fire the alarm. The alarm should cause a packet to be sent.
5541 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5542 connection_.GetMtuDiscoveryAlarm()->Fire();
5543 // Record the packet number of the MTU discovery packet in order to
5544 // mark it as NACK'd.
5545 mtu_discovery_packets.push_back(creator_->packet_number());
5546 }
5547
5548 // Ensure the number of packets between probes grows exponentially by checking
5549 // it against the closed-form expression for the packet number.
5550 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5551 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5552 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5553 const QuicPacketCount packets_between_probes =
5554 packets_between_probes_base * ((1 << (i + 1)) - 1);
5555 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5556 mtu_discovery_packets[i]);
5557 }
5558
5559 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5560 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5561 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5562}
5563
5564// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5565TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
5566 MtuDiscoveryTestInit();
5567
5568 const QuicPacketCount packets_between_probes_base = 5;
5569 set_packets_between_probes_base(packets_between_probes_base);
5570
5571 connection_.EnablePathMtuDiscovery(send_algorithm_);
5572
5573 // Send enough packets so that the next one triggers path MTU discovery.
5574 QuicStreamOffset stream_offset = 0;
5575 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5576 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5577 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5578 }
5579
5580 // Trigger the probe.
5581 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5582 nullptr);
5583 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5584 QuicByteCount probe_size;
5585 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5586 .WillOnce(SaveArg<3>(&probe_size));
5587 connection_.GetMtuDiscoveryAlarm()->Fire();
5588 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5589 kMtuDiscoveryTargetPacketSizeHigh));
5590
5591 const QuicPacketNumber probe_packet_number =
5592 FirstSendingPacketNumber() + packets_between_probes_base;
5593 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5594
5595 // Acknowledge all packets sent so far.
5596 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
martindukeba002452023-03-21 08:10:46 -07005597 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04005598 .Times(AnyNumber());
5599 ProcessAckPacket(&first_ack);
5600 EXPECT_EQ(probe_size, connection_.max_packet_length());
5601 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5602
5603 EXPECT_EQ(1u, connection_.mtu_probe_count());
5604
5605 // Send just enough packets without triggering the second probe.
5606 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5607 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5608 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5609 }
5610
5611 // Trigger the second probe.
5612 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5613 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5614 QuicByteCount second_probe_size;
5615 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5616 .WillOnce(SaveArg<3>(&second_probe_size));
5617 connection_.GetMtuDiscoveryAlarm()->Fire();
5618 EXPECT_THAT(second_probe_size,
5619 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5620 EXPECT_EQ(2u, connection_.mtu_probe_count());
5621
5622 // Acknowledge all packets sent so far, except the second probe.
5623 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5624 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5625 ProcessAckPacket(&first_ack);
5626 EXPECT_EQ(probe_size, connection_.max_packet_length());
5627
5628 // Send just enough packets without triggering the third probe.
5629 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5630 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5631 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5632 }
5633
5634 // Trigger the third probe.
5635 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5636 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5637 QuicByteCount third_probe_size;
5638 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5639 .WillOnce(SaveArg<3>(&third_probe_size));
5640 connection_.GetMtuDiscoveryAlarm()->Fire();
5641 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5642 EXPECT_EQ(3u, connection_.mtu_probe_count());
5643
5644 // Acknowledge all packets sent so far, except the second probe.
5645 QuicAckFrame third_ack =
5646 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5647 ProcessAckPacket(&third_ack);
5648 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5649
5650 SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr);
5651 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5652
5653 if (connection_.PathDegradingDetectionInProgress() &&
5654 QuicConnectionPeer::GetPathDegradingDeadline(&connection_) <
5655 QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(
5656 &connection_)) {
5657 // Fire path degrading alarm first.
5658 connection_.PathDegradingTimeout();
5659 }
5660
5661 // Verify the max packet size has not reduced.
5662 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5663
5664 // Fire alarm to get path mtu reduction callback called.
5665 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5666 connection_.GetBlackholeDetectorAlarm()->Fire();
5667
5668 // Verify the max packet size has reduced to the previous value.
5669 EXPECT_EQ(probe_size, connection_.max_packet_length());
5670}
5671
5672// Tests whether MTU discovery works when the writer has a limit on how large a
5673// packet can be.
5674TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5675 MtuDiscoveryTestInit();
5676
5677 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5678 writer_->set_max_packet_size(mtu_limit);
5679
5680 const QuicPacketCount packets_between_probes_base = 5;
5681 set_packets_between_probes_base(packets_between_probes_base);
5682
5683 connection_.EnablePathMtuDiscovery(send_algorithm_);
5684
5685 // Send enough packets so that the next one triggers path MTU discovery.
5686 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5687 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5688 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5689 }
5690
5691 // Trigger the probe.
5692 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5693 nullptr);
5694 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5695 QuicByteCount probe_size;
5696 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5697 .WillOnce(SaveArg<3>(&probe_size));
5698 connection_.GetMtuDiscoveryAlarm()->Fire();
5699
5700 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
5701
5702 const QuicPacketNumber probe_sequence_number =
5703 FirstSendingPacketNumber() + packets_between_probes_base;
5704 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5705
5706 // Acknowledge all packets sent so far.
QUICHE teame2a24ee2024-01-09 06:34:35 -08005707 {
5708 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5709 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
5710 .Times(AnyNumber());
5711 ProcessAckPacket(&probe_ack);
5712 EXPECT_EQ(probe_size, connection_.max_packet_length());
5713 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5714 }
Bence Békybac04052022-04-07 15:44:29 -04005715
5716 EXPECT_EQ(1u, connection_.mtu_probe_count());
5717
5718 QuicStreamOffset stream_offset = packets_between_probes_base;
5719 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5720 ++num_probes) {
5721 // Send just enough packets without triggering the next probe.
5722 for (QuicPacketCount i = 0;
5723 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5724 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5725 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5726 }
5727
5728 // Trigger the next probe.
5729 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5730 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5731 QuicByteCount new_probe_size;
5732 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5733 .WillOnce(SaveArg<3>(&new_probe_size));
5734 connection_.GetMtuDiscoveryAlarm()->Fire();
5735 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5736 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5737
5738 // Acknowledge all packets sent so far.
5739 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5740 ProcessAckPacket(&probe_ack);
5741 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5742 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5743
5744 probe_size = new_probe_size;
5745 }
5746
5747 // The last probe size should be equal to the target.
5748 EXPECT_EQ(probe_size, mtu_limit);
5749}
5750
5751// Tests whether MTU discovery works when the writer returns an error despite
5752// advertising higher packet length.
5753TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5754 MtuDiscoveryTestInit();
5755
5756 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5757 const QuicByteCount initial_mtu = connection_.max_packet_length();
5758 EXPECT_LT(initial_mtu, mtu_limit);
5759 writer_->set_max_packet_size(mtu_limit);
5760
5761 const QuicPacketCount packets_between_probes_base = 5;
5762 set_packets_between_probes_base(packets_between_probes_base);
5763
5764 connection_.EnablePathMtuDiscovery(send_algorithm_);
5765
5766 // Send enough packets so that the next one triggers path MTU discovery.
5767 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5768 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5769 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5770 }
5771
5772 // Trigger the probe.
5773 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5774 nullptr);
5775 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5776 writer_->SimulateNextPacketTooLarge();
5777 connection_.GetMtuDiscoveryAlarm()->Fire();
5778 ASSERT_TRUE(connection_.connected());
5779
5780 // Send more data.
5781 QuicPacketNumber probe_number = creator_->packet_number();
5782 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5783 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5784 connection_.EnsureWritableAndSendStreamData5();
5785 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5786 }
5787
5788 // Acknowledge all packets sent so far, except for the lost probe.
5789 QuicAckFrame probe_ack =
5790 ConstructAckFrame(creator_->packet_number(), probe_number);
martindukeba002452023-03-21 08:10:46 -07005791 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04005792 ProcessAckPacket(&probe_ack);
5793 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5794
5795 // Send more packets, and ensure that none of them sets the alarm.
5796 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5797 connection_.EnsureWritableAndSendStreamData5();
5798 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5799 }
5800
5801 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5802 EXPECT_EQ(1u, connection_.mtu_probe_count());
5803}
5804
5805TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5806 MtuDiscoveryTestInit();
5807
5808 const QuicPacketCount packets_between_probes_base = 10;
5809 set_packets_between_probes_base(packets_between_probes_base);
5810
5811 connection_.EnablePathMtuDiscovery(send_algorithm_);
5812
5813 // Send enough packets so that the next one triggers path MTU discovery.
5814 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5815 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5816 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5817 }
5818
5819 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5820 nullptr);
5821 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5822
5823 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
5824 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5825 ConnectionCloseBehavior::SILENT_CLOSE);
5826 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5827}
5828
5829TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
5830 EXPECT_TRUE(connection_.connected());
5831 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5832 QuicConfig config;
5833 connection_.SetFromConfig(config);
5834
5835 const QuicTime::Delta initial_idle_timeout =
5836 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5837 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5838 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5839
5840 // When we send a packet, the timeout will change to 5ms +
5841 // kInitialIdleTimeoutSecs.
5842 clock_.AdvanceTime(five_ms);
5843 SendStreamDataToPeer(
5844 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5845 0, FIN, nullptr);
5846 EXPECT_EQ(default_timeout + five_ms,
5847 connection_.GetTimeoutAlarm()->deadline());
5848
5849 // Now send more data. This will not move the timeout because
5850 // no data has been received since the previous write.
5851 clock_.AdvanceTime(five_ms);
5852 SendStreamDataToPeer(
5853 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5854 3, FIN, nullptr);
5855 EXPECT_EQ(default_timeout + five_ms,
5856 connection_.GetTimeoutAlarm()->deadline());
5857
5858 // The original alarm will fire. We should not time out because we had a
5859 // network event at t=5ms. The alarm will reregister.
5860 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5861 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5862 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5863 EXPECT_TRUE(connection_.connected());
5864 EXPECT_EQ(default_timeout + five_ms,
5865 connection_.GetTimeoutAlarm()->deadline());
5866
5867 // This time, we should time out.
5868 EXPECT_CALL(visitor_,
5869 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5870 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5871 clock_.AdvanceTime(five_ms);
5872 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5873 connection_.GetTimeoutAlarm()->Fire();
5874 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5875 EXPECT_FALSE(connection_.connected());
5876 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5877}
5878
Bence Békybac04052022-04-07 15:44:29 -04005879TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5880 // When the idle timeout fires, verify that by default we do not send any
5881 // connection close packets.
5882 EXPECT_TRUE(connection_.connected());
5883 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5884 QuicConfig config;
5885
5886 // Create a handshake message that also enables silent close.
5887 CryptoHandshakeMessage msg;
5888 std::string error_details;
5889 QuicConfig client_config;
5890 client_config.SetInitialStreamFlowControlWindowToSend(
5891 kInitialStreamFlowControlWindowForTest);
5892 client_config.SetInitialSessionFlowControlWindowToSend(
5893 kInitialSessionFlowControlWindowForTest);
5894 client_config.SetIdleNetworkTimeout(
5895 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5896 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5897 const QuicErrorCode error =
5898 config.ProcessPeerHello(msg, CLIENT, &error_details);
5899 EXPECT_THAT(error, IsQuicNoError());
5900
5901 if (connection_.version().UsesTls()) {
5902 QuicConfigPeer::SetReceivedOriginalConnectionId(
5903 &config, connection_.connection_id());
5904 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5905 &config, connection_.connection_id());
5906 }
5907 connection_.SetFromConfig(config);
5908
5909 const QuicTime::Delta default_idle_timeout =
5910 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5911 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5912 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5913
5914 // When we send a packet, the timeout will change to 5ms +
5915 // kInitialIdleTimeoutSecs.
5916 clock_.AdvanceTime(five_ms);
5917 SendStreamDataToPeer(
5918 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5919 0, FIN, nullptr);
5920 EXPECT_EQ(default_timeout + five_ms,
5921 connection_.GetTimeoutAlarm()->deadline());
5922
5923 // Now send more data. This will not move the timeout because
5924 // no data has been received since the previous write.
5925 clock_.AdvanceTime(five_ms);
5926 SendStreamDataToPeer(
5927 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5928 3, FIN, nullptr);
5929 EXPECT_EQ(default_timeout + five_ms,
5930 connection_.GetTimeoutAlarm()->deadline());
5931
5932 // The original alarm will fire. We should not time out because we had a
5933 // network event at t=5ms. The alarm will reregister.
5934 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5935 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5936 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5937 EXPECT_TRUE(connection_.connected());
5938 EXPECT_EQ(default_timeout + five_ms,
5939 connection_.GetTimeoutAlarm()->deadline());
5940
5941 // This time, we should time out.
5942 // This results in a SILENT_CLOSE, so the writer will not be invoked
5943 // and will not save the frame. Grab the frame from OnConnectionClosed
5944 // directly.
5945 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5946 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5947
5948 clock_.AdvanceTime(five_ms);
5949 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5950 connection_.GetTimeoutAlarm()->Fire();
5951 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5952 EXPECT_FALSE(connection_.connected());
5953 EXPECT_EQ(1, connection_close_frame_count_);
5954 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5955 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
5956}
5957
Bence Békybac04052022-04-07 15:44:29 -04005958TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5959 // Same test as above, but having open streams causes a connection close
5960 // to be sent.
5961 EXPECT_TRUE(connection_.connected());
5962 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5963 QuicConfig config;
5964
5965 // Create a handshake message that also enables silent close.
5966 CryptoHandshakeMessage msg;
5967 std::string error_details;
5968 QuicConfig client_config;
5969 client_config.SetInitialStreamFlowControlWindowToSend(
5970 kInitialStreamFlowControlWindowForTest);
5971 client_config.SetInitialSessionFlowControlWindowToSend(
5972 kInitialSessionFlowControlWindowForTest);
5973 client_config.SetIdleNetworkTimeout(
5974 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5975 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5976 const QuicErrorCode error =
5977 config.ProcessPeerHello(msg, CLIENT, &error_details);
5978 EXPECT_THAT(error, IsQuicNoError());
5979
5980 if (connection_.version().UsesTls()) {
5981 QuicConfigPeer::SetReceivedOriginalConnectionId(
5982 &config, connection_.connection_id());
5983 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5984 &config, connection_.connection_id());
5985 }
5986 connection_.SetFromConfig(config);
5987
5988 const QuicTime::Delta default_idle_timeout =
5989 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5990 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5991 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5992
5993 // When we send a packet, the timeout will change to 5ms +
5994 // kInitialIdleTimeoutSecs.
5995 clock_.AdvanceTime(five_ms);
5996 SendStreamDataToPeer(
5997 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5998 0, FIN, nullptr);
5999 EXPECT_EQ(default_timeout + five_ms,
6000 connection_.GetTimeoutAlarm()->deadline());
6001
6002 // Indicate streams are still open.
6003 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
6004 .WillRepeatedly(Return(true));
6005 if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) {
6006 EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return(""));
6007 }
6008
6009 // This time, we should time out and send a connection close due to the TLP.
6010 EXPECT_CALL(visitor_,
6011 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6012 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6013 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
6014 clock_.ApproximateNow() + five_ms);
6015 connection_.GetTimeoutAlarm()->Fire();
6016 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6017 EXPECT_FALSE(connection_.connected());
6018 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6019}
6020
6021TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
6022 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6023 EXPECT_TRUE(connection_.connected());
6024 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6025 QuicConfig config;
6026 connection_.SetFromConfig(config);
6027
6028 const QuicTime::Delta initial_idle_timeout =
6029 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6030 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6031 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6032
6033 connection_.SendStreamDataWithString(
6034 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6035 0, NO_FIN);
6036 connection_.SendStreamDataWithString(
6037 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6038 3, NO_FIN);
6039
6040 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6041 clock_.AdvanceTime(five_ms);
6042
6043 // When we receive a packet, the timeout will change to 5ms +
6044 // kInitialIdleTimeoutSecs.
6045 QuicAckFrame ack = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07006046 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006047 ProcessAckPacket(&ack);
6048
6049 // The original alarm will fire. We should not time out because we had a
6050 // network event at t=5ms. The alarm will reregister.
6051 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6052 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6053 EXPECT_TRUE(connection_.connected());
6054 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6055 EXPECT_EQ(default_timeout + five_ms,
6056 connection_.GetTimeoutAlarm()->deadline());
6057
6058 // This time, we should time out.
6059 EXPECT_CALL(visitor_,
6060 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6061 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6062 clock_.AdvanceTime(five_ms);
6063 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6064 connection_.GetTimeoutAlarm()->Fire();
6065 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6066 EXPECT_FALSE(connection_.connected());
6067 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6068}
6069
6070TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6071 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6072 EXPECT_TRUE(connection_.connected());
6073 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6074 QuicConfig config;
6075 connection_.SetFromConfig(config);
6076
6077 const QuicTime::Delta initial_idle_timeout =
6078 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6079 connection_.SetNetworkTimeouts(
6080 QuicTime::Delta::Infinite(),
6081 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
6082 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6083 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6084
6085 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6086 connection_.SendStreamDataWithString(
6087 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6088 0, NO_FIN);
6089 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6090 connection_.SendStreamDataWithString(
6091 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6092 3, NO_FIN);
6093
6094 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6095
6096 clock_.AdvanceTime(five_ms);
6097
6098 // When we receive a packet, the timeout will change to 5ms +
6099 // kInitialIdleTimeoutSecs.
6100 QuicAckFrame ack = InitAckFrame(2);
martindukeba002452023-03-21 08:10:46 -07006101 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006102 ProcessAckPacket(&ack);
6103
6104 // The original alarm will fire. We should not time out because we had a
6105 // network event at t=5ms. The alarm will reregister.
6106 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6107 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6108 EXPECT_TRUE(connection_.connected());
6109 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6110 EXPECT_EQ(default_timeout + five_ms,
6111 connection_.GetTimeoutAlarm()->deadline());
6112
6113 // Now, send packets while advancing the time and verify that the connection
6114 // eventually times out.
6115 EXPECT_CALL(visitor_,
6116 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6117 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6118 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6119 QUIC_LOG(INFO) << "sending data packet";
6120 connection_.SendStreamDataWithString(
6121 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6122 "foo", 0, NO_FIN);
6123 connection_.GetTimeoutAlarm()->Fire();
6124 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6125 }
6126 EXPECT_FALSE(connection_.connected());
6127 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6128 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6129}
6130
Bence Békybac04052022-04-07 15:44:29 -04006131TEST_P(QuicConnectionTest, SendScheduler) {
6132 // Test that if we send a packet without delay, it is not queued.
6133 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6134 std::unique_ptr<QuicPacket> packet =
6135 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6136 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6137 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6138 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6139 HAS_RETRANSMITTABLE_DATA, false, false);
6140 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6141}
6142
6143TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6144 // Test that the connection does not crash when it fails to send the first
6145 // packet at which point self_address_ might be uninitialized.
6146 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6147 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
6148 std::unique_ptr<QuicPacket> packet =
6149 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6150 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6151 writer_->SetShouldWriteFail();
6152 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6153 HAS_RETRANSMITTABLE_DATA, false, false);
6154}
6155
6156TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6157 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6158 std::unique_ptr<QuicPacket> packet =
6159 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6160 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6161 BlockOnNextWrite();
6162 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6163 .Times(0);
6164 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6165 HAS_RETRANSMITTABLE_DATA, false, false);
6166 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6167}
6168
6169TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
6170 // Queue the first packet.
6171 size_t payload_length = connection_.max_packet_length();
6172 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
6173 const std::string payload(payload_length, 'a');
6174 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6175 connection_.version().transport_version, Perspective::IS_CLIENT));
6176 EXPECT_EQ(0u, connection_
6177 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6178 NO_FIN)
6179 .bytes_consumed);
6180 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6181}
6182
6183TEST_P(QuicConnectionTest, SendingThreePackets) {
6184 // Make the payload twice the size of the packet, so 3 packets are written.
6185 size_t total_payload_length = 2 * connection_.max_packet_length();
6186 const std::string payload(total_payload_length, 'a');
6187 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6188 connection_.version().transport_version, Perspective::IS_CLIENT));
6189 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6190 EXPECT_EQ(payload.size(), connection_
6191 .SendStreamDataWithString(first_bidi_stream_id,
6192 payload, 0, NO_FIN)
6193 .bytes_consumed);
6194}
6195
6196TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6197 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -04006198 // Set up a larger payload than will fit in one packet.
6199 const std::string payload(connection_.max_packet_length(), 'a');
6200 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6201
6202 // Now send some packets with no truncation.
6203 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6204 EXPECT_EQ(payload.size(),
6205 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6206 .bytes_consumed);
6207 // Track the size of the second packet here. The overhead will be the largest
6208 // we see in this test, due to the non-truncated connection id.
6209 size_t non_truncated_packet_size = writer_->last_packet_size();
6210
6211 // Change to a 0 byte connection id.
6212 QuicConfig config;
6213 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6214 connection_.SetFromConfig(config);
6215 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6216 EXPECT_EQ(payload.size(),
6217 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6218 .bytes_consumed);
fayangfc04b8a2023-05-18 09:26:25 -07006219 // Short header packets sent from server omit connection ID already, and
6220 // stream offset size increases from 0 to 2.
6221 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
Bence Békybac04052022-04-07 15:44:29 -04006222}
6223
6224TEST_P(QuicConnectionTest, SendDelayedAck) {
6225 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6226 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6227 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006228 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006229 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6230 peer_framer_.SetEncrypter(
6231 ENCRYPTION_ZERO_RTT,
6232 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006233 // Process a packet from the non-crypto stream.
6234 frame1_.stream_id = 3;
6235
6236 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6237 // instead of ENCRYPTION_INITIAL.
6238 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6239 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6240
6241 // Check if delayed ack timer is running for the expected interval.
6242 EXPECT_TRUE(connection_.HasPendingAcks());
6243 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6244 // Simulate delayed ack alarm firing.
6245 clock_.AdvanceTime(DefaultDelayedAckTime());
6246 connection_.GetAckAlarm()->Fire();
6247 // Check that ack is sent and that delayed ack alarm is reset.
6248 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006249 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6250 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006251 EXPECT_FALSE(writer_->ack_frames().empty());
6252 EXPECT_FALSE(connection_.HasPendingAcks());
6253}
6254
6255TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6256 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6257
6258 const size_t kMinRttMs = 40;
6259 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6260 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6261 QuicTime::Delta::Zero(), QuicTime::Zero());
6262 // The ack time should be based on min_rtt/4, since it's less than the
6263 // default delayed ack time.
6264 QuicTime ack_time = clock_.ApproximateNow() +
6265 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6266 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6267 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006268 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006269 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6270 peer_framer_.SetEncrypter(
6271 ENCRYPTION_ZERO_RTT,
6272 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006273 // Process a packet from the non-crypto stream.
6274 frame1_.stream_id = 3;
6275
6276 // Process all the initial packets in order so there aren't missing packets.
6277 uint64_t kFirstDecimatedPacket = 101;
6278 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6279 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6280 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6281 }
6282 EXPECT_FALSE(connection_.HasPendingAcks());
6283 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6284 // instead of ENCRYPTION_INITIAL.
6285 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6286 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6287 ENCRYPTION_ZERO_RTT);
6288
6289 // Check if delayed ack timer is running for the expected interval.
6290 EXPECT_TRUE(connection_.HasPendingAcks());
6291 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6292
6293 // The 10th received packet causes an ack to be sent.
6294 for (int i = 0; i < 9; ++i) {
6295 EXPECT_TRUE(connection_.HasPendingAcks());
6296 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6297 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6298 ENCRYPTION_ZERO_RTT);
6299 }
6300 // Check that ack is sent and that delayed ack alarm is reset.
6301 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006302 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6303 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006304 EXPECT_FALSE(writer_->ack_frames().empty());
6305 EXPECT_FALSE(connection_.HasPendingAcks());
6306}
6307
6308TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6309 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6310 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6311 QuicConfig config;
6312 QuicTagVector connection_options;
6313 // No limit on the number of packets received before sending an ack.
6314 connection_options.push_back(kAKDU);
6315 config.SetConnectionOptionsToSend(connection_options);
6316 connection_.SetFromConfig(config);
6317
6318 const size_t kMinRttMs = 40;
6319 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6320 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6321 QuicTime::Delta::Zero(), QuicTime::Zero());
6322 // The ack time should be based on min_rtt/4, since it's less than the
6323 // default delayed ack time.
6324 QuicTime ack_time = clock_.ApproximateNow() +
6325 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6326 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6327 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006328 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006329 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6330 peer_framer_.SetEncrypter(
6331 ENCRYPTION_ZERO_RTT,
6332 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006333 // Process a packet from the non-crypto stream.
6334 frame1_.stream_id = 3;
6335
6336 // Process all the initial packets in order so there aren't missing packets.
6337 uint64_t kFirstDecimatedPacket = 101;
6338 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6339 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6340 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6341 }
6342 EXPECT_FALSE(connection_.HasPendingAcks());
6343 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6344 // instead of ENCRYPTION_INITIAL.
6345 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6346 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6347 ENCRYPTION_ZERO_RTT);
6348
6349 // Check if delayed ack timer is running for the expected interval.
6350 EXPECT_TRUE(connection_.HasPendingAcks());
6351 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6352
6353 // 18 packets will not cause an ack to be sent. 19 will because when
6354 // stop waiting frames are in use, we ack every 20 packets no matter what.
6355 for (int i = 0; i < 18; ++i) {
6356 EXPECT_TRUE(connection_.HasPendingAcks());
6357 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6358 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6359 ENCRYPTION_ZERO_RTT);
6360 }
6361 // The delayed ack timer should still be set to the expected deadline.
6362 EXPECT_TRUE(connection_.HasPendingAcks());
6363 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6364}
6365
6366TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6367 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6368 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6369
6370 const size_t kMinRttMs = 40;
6371 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6372 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6373 QuicTime::Delta::Zero(), QuicTime::Zero());
6374 // The ack time should be based on min_rtt/8, since it's less than the
6375 // default delayed ack time.
6376 QuicTime ack_time = clock_.ApproximateNow() +
6377 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6378 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6379 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006380 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006381 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6382 peer_framer_.SetEncrypter(
6383 ENCRYPTION_ZERO_RTT,
6384 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006385 // Process a packet from the non-crypto stream.
6386 frame1_.stream_id = 3;
6387
6388 // Process all the initial packets in order so there aren't missing packets.
6389 uint64_t kFirstDecimatedPacket = 101;
6390 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6391 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6392 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6393 }
6394 EXPECT_FALSE(connection_.HasPendingAcks());
6395 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6396 // instead of ENCRYPTION_INITIAL.
6397 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6398 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6399 ENCRYPTION_ZERO_RTT);
6400
6401 // Check if delayed ack timer is running for the expected interval.
6402 EXPECT_TRUE(connection_.HasPendingAcks());
6403 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6404
6405 // The 10th received packet causes an ack to be sent.
6406 for (int i = 0; i < 9; ++i) {
6407 EXPECT_TRUE(connection_.HasPendingAcks());
6408 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6409 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6410 ENCRYPTION_ZERO_RTT);
6411 }
6412 // Check that ack is sent and that delayed ack alarm is reset.
6413 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006414 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6415 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006416 EXPECT_FALSE(writer_->ack_frames().empty());
6417 EXPECT_FALSE(connection_.HasPendingAcks());
6418}
6419
6420TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6421 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6422 ProcessPacket(1);
6423 // Check that ack is sent and that delayed ack alarm is set.
6424 EXPECT_TRUE(connection_.HasPendingAcks());
6425 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6426 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6427
6428 // Completing the handshake as the server does nothing.
6429 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6430 connection_.OnHandshakeComplete();
6431 EXPECT_TRUE(connection_.HasPendingAcks());
6432 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6433
6434 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6435 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6436 connection_.OnHandshakeComplete();
6437 EXPECT_TRUE(connection_.HasPendingAcks());
6438 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6439 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6440 connection_.GetAckAlarm()->deadline());
6441 } else {
6442 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6443 }
6444}
6445
6446TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6447 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6448 ProcessPacket(1);
6449 ProcessPacket(2);
6450 // Check that ack is sent and that delayed ack alarm is reset.
6451 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07006452 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6453 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006454 EXPECT_FALSE(writer_->ack_frames().empty());
6455 EXPECT_FALSE(connection_.HasPendingAcks());
6456}
6457
6458TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6459 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6460 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6461 ProcessPacket(2);
fayangfc04b8a2023-05-18 09:26:25 -07006462 size_t frames_per_ack = 1;
Bence Békybac04052022-04-07 15:44:29 -04006463
6464 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6465 ProcessPacket(3);
6466 size_t padding_frame_count = writer_->padding_frames().size();
6467 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6468 EXPECT_FALSE(writer_->ack_frames().empty());
6469 writer_->Reset();
6470
6471 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6472 ProcessPacket(4);
6473 EXPECT_EQ(0u, writer_->frame_count());
6474
6475 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6476 ProcessPacket(5);
6477 padding_frame_count = writer_->padding_frames().size();
6478 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6479 EXPECT_FALSE(writer_->ack_frames().empty());
6480 writer_->Reset();
6481
6482 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6483 // Now only set the timer on the 6th packet, instead of sending another ack.
6484 ProcessPacket(6);
6485 padding_frame_count = writer_->padding_frames().size();
6486 EXPECT_EQ(padding_frame_count, writer_->frame_count());
6487 EXPECT_TRUE(connection_.HasPendingAcks());
6488}
6489
6490TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6491 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6492 EXPECT_CALL(visitor_, OnStreamFrame(_));
martinduke9e0811c2022-12-08 20:35:57 -08006493 peer_framer_.SetEncrypter(
6494 ENCRYPTION_FORWARD_SECURE,
6495 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
6496 SetDecrypter(
6497 ENCRYPTION_FORWARD_SECURE,
6498 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04006499 ProcessDataPacket(1);
6500 connection_.SendStreamDataWithString(
6501 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6502 0, NO_FIN);
6503 // Check that ack is bundled with outgoing data and that delayed ack
6504 // alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006505 EXPECT_EQ(2u, writer_->frame_count());
6506 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006507 EXPECT_FALSE(writer_->ack_frames().empty());
6508 EXPECT_FALSE(connection_.HasPendingAcks());
6509}
6510
6511TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6512 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6513 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6514 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6515 } else {
6516 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6517 }
6518 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6519 connection_.SendCryptoDataWithString("foo", 0);
6520 // Check that ack is bundled with outgoing crypto data.
fayangfc04b8a2023-05-18 09:26:25 -07006521 EXPECT_EQ(3u, writer_->frame_count());
6522 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006523 EXPECT_FALSE(connection_.HasPendingAcks());
6524}
6525
6526TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6527 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6528 ProcessPacket(1);
6529 BlockOnNextWrite();
6530 writer_->set_is_write_blocked_data_buffered(true);
6531 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6532 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6533 } else {
6534 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6535 }
6536 connection_.SendCryptoDataWithString("foo", 0);
6537 EXPECT_TRUE(writer_->IsWriteBlocked());
6538 EXPECT_FALSE(connection_.HasQueuedData());
6539 connection_.SendCryptoDataWithString("bar", 3);
6540 EXPECT_TRUE(writer_->IsWriteBlocked());
6541 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6542 // CRYPTO frames are not flushed when writer is blocked.
6543 EXPECT_FALSE(connection_.HasQueuedData());
6544 } else {
6545 EXPECT_TRUE(connection_.HasQueuedData());
6546 }
6547}
6548
6549TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6550 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6551 EXPECT_FALSE(connection_.HasPendingAcks());
6552 EXPECT_CALL(visitor_, OnCanWrite())
6553 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6554 &connection_, &TestConnection::SendCryptoStreamData)));
6555 // Process a packet from the crypto stream, which is frame1_'s default.
6556 // Receiving the CHLO as packet 2 first will cause the connection to
6557 // immediately send an ack, due to the packet gap.
6558 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6559 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6560 } else {
6561 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6562 }
wubc9fd4292023-08-14 13:00:21 -07006563 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006564 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6565 // Check that ack is sent and that delayed ack alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006566 EXPECT_EQ(3u, writer_->frame_count());
6567 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006568 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6569 EXPECT_EQ(1u, writer_->stream_frames().size());
6570 } else {
6571 EXPECT_EQ(1u, writer_->crypto_frames().size());
6572 }
6573 EXPECT_EQ(1u, writer_->padding_frames().size());
6574 ASSERT_FALSE(writer_->ack_frames().empty());
6575 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6576 EXPECT_FALSE(connection_.HasPendingAcks());
6577}
6578
6579TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6580 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6581 EXPECT_FALSE(connection_.HasPendingAcks());
6582
6583 // Process two packets from the crypto stream, which is frame1_'s default,
6584 // simulating a 2 packet reject.
6585 {
6586 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6587 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6588 } else {
6589 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6590 }
6591 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6592 // Send the new CHLO when the REJ is processed.
6593 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6594 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6595 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6596 &connection_, &TestConnection::SendCryptoStreamData)));
6597 } else {
6598 EXPECT_CALL(visitor_, OnStreamFrame(_))
6599 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6600 &connection_, &TestConnection::SendCryptoStreamData)));
6601 }
wubc9fd4292023-08-14 13:00:21 -07006602 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006603 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6604 }
6605 // Check that ack is sent and that delayed ack alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006606 EXPECT_EQ(3u, writer_->frame_count());
6607 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006608 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6609 EXPECT_EQ(1u, writer_->stream_frames().size());
6610 } else {
6611 EXPECT_EQ(1u, writer_->crypto_frames().size());
6612 }
6613 EXPECT_EQ(1u, writer_->padding_frames().size());
6614 ASSERT_FALSE(writer_->ack_frames().empty());
6615 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6616 EXPECT_FALSE(connection_.HasPendingAcks());
6617}
6618
6619TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6620 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6621 connection_.SendStreamDataWithString(
6622 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6623 0, NO_FIN);
6624 connection_.SendStreamDataWithString(
6625 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6626 3, NO_FIN);
6627 // Ack the second packet, which will retransmit the first packet.
6628 QuicAckFrame ack = ConstructAckFrame(2, 1);
6629 LostPacketVector lost_packets;
6630 lost_packets.push_back(
6631 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6632 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6633 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
6634 Return(LossDetectionInterface::DetectionStats())));
martindukeba002452023-03-21 08:10:46 -07006635 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006636 ProcessAckPacket(&ack);
6637 size_t padding_frame_count = writer_->padding_frames().size();
6638 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6639 EXPECT_EQ(1u, writer_->stream_frames().size());
6640 writer_->Reset();
6641
6642 // Now ack the retransmission, which will both raise the high water mark
6643 // and see if there is more data to send.
6644 ack = ConstructAckFrame(3, 1);
6645 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07006646 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04006647 ProcessAckPacket(&ack);
6648
6649 // Check that no packet is sent and the ack alarm isn't set.
6650 EXPECT_EQ(0u, writer_->frame_count());
6651 EXPECT_FALSE(connection_.HasPendingAcks());
6652 writer_->Reset();
6653
6654 // Send the same ack, but send both data and an ack together.
6655 ack = ConstructAckFrame(3, 1);
6656 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6657 EXPECT_CALL(visitor_, OnCanWrite())
6658 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6659 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
wubc9fd4292023-08-14 13:00:21 -07006660 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04006661 ProcessAckPacket(&ack);
6662
6663 // Check that ack is bundled with outgoing data and the delayed ack
6664 // alarm is reset.
fayangfc04b8a2023-05-18 09:26:25 -07006665 // Do not ACK acks.
6666 EXPECT_EQ(1u, writer_->frame_count());
6667 EXPECT_TRUE(writer_->ack_frames().empty());
Bence Békybac04052022-04-07 15:44:29 -04006668 EXPECT_EQ(1u, writer_->stream_frames().size());
6669 EXPECT_FALSE(connection_.HasPendingAcks());
6670}
6671
6672TEST_P(QuicConnectionTest, NoAckSentForClose) {
6673 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6674 ProcessPacket(1);
6675 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6676 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6677 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6678 ProcessClosePacket(2);
6679 EXPECT_EQ(1, connection_close_frame_count_);
6680 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6681 IsError(QUIC_PEER_GOING_AWAY));
6682}
6683
6684TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6685 EXPECT_TRUE(connection_.connected());
6686 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6687 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6688 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6689 ConnectionCloseBehavior::SILENT_CLOSE);
6690 EXPECT_FALSE(connection_.connected());
6691 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6692 EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
6693 /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
6694}
6695
6696TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6697 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
6698 if (!IsDefaultTestConfiguration()) {
6699 return;
6700 }
6701
6702 EXPECT_TRUE(connection_.connected());
6703 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6704 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6705 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6706 ConnectionCloseBehavior::SILENT_CLOSE);
6707 EXPECT_FALSE(connection_.connected());
6708 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6709
6710 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6711 .Times(0);
6712
6713 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6714 writer_.get(), connection_.peer_address()),
6715 "Not sending connectivity probing packet as connection is "
6716 "disconnected.");
6717 EXPECT_EQ(1, connection_close_frame_count_);
6718 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6719 IsError(QUIC_PEER_GOING_AWAY));
6720}
6721
6722TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6723 PathProbeTestInit(Perspective::IS_CLIENT);
6724 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6725 // Block next write so that sending connectivity probe will encounter a
6726 // blocked write when send a connectivity probe to the peer.
6727 probing_writer.BlockOnNextWrite();
6728 // Connection will not be marked as write blocked as connectivity probe only
6729 // affects the probing_writer which is not the default.
6730 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6731
6732 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6733 .Times(1);
6734 connection_.SendConnectivityProbingPacket(&probing_writer,
6735 connection_.peer_address());
6736}
6737
6738TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6739 PathProbeTestInit(Perspective::IS_SERVER);
6740 if (version().SupportsAntiAmplificationLimit()) {
6741 QuicConnectionPeer::SetAddressValidated(&connection_);
6742 }
6743
6744 // Block next write so that sending connectivity probe will encounter a
6745 // blocked write when send a connectivity probe to the peer.
6746 writer_->BlockOnNextWrite();
6747 // Connection will be marked as write blocked as server uses the default
6748 // writer to send connectivity probes.
6749 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6750
6751 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6752 .Times(1);
6753 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6754 QuicPathFrameBuffer payload{
6755 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
6756 QuicConnection::ScopedPacketFlusher flusher(&connection_);
6757 connection_.SendPathChallenge(
6758 payload, connection_.self_address(), connection_.peer_address(),
6759 connection_.effective_peer_address(), writer_.get());
6760 } else {
6761 connection_.SendConnectivityProbingPacket(writer_.get(),
6762 connection_.peer_address());
6763 }
6764}
6765
6766TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6767 PathProbeTestInit(Perspective::IS_CLIENT);
6768 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6769 probing_writer.SetShouldWriteFail();
6770
6771 // Connection should not be closed if a connectivity probe is failed to be
6772 // sent.
6773 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6774
6775 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6776 .Times(0);
6777 connection_.SendConnectivityProbingPacket(&probing_writer,
6778 connection_.peer_address());
6779}
6780
6781TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6782 PathProbeTestInit(Perspective::IS_SERVER);
6783
6784 writer_->SetShouldWriteFail();
6785 // Connection should not be closed if a connectivity probe is failed to be
6786 // sent.
6787 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6788
6789 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6790 .Times(0);
6791 connection_.SendConnectivityProbingPacket(writer_.get(),
6792 connection_.peer_address());
6793}
6794
Bence Békybac04052022-04-07 15:44:29 -04006795TEST_P(QuicConnectionTest, IetfStatelessReset) {
Bence Békybac04052022-04-07 15:44:29 -04006796 QuicConfig config;
6797 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6798 kTestStatelessResetToken);
6799 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6800 connection_.SetFromConfig(config);
6801 std::unique_ptr<QuicEncryptedPacket> packet(
6802 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6803 /*received_packet_length=*/100,
6804 kTestStatelessResetToken));
6805 std::unique_ptr<QuicReceivedPacket> received(
6806 ConstructReceivedPacket(*packet, QuicTime::Zero()));
Bence Békybac04052022-04-07 15:44:29 -04006807 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6808 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6809 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6810 EXPECT_EQ(1, connection_close_frame_count_);
6811 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6812 IsError(QUIC_PUBLIC_RESET));
6813}
6814
6815TEST_P(QuicConnectionTest, GoAway) {
6816 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6817 // GoAway is not available in version 99.
6818 return;
6819 }
6820
6821 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6822
6823 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
6824 goaway->last_good_stream_id = 1;
6825 goaway->error_code = QUIC_PEER_GOING_AWAY;
6826 goaway->reason_phrase = "Going away.";
6827 EXPECT_CALL(visitor_, OnGoAway(_));
6828 ProcessGoAwayPacket(goaway);
6829}
6830
6831TEST_P(QuicConnectionTest, WindowUpdate) {
6832 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6833
6834 QuicWindowUpdateFrame window_update;
6835 window_update.stream_id = 3;
6836 window_update.max_data = 1234;
6837 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6838 ProcessFramePacket(QuicFrame(window_update));
6839}
6840
6841TEST_P(QuicConnectionTest, Blocked) {
6842 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6843
6844 QuicBlockedFrame blocked;
6845 blocked.stream_id = 3;
6846 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6847 ProcessFramePacket(QuicFrame(blocked));
6848 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6849 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6850}
6851
6852TEST_P(QuicConnectionTest, ZeroBytePacket) {
6853 // Don't close the connection for zero byte packets.
6854 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6855 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6856 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6857}
6858
Bence Békybac04052022-04-07 15:44:29 -04006859TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
6860 // All supported versions except the one the connection supports.
6861 ParsedQuicVersionVector versions;
6862 for (auto version : AllSupportedVersions()) {
6863 if (version != connection_.version()) {
6864 versions.push_back(version);
6865 }
6866 }
6867
6868 // Send a version negotiation packet.
6869 std::unique_ptr<QuicEncryptedPacket> encrypted(
6870 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07006871 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04006872 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6873 std::unique_ptr<QuicReceivedPacket> received(
6874 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6875 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6876 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6877 // Verify no connection close packet gets sent.
6878 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6879 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6880 EXPECT_FALSE(connection_.connected());
6881 EXPECT_EQ(1, connection_close_frame_count_);
6882 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6883 IsError(QUIC_INVALID_VERSION));
6884}
6885
6886TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiationWithConnectionClose) {
6887 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6888 QuicConfig config;
6889 QuicTagVector connection_options;
6890 connection_options.push_back(kINVC);
6891 config.SetClientConnectionOptions(connection_options);
6892 connection_.SetFromConfig(config);
6893
6894 // All supported versions except the one the connection supports.
6895 ParsedQuicVersionVector versions;
6896 for (auto version : AllSupportedVersions()) {
6897 if (version != connection_.version()) {
6898 versions.push_back(version);
6899 }
6900 }
6901
6902 // Send a version negotiation packet.
6903 std::unique_ptr<QuicEncryptedPacket> encrypted(
6904 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07006905 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04006906 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6907 std::unique_ptr<QuicReceivedPacket> received(
6908 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6909 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6910 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6911 // Verify connection close packet gets sent.
6912 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1u));
6913 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6914 EXPECT_FALSE(connection_.connected());
6915 EXPECT_EQ(1, connection_close_frame_count_);
6916 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6917 IsError(QUIC_INVALID_VERSION));
6918}
6919
6920TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6921 // Send a version negotiation packet with the version the client started with.
6922 // It should be rejected.
6923 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6924 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6925 std::unique_ptr<QuicEncryptedPacket> encrypted(
6926 QuicFramer::BuildVersionNegotiationPacket(
fayangfc04b8a2023-05-18 09:26:25 -07006927 connection_id_, EmptyQuicConnectionId(), /*ietf_quic=*/true,
Bence Békybac04052022-04-07 15:44:29 -04006928 connection_.version().HasLengthPrefixedConnectionIds(),
6929 AllSupportedVersions()));
6930 std::unique_ptr<QuicReceivedPacket> received(
6931 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6932 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6933 EXPECT_EQ(1, connection_close_frame_count_);
6934 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6935 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
6936}
6937
Bence Békybac04052022-04-07 15:44:29 -04006938TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
6939 // Construct a packet with stream frame and connection close frame.
6940 QuicPacketHeader header;
6941 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
6942 header.source_connection_id = connection_id_;
6943 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04006944 } else {
6945 header.destination_connection_id = connection_id_;
fayangfc04b8a2023-05-18 09:26:25 -07006946 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
Bence Békybac04052022-04-07 15:44:29 -04006947 }
6948 header.packet_number = QuicPacketNumber(1);
6949 header.version_flag = false;
6950
6951 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
6952 // This QuicConnectionCloseFrame will default to being for a Google QUIC
6953 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
6954 // depending on the mapping.
6955 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
6956 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
6957 /*transport_close_frame_type=*/0);
6958 QuicFrames frames;
6959 frames.push_back(QuicFrame(frame1_));
6960 frames.push_back(QuicFrame(&qccf));
6961 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6962 EXPECT_TRUE(nullptr != packet);
6963 char buffer[kMaxOutgoingPacketSize];
6964 size_t encrypted_length = peer_framer_.EncryptPayload(
6965 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
6966 kMaxOutgoingPacketSize);
6967
6968 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6969 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6970 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6971 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6972
6973 connection_.ProcessUdpPacket(
6974 kSelfAddress, kPeerAddress,
6975 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6976 EXPECT_EQ(1, connection_close_frame_count_);
6977 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6978 IsError(QUIC_PEER_GOING_AWAY));
6979}
6980
6981TEST_P(QuicConnectionTest, SelectMutualVersion) {
6982 connection_.SetSupportedVersions(AllSupportedVersions());
6983 // Set the connection to speak the lowest quic version.
6984 connection_.set_version(QuicVersionMin());
6985 EXPECT_EQ(QuicVersionMin(), connection_.version());
6986
6987 // Pass in available versions which includes a higher mutually supported
6988 // version. The higher mutually supported version should be selected.
6989 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
6990 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
6991 EXPECT_EQ(QuicVersionMax(), connection_.version());
6992
6993 // Expect that the lowest version is selected.
6994 // Ensure the lowest supported version is less than the max, unless they're
6995 // the same.
6996 ParsedQuicVersionVector lowest_version_vector;
6997 lowest_version_vector.push_back(QuicVersionMin());
6998 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
6999 EXPECT_EQ(QuicVersionMin(), connection_.version());
7000
7001 // Shouldn't be able to find a mutually supported version.
7002 ParsedQuicVersionVector unsupported_version;
7003 unsupported_version.push_back(UnsupportedQuicVersion());
7004 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7005}
7006
7007TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7008 EXPECT_FALSE(writer_->IsWriteBlocked());
7009
7010 // Send a packet.
7011 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7012 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7013 EXPECT_EQ(1u, writer_->packets_write_attempts());
7014
7015 TriggerConnectionClose();
7016 EXPECT_LE(2u, writer_->packets_write_attempts());
7017}
7018
7019TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7020 BlockOnNextWrite();
7021 TriggerConnectionClose();
7022 EXPECT_EQ(1u, writer_->packets_write_attempts());
7023 EXPECT_TRUE(writer_->IsWriteBlocked());
7024}
7025
7026TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7027 BlockOnNextWrite();
7028 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7029 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7030 EXPECT_EQ(1u, writer_->packets_write_attempts());
7031 EXPECT_TRUE(writer_->IsWriteBlocked());
7032 TriggerConnectionClose();
7033 EXPECT_EQ(1u, writer_->packets_write_attempts());
7034}
7035
7036TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7037 PathProbeTestInit(Perspective::IS_CLIENT);
7038 MockQuicConnectionDebugVisitor debug_visitor;
7039 connection_.set_debug_visitor(&debug_visitor);
7040
wub92727922023-07-13 08:47:39 -07007041 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007042 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7043
wub92727922023-07-13 08:47:39 -07007044 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007045 connection_.SendConnectivityProbingPacket(writer_.get(),
7046 connection_.peer_address());
7047}
7048
7049TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7050 QuicPacketHeader header;
7051 header.packet_number = QuicPacketNumber(1);
fayangfc04b8a2023-05-18 09:26:25 -07007052 header.form = IETF_QUIC_LONG_HEADER_PACKET;
Bence Békybac04052022-04-07 15:44:29 -04007053
7054 MockQuicConnectionDebugVisitor debug_visitor;
7055 connection_.set_debug_visitor(&debug_visitor);
7056 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header), _, _)).Times(1);
7057 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7058 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7059 connection_.OnPacketHeader(header);
7060}
7061
7062TEST_P(QuicConnectionTest, Pacing) {
7063 TestConnection server(connection_id_, kPeerAddress, kSelfAddress,
7064 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07007065 Perspective::IS_SERVER, version(),
7066 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04007067 TestConnection client(connection_id_, kSelfAddress, kPeerAddress,
7068 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07007069 Perspective::IS_CLIENT, version(),
7070 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04007071 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7072 static_cast<const QuicSentPacketManager*>(
7073 &client.sent_packet_manager())));
7074 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7075 static_cast<const QuicSentPacketManager*>(
7076 &server.sent_packet_manager())));
7077}
7078
7079TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7080 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7081
7082 // Send a WINDOW_UPDATE frame.
7083 QuicWindowUpdateFrame window_update;
7084 window_update.stream_id = 3;
7085 window_update.max_data = 1234;
7086 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7087 ProcessFramePacket(QuicFrame(window_update));
7088
7089 // Ensure that this has caused the ACK alarm to be set.
7090 EXPECT_TRUE(connection_.HasPendingAcks());
7091}
7092
7093TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7094 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7095
7096 // Send a BLOCKED frame.
7097 QuicBlockedFrame blocked;
7098 blocked.stream_id = 3;
7099 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7100 ProcessFramePacket(QuicFrame(blocked));
7101
7102 // Ensure that this has caused the ACK alarm to be set.
7103 EXPECT_TRUE(connection_.HasPendingAcks());
7104}
7105
7106TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7107 // Enable pacing.
7108 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7109 QuicConfig config;
7110 connection_.SetFromConfig(config);
7111
7112 // Send two packets. One packet is not sufficient because if it gets acked,
7113 // there will be no packets in flight after that and the pacer will always
7114 // allow the next packet in that situation.
7115 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7116 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7117 connection_.SendStreamDataWithString(
7118 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7119 0, NO_FIN);
7120 connection_.SendStreamDataWithString(
7121 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7122 3, NO_FIN);
7123 connection_.OnCanWrite();
7124
7125 // Schedule the next packet for a few milliseconds in future.
7126 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7127 QuicTime scheduled_pacing_time =
7128 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7129 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7130 scheduled_pacing_time);
7131
7132 // Send a packet and have it be blocked by congestion control.
7133 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7134 connection_.SendStreamDataWithString(
7135 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7136 6, NO_FIN);
7137 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7138
7139 // Process an ack and the send alarm will be set to the new 5ms delay.
7140 QuicAckFrame ack = InitAckFrame(1);
7141 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07007142 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007143 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7144 ProcessAckPacket(&ack);
7145 size_t padding_frame_count = writer_->padding_frames().size();
7146 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
7147 EXPECT_EQ(1u, writer_->stream_frames().size());
7148 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7149 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7150 writer_->Reset();
7151}
7152
7153TEST_P(QuicConnectionTest, SendAcksImmediately) {
7154 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7155 return;
7156 }
7157 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7158 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7159 ProcessDataPacket(1);
7160 CongestionBlockWrites();
7161 SendAckPacketToPeer();
7162}
7163
7164TEST_P(QuicConnectionTest, SendPingImmediately) {
7165 MockQuicConnectionDebugVisitor debug_visitor;
7166 connection_.set_debug_visitor(&debug_visitor);
7167
7168 CongestionBlockWrites();
7169 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7170 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wub92727922023-07-13 08:47:39 -07007171 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007172 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7173 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7174 EXPECT_FALSE(connection_.HasQueuedData());
7175}
7176
7177TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7178 MockQuicConnectionDebugVisitor debug_visitor;
7179 connection_.set_debug_visitor(&debug_visitor);
7180
7181 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7182 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wub92727922023-07-13 08:47:39 -07007183 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -04007184 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
QUICHE team1a271082022-05-18 10:22:22 -07007185 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04007186 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7187 EXPECT_FALSE(connection_.HasQueuedData());
7188}
7189
7190TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7191 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7192 return;
7193 }
7194 MockQuicConnectionDebugVisitor debug_visitor;
7195 connection_.set_debug_visitor(&debug_visitor);
QUICHE team1a271082022-05-18 10:22:22 -07007196 QuicBlockedFrame blocked(1, 3, 0);
Bence Békybac04052022-04-07 15:44:29 -04007197
7198 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
wub92727922023-07-13 08:47:39 -07007199 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(0);
Bence Békybac04052022-04-07 15:44:29 -04007200 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7201 connection_.SendControlFrame(QuicFrame(blocked));
7202 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7203 EXPECT_FALSE(connection_.HasQueuedData());
7204}
7205
7206TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7207 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7208 if (!IsDefaultTestConfiguration()) {
7209 return;
7210 }
7211
vasilvvac2e30d2022-06-02 14:26:59 -07007212 EXPECT_QUIC_BUG(
7213 {
7214 EXPECT_CALL(visitor_,
7215 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7216 .WillOnce(
7217 Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7218 connection_.SaveAndSendStreamData(3, {}, 0, FIN);
7219 EXPECT_FALSE(connection_.connected());
7220 EXPECT_EQ(1, connection_close_frame_count_);
7221 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7222 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
7223 },
7224 "Cannot send stream data with level: ENCRYPTION_INITIAL");
Bence Békybac04052022-04-07 15:44:29 -04007225}
7226
7227TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7228 EXPECT_TRUE(connection_.connected());
7229 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7230
7231 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7232 connection_.SendCryptoStreamData();
7233
7234 // Verify retransmission timer is correctly set after crypto packet has been
7235 // sent.
7236 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7237 QuicTime retransmission_time =
7238 QuicConnectionPeer::GetSentPacketManager(&connection_)
7239 ->GetRetransmissionTime();
7240 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7241 EXPECT_EQ(retransmission_time,
7242 connection_.GetRetransmissionAlarm()->deadline());
7243
7244 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7245 connection_.GetRetransmissionAlarm()->Fire();
7246}
7247
7248// Includes regression test for b/69979024.
7249TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
7250 EXPECT_TRUE(connection_.connected());
7251 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7252 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007253 EXPECT_CALL(visitor_, GetHandshakeState())
7254 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7255 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007256
7257 const char data[] = "data";
7258 size_t data_size = strlen(data);
7259 QuicStreamOffset offset = 0;
7260
7261 for (int i = 0; i < 2; ++i) {
7262 // Send a packet. Now there's a retransmittable packet on the wire, so the
7263 // path degrading detection should be set.
7264 connection_.SendStreamDataWithString(
7265 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7266 offset, NO_FIN);
7267 offset += data_size;
7268 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7269 // Check the deadline of the path degrading detection.
7270 QuicTime::Delta delay =
7271 QuicConnectionPeer::GetSentPacketManager(&connection_)
7272 ->GetPathDegradingDelay();
7273 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7274 clock_.ApproximateNow());
7275
7276 // Send a second packet. The path degrading detection's deadline should
7277 // remain the same.
7278 // Regression test for b/69979024.
7279 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7280 QuicTime prev_deadline =
7281 connection_.GetBlackholeDetectorAlarm()->deadline();
7282 connection_.SendStreamDataWithString(
7283 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7284 offset, NO_FIN);
7285 offset += data_size;
7286 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7287 EXPECT_EQ(prev_deadline,
7288 connection_.GetBlackholeDetectorAlarm()->deadline());
7289
7290 // Now receive an ACK of the first packet. This should advance the path
7291 // degrading detection's deadline since forward progress has been made.
7292 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7293 if (i == 0) {
7294 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7295 }
martindukeba002452023-03-21 08:10:46 -07007296 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007297 QuicAckFrame frame = InitAckFrame(
7298 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7299 ProcessAckPacket(&frame);
7300 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7301 // Check the deadline of the path degrading detection.
7302 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7303 ->GetPathDegradingDelay();
7304 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7305 clock_.ApproximateNow());
7306
7307 if (i == 0) {
7308 // Now receive an ACK of the second packet. Since there are no more
7309 // retransmittable packets on the wire, this should cancel the path
7310 // degrading detection.
7311 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007312 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007313 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7314 ProcessAckPacket(&frame);
7315 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7316 } else {
7317 // Advance time to the path degrading alarm's deadline and simulate
7318 // firing the alarm.
7319 clock_.AdvanceTime(delay);
7320 EXPECT_CALL(visitor_, OnPathDegrading());
7321 connection_.PathDegradingTimeout();
7322 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7323 }
7324 }
7325 EXPECT_TRUE(connection_.IsPathDegrading());
7326}
7327
7328TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7329 const QuicTime::Delta retransmittable_on_wire_timeout =
7330 QuicTime::Delta::FromMilliseconds(50);
7331 connection_.set_initial_retransmittable_on_wire_timeout(
7332 retransmittable_on_wire_timeout);
7333
7334 EXPECT_TRUE(connection_.connected());
7335 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7336 .WillRepeatedly(Return(true));
7337
7338 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7339 EXPECT_FALSE(connection_.IsPathDegrading());
7340 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
fayang59e518a2022-11-29 11:16:45 -08007341 EXPECT_CALL(visitor_, GetHandshakeState())
7342 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7343 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007344
7345 const char data[] = "data";
7346 size_t data_size = strlen(data);
7347 QuicStreamOffset offset = 0;
7348
7349 // Send a packet.
7350 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7351 offset += data_size;
7352 // Now there's a retransmittable packet on the wire, so the path degrading
7353 // alarm should be set.
7354 // The retransmittable-on-wire alarm should not be set.
7355 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7356 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7357 ->GetPathDegradingDelay();
7358 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7359 clock_.ApproximateNow());
7360 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7361 // The ping alarm is set for the ping timeout, not the shorter
7362 // retransmittable_on_wire_timeout.
7363 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7364 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7365 EXPECT_EQ(ping_delay,
7366 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7367
7368 // Now receive an ACK of the packet.
7369 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7370 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007371 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007372 QuicAckFrame frame =
7373 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7374 ProcessAckPacket(&frame);
7375 // No more retransmittable packets on the wire, so the path degrading alarm
7376 // should be cancelled, and the ping alarm should be set to the
7377 // retransmittable_on_wire_timeout.
7378 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7379 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7380 EXPECT_EQ(retransmittable_on_wire_timeout,
7381 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7382
7383 // Simulate firing the ping alarm and sending a PING.
7384 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7385 connection_.GetPingAlarm()->Fire();
7386
7387 // Now there's a retransmittable packet (PING) on the wire, so the path
7388 // degrading alarm should be set.
fayang59e518a2022-11-29 11:16:45 -08007389 ASSERT_TRUE(connection_.PathDegradingDetectionInProgress());
Bence Békybac04052022-04-07 15:44:29 -04007390 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7391 ->GetPathDegradingDelay();
7392 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7393 clock_.ApproximateNow());
7394}
7395
7396TEST_P(QuicConnectionTest, ServerRetransmittableOnWire) {
7397 set_perspective(Perspective::IS_SERVER);
7398 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7399 SetQuicReloadableFlag(quic_enable_server_on_wire_ping, true);
7400
7401 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7402 QuicConfig config;
7403 QuicTagVector connection_options;
7404 connection_options.push_back(kSRWP);
7405 config.SetInitialReceivedConnectionOptions(connection_options);
7406 connection_.SetFromConfig(config);
7407
7408 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7409 .WillRepeatedly(Return(true));
7410
7411 ProcessPacket(1);
7412
7413 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7414 QuicTime::Delta ping_delay = QuicTime::Delta::FromMilliseconds(200);
7415 EXPECT_EQ(ping_delay,
7416 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7417
7418 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
7419 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
7420 // Verify PING alarm gets cancelled.
7421 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7422
7423 // Now receive an ACK of the packet.
7424 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
martindukeba002452023-03-21 08:10:46 -07007425 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007426 QuicAckFrame frame =
7427 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7428 ProcessAckPacket(2, &frame);
7429 // Verify PING alarm gets scheduled.
7430 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7431 EXPECT_EQ(ping_delay,
7432 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7433}
7434
fayangf6607db2022-04-21 18:10:41 -07007435TEST_P(QuicConnectionTest, RetransmittableOnWireSendFirstPacket) {
fayang9b455102022-11-29 18:19:20 -08007436 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007437 return;
7438 }
7439 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7440 .WillRepeatedly(Return(true));
7441 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7442
7443 const QuicTime::Delta kRetransmittableOnWireTimeout =
7444 QuicTime::Delta::FromMilliseconds(200);
7445 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7446
7447 connection_.set_initial_retransmittable_on_wire_timeout(
7448 kRetransmittableOnWireTimeout);
7449
7450 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7451 QuicConfig config;
7452 QuicTagVector connection_options;
7453 connection_options.push_back(kROWF);
7454 config.SetClientConnectionOptions(connection_options);
7455 connection_.SetFromConfig(config);
7456
7457 // Send a request.
7458 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7459 // Receive an ACK after 1-RTT.
7460 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007461 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007462 QuicAckFrame frame =
7463 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7464 ProcessAckPacket(&frame);
7465 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7466 EXPECT_EQ(kRetransmittableOnWireTimeout,
7467 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7468 EXPECT_EQ(1u, writer_->packets_write_attempts());
7469
7470 // Fire retransmittable-on-wire alarm.
7471 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7472 connection_.GetPingAlarm()->Fire();
7473 EXPECT_EQ(2u, writer_->packets_write_attempts());
7474 // Verify alarm is set in keep-alive mode.
7475 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7476 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7477 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7478}
7479
7480TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytes) {
fayang9b455102022-11-29 18:19:20 -08007481 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007482 return;
7483 }
7484 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7485 .WillRepeatedly(Return(true));
7486 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7487
7488 const QuicTime::Delta kRetransmittableOnWireTimeout =
7489 QuicTime::Delta::FromMilliseconds(200);
7490 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7491
7492 connection_.set_initial_retransmittable_on_wire_timeout(
7493 kRetransmittableOnWireTimeout);
7494
7495 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7496 QuicConfig config;
7497 QuicTagVector connection_options;
7498 connection_options.push_back(kROWR);
7499 config.SetClientConnectionOptions(connection_options);
7500 connection_.SetFromConfig(config);
7501
7502 // Send a request.
7503 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7504 // Receive an ACK after 1-RTT.
7505 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007506 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007507 QuicAckFrame frame =
7508 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7509 ProcessAckPacket(&frame);
7510 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7511 EXPECT_EQ(kRetransmittableOnWireTimeout,
7512 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7513 EXPECT_EQ(1u, writer_->packets_write_attempts());
7514
7515 // Fire retransmittable-on-wire alarm.
7516 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7517 // Next packet is not processable by the framer in the test writer.
7518 ExpectNextPacketUnprocessable();
7519 connection_.GetPingAlarm()->Fire();
7520 EXPECT_EQ(2u, writer_->packets_write_attempts());
7521 // Verify alarm is set in keep-alive mode.
7522 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7523 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7524 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7525}
7526
7527TEST_P(QuicConnectionTest,
7528 RetransmittableOnWireSendRandomBytesWithWriterBlocked) {
fayang9b455102022-11-29 18:19:20 -08007529 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007530 return;
7531 }
7532 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7533 .WillRepeatedly(Return(true));
7534 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7535 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7536
7537 const QuicTime::Delta kRetransmittableOnWireTimeout =
7538 QuicTime::Delta::FromMilliseconds(200);
7539 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7540
7541 connection_.set_initial_retransmittable_on_wire_timeout(
7542 kRetransmittableOnWireTimeout);
7543
7544 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7545 QuicConfig config;
7546 QuicTagVector connection_options;
7547 connection_options.push_back(kROWR);
7548 config.SetClientConnectionOptions(connection_options);
7549 connection_.SetFromConfig(config);
7550
7551 // Send a request.
7552 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7553 // Receive an ACK after 1-RTT.
7554 clock_.AdvanceTime(kTestRtt);
martindukeba002452023-03-21 08:10:46 -07007555 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
fayangf6607db2022-04-21 18:10:41 -07007556 QuicAckFrame frame =
7557 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7558 ProcessAckPacket(&frame);
7559 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7560 EXPECT_EQ(kRetransmittableOnWireTimeout,
7561 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7562 EXPECT_EQ(1u, writer_->packets_write_attempts());
7563 // Receive an out of order data packet and block the ACK packet.
7564 BlockOnNextWrite();
7565 ProcessDataPacket(3);
7566 EXPECT_EQ(2u, writer_->packets_write_attempts());
7567 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7568
7569 // Fire retransmittable-on-wire alarm.
7570 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7571 connection_.GetPingAlarm()->Fire();
7572 // Verify the random bytes packet gets queued.
7573 EXPECT_EQ(2u, connection_.NumQueuedPackets());
7574}
7575
Bence Békybac04052022-04-07 15:44:29 -04007576// This test verifies that the connection marks path as degrading and does not
7577// spin timer to detect path degrading when a new packet is sent on the
7578// degraded path.
7579TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
7580 EXPECT_TRUE(connection_.connected());
7581 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7582 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007583 EXPECT_CALL(visitor_, GetHandshakeState())
7584 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7585 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007586
7587 const char data[] = "data";
7588 size_t data_size = strlen(data);
7589 QuicStreamOffset offset = 0;
7590
7591 // Send the first packet. Now there's a retransmittable packet on the wire, so
7592 // the path degrading alarm should be set.
7593 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7594 offset += data_size;
7595 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7596 // Check the deadline of the path degrading detection.
7597 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7598 ->GetPathDegradingDelay();
7599 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7600 clock_.ApproximateNow());
7601
7602 // Send a second packet. The path degrading detection's deadline should remain
7603 // the same.
7604 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7605 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7606 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7607 offset += data_size;
7608 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7609 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7610
7611 // Now receive an ACK of the first packet. This should advance the path
7612 // degrading detection's deadline since forward progress has been made.
7613 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7614 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007615 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007616 QuicAckFrame frame =
7617 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7618 ProcessAckPacket(&frame);
7619 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7620 // Check the deadline of the path degrading alarm.
7621 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7622 ->GetPathDegradingDelay();
7623 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7624 clock_.ApproximateNow());
7625
7626 // Advance time to the path degrading detection's deadline and simulate
7627 // firing the path degrading detection. This path will be considered as
7628 // degrading.
7629 clock_.AdvanceTime(delay);
7630 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7631 connection_.PathDegradingTimeout();
7632 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7633 EXPECT_TRUE(connection_.IsPathDegrading());
7634
7635 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7636 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7637 // Send a third packet. The path degrading detection is no longer set but path
7638 // should still be marked as degrading.
7639 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7640 offset += data_size;
7641 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7642 EXPECT_TRUE(connection_.IsPathDegrading());
7643}
7644
fayang59e518a2022-11-29 11:16:45 -08007645TEST_P(QuicConnectionTest, NoPathDegradingDetectionBeforeHandshakeConfirmed) {
7646 EXPECT_TRUE(connection_.connected());
7647 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7648 EXPECT_FALSE(connection_.IsPathDegrading());
7649 EXPECT_CALL(visitor_, GetHandshakeState())
7650 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
7651
7652 connection_.SendStreamDataWithString(1, "data", 0, NO_FIN);
7653 if (GetQuicReloadableFlag(
7654 quic_no_path_degrading_before_handshake_confirmed) &&
7655 connection_.SupportsMultiplePacketNumberSpaces()) {
7656 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7657 } else {
7658 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7659 }
7660}
7661
Bence Békybac04052022-04-07 15:44:29 -04007662// This test verifies that the connection unmarks path as degrarding and spins
7663// the timer to detect future path degrading when forward progress is made
7664// after path has been marked degrading.
7665TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7666 EXPECT_TRUE(connection_.connected());
7667 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7668 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007669 EXPECT_CALL(visitor_, GetHandshakeState())
7670 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7671 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007672
7673 const char data[] = "data";
7674 size_t data_size = strlen(data);
7675 QuicStreamOffset offset = 0;
7676
7677 // Send the first packet. Now there's a retransmittable packet on the wire, so
7678 // the path degrading alarm should be set.
7679 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7680 offset += data_size;
7681 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7682 // Check the deadline of the path degrading alarm.
7683 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7684 ->GetPathDegradingDelay();
7685 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7686 clock_.ApproximateNow());
7687
7688 // Send a second packet. The path degrading alarm's deadline should remain
7689 // the same.
7690 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7691 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7692 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7693 offset += data_size;
7694 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7695 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7696
7697 // Now receive an ACK of the first packet. This should advance the path
7698 // degrading alarm's deadline since forward progress has been made.
7699 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7700 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07007701 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007702 QuicAckFrame frame =
7703 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7704 ProcessAckPacket(&frame);
7705 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7706 // Check the deadline of the path degrading alarm.
7707 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7708 ->GetPathDegradingDelay();
7709 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7710 clock_.ApproximateNow());
7711
7712 // Advance time to the path degrading alarm's deadline and simulate
7713 // firing the alarm.
7714 clock_.AdvanceTime(delay);
7715 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7716 connection_.PathDegradingTimeout();
7717 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7718 EXPECT_TRUE(connection_.IsPathDegrading());
7719
7720 // Send a third packet. The path degrading alarm is no longer set but path
7721 // should still be marked as degrading.
7722 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7723 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7724 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7725 offset += data_size;
7726 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7727 EXPECT_TRUE(connection_.IsPathDegrading());
7728
7729 // Now receive an ACK of the second packet. This should unmark the path as
7730 // degrading. And will set a timer to detect new path degrading.
7731 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007732 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007733 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
7734 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7735 ProcessAckPacket(&frame);
renjietang201bfa52023-04-24 18:12:27 -07007736 EXPECT_EQ(1,
7737 connection_.GetStats().num_forward_progress_after_path_degrading);
Bence Békybac04052022-04-07 15:44:29 -04007738 EXPECT_FALSE(connection_.IsPathDegrading());
7739 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7740}
7741
7742TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
7743 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7744 return;
7745 }
7746 set_perspective(Perspective::IS_SERVER);
7747 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7748
7749 EXPECT_FALSE(connection_.IsPathDegrading());
7750 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7751
7752 // Send data.
7753 const char data[] = "data";
7754 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7755 EXPECT_FALSE(connection_.IsPathDegrading());
7756 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7757
7758 // Ack data.
7759 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07007760 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04007761 QuicAckFrame frame =
7762 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7763 ProcessAckPacket(&frame);
7764 EXPECT_FALSE(connection_.IsPathDegrading());
7765 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7766}
7767
7768TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
7769 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7770 return;
7771 }
7772 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7773 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7774 ProcessDataPacket(1);
7775 SendAckPacketToPeer();
7776 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7777 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7778 EXPECT_FALSE(connection_.IsPathDegrading());
7779 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7780}
7781
7782TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7783 // Verifies that multiple calls to CloseConnection do not
7784 // result in multiple attempts to close the connection - it will be marked as
7785 // disconnected after the first call.
7786 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
7787 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7788 ConnectionCloseBehavior::SILENT_CLOSE);
7789 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7790 ConnectionCloseBehavior::SILENT_CLOSE);
7791}
7792
7793TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7794 set_perspective(Perspective::IS_SERVER);
7795 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang161ce6e2022-07-01 18:02:11 -07007796 QuicConnectionPeer::SetAddressValidated(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04007797
7798 CryptoHandshakeMessage message;
7799 CryptoFramer framer;
7800 message.set_tag(kCHLO);
7801 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7802 frame1_.stream_id = 10;
7803 frame1_.data_buffer = data->data();
7804 frame1_.data_length = data->length();
7805
7806 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7807 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7808 }
7809 EXPECT_CALL(visitor_,
7810 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7811 ForceProcessFramePacket(QuicFrame(frame1_));
7812 if (VersionHasIetfQuicFrames(version().transport_version)) {
7813 // INITIAL packet should not contain STREAM frame.
7814 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7815 } else {
7816 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7817 }
7818}
7819
7820TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7821 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7822
7823 CryptoHandshakeMessage message;
7824 CryptoFramer framer;
7825 message.set_tag(kREJ);
7826 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7827 frame1_.stream_id = 10;
7828 frame1_.data_buffer = data->data();
7829 frame1_.data_length = data->length();
7830
7831 EXPECT_CALL(visitor_,
7832 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7833 ForceProcessFramePacket(QuicFrame(frame1_));
7834 if (VersionHasIetfQuicFrames(version().transport_version)) {
7835 // INITIAL packet should not contain STREAM frame.
7836 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7837 } else {
7838 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7839 }
7840}
7841
7842TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7843 SimulateNextPacketTooLarge();
7844 // A connection close packet is sent
7845 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7846 .Times(1);
7847 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7848 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7849}
7850
7851TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7852 // Test even we always get packet too large, we do not infinitely try to send
7853 // close packet.
7854 AlwaysGetPacketTooLarge();
7855 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7856 .Times(1);
7857 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7858 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7859}
7860
7861TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
7862 // Regression test for crbug.com/979507.
7863 //
7864 // If we get a write error when writing queued packets, we should attempt to
7865 // send a connection close packet, but if sending that fails, it shouldn't get
7866 // queued.
7867
7868 // Queue a packet to write.
7869 BlockOnNextWrite();
7870 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7871 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7872
7873 // Configure writer to always fail.
7874 AlwaysGetPacketTooLarge();
7875
7876 // Expect that we attempt to close the connection exactly once.
7877 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7878 .Times(1);
7879
7880 // Unblock the writes and actually send.
7881 writer_->SetWritable();
7882 connection_.OnCanWrite();
7883 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7884
7885 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7886}
7887
7888// Verify that if connection has no outstanding data, it notifies the send
7889// algorithm after the write.
7890TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7891 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7892 {
7893 InSequence seq;
7894 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7895 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7896 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7897 .WillRepeatedly(Return(false));
7898 }
7899
7900 connection_.SendStreamData3();
7901}
7902
7903// Verify that the connection does not become app-limited if there is
7904// outstanding data to send after the write.
7905TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7906 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7907 {
7908 InSequence seq;
7909 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7910 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7911 }
7912
7913 connection_.SendStreamData3();
7914}
7915
7916// Verify that the connection does not become app-limited after blocked write
7917// even if there is outstanding data to send after the write.
7918TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7919 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7920 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7921 BlockOnNextWrite();
7922
7923 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7924 connection_.SendStreamData3();
7925
7926 // Now unblock the writer, become congestion control blocked,
7927 // and ensure we become app-limited after writing.
7928 writer_->SetWritable();
7929 CongestionBlockWrites();
7930 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7931 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7932 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7933 connection_.OnCanWrite();
7934}
7935
Bence Békybac04052022-04-07 15:44:29 -04007936TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
7937 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7938 // Send an ack by simulating delayed ack alarm firing.
7939 ProcessPacket(1);
7940 EXPECT_TRUE(connection_.HasPendingAcks());
7941 connection_.GetAckAlarm()->Fire();
7942 // Simulate data packet causes write error.
7943 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7944 SimulateNextPacketTooLarge();
7945 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7946 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7947 // Ack frame is not bundled in connection close packet.
7948 EXPECT_TRUE(writer_->ack_frames().empty());
7949 if (writer_->padding_frames().empty()) {
7950 EXPECT_EQ(1u, writer_->frame_count());
7951 } else {
7952 EXPECT_EQ(2u, writer_->frame_count());
7953 }
7954
7955 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7956}
7957
7958TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
7959 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7960 return;
7961 }
7962
7963 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7964 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7965 connection_.CloseConnection(
7966 kQuicErrorCode, "Some random error message",
7967 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7968
7969 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7970
7971 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7972 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7973
7974 if (!connection_.version().CanSendCoalescedPackets()) {
7975 // Each connection close packet should be sent in distinct UDP packets.
7976 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7977 writer_->connection_close_packets());
7978 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7979 writer_->packets_write_attempts());
7980 return;
7981 }
7982
7983 // A single UDP packet should be sent with multiple connection close packets
7984 // coalesced together.
7985 EXPECT_EQ(1u, writer_->packets_write_attempts());
7986
7987 // Only the first packet has been processed yet.
7988 EXPECT_EQ(1u, writer_->connection_close_packets());
7989
7990 // ProcessPacket resets the visitor and frees the coalesced packet.
7991 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
7992 auto packet = writer_->coalesced_packet()->Clone();
7993 writer_->framer()->ProcessPacket(*packet);
7994 EXPECT_EQ(1u, writer_->connection_close_packets());
7995 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7996}
7997
7998TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
7999 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8000 return;
8001 }
8002
8003 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8004 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8005 connection_.CloseConnection(
8006 kQuicErrorCode, "Some random error message",
8007 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8008
8009 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8010
8011 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8012 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8013 EXPECT_EQ(1u, writer_->connection_close_packets());
8014 EXPECT_EQ(1u, writer_->packets_write_attempts());
8015 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8016}
8017
8018TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8019 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8020 return;
8021 }
8022 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07008023 // Receives packet 1000 in initial data.
8024 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8025 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -04008026
8027 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
8028 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
8029 }
8030 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8031 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8032 connection_.CloseConnection(
8033 kQuicErrorCode, "Some random error message",
8034 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8035
8036 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8037
8038 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8039 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8040 EXPECT_TRUE(writer_->padding_frames().empty());
8041 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8042}
8043
8044// Regression test for b/63620844.
8045TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8046 SimulateNextPacketTooLarge();
8047 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8048 .Times(1);
8049
8050 connection_.SendCryptoStreamData();
8051 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8052}
8053
8054TEST_P(QuicConnectionTest, MaxPacingRate) {
8055 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8056 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8057 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8058}
8059
8060TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8061 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8062 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8063 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8064 EXPECT_EQ(CONNECTION_ID_PRESENT,
8065 writer_->last_packet_header().destination_connection_id_included);
8066
8067 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8068 QuicConfig config;
8069 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8070 connection_.SetFromConfig(config);
8071
8072 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8073 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8074 // Verify connection id is still sent in the packet.
8075 EXPECT_EQ(CONNECTION_ID_PRESENT,
8076 writer_->last_packet_header().destination_connection_id_included);
8077}
8078
Bence Békybac04052022-04-07 15:44:29 -04008079TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8080 const QuicTime::Delta retransmittable_on_wire_timeout =
8081 QuicTime::Delta::FromMilliseconds(50);
8082 connection_.set_initial_retransmittable_on_wire_timeout(
8083 retransmittable_on_wire_timeout);
8084
8085 EXPECT_TRUE(connection_.connected());
8086 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8087 .WillRepeatedly(Return(true));
8088
8089 const char data[] = "data";
8090 size_t data_size = strlen(data);
8091 QuicStreamOffset offset = 0;
8092
8093 // Advance 5ms, send a retransmittable packet to the peer.
8094 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8095 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8096 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8097 offset += data_size;
8098 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8099 // The ping alarm is set for the ping timeout, not the shorter
8100 // retransmittable_on_wire_timeout.
8101 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8102 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8103 EXPECT_EQ(ping_delay,
8104 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8105
8106 // Advance 5ms, send a second retransmittable packet to the peer.
8107 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8108 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8109 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8110 offset += data_size;
8111 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8112
8113 // Now receive an ACK of the first packet. This should not set the
8114 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8115 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8116 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07008117 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008118 QuicAckFrame frame =
8119 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8120 ProcessAckPacket(&frame);
8121 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8122 // The ping alarm is set for the ping timeout, not the shorter
8123 // retransmittable_on_wire_timeout.
8124 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8125 // The ping alarm has a 1 second granularity, and the clock has been advanced
8126 // 10ms since it was originally set.
8127 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8128 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8129
8130 // Now receive an ACK of the second packet. This should set the
8131 // retransmittable-on-wire alarm now that no retransmittable packets are on
8132 // the wire.
8133 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07008134 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008135 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8136 ProcessAckPacket(&frame);
8137 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8138 EXPECT_EQ(retransmittable_on_wire_timeout,
8139 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8140
8141 // Now receive a duplicate ACK of the second packet. This should not update
8142 // the ping alarm.
8143 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8144 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8145 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8146 ProcessAckPacket(&frame);
8147 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8148 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8149
8150 // Now receive a non-ACK packet. This should not update the ping alarm.
8151 prev_deadline = connection_.GetPingAlarm()->deadline();
8152 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8153 ProcessPacket(4);
8154 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8155 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8156
8157 // Simulate the alarm firing and check that a PING is sent.
8158 connection_.GetPingAlarm()->Fire();
8159 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07008160 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04008161 ASSERT_EQ(1u, writer_->ping_frames().size());
8162}
8163
8164TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8165 const QuicTime::Delta retransmittable_on_wire_timeout =
8166 QuicTime::Delta::FromMilliseconds(50);
8167 connection_.set_initial_retransmittable_on_wire_timeout(
8168 retransmittable_on_wire_timeout);
8169
8170 EXPECT_TRUE(connection_.connected());
8171 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8172 .WillRepeatedly(Return(true));
8173
8174 const char data[] = "data";
8175 size_t data_size = strlen(data);
8176 QuicStreamOffset offset = 0;
8177
8178 // Advance 5ms, send a retransmittable packet to the peer.
8179 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8180 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8181 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8182 offset += data_size;
8183 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8184 // The ping alarm is set for the ping timeout, not the shorter
8185 // retransmittable_on_wire_timeout.
8186 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8187 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8188 EXPECT_EQ(ping_delay,
8189 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8190
8191 // Now receive an ACK of the first packet. This should set the
8192 // retransmittable-on-wire alarm now that no retransmittable packets are on
8193 // the wire.
8194 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8195 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -07008196 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008197 QuicAckFrame frame =
8198 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8199 ProcessAckPacket(&frame);
8200 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8201 EXPECT_EQ(retransmittable_on_wire_timeout,
8202 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8203
8204 // Before the alarm fires, send another retransmittable packet. This should
8205 // cancel the retransmittable-on-wire alarm since now there's a
8206 // retransmittable packet on the wire.
8207 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8208 offset += data_size;
8209 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8210
8211 // Now receive an ACK of the second packet. This should set the
8212 // retransmittable-on-wire alarm now that no retransmittable packets are on
8213 // the wire.
8214 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martindukeba002452023-03-21 08:10:46 -07008215 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008216 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8217 ProcessAckPacket(&frame);
8218 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8219 EXPECT_EQ(retransmittable_on_wire_timeout,
8220 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8221
8222 // Simulate the alarm firing and check that a PING is sent.
8223 writer_->Reset();
8224 connection_.GetPingAlarm()->Fire();
8225 size_t padding_frame_count = writer_->padding_frames().size();
fayangfc04b8a2023-05-18 09:26:25 -07008226 // Do not ACK acks.
8227 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04008228 ASSERT_EQ(1u, writer_->ping_frames().size());
8229}
8230
8231// When there is no stream data received but are open streams, send the
8232// first few consecutive pings with aggressive retransmittable-on-wire
8233// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8234// afterwards until it exceeds the default ping timeout.
8235TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8236 int max_aggressive_retransmittable_on_wire_ping_count = 5;
birenroyef686222022-09-12 11:34:34 -07008237 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008238 max_aggressive_retransmittable_on_wire_ping_count);
8239 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8240 QuicTime::Delta::FromMilliseconds(200);
8241 connection_.set_initial_retransmittable_on_wire_timeout(
8242 initial_retransmittable_on_wire_timeout);
8243
8244 EXPECT_TRUE(connection_.connected());
8245 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8246 .WillRepeatedly(Return(true));
8247
8248 const char data[] = "data";
8249 // Advance 5ms, send a retransmittable data packet to the peer.
8250 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8251 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8252 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8253 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8254 // The ping alarm is set for the ping timeout, not the shorter
8255 // retransmittable_on_wire_timeout.
8256 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008257 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008258 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8259
8260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008261 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008262 .Times(AnyNumber());
8263
8264 // Verify that the first few consecutive retransmittable on wire pings are
8265 // sent with aggressive timeout.
8266 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8267 // Receive an ACK of the previous packet. This should set the ping alarm
8268 // with the initial retransmittable-on-wire timeout.
8269 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8270 QuicPacketNumber ack_num = creator_->packet_number();
8271 QuicAckFrame frame = InitAckFrame(
8272 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8273 ProcessAckPacket(&frame);
8274 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8275 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8276 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8277 // Simulate the alarm firing and check that a PING is sent.
8278 writer_->Reset();
8279 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8280 connection_.GetPingAlarm()->Fire();
8281 }
8282
8283 QuicTime::Delta retransmittable_on_wire_timeout =
8284 initial_retransmittable_on_wire_timeout;
8285
8286 // Verify subsequent pings are sent with timeout that is exponentially backed
8287 // off.
fayang5d393332022-04-18 13:34:54 -07008288 while (retransmittable_on_wire_timeout * 2 <
8289 QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) {
Bence Békybac04052022-04-07 15:44:29 -04008290 // Receive an ACK for the previous PING. This should set the
8291 // ping alarm with backed off retransmittable-on-wire timeout.
8292 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8293 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8294 QuicPacketNumber ack_num = creator_->packet_number();
8295 QuicAckFrame frame = InitAckFrame(
8296 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8297 ProcessAckPacket(&frame);
8298 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8299 EXPECT_EQ(retransmittable_on_wire_timeout,
8300 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8301
8302 // Simulate the alarm firing and check that a PING is sent.
8303 writer_->Reset();
8304 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8305 connection_.GetPingAlarm()->Fire();
8306 }
8307
8308 // The ping alarm is set with default ping timeout.
8309 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008310 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008311 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8312
8313 // Receive an ACK for the previous PING. The ping alarm is set with an
8314 // earlier deadline.
8315 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8316 QuicPacketNumber ack_num = creator_->packet_number();
8317 QuicAckFrame frame = InitAckFrame(
8318 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8319 ProcessAckPacket(&frame);
8320 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008321 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) -
8322 QuicTime::Delta::FromMilliseconds(5),
Bence Békybac04052022-04-07 15:44:29 -04008323 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8324}
8325
8326// This test verify that the count of consecutive aggressive pings is reset
8327// when new data is received. And it also verifies the connection resets
8328// the exponential back-off of the retransmittable-on-wire ping timeout
8329// after receiving new stream data.
8330TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8331 int max_aggressive_retransmittable_on_wire_ping_count = 3;
birenroyef686222022-09-12 11:34:34 -07008332 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
Bence Békybac04052022-04-07 15:44:29 -04008333 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8334 QuicTime::Delta::FromMilliseconds(200);
8335 connection_.set_initial_retransmittable_on_wire_timeout(
8336 initial_retransmittable_on_wire_timeout);
8337
8338 EXPECT_TRUE(connection_.connected());
8339 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8340 .WillRepeatedly(Return(true));
8341 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008342 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008343 .Times(AnyNumber());
8344
8345 const char data[] = "data";
8346 // Advance 5ms, send a retransmittable data packet to the peer.
8347 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8348 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8349 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8350 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8351 // The ping alarm is set for the ping timeout, not the shorter
8352 // retransmittable_on_wire_timeout.
8353 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008354 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008355 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8356
8357 // Receive an ACK of the first packet. This should set the ping alarm with
8358 // initial retransmittable-on-wire timeout since there is no retransmittable
8359 // packet on the wire.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008360 {
8361 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8362 QuicAckFrame frame =
8363 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8364 ProcessAckPacket(&frame);
8365 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8366 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8367 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8368 }
Bence Békybac04052022-04-07 15:44:29 -04008369
8370 // Simulate the alarm firing and check that a PING is sent.
8371 writer_->Reset();
8372 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8373 connection_.GetPingAlarm()->Fire();
8374
8375 // Receive an ACK for the previous PING. Ping alarm will be set with
8376 // aggressive timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008377 {
8378 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8379 QuicPacketNumber ack_num = creator_->packet_number();
8380 QuicAckFrame frame = InitAckFrame(
8381 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8382 ProcessAckPacket(&frame);
8383 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8384 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8385 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8386 }
Bence Békybac04052022-04-07 15:44:29 -04008387
8388 // Process a data packet.
8389 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8390 ProcessDataPacket(peer_creator_.packet_number() + 1);
8391 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8392 peer_creator_.packet_number() + 1);
8393 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8394 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
fayang327663d2022-05-10 18:25:36 -07008395 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8396 connection_.GetPingAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -04008397
8398 // Verify the count of consecutive aggressive pings is reset.
8399 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8400 // Receive an ACK of the previous packet. This should set the ping alarm
8401 // with the initial retransmittable-on-wire timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008402 const QuicPacketNumber ack_num = creator_->packet_number();
Bence Békybac04052022-04-07 15:44:29 -04008403 QuicAckFrame frame = InitAckFrame(
8404 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8405 ProcessAckPacket(&frame);
8406 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8407 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8408 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8409 // Simulate the alarm firing and check that a PING is sent.
8410 writer_->Reset();
8411 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8412 connection_.GetPingAlarm()->Fire();
8413 // Advance 5ms to receive next packet.
8414 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8415 }
8416
8417 // Receive another ACK for the previous PING. This should set the
8418 // ping alarm with backed off retransmittable-on-wire timeout.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008419 {
8420 const QuicPacketNumber ack_num = creator_->packet_number();
8421 QuicAckFrame frame = InitAckFrame(
8422 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8423 ProcessAckPacket(&frame);
8424 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8425 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8426 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8427 }
Bence Békybac04052022-04-07 15:44:29 -04008428
8429 writer_->Reset();
8430 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8431 connection_.GetPingAlarm()->Fire();
8432
8433 // Process another data packet and a new ACK packet. The ping alarm is set
8434 // with aggressive ping timeout again.
QUICHE teame2a24ee2024-01-09 06:34:35 -08008435 {
8436 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8437 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8438 ProcessDataPacket(peer_creator_.packet_number() + 1);
8439 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8440 peer_creator_.packet_number() + 1);
8441 const QuicPacketNumber ack_num = creator_->packet_number();
8442 QuicAckFrame frame = InitAckFrame(
8443 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8444 ProcessAckPacket(&frame);
8445 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8446 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8447 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8448 }
Bence Békybac04052022-04-07 15:44:29 -04008449}
8450
8451// Make sure that we never send more retransmissible on the wire pings than
8452// the limit in FLAGS_quic_max_retransmittable_on_wire_ping_count.
8453TEST_P(QuicConnectionTest, RetransmittableOnWirePingLimit) {
8454 static constexpr int kMaxRetransmittableOnWirePingCount = 3;
birenroyef686222022-09-12 11:34:34 -07008455 SetQuicFlag(quic_max_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008456 kMaxRetransmittableOnWirePingCount);
8457 static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout =
8458 QuicTime::Delta::FromMilliseconds(200);
8459 static constexpr QuicTime::Delta short_delay =
8460 QuicTime::Delta::FromMilliseconds(5);
8461 ASSERT_LT(short_delay * 10, initial_retransmittable_on_wire_timeout);
8462 connection_.set_initial_retransmittable_on_wire_timeout(
8463 initial_retransmittable_on_wire_timeout);
8464
8465 EXPECT_TRUE(connection_.connected());
8466 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8467 .WillRepeatedly(Return(true));
8468
8469 const char data[] = "data";
8470 // Advance 5ms, send a retransmittable data packet to the peer.
8471 clock_.AdvanceTime(short_delay);
8472 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8473 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8474 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8475 // The ping alarm is set for the ping timeout, not the shorter
8476 // retransmittable_on_wire_timeout.
8477 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008478 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008479 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8480
8481 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
martindukeba002452023-03-21 08:10:46 -07008482 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -04008483 .Times(AnyNumber());
8484
8485 // Verify that the first few consecutive retransmittable on wire pings are
8486 // sent with aggressive timeout.
8487 for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) {
8488 // Receive an ACK of the previous packet. This should set the ping alarm
8489 // with the initial retransmittable-on-wire timeout.
8490 clock_.AdvanceTime(short_delay);
8491 QuicPacketNumber ack_num = creator_->packet_number();
8492 QuicAckFrame frame = InitAckFrame(
8493 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8494 ProcessAckPacket(&frame);
8495 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8496 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8497 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8498 // Simulate the alarm firing and check that a PING is sent.
8499 writer_->Reset();
8500 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8501 connection_.GetPingAlarm()->Fire();
8502 }
8503
8504 // Receive an ACK of the previous packet. This should set the ping alarm
8505 // but this time with the default ping timeout.
8506 QuicPacketNumber ack_num = creator_->packet_number();
8507 QuicAckFrame frame = InitAckFrame(
8508 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8509 ProcessAckPacket(&frame);
8510 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008511 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008512 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8513}
8514
8515TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8516 const StatelessResetToken kTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8517 0, 1, 0, 1, 0, 1, 0, 1};
8518 const StatelessResetToken kWrongTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8519 0, 1, 0, 1, 0, 1, 0, 2};
8520 QuicConfig config;
8521 // No token has been received.
8522 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8523
8524 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8525 // Token is different from received token.
8526 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8527 connection_.SetFromConfig(config);
8528 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8529
8530 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8531 connection_.SetFromConfig(config);
8532 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8533}
8534
8535TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8536 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8537 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8538 BlockOnNextWrite();
8539 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8540 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8541 // This causes connection to be closed because packet 1 has not been sent yet.
8542 QuicAckFrame frame = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -07008543 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008544 ProcessAckPacket(1, &frame);
8545 EXPECT_EQ(0, connection_close_frame_count_);
8546}
8547
8548TEST_P(QuicConnectionTest, SendMessage) {
Bence Békybac04052022-04-07 15:44:29 -04008549 if (connection_.version().UsesTls()) {
8550 QuicConfig config;
8551 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8552 &config, kMaxAcceptedDatagramFrameSize);
8553 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8554 connection_.SetFromConfig(config);
8555 }
8556 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
8557 quiche::QuicheMemSlice slice;
8558 {
8559 QuicConnection::ScopedPacketFlusher flusher(&connection_);
8560 connection_.SendStreamData3();
8561 // Send a message which cannot fit into current open packet, and 2 packets
8562 // get sent, one contains stream frame, and the other only contains the
8563 // message frame.
8564 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8565 slice = MemSliceFromString(absl::string_view(
8566 message.data(), connection_.GetCurrentLargestMessagePayload()));
8567 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8568 connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false));
8569 }
8570 // Fail to send a message if connection is congestion control blocked.
8571 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8572 slice = MemSliceFromString("message");
8573 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8574 connection_.SendMessage(2, absl::MakeSpan(&slice, 1), false));
8575
8576 // Always fail to send a message which cannot fit into one packet.
8577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8578 slice = MemSliceFromString(absl::string_view(
8579 message.data(), connection_.GetCurrentLargestMessagePayload() + 1));
8580 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8581 connection_.SendMessage(3, absl::MakeSpan(&slice, 1), false));
8582}
8583
8584TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
martinduke225e91a2022-11-28 17:18:13 -08008585 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008586 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
8587 expected_largest_payload += 3;
8588 }
8589 if (connection_.version().HasLongHeaderLengths()) {
8590 expected_largest_payload -= 2;
8591 }
8592 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8593 expected_largest_payload -= 1;
8594 }
8595 if (connection_.version().UsesTls()) {
8596 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8597 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8598 QuicConfig config;
8599 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8600 &config, kMaxAcceptedDatagramFrameSize);
8601 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8602 connection_.SetFromConfig(config);
8603 // Verify the value post-handshake.
8604 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8605 expected_largest_payload);
8606 } else {
8607 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8608 expected_largest_payload);
8609 }
8610}
8611
8612TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
martinduke225e91a2022-11-28 17:18:13 -08008613 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008614 if (connection_.version().HasLongHeaderLengths()) {
8615 expected_largest_payload -= 2;
8616 }
8617 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8618 expected_largest_payload -= 1;
8619 }
8620 if (connection_.version().UsesTls()) {
8621 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8622 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8623 QuicConfig config;
8624 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8625 &config, kMaxAcceptedDatagramFrameSize);
8626 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8627 connection_.SetFromConfig(config);
8628 // Verify the value post-handshake.
8629 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8630 expected_largest_payload);
8631 } else {
8632 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8633 expected_largest_payload);
8634 }
8635}
8636
8637TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
fayangfc04b8a2023-05-18 09:26:25 -07008638 if (!connection_.version().UsesTls()) {
Bence Békybac04052022-04-07 15:44:29 -04008639 return;
8640 }
8641 constexpr QuicPacketLength kFrameSizeLimit = 1000;
8642 constexpr QuicPacketLength kPayloadSizeLimit =
8643 kFrameSizeLimit - kQuicFrameTypeSize;
8644 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8645 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8646 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8647 QuicConfig config;
8648 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
8649 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8650 connection_.SetFromConfig(config);
8651 // Verify the value post-handshake.
8652 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
8653 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8654 kPayloadSizeLimit);
8655}
8656
8657// Test to check that the path challenge/path response logic works
8658// correctly. This test is only for version-99
8659TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) {
8660 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8661 return;
8662 }
8663 PathProbeTestInit(Perspective::IS_SERVER);
8664 QuicConnectionPeer::SetAddressValidated(&connection_);
8665 // First check if the server can send probing packet.
8666 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8667
8668 // Create and send the probe request (PATH_CHALLENGE frame).
8669 // SendConnectivityProbingPacket ends up calling
8670 // TestPacketWriter::WritePacket() which in turns receives and parses the
8671 // packet by calling framer_.ProcessPacket() -- which in turn calls
8672 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8673 // the packet in writer_->path_challenge_frames()
8674 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8675 connection_.SendConnectivityProbingPacket(writer_.get(),
8676 connection_.peer_address());
8677 // Save the random contents of the challenge for later comparison to the
8678 // response.
8679 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8680 QuicPathFrameBuffer challenge_data =
8681 writer_->path_challenge_frames().front().data_buffer;
8682
8683 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8684 // called and it will perform actions to ensure that the rest of the protocol
8685 // is performed.
8686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8687 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8688 writer_->path_challenge_frames().front()));
8689 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8690 creator_->FlushCurrentPacket();
8691
8692 // The final check is to ensure that the random data in the response matches
8693 // the random data from the challenge.
8694 EXPECT_EQ(1u, writer_->path_response_frames().size());
8695 EXPECT_EQ(0, memcmp(&challenge_data,
8696 &(writer_->path_response_frames().front().data_buffer),
8697 sizeof(challenge_data)));
8698}
8699
8700TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnDefaulSocket) {
8701 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8702 return;
8703 }
8704 PathProbeTestInit(Perspective::IS_CLIENT);
8705 // First check if the client can send probing packet.
8706 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8707
8708 // Create and send the probe request (PATH_CHALLENGE frame).
8709 // SendConnectivityProbingPacket ends up calling
8710 // TestPacketWriter::WritePacket() which in turns receives and parses the
8711 // packet by calling framer_.ProcessPacket() -- which in turn calls
8712 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8713 // the packet in writer_->path_challenge_frames()
8714 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8715 connection_.SendConnectivityProbingPacket(writer_.get(),
8716 connection_.peer_address());
8717 // Save the random contents of the challenge for later validation against the
8718 // response.
8719 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8720 QuicPathFrameBuffer challenge_data =
8721 writer_->path_challenge_frames().front().data_buffer;
8722
8723 // Normally, QuicConnection::OnPathChallengeFrame would be
8724 // called and it will perform actions to ensure that the rest of the protocol
8725 // is performed.
8726 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8727 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8728 writer_->path_challenge_frames().front()));
8729 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8730 creator_->FlushCurrentPacket();
8731
8732 // The final check is to ensure that the random data in the response matches
8733 // the random data from the challenge.
8734 EXPECT_EQ(1u, writer_->path_response_frames().size());
8735 EXPECT_EQ(0, memcmp(&challenge_data,
8736 &(writer_->path_response_frames().front().data_buffer),
8737 sizeof(challenge_data)));
8738}
8739
8740TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnAlternativeSocket) {
danzh87605712022-04-11 14:36:39 -07008741 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -04008742 return;
8743 }
8744 PathProbeTestInit(Perspective::IS_CLIENT);
8745 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8746
8747 QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8748 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8749 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8750 .Times(AtLeast(1u))
8751 .WillOnce(Invoke([&]() {
8752 EXPECT_EQ(1u, new_writer.packets_write_attempts());
8753 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
8754 EXPECT_EQ(1u, new_writer.padding_frames().size());
8755 EXPECT_EQ(kNewSelfAddress.host(),
8756 new_writer.last_write_source_address());
8757 }));
8758 bool success = false;
8759 connection_.ValidatePath(
8760 std::make_unique<TestQuicPathValidationContext>(
8761 kNewSelfAddress, connection_.peer_address(), &new_writer),
8762 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -08008763 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
8764 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -04008765
8766 // Receiving a PATH_CHALLENGE on the alternative path. Response to this
8767 // PATH_CHALLENGE should be sent via the alternative writer.
8768 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8769 .Times(AtLeast(1u))
8770 .WillOnce(Invoke([&]() {
8771 EXPECT_EQ(2u, new_writer.packets_write_attempts());
8772 EXPECT_EQ(1u, new_writer.path_response_frames().size());
8773 EXPECT_EQ(1u, new_writer.padding_frames().size());
8774 EXPECT_EQ(kNewSelfAddress.host(),
8775 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -07008776 }))
8777 .WillRepeatedly(DoDefault());
8778 ;
Bence Békybac04052022-04-07 15:44:29 -04008779 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8780 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8781 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8782 probing_packet->encrypted_length),
8783 clock_.Now()));
8784 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8785
8786 QuicSocketAddress kNewerSelfAddress(QuicIpAddress::Loopback6(),
8787 /*port=*/34567);
8788 // Receiving a PATH_CHALLENGE on an unknown socket should be ignored.
8789 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
8790 ProcessReceivedPacket(kNewerSelfAddress, kPeerAddress, *received);
8791}
8792
8793TEST_P(QuicConnectionTest,
8794 RestartPathDegradingDetectionAfterMigrationWithProbe) {
danzh65153092023-06-16 10:59:32 -07008795 if (!version().HasIetfQuicFrames() &&
8796 GetQuicReloadableFlag(quic_ignore_gquic_probing)) {
8797 return;
8798 }
Bence Békybac04052022-04-07 15:44:29 -04008799 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8800 PathProbeTestInit(Perspective::IS_CLIENT);
8801
8802 // Send data and verify the path degrading detection is set.
8803 const char data[] = "data";
8804 size_t data_size = strlen(data);
8805 QuicStreamOffset offset = 0;
8806 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8807 offset += data_size;
8808
8809 // Verify the path degrading detection is in progress.
8810 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8811 EXPECT_FALSE(connection_.IsPathDegrading());
8812 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
8813
8814 // Simulate the firing of path degrading.
8815 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
8816 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
8817 connection_.PathDegradingTimeout();
8818 EXPECT_TRUE(connection_.IsPathDegrading());
8819 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8820
8821 if (!GetParam().version.HasIetfQuicFrames()) {
8822 // Simulate path degrading handling by sending a probe on an alternet path.
8823 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8824 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
8825 connection_.SendConnectivityProbingPacket(&probing_writer,
8826 connection_.peer_address());
8827 // Verify that path degrading detection is not reset.
8828 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8829
8830 // Simulate successful path degrading handling by receiving probe response.
8831 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
8832
8833 EXPECT_CALL(visitor_,
8834 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
8835 .Times(1);
8836 const QuicSocketAddress kNewSelfAddress =
8837 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8838
8839 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8840 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8841 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8842 probing_packet->encrypted_length),
8843 clock_.Now()));
8844 uint64_t num_probing_received =
8845 connection_.GetStats().num_connectivity_probing_received;
8846 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8847
danzh65153092023-06-16 10:59:32 -07008848 EXPECT_EQ(num_probing_received +
8849 (GetQuicReloadableFlag(quic_ignore_gquic_probing) ? 0u : 1u),
Bence Békybac04052022-04-07 15:44:29 -04008850 connection_.GetStats().num_connectivity_probing_received);
8851 EXPECT_EQ(kPeerAddress, connection_.peer_address());
8852 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8853 EXPECT_TRUE(connection_.IsPathDegrading());
8854 }
8855
8856 // Verify new path degrading detection is activated.
8857 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
8858 connection_.OnSuccessfulMigration(/*is_port_change*/ true);
8859 EXPECT_FALSE(connection_.IsPathDegrading());
8860 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8861}
8862
8863TEST_P(QuicConnectionTest, ClientsResetCwndAfterConnectionMigration) {
8864 if (!GetParam().version.HasIetfQuicFrames()) {
8865 return;
8866 }
8867 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8868 PathProbeTestInit(Perspective::IS_CLIENT);
8869 EXPECT_EQ(kSelfAddress, connection_.self_address());
8870
8871 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
8872 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
8873 rtt_stats->set_initial_rtt(default_init_rtt * 2);
8874 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
8875
fayang339f0c82022-04-30 14:20:02 -07008876 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
8877 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008878 const SendAlgorithmInterface* send_algorithm = manager_->GetSendAlgorithm();
8879
8880 // Migrate to a new address with different IP.
8881 const QuicSocketAddress kNewSelfAddress =
8882 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
8883 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8884 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
8885 &new_writer, false);
8886 EXPECT_EQ(default_init_rtt, manager_->GetRttStats()->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07008887 EXPECT_EQ(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008888 EXPECT_NE(send_algorithm, manager_->GetSendAlgorithm());
8889}
8890
8891// Regression test for b/110259444
8892TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8893 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8894 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8895 writer_->SetWriteBlocked();
8896
8897 ProcessPacket(1);
8898 // Verify ack alarm is set.
8899 EXPECT_TRUE(connection_.HasPendingAcks());
8900 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8901 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8902 connection_.GetAckAlarm()->Fire();
8903
8904 writer_->SetWritable();
8905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8906 ProcessPacket(2);
8907 // Verify ack alarm is not set.
8908 EXPECT_FALSE(connection_.HasPendingAcks());
8909}
8910
8911TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8912 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8913 writer_->set_supports_release_time(true);
8914 QuicConfig config;
8915 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8916 connection_.SetFromConfig(config);
8917 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8918
8919 QuicTagVector connection_options;
8920 connection_options.push_back(kNPCO);
8921 config.SetConnectionOptionsToSend(connection_options);
8922 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8923 connection_.SetFromConfig(config);
8924 // Verify pacing offload is disabled.
8925 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8926}
8927
8928// Regression test for b/110259444
8929// Get a path response without having issued a path challenge...
8930TEST_P(QuicConnectionTest, OrphanPathResponse) {
8931 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8932
8933 QuicPathResponseFrame frame(99, data);
8934 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8935 // If PATH_RESPONSE was accepted (payload matches the payload saved
8936 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8937 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8938 // Since this PATH_RESPONSE does not match, current_packet_content_
8939 // must not be FIRST_FRAME_IS_PING.
8940 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8941 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8942}
8943
Bence Békybac04052022-04-07 15:44:29 -04008944TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
8945 if (!VersionHasIetfQuicFrames(version().transport_version)) {
8946 return;
8947 }
8948 // Set first_sending_packet_number to be 0 to allow successfully processing
8949 // acks which ack packet number 0.
8950 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8951 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8952
8953 ProcessPacket(0);
8954 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8955 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8956
8957 ProcessPacket(1);
8958 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8959 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8960
8961 ProcessPacket(2);
8962 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8963 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8964}
8965
8966TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8967 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8968 return;
8969 }
Bence Békybac04052022-04-07 15:44:29 -04008970 connection_.SendCryptoStreamData();
8971 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8972 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07008973 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008974 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8975 QuicAckFrame frame1 = InitAckFrame(1);
8976 // Received ACK for packet 1.
8977 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8978
8979 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8980 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8981 NO_FIN);
8982 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8983 NO_FIN);
8984 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8985 8, NO_FIN);
8986 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8987 12, FIN);
8988 // Received ACK for packets 2, 4, 5.
8989 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07008990 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04008991 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8992 QuicAckFrame frame2 =
8993 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8994 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8995 // Make sure although the same packet number is used, but they are in
8996 // different packet number spaces.
8997 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8998}
8999
9000TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9001 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9002 return;
9003 }
Bence Békybac04052022-04-07 15:44:29 -04009004 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9005 std::make_unique<TaggingEncrypter>(0x01));
9006
9007 connection_.SendCryptoStreamData();
9008 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9009 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07009010 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04009011 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9012 QuicAckFrame frame1 = InitAckFrame(1);
9013 // Received ACK for packet 1.
9014 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9015
9016 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9017 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9018 NO_FIN);
9019 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9020 NO_FIN);
9021
9022 // Received ACK for packets 2 and 3 in wrong packet number space.
9023 QuicAckFrame invalid_ack =
9024 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
9025 EXPECT_CALL(visitor_,
9026 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9028 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
9029 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
9030}
9031
9032TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9033 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9034 return;
9035 }
9036 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9037 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9038 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9039 }
9040 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009041 // Receives packet 1000 in initial data.
9042 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9043 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009044 peer_framer_.SetEncrypter(
9045 ENCRYPTION_FORWARD_SECURE,
9046 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
9047 SetDecrypter(
9048 ENCRYPTION_FORWARD_SECURE,
9049 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009050 // Receives packet 1000 in application data.
9051 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
9052 EXPECT_TRUE(connection_.HasPendingAcks());
9053 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9054 0, NO_FIN);
9055 // Verify application data ACK gets bundled with outgoing data.
9056 EXPECT_EQ(2u, writer_->frame_count());
9057 // Make sure ACK alarm is still set because initial data is not ACKed.
9058 EXPECT_TRUE(connection_.HasPendingAcks());
9059 // Receive packet 1001 in application data.
9060 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_FORWARD_SECURE);
9061 clock_.AdvanceTime(DefaultRetransmissionTime());
9062 // Simulates ACK alarm fires and verify two ACKs are flushed.
9063 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
martinduke9e0811c2022-12-08 20:35:57 -08009064 connection_.SetEncrypter(
9065 ENCRYPTION_FORWARD_SECURE,
9066 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009067 connection_.GetAckAlarm()->Fire();
9068 EXPECT_FALSE(connection_.HasPendingAcks());
9069 // Receives more packets in application data.
9070 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_FORWARD_SECURE);
9071 EXPECT_TRUE(connection_.HasPendingAcks());
9072
9073 // Verify zero rtt and forward secure packets get acked in the same packet.
9074 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9075 ProcessDataPacket(1003);
9076 EXPECT_FALSE(connection_.HasPendingAcks());
9077}
9078
9079TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9080 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9081 return;
9082 }
9083 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9084 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9085 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9086 }
9087 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009088 // Receives packet 1000 in initial data.
9089 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9090 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009091 peer_framer_.SetEncrypter(
9092 ENCRYPTION_ZERO_RTT,
9093 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009094 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08009095 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009096 // Receives packet 1000 in application data.
9097 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9098 EXPECT_TRUE(connection_.HasPendingAcks());
9099
9100 writer_->SetWriteBlocked();
9101 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9102 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9103 // blocked.
9104 clock_.AdvanceTime(DefaultDelayedAckTime());
9105 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9106 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9107 std::make_unique<TaggingEncrypter>(0x02));
9108 connection_.GetAckAlarm()->Fire();
9109 // Verify ACK alarm is not set.
9110 EXPECT_FALSE(connection_.HasPendingAcks());
9111
9112 writer_->SetWritable();
9113 // Verify 2 ACKs are sent when connection gets unblocked.
9114 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9115 connection_.OnCanWrite();
9116 EXPECT_FALSE(connection_.HasPendingAcks());
9117}
9118
9119// Make sure a packet received with the right client connection ID is processed.
9120TEST_P(QuicConnectionTest, ValidClientConnectionId) {
9121 if (!framer_.version().SupportsClientConnectionIds()) {
9122 return;
9123 }
9124 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9125 SetClientConnectionId(TestConnectionId(0x33));
9126 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9127 header.destination_connection_id = TestConnectionId(0x33);
9128 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9129 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9130 QuicFrames frames;
9131 QuicPingFrame ping_frame;
9132 QuicPaddingFrame padding_frame;
9133 frames.push_back(QuicFrame(ping_frame));
9134 frames.push_back(QuicFrame(padding_frame));
9135 std::unique_ptr<QuicPacket> packet =
9136 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9137 char buffer[kMaxOutgoingPacketSize];
9138 size_t encrypted_length = peer_framer_.EncryptPayload(
9139 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9140 kMaxOutgoingPacketSize);
9141 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9142 false);
9143 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9144 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9145 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9146}
9147
9148// Make sure a packet received with a different client connection ID is dropped.
9149TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
9150 if (!framer_.version().SupportsClientConnectionIds()) {
9151 return;
9152 }
9153 SetClientConnectionId(TestConnectionId(0x33));
9154 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9155 header.destination_connection_id = TestConnectionId(0xbad);
9156 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9157 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9158 QuicFrames frames;
9159 QuicPingFrame ping_frame;
9160 QuicPaddingFrame padding_frame;
9161 frames.push_back(QuicFrame(ping_frame));
9162 frames.push_back(QuicFrame(padding_frame));
9163 std::unique_ptr<QuicPacket> packet =
9164 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9165 char buffer[kMaxOutgoingPacketSize];
9166 size_t encrypted_length = peer_framer_.EncryptPayload(
9167 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9168 kMaxOutgoingPacketSize);
9169 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9170 false);
9171 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9172 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9173 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9174}
9175
9176// Make sure the first packet received with a different client connection ID on
9177// the server is processed and it changes the client connection ID.
9178TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
9179 if (!framer_.version().SupportsClientConnectionIds()) {
9180 return;
9181 }
9182 set_perspective(Perspective::IS_SERVER);
9183 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9184 header.source_connection_id = TestConnectionId(0x33);
9185 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9186 QuicFrames frames;
9187 QuicPingFrame ping_frame;
9188 QuicPaddingFrame padding_frame;
9189 frames.push_back(QuicFrame(ping_frame));
9190 frames.push_back(QuicFrame(padding_frame));
9191 std::unique_ptr<QuicPacket> packet =
9192 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9193 char buffer[kMaxOutgoingPacketSize];
9194 size_t encrypted_length =
9195 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9196 *packet, buffer, kMaxOutgoingPacketSize);
9197 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9198 false);
9199 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9200 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9201 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9202 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9203}
9204void QuicConnectionTest::TestReplaceConnectionIdFromInitial() {
9205 if (!framer_.version().AllowsVariableLengthConnectionIds()) {
9206 return;
9207 }
9208 // We start with a known connection ID.
9209 EXPECT_TRUE(connection_.connected());
9210 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9211 EXPECT_NE(TestConnectionId(0x33), connection_.connection_id());
9212 // Receiving an initial can replace the connection ID once.
9213 {
9214 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9215 header.source_connection_id = TestConnectionId(0x33);
9216 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9217 QuicFrames frames;
9218 QuicPingFrame ping_frame;
9219 QuicPaddingFrame padding_frame;
9220 frames.push_back(QuicFrame(ping_frame));
9221 frames.push_back(QuicFrame(padding_frame));
9222 std::unique_ptr<QuicPacket> packet =
9223 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9224 char buffer[kMaxOutgoingPacketSize];
9225 size_t encrypted_length =
9226 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9227 *packet, buffer, kMaxOutgoingPacketSize);
9228 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9229 false);
9230 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9231 }
9232 EXPECT_TRUE(connection_.connected());
9233 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9234 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9235 // Trying to replace the connection ID a second time drops the packet.
9236 {
9237 QuicPacketHeader header = ConstructPacketHeader(2, ENCRYPTION_INITIAL);
9238 header.source_connection_id = TestConnectionId(0x66);
9239 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9240 QuicFrames frames;
9241 QuicPingFrame ping_frame;
9242 QuicPaddingFrame padding_frame;
9243 frames.push_back(QuicFrame(ping_frame));
9244 frames.push_back(QuicFrame(padding_frame));
9245 std::unique_ptr<QuicPacket> packet =
9246 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9247 char buffer[kMaxOutgoingPacketSize];
9248 size_t encrypted_length =
9249 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9250 *packet, buffer, kMaxOutgoingPacketSize);
9251 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9252 false);
9253 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9254 }
9255 EXPECT_TRUE(connection_.connected());
9256 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9257 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9258}
9259
9260TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromInitial) {
9261 TestReplaceConnectionIdFromInitial();
9262}
9263
9264TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromRetryAndInitial) {
9265 // First make the connection process a RETRY and replace the server connection
9266 // ID a first time.
9267 TestClientRetryHandling(/*invalid_retry_tag=*/false,
9268 /*missing_original_id_in_config=*/false,
9269 /*wrong_original_id_in_config=*/false,
9270 /*missing_retry_id_in_config=*/false,
9271 /*wrong_retry_id_in_config=*/false);
9272 // Reset the test framer to use the right connection ID.
9273 peer_framer_.SetInitialObfuscators(connection_.connection_id());
9274 // Now process an INITIAL and replace the server connection ID a second time.
9275 TestReplaceConnectionIdFromInitial();
9276}
9277
9278// Regression test for b/134416344.
9279TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9280 // This test mimics a scenario where a connection processes 2 packets and the
9281 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9282 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9283 // because connection is disconnected.
9284 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9285 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9286 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
9287 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
9288 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
9289 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9290 NO_IETF_QUIC_ERROR, "",
9291 /*transport_close_frame_type=*/0));
9292
9293 // Received 2 packets.
9294 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9295 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9296 } else {
9297 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9298 }
9299 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
9300 ENCRYPTION_INITIAL);
9301 EXPECT_TRUE(connection_.HasPendingAcks());
9302 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
9303 kSelfAddress, kPeerAddress,
9304 ENCRYPTION_INITIAL);
9305 // Verify ack alarm is not set.
9306 EXPECT_FALSE(connection_.HasPendingAcks());
9307}
9308
9309// Verify that a packet containing three coalesced packets is parsed correctly.
9310TEST_P(QuicConnectionTest, CoalescedPacket) {
9311 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9312 // Coalesced packets can only be encoded using long header lengths.
9313 return;
9314 }
9315 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9316 EXPECT_TRUE(connection_.connected());
9317 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9318 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9319 } else {
9320 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9321 }
9322
9323 uint64_t packet_numbers[3] = {1, 2, 3};
9324 EncryptionLevel encryption_levels[3] = {
9325 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9326 char buffer[kMaxOutgoingPacketSize] = {};
9327 size_t total_encrypted_length = 0;
9328 for (int i = 0; i < 3; i++) {
9329 QuicPacketHeader header =
9330 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9331 QuicFrames frames;
9332 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9333 frames.push_back(QuicFrame(&crypto_frame_));
9334 } else {
9335 frames.push_back(QuicFrame(frame1_));
9336 }
9337 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9338 peer_creator_.set_encryption_level(encryption_levels[i]);
9339 size_t encrypted_length = peer_framer_.EncryptPayload(
9340 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9341 buffer + total_encrypted_length,
9342 sizeof(buffer) - total_encrypted_length);
9343 EXPECT_GT(encrypted_length, 0u);
9344 total_encrypted_length += encrypted_length;
9345 }
9346 connection_.ProcessUdpPacket(
9347 kSelfAddress, kPeerAddress,
9348 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9349 if (connection_.GetSendAlarm()->IsSet()) {
9350 connection_.GetSendAlarm()->Fire();
9351 }
9352
9353 EXPECT_TRUE(connection_.connected());
9354}
9355
9356// Regression test for crbug.com/992831.
9357TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9358 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9359 // Coalesced packets can only be encoded using long header lengths.
9360 return;
9361 }
9362 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9363 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9364 return;
9365 }
9366 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9367 EXPECT_TRUE(connection_.connected());
9368 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9369 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9370 .Times(3)
9371 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9372 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009373 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009374 });
9375 } else {
9376 EXPECT_CALL(visitor_, OnStreamFrame(_))
9377 .Times(3)
9378 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9379 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009380 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009381 });
9382 }
9383
9384 uint64_t packet_numbers[3] = {1, 2, 3};
9385 EncryptionLevel encryption_levels[3] = {
9386 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9387 char buffer[kMaxOutgoingPacketSize] = {};
9388 size_t total_encrypted_length = 0;
9389 for (int i = 0; i < 3; i++) {
9390 QuicPacketHeader header =
9391 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9392 QuicFrames frames;
9393 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9394 frames.push_back(QuicFrame(&crypto_frame_));
9395 } else {
9396 frames.push_back(QuicFrame(frame1_));
9397 }
9398 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9399 peer_creator_.set_encryption_level(encryption_levels[i]);
9400 size_t encrypted_length = peer_framer_.EncryptPayload(
9401 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9402 buffer + total_encrypted_length,
9403 sizeof(buffer) - total_encrypted_length);
9404 EXPECT_GT(encrypted_length, 0u);
9405 total_encrypted_length += encrypted_length;
9406 }
9407 connection_.ProcessUdpPacket(
9408 kSelfAddress, kPeerAddress,
9409 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9410 if (connection_.GetSendAlarm()->IsSet()) {
9411 connection_.GetSendAlarm()->Fire();
9412 }
9413
9414 EXPECT_TRUE(connection_.connected());
9415
9416 SendAckPacketToPeer();
9417}
9418
9419// Regresstion test for b/138962304.
9420TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
9421 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9422
9423 QuicStreamId stream_id = 2;
9424 QuicPacketNumber last_data_packet;
9425 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9426 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9427
9428 // Writer gets blocked.
9429 writer_->SetWriteBlocked();
9430
9431 // Cancel the stream.
9432 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9433 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9434 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9435 .WillRepeatedly(
9436 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
9437 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9438
9439 // Retransmission timer fires in RTO mode.
9440 connection_.GetRetransmissionAlarm()->Fire();
9441 // Verify no packets get flushed when writer is blocked.
9442 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9443}
9444
9445// Regresstion test for b/138962304.
fayang339f0c82022-04-30 14:20:02 -07009446TEST_P(QuicConnectionTest, PtoAndWriteBlocked) {
Bence Békybac04052022-04-07 15:44:29 -04009447 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
Bence Békybac04052022-04-07 15:44:29 -04009448
9449 QuicStreamId stream_id = 2;
9450 QuicPacketNumber last_data_packet;
9451 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9452 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9453 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9454
9455 // Writer gets blocked.
9456 writer_->SetWriteBlocked();
9457
9458 // Cancel stream 2.
9459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9460 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9461 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9462
9463 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9464 // Retransmission timer fires in TLP mode.
9465 connection_.GetRetransmissionAlarm()->Fire();
9466 // Verify one packets is forced flushed when writer is blocked.
9467 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9468}
9469
Bence Békybac04052022-04-07 15:44:29 -04009470TEST_P(QuicConnectionTest, ProbeTimeout) {
9471 QuicConfig config;
9472 QuicTagVector connection_options;
9473 connection_options.push_back(k2PTO);
9474 config.SetConnectionOptionsToSend(connection_options);
9475 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9476 connection_.SetFromConfig(config);
9477 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9478
9479 QuicStreamId stream_id = 2;
9480 QuicPacketNumber last_packet;
9481 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9482 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9483 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9484
9485 // Reset stream.
9486 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9487 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9488
9489 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9490 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9491 connection_.GetRetransmissionAlarm()->Fire();
9492 EXPECT_EQ(0u, writer_->stream_frames().size());
9493 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9494 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9495}
9496
9497TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
9498 QuicConfig config;
9499 QuicTagVector connection_options;
9500 connection_options.push_back(k1PTO);
9501 connection_options.push_back(k6PTO);
9502 config.SetConnectionOptionsToSend(connection_options);
9503 QuicConfigPeer::SetNegotiated(&config, true);
9504 if (connection_.version().UsesTls()) {
9505 QuicConfigPeer::SetReceivedOriginalConnectionId(
9506 &config, connection_.connection_id());
9507 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9508 &config, connection_.connection_id());
9509 }
9510 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9511 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009512 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9513 GetQuicReloadableFlag(
9514 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009515 EXPECT_CALL(visitor_, GetHandshakeState())
9516 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9517 }
9518 connection_.OnHandshakeComplete();
9519 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9520
9521 // Send stream data.
9522 SendStreamDataToPeer(
9523 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9524 0, FIN, nullptr);
9525
9526 // Fire the retransmission alarm 5 times.
9527 for (int i = 0; i < 5; ++i) {
9528 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9529 connection_.GetRetransmissionAlarm()->Fire();
9530 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9531 EXPECT_TRUE(connection_.connected());
9532 }
9533 EXPECT_CALL(visitor_, OnPathDegrading());
9534 connection_.PathDegradingTimeout();
9535
Bence Békybac04052022-04-07 15:44:29 -04009536 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9537 // Closes connection on 6th PTO.
9538 // May send multiple connecction close packets with multiple PN spaces.
9539 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9540 EXPECT_CALL(visitor_,
9541 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9542 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9543 connection_.GetBlackholeDetectorAlarm()->Fire();
9544 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9545 EXPECT_FALSE(connection_.connected());
9546 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9547}
9548
9549TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
9550 QuicConfig config;
9551 QuicTagVector connection_options;
9552 connection_options.push_back(k2PTO);
9553 connection_options.push_back(k7PTO);
9554 config.SetConnectionOptionsToSend(connection_options);
9555 QuicConfigPeer::SetNegotiated(&config, true);
9556 if (connection_.version().UsesTls()) {
9557 QuicConfigPeer::SetReceivedOriginalConnectionId(
9558 &config, connection_.connection_id());
9559 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9560 &config, connection_.connection_id());
9561 }
9562 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9563 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009564 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9565 GetQuicReloadableFlag(
9566 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009567 EXPECT_CALL(visitor_, GetHandshakeState())
9568 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9569 }
9570 connection_.OnHandshakeComplete();
9571 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9572
9573 // Send stream data.
9574 SendStreamDataToPeer(
9575 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9576 0, FIN, nullptr);
9577
9578 // Fire the retransmission alarm 6 times.
9579 for (int i = 0; i < 6; ++i) {
9580 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9581 connection_.GetRetransmissionAlarm()->Fire();
9582 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9583 EXPECT_TRUE(connection_.connected());
9584 }
9585 EXPECT_CALL(visitor_, OnPathDegrading());
9586 connection_.PathDegradingTimeout();
9587
Bence Békybac04052022-04-07 15:44:29 -04009588 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9589 // Closes connection on 7th PTO.
9590 EXPECT_CALL(visitor_,
9591 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9592 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9593 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9594 connection_.GetBlackholeDetectorAlarm()->Fire();
9595 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9596 EXPECT_FALSE(connection_.connected());
9597 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9598}
9599
9600TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
9601 QuicConfig config;
9602 QuicTagVector connection_options;
9603 connection_options.push_back(k2PTO);
9604 connection_options.push_back(k8PTO);
9605 QuicConfigPeer::SetNegotiated(&config, true);
9606 if (connection_.version().UsesTls()) {
9607 QuicConfigPeer::SetReceivedOriginalConnectionId(
9608 &config, connection_.connection_id());
9609 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9610 &config, connection_.connection_id());
9611 }
9612 config.SetConnectionOptionsToSend(connection_options);
9613 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9614 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009615 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9616 GetQuicReloadableFlag(
9617 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009618 EXPECT_CALL(visitor_, GetHandshakeState())
9619 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9620 }
9621 connection_.OnHandshakeComplete();
9622 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9623
9624 // Send stream data.
9625 SendStreamDataToPeer(
9626 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9627 0, FIN, nullptr);
9628
9629 // Fire the retransmission alarm 7 times.
9630 for (int i = 0; i < 7; ++i) {
9631 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9632 connection_.GetRetransmissionAlarm()->Fire();
9633 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9634 EXPECT_TRUE(connection_.connected());
9635 }
9636 EXPECT_CALL(visitor_, OnPathDegrading());
9637 connection_.PathDegradingTimeout();
9638
Bence Békybac04052022-04-07 15:44:29 -04009639 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9640 // Closes connection on 8th PTO.
9641 EXPECT_CALL(visitor_,
9642 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9643 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9644 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9645 connection_.GetBlackholeDetectorAlarm()->Fire();
9646 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9647 EXPECT_FALSE(connection_.connected());
9648 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9649}
9650
9651TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9652 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9653 return;
9654 }
9655 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9656 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9657
9658 // Send CHLO.
9659 connection_.SendCryptoStreamData();
9660 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9661
9662 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
martindukeba002452023-03-21 08:10:46 -07009663 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -04009664 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9665 QuicAckFrame frame1 = InitAckFrame(1);
9666 // Received ACK for packet 1.
9667 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9668
9669 // Verify retransmission alarm is still set because handshake is not
9670 // confirmed although there is nothing in flight.
9671 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9672 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9673 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9674
9675 // PTO fires, verify a PING packet gets sent because there is no data to send.
9676 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9677 connection_.GetRetransmissionAlarm()->Fire();
9678 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9679 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
9680 EXPECT_EQ(1u, writer_->ping_frames().size());
9681}
9682
9683TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009684 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009685 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009686 return;
9687 }
9688 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9689
9690 set_perspective(Perspective::IS_SERVER);
9691 // Verify no data can be sent at the beginning because bytes received is 0.
9692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9693 connection_.SendCryptoDataWithString("foo", 0);
9694 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9695 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9696 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9697
9698 // Receives packet 1.
9699 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009700 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009701 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9702
9703 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -07009704 GetQuicFlag(quic_anti_amplification_factor);
Bence Békybac04052022-04-07 15:44:29 -04009705 // Verify now packets can be sent.
9706 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9707 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9708 connection_.SendCryptoDataWithString("foo", i * 3);
9709 // Verify retransmission alarm is not set if throttled by anti-amplification
9710 // limit.
9711 EXPECT_EQ(i != anti_amplification_factor - 1,
9712 connection_.GetRetransmissionAlarm()->IsSet());
9713 }
9714 // Verify server is throttled by anti-amplification limit.
9715 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9716 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9717
9718 // Receives packet 2.
9719 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009720 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009721 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9722 // Verify more packets can be sent.
9723 for (size_t i = anti_amplification_factor + 1;
9724 i < anti_amplification_factor * 2; ++i) {
9725 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9726 connection_.SendCryptoDataWithString("foo", i * 3);
9727 }
9728 // Verify server is throttled by anti-amplification limit.
9729 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9730 connection_.SendCryptoDataWithString("foo",
9731 2 * anti_amplification_factor * 3);
9732
9733 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009734 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009735 ProcessPacket(3);
9736 // Verify anti-amplification limit is gone after address validation.
9737 for (size_t i = 0; i < 100; ++i) {
9738 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9739 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9740 }
9741}
9742
9743TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009744 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009745 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009746 return;
9747 }
9748 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9749
9750 set_perspective(Perspective::IS_SERVER);
9751 QuicConfig config;
9752 QuicTagVector connection_options;
9753 connection_options.push_back(k3AFF);
9754 config.SetInitialReceivedConnectionOptions(connection_options);
9755 if (connection_.version().UsesTls()) {
9756 QuicConfigPeer::SetReceivedOriginalConnectionId(
9757 &config, connection_.connection_id());
9758 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9759 QuicConnectionId());
9760 }
9761 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9762 connection_.SetFromConfig(config);
9763
9764 // Verify no data can be sent at the beginning because bytes received is 0.
9765 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9766 connection_.SendCryptoDataWithString("foo", 0);
9767 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9768 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9769 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9770
9771 // Receives packet 1.
9772 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009773 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009774 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9775
9776 const size_t anti_amplification_factor = 3;
9777 // Verify now packets can be sent.
9778 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9779 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9780 connection_.SendCryptoDataWithString("foo", i * 3);
9781 // Verify retransmission alarm is not set if throttled by anti-amplification
9782 // limit.
9783 EXPECT_EQ(i != anti_amplification_factor - 1,
9784 connection_.GetRetransmissionAlarm()->IsSet());
9785 }
9786 // Verify server is throttled by anti-amplification limit.
9787 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9788 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9789
9790 // Receives packet 2.
9791 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009792 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009793 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9794 // Verify more packets can be sent.
9795 for (size_t i = anti_amplification_factor + 1;
9796 i < anti_amplification_factor * 2; ++i) {
9797 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9798 connection_.SendCryptoDataWithString("foo", i * 3);
9799 }
9800 // Verify server is throttled by anti-amplification limit.
9801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9802 connection_.SendCryptoDataWithString("foo",
9803 2 * anti_amplification_factor * 3);
9804
9805 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009806 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009807 ProcessPacket(3);
9808 // Verify anti-amplification limit is gone after address validation.
9809 for (size_t i = 0; i < 100; ++i) {
9810 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9811 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9812 }
9813}
9814
9815TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009816 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009817 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009818 return;
9819 }
9820 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9821
9822 set_perspective(Perspective::IS_SERVER);
9823 QuicConfig config;
9824 QuicTagVector connection_options;
9825 connection_options.push_back(k10AF);
9826 config.SetInitialReceivedConnectionOptions(connection_options);
9827 if (connection_.version().UsesTls()) {
9828 QuicConfigPeer::SetReceivedOriginalConnectionId(
9829 &config, connection_.connection_id());
9830 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9831 QuicConnectionId());
9832 }
9833 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9834 connection_.SetFromConfig(config);
9835
9836 // Verify no data can be sent at the beginning because bytes received is 0.
9837 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9838 connection_.SendCryptoDataWithString("foo", 0);
9839 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9840 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9841 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9842
9843 // Receives packet 1.
9844 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009845 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009846 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9847
9848 const size_t anti_amplification_factor = 10;
9849 // Verify now packets can be sent.
9850 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9851 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9852 connection_.SendCryptoDataWithString("foo", i * 3);
9853 // Verify retransmission alarm is not set if throttled by anti-amplification
9854 // limit.
9855 EXPECT_EQ(i != anti_amplification_factor - 1,
9856 connection_.GetRetransmissionAlarm()->IsSet());
9857 }
9858 // Verify server is throttled by anti-amplification limit.
9859 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9860 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9861
9862 // Receives packet 2.
9863 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009864 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009865 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9866 // Verify more packets can be sent.
9867 for (size_t i = anti_amplification_factor + 1;
9868 i < anti_amplification_factor * 2; ++i) {
9869 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9870 connection_.SendCryptoDataWithString("foo", i * 3);
9871 }
9872 // Verify server is throttled by anti-amplification limit.
9873 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9874 connection_.SendCryptoDataWithString("foo",
9875 2 * anti_amplification_factor * 3);
9876
9877 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
wubc9fd4292023-08-14 13:00:21 -07009878 ForceWillingAndAbleToWriteOnceForDeferSending();
Bence Békybac04052022-04-07 15:44:29 -04009879 ProcessPacket(3);
9880 // Verify anti-amplification limit is gone after address validation.
9881 for (size_t i = 0; i < 100; ++i) {
9882 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9883 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9884 }
9885}
9886
9887TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
9888 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9889 return;
9890 }
9891 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9892 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
9893 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -04009894 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9895 // Receives packet 1.
9896 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08009897 connection_.SetEncrypter(
9898 ENCRYPTION_HANDSHAKE,
9899 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -04009900 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9901 EXPECT_TRUE(connection_.HasPendingAcks());
9902 // Send response in different encryption level and cause amplification factor
9903 // throttled.
9904 size_t i = 0;
9905 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
9906 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
9907 ENCRYPTION_HANDSHAKE);
9908 ++i;
9909 }
9910 // Verify ACK is still pending.
9911 EXPECT_TRUE(connection_.HasPendingAcks());
9912
9913 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
9914 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
9915 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9916 connection_.GetAckAlarm()->Fire();
9917 // Verify ACK alarm is cancelled.
9918 EXPECT_FALSE(connection_.HasPendingAcks());
9919
9920 // Receives packet 2 and verify ACK gets flushed.
9921 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9922 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9923 EXPECT_FALSE(writer_->ack_frames().empty());
9924}
9925
9926TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9927 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9928 // Test relevent only for IETF QUIC.
9929 return;
9930 }
9931 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9932 // Use the (unknown) frame type of 9999 to avoid triggering any logic
9933 // which might be associated with the processing of a known frame type.
9934 const uint64_t kTransportCloseFrameType = 9999u;
9935 QuicFramerPeer::set_current_received_frame_type(
9936 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9937 // Do a transport connection close
9938 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9939 connection_.CloseConnection(
9940 kQuicErrorCode, "Some random error message",
9941 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9942 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9943 writer_->connection_close_frames();
9944 ASSERT_EQ(1u, connection_close_frames.size());
9945 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9946 connection_close_frames[0].close_type);
9947 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
9948 EXPECT_EQ(kTransportCloseFrameType,
9949 connection_close_frames[0].transport_close_frame_type);
9950}
9951
Bence Békybac04052022-04-07 15:44:29 -04009952TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
9953 QuicConfig config;
9954 QuicTagVector connection_options;
9955 connection_options.push_back(k1PTO);
9956 connection_options.push_back(kPTOS);
9957 config.SetConnectionOptionsToSend(connection_options);
9958 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9959 connection_.SetFromConfig(config);
9960 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9961
9962 QuicStreamId stream_id = 2;
9963 QuicPacketNumber last_packet;
9964 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9965 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9966 EXPECT_EQ(QuicPacketNumber(2), last_packet);
9967 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9968
9969 // Fire PTO and verify the PTO retransmission skips one packet number.
9970 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9971 connection_.GetRetransmissionAlarm()->Fire();
9972 EXPECT_EQ(1u, writer_->stream_frames().size());
9973 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9974 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9975}
9976
9977TEST_P(QuicConnectionTest, SendCoalescedPackets) {
9978 if (!connection_.version().CanSendCoalescedPackets()) {
9979 return;
9980 }
9981 MockQuicConnectionDebugVisitor debug_visitor;
9982 connection_.set_debug_visitor(&debug_visitor);
wub92727922023-07-13 08:47:39 -07009983 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -04009984 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
9985 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
9986 {
9987 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04009988 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9989 connection_.SendCryptoDataWithString("foo", 0);
9990 // Verify this packet is on hold.
9991 EXPECT_EQ(0u, writer_->packets_write_attempts());
9992
9993 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9994 std::make_unique<TaggingEncrypter>(0x02));
9995 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9996 connection_.SendCryptoDataWithString("bar", 3);
9997 EXPECT_EQ(0u, writer_->packets_write_attempts());
9998
9999 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10000 std::make_unique<TaggingEncrypter>(0x03));
10001 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10002 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10003 }
10004 // Verify all 3 packets are coalesced in the same UDP datagram.
10005 EXPECT_EQ(1u, writer_->packets_write_attempts());
10006 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10007 // Verify the packet is padded to full.
10008 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10009
10010 // Verify packet process.
10011 EXPECT_EQ(1u, writer_->crypto_frames().size());
10012 EXPECT_EQ(0u, writer_->stream_frames().size());
10013 // Verify there is coalesced packet.
10014 EXPECT_NE(nullptr, writer_->coalesced_packet());
10015}
10016
10017TEST_P(QuicConnectionTest, FailToCoalescePacket) {
10018 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
10019 if (!IsDefaultTestConfiguration() ||
fayang161ce6e2022-07-01 18:02:11 -070010020 !connection_.version().CanSendCoalescedPackets() ||
birenroyef686222022-09-12 11:34:34 -070010021 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040010022 return;
10023 }
10024
10025 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040010026
Bence Békybac04052022-04-07 15:44:29 -040010027 auto test_body = [&] {
vasilvvac2e30d2022-06-02 14:26:59 -070010028 EXPECT_CALL(visitor_,
10029 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10030 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
Bence Békybac04052022-04-07 15:44:29 -040010031
vasilvvac2e30d2022-06-02 14:26:59 -070010032 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -040010033
vasilvvac2e30d2022-06-02 14:26:59 -070010034 {
10035 QuicConnection::ScopedPacketFlusher flusher(&connection_);
vasilvvac2e30d2022-06-02 14:26:59 -070010036 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10037 connection_.SendCryptoDataWithString("foo", 0);
10038 // Verify this packet is on hold.
10039 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -040010040
vasilvvac2e30d2022-06-02 14:26:59 -070010041 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10042 std::make_unique<TaggingEncrypter>(0x02));
10043 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10044 connection_.SendCryptoDataWithString("bar", 3);
10045 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -040010046
vasilvvac2e30d2022-06-02 14:26:59 -070010047 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10048 std::make_unique<TaggingEncrypter>(0x03));
10049 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10050 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
Bence Békybac04052022-04-07 15:44:29 -040010051
vasilvvac2e30d2022-06-02 14:26:59 -070010052 creator_->Flush();
10053
10054 auto& coalesced_packet =
10055 QuicConnectionPeer::GetCoalescedPacket(&connection_);
10056 QuicPacketLength coalesced_packet_max_length =
10057 coalesced_packet.max_packet_length();
10058 QuicCoalescedPacketPeer::SetMaxPacketLength(coalesced_packet,
10059 coalesced_packet.length());
10060
10061 // Make the coalescer's FORWARD_SECURE packet longer.
10062 *QuicCoalescedPacketPeer::GetMutableEncryptedBuffer(
10063 coalesced_packet, ENCRYPTION_FORWARD_SECURE) += "!!! TEST !!!";
10064
10065 QUIC_LOG(INFO) << "Reduced coalesced_packet_max_length from "
10066 << coalesced_packet_max_length << " to "
10067 << coalesced_packet.max_packet_length()
10068 << ", coalesced_packet.length:"
10069 << coalesced_packet.length()
10070 << ", coalesced_packet.packet_lengths:"
10071 << absl::StrJoin(coalesced_packet.packet_lengths(), ":");
10072 }
10073
10074 EXPECT_FALSE(connection_.connected());
10075 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10076 IsError(QUIC_FAILED_TO_SERIALIZE_PACKET));
10077 EXPECT_EQ(saved_connection_close_frame_.error_details,
10078 "Failed to serialize coalesced packet.");
Bence Békybac04052022-04-07 15:44:29 -040010079 };
10080
10081 EXPECT_QUIC_BUG(test_body(), "SerializeCoalescedPacket failed.");
Bence Békybac04052022-04-07 15:44:29 -040010082}
10083
Bence Békybac04052022-04-07 15:44:29 -040010084TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10085 if (!connection_.version().UsesTls()) {
10086 return;
10087 }
10088 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10089 QuicFrames frames;
10090 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10091 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10092 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10093}
10094
10095TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10096 if (!connection_.version().UsesTls()) {
10097 return;
10098 }
10099 set_perspective(Perspective::IS_SERVER);
10100 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10101 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
10102 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
10103 }
10104 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10105 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10106 QuicFrames frames;
10107 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10108 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10109 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10110 EXPECT_EQ(1, connection_close_frame_count_);
10111 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10112 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10113}
10114
10115TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10116 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10117 return;
10118 }
Bence Békybac04052022-04-07 15:44:29 -040010119 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010120 connection_.SetEncrypter(
10121 ENCRYPTION_HANDSHAKE,
10122 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010123 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10124 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10125 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080010126 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010127
10128 // Send application data.
10129 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10130 0, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010131 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010132 QuicTime retransmission_time =
10133 connection_.GetRetransmissionAlarm()->deadline();
10134 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10135
10136 // Retransmit handshake data.
10137 clock_.AdvanceTime(retransmission_time - clock_.Now());
10138 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _));
10139 connection_.GetRetransmissionAlarm()->Fire();
10140 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010141 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010142
10143 // Send application data.
10144 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10145 4, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010146 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010147 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10148 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10149
10150 // Retransmit handshake data again.
10151 clock_.AdvanceTime(retransmission_time - clock_.Now());
10152 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _));
10153 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(8), _, _));
10154 connection_.GetRetransmissionAlarm()->Fire();
10155 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010156 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010157
10158 // Discard handshake key.
10159 connection_.OnHandshakeComplete();
10160 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10161 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10162
10163 // Retransmit application data.
10164 clock_.AdvanceTime(retransmission_time - clock_.Now());
10165 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(11), _, _));
10166 connection_.GetRetransmissionAlarm()->Fire();
martinduke9e0811c2022-12-08 20:35:57 -080010167 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010168}
10169
10170void QuicConnectionTest::TestClientRetryHandling(
10171 bool invalid_retry_tag, bool missing_original_id_in_config,
10172 bool wrong_original_id_in_config, bool missing_retry_id_in_config,
10173 bool wrong_retry_id_in_config) {
10174 if (invalid_retry_tag) {
10175 ASSERT_FALSE(missing_original_id_in_config);
10176 ASSERT_FALSE(wrong_original_id_in_config);
10177 ASSERT_FALSE(missing_retry_id_in_config);
10178 ASSERT_FALSE(wrong_retry_id_in_config);
10179 } else {
10180 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10181 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
10182 }
10183 if (!version().UsesTls()) {
10184 return;
10185 }
10186
10187 // These values come from draft-ietf-quic-v2 Appendix A.4.
10188 uint8_t retry_packet_rfcv2[] = {
martindukea2cb68a2022-12-12 17:24:39 -080010189 0xcf, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10190 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xc8, 0x64, 0x6c, 0xe8,
10191 0xbf, 0xe3, 0x39, 0x52, 0xd9, 0x55, 0x54, 0x36, 0x65, 0xdc, 0xc7, 0xb6};
Bence Békybac04052022-04-07 15:44:29 -040010192 // These values come from RFC9001 Appendix A.4.
10193 uint8_t retry_packet_rfcv1[] = {
10194 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10195 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba,
10196 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba};
10197 uint8_t retry_packet29[] = {
10198 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10199 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10200 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
10201
10202 uint8_t* retry_packet;
10203 size_t retry_packet_length;
martinduke88918ac2023-06-02 10:44:08 -070010204 if (version() == ParsedQuicVersion::RFCv2()) {
Bence Békybac04052022-04-07 15:44:29 -040010205 retry_packet = retry_packet_rfcv2;
10206 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv2);
10207 } else if (version() == ParsedQuicVersion::RFCv1()) {
10208 retry_packet = retry_packet_rfcv1;
10209 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv1);
10210 } else if (version() == ParsedQuicVersion::Draft29()) {
10211 retry_packet = retry_packet29;
10212 retry_packet_length = ABSL_ARRAYSIZE(retry_packet29);
10213 } else {
10214 // TODO(dschinazi) generate retry packets for all versions once we have
10215 // server-side support for generating these programmatically.
10216 return;
10217 }
10218
10219 uint8_t original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10220 0x3e, 0x51, 0x57, 0x08};
10221 uint8_t new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10222 0x2a, 0x42, 0x62, 0xb5};
10223 uint8_t retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10224
10225 QuicConnectionId original_connection_id(
10226 reinterpret_cast<char*>(original_connection_id_bytes),
10227 ABSL_ARRAYSIZE(original_connection_id_bytes));
10228 QuicConnectionId new_connection_id(
10229 reinterpret_cast<char*>(new_connection_id_bytes),
10230 ABSL_ARRAYSIZE(new_connection_id_bytes));
10231
10232 std::string retry_token(reinterpret_cast<char*>(retry_token_bytes),
10233 ABSL_ARRAYSIZE(retry_token_bytes));
10234
10235 if (invalid_retry_tag) {
10236 // Flip the last bit of the retry packet to prevent the integrity tag
10237 // from validating correctly.
10238 retry_packet[retry_packet_length - 1] ^= 1;
10239 }
10240
10241 QuicConnectionId config_original_connection_id = original_connection_id;
10242 if (wrong_original_id_in_config) {
10243 // Flip the first bit of the connection ID.
10244 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10245 config_original_connection_id.mutable_data()[0] ^= 0x80;
10246 }
10247 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10248 if (wrong_retry_id_in_config) {
10249 // Flip the first bit of the connection ID.
10250 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10251 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10252 }
10253
10254 // Make sure the connection uses the connection ID from the test vectors,
10255 QuicConnectionPeer::SetServerConnectionId(&connection_,
10256 original_connection_id);
10257 // Make sure our fake framer has the new post-retry INITIAL keys so that any
10258 // retransmission triggered by retry can be decrypted.
10259 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10260
10261 // Process the RETRY packet.
10262 connection_.ProcessUdpPacket(
10263 kSelfAddress, kPeerAddress,
10264 QuicReceivedPacket(reinterpret_cast<char*>(retry_packet),
10265 retry_packet_length, clock_.Now()));
10266
10267 if (invalid_retry_tag) {
10268 // Make sure we refuse to process a RETRY with invalid tag.
10269 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10270 EXPECT_EQ(connection_.connection_id(), original_connection_id);
10271 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
10272 QuicConnectionPeer::GetPacketCreator(&connection_))
10273 .empty());
10274 return;
10275 }
10276
10277 // Make sure we correctly parsed the RETRY.
10278 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10279 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10280 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10281 QuicConnectionPeer::GetPacketCreator(&connection_)),
10282 retry_token);
10283
10284 // Test validating the original_connection_id from the config.
10285 QuicConfig received_config;
10286 QuicConfigPeer::SetNegotiated(&received_config, true);
10287 if (connection_.version().UsesTls()) {
10288 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10289 &received_config, connection_.connection_id());
10290 if (!missing_retry_id_in_config) {
10291 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10292 &received_config, config_retry_source_connection_id);
10293 }
10294 }
10295 if (!missing_original_id_in_config) {
10296 QuicConfigPeer::SetReceivedOriginalConnectionId(
10297 &received_config, config_original_connection_id);
10298 }
10299
10300 if (missing_original_id_in_config || wrong_original_id_in_config ||
10301 missing_retry_id_in_config || wrong_retry_id_in_config) {
10302 EXPECT_CALL(visitor_,
10303 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10304 .Times(1);
10305 } else {
10306 EXPECT_CALL(visitor_,
10307 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10308 .Times(0);
10309 }
10310 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10311 connection_.SetFromConfig(received_config);
10312 if (missing_original_id_in_config || wrong_original_id_in_config ||
10313 missing_retry_id_in_config || wrong_retry_id_in_config) {
10314 ASSERT_FALSE(connection_.connected());
10315 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10316 } else {
10317 EXPECT_TRUE(connection_.connected());
10318 }
10319}
10320
fayangc0123f72024-09-22 16:03:58 -070010321TEST_P(QuicConnectionTest, FixTimeoutsClient) {
10322 if (!connection_.version().UsesTls()) {
10323 return;
10324 }
10325 set_perspective(Perspective::IS_CLIENT);
10326 if (GetQuicReloadableFlag(quic_fix_timeouts)) {
10327 EXPECT_CALL(visitor_, GetHandshakeState())
10328 .WillRepeatedly(Return(HANDSHAKE_START));
10329 }
10330 QuicConfig config;
10331 QuicTagVector connection_options;
10332 connection_options.push_back(kFTOE);
10333 config.SetConnectionOptionsToSend(connection_options);
10334 QuicConfigPeer::SetNegotiated(&config, true);
10335 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
10336 connection_.connection_id());
10337 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10338 &config, connection_.connection_id());
10339
10340 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
10341 connection_.SetFromConfig(config);
10342 QuicIdleNetworkDetector& idle_network_detector =
10343 QuicConnectionPeer::GetIdleNetworkDetector(&connection_);
10344 if (GetQuicReloadableFlag(quic_fix_timeouts)) {
10345 // Handshake timeout has not been removed yet.
10346 EXPECT_NE(idle_network_detector.handshake_timeout(),
10347 QuicTime::Delta::Infinite());
10348 } else {
10349 // Handshake timeout has been set to infinite.
10350 EXPECT_EQ(idle_network_detector.handshake_timeout(),
10351 QuicTime::Delta::Infinite());
10352 }
10353}
10354
10355TEST_P(QuicConnectionTest, FixTimeoutsServer) {
10356 if (!connection_.version().UsesTls()) {
10357 return;
10358 }
10359 set_perspective(Perspective::IS_SERVER);
10360 if (GetQuicReloadableFlag(quic_fix_timeouts)) {
10361 EXPECT_CALL(visitor_, GetHandshakeState())
10362 .WillRepeatedly(Return(HANDSHAKE_START));
10363 }
10364 QuicConfig config;
10365 quic::QuicTagVector initial_received_options;
10366 initial_received_options.push_back(quic::kFTOE);
10367 ASSERT_TRUE(
10368 config.SetInitialReceivedConnectionOptions(initial_received_options));
10369 QuicConfigPeer::SetNegotiated(&config, true);
10370 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
10371 connection_.connection_id());
10372 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
10373 QuicConnectionId());
10374
10375 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
10376 connection_.SetFromConfig(config);
10377 QuicIdleNetworkDetector& idle_network_detector =
10378 QuicConnectionPeer::GetIdleNetworkDetector(&connection_);
10379 if (GetQuicReloadableFlag(quic_fix_timeouts)) {
10380 // Handshake timeout has not been removed yet.
10381 EXPECT_NE(idle_network_detector.handshake_timeout(),
10382 QuicTime::Delta::Infinite());
10383 } else {
10384 // Handshake timeout has been set to infinite.
10385 EXPECT_EQ(idle_network_detector.handshake_timeout(),
10386 QuicTime::Delta::Infinite());
10387 }
10388}
10389
Bence Békybac04052022-04-07 15:44:29 -040010390TEST_P(QuicConnectionTest, ClientParsesRetry) {
10391 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10392 /*missing_original_id_in_config=*/false,
10393 /*wrong_original_id_in_config=*/false,
10394 /*missing_retry_id_in_config=*/false,
10395 /*wrong_retry_id_in_config=*/false);
10396}
10397
10398TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
10399 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10400 /*missing_original_id_in_config=*/false,
10401 /*wrong_original_id_in_config=*/false,
10402 /*missing_retry_id_in_config=*/false,
10403 /*wrong_retry_id_in_config=*/false);
10404}
10405
10406TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
10407 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10408 /*missing_original_id_in_config=*/true,
10409 /*wrong_original_id_in_config=*/false,
10410 /*missing_retry_id_in_config=*/false,
10411 /*wrong_retry_id_in_config=*/false);
10412}
10413
10414TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
10415 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10416 /*missing_original_id_in_config=*/false,
10417 /*wrong_original_id_in_config=*/true,
10418 /*missing_retry_id_in_config=*/false,
10419 /*wrong_retry_id_in_config=*/false);
10420}
10421
10422TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10423 if (!connection_.version().UsesTls()) {
10424 // Versions that do not authenticate connection IDs never send the
10425 // retry_source_connection_id transport parameter.
10426 return;
10427 }
10428 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10429 /*missing_original_id_in_config=*/false,
10430 /*wrong_original_id_in_config=*/false,
10431 /*missing_retry_id_in_config=*/true,
10432 /*wrong_retry_id_in_config=*/false);
10433}
10434
10435TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10436 if (!connection_.version().UsesTls()) {
10437 // Versions that do not authenticate connection IDs never send the
10438 // retry_source_connection_id transport parameter.
10439 return;
10440 }
10441 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10442 /*missing_original_id_in_config=*/false,
10443 /*wrong_original_id_in_config=*/false,
10444 /*missing_retry_id_in_config=*/false,
10445 /*wrong_retry_id_in_config=*/true);
10446}
10447
10448TEST_P(QuicConnectionTest, ClientRetransmitsInitialPacketsOnRetry) {
10449 if (!connection_.version().HasIetfQuicFrames()) {
10450 // TestClientRetryHandling() currently only supports IETF draft versions.
10451 return;
10452 }
10453 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10454
10455 connection_.SendCryptoStreamData();
10456
10457 EXPECT_EQ(1u, writer_->packets_write_attempts());
10458 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10459 /*missing_original_id_in_config=*/false,
10460 /*wrong_original_id_in_config=*/false,
10461 /*missing_retry_id_in_config=*/false,
10462 /*wrong_retry_id_in_config=*/false);
10463
10464 // Verify that initial data is retransmitted immediately after receiving
10465 // RETRY.
10466 if (GetParam().ack_response == AckResponse::kImmediate) {
10467 EXPECT_EQ(2u, writer_->packets_write_attempts());
10468 EXPECT_EQ(1u, writer_->framer()->crypto_frames().size());
10469 }
10470}
10471
10472TEST_P(QuicConnectionTest, NoInitialPacketsRetransmissionOnInvalidRetry) {
10473 if (!connection_.version().HasIetfQuicFrames()) {
10474 return;
10475 }
10476 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10477
10478 connection_.SendCryptoStreamData();
10479
10480 EXPECT_EQ(1u, writer_->packets_write_attempts());
10481 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10482 /*missing_original_id_in_config=*/false,
10483 /*wrong_original_id_in_config=*/false,
10484 /*missing_retry_id_in_config=*/false,
10485 /*wrong_retry_id_in_config=*/false);
10486
10487 EXPECT_EQ(1u, writer_->packets_write_attempts());
10488}
10489
10490TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
10491 if (!connection_.version().UsesTls()) {
10492 // QUIC+TLS is required to transmit connection ID transport parameters.
10493 return;
10494 }
10495 if (connection_.version().UsesTls()) {
10496 // Versions that authenticate connection IDs always send the
10497 // original_destination_connection_id transport parameter.
10498 return;
10499 }
10500 // Make sure that receiving the original_destination_connection_id transport
10501 // parameter fails the handshake when no RETRY packet was received before it.
10502 QuicConfig received_config;
10503 QuicConfigPeer::SetNegotiated(&received_config, true);
10504 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10505 TestConnectionId(0x12345));
10506 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10507 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10508 .Times(1);
10509 connection_.SetFromConfig(received_config);
10510 EXPECT_FALSE(connection_.connected());
10511 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10512}
10513
10514TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10515 if (!connection_.version().UsesTls()) {
10516 // Versions that do not authenticate connection IDs never send the
10517 // retry_source_connection_id transport parameter.
10518 return;
10519 }
10520 // Make sure that receiving the retry_source_connection_id transport parameter
10521 // fails the handshake when no RETRY packet was received before it.
10522 QuicConfig received_config;
10523 QuicConfigPeer::SetNegotiated(&received_config, true);
10524 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10525 TestConnectionId(0x12345));
10526 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10527 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10528 .Times(1);
10529 connection_.SetFromConfig(received_config);
10530 EXPECT_FALSE(connection_.connected());
10531 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10532}
10533
10534// Regression test for http://crbug/1047977
10535TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10536 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10537 return;
10538 }
10539 // Received frame causes connection close.
10540 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10541 .WillOnce(InvokeWithoutArgs([this]() {
10542 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10543 connection_.CloseConnection(
10544 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10545 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10546 return true;
10547 }));
10548 QuicFrames frames;
10549 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10550 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10551 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10552}
10553
10554TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10555 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10556 return;
10557 }
10558 // Received frame causes connection close.
10559 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10560 .WillOnce(InvokeWithoutArgs([this]() {
10561 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10562 connection_.CloseConnection(
10563 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10564 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10565 return true;
10566 }));
10567 QuicFrames frames;
10568 frames.push_back(
10569 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10570 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10571 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10572}
10573
10574TEST_P(QuicConnectionTest,
10575 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10576 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10577 return;
10578 }
10579 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10580 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10581 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10582 // Receives packet 1000 in initial data.
10583 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10584 // Receives packet 2000 in application data.
10585 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10586 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10587 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10588 connection_.CloseConnection(
10589 kQuicErrorCode, "Some random error message",
10590 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10591
10592 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10593
10594 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10595 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10596 // Verify ack is bundled.
10597 EXPECT_EQ(1u, writer_->ack_frames().size());
10598
10599 if (!connection_.version().CanSendCoalescedPackets()) {
10600 // Each connection close packet should be sent in distinct UDP packets.
10601 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10602 writer_->connection_close_packets());
10603 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10604 writer_->packets_write_attempts());
10605 return;
10606 }
10607
10608 // A single UDP packet should be sent with multiple connection close packets
10609 // coalesced together.
10610 EXPECT_EQ(1u, writer_->packets_write_attempts());
10611
10612 // Only the first packet has been processed yet.
10613 EXPECT_EQ(1u, writer_->connection_close_packets());
10614
10615 // ProcessPacket resets the visitor and frees the coalesced packet.
10616 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10617 auto packet = writer_->coalesced_packet()->Clone();
10618 writer_->framer()->ProcessPacket(*packet);
10619 EXPECT_EQ(1u, writer_->connection_close_packets());
10620 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10621 // Verify ack is bundled.
10622 EXPECT_EQ(1u, writer_->ack_frames().size());
10623 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10624}
10625
10626// Regression test for b/151220135.
10627TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
Bence Békybac04052022-04-07 15:44:29 -040010628 QuicConfig config;
10629 QuicTagVector connection_options;
10630 connection_options.push_back(kPTOS);
10631 connection_options.push_back(k1PTO);
10632 config.SetConnectionOptionsToSend(connection_options);
10633 if (connection_.version().UsesTls()) {
10634 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10635 &config, kMaxAcceptedDatagramFrameSize);
10636 }
10637 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10638 connection_.SetFromConfig(config);
10639 connection_.OnHandshakeComplete();
10640 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10641
10642 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10643 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10644
10645 // PTO fires, verify a PING packet gets sent because there is no data to
10646 // send.
10647 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10648 connection_.GetRetransmissionAlarm()->Fire();
10649 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10650 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10651 EXPECT_EQ(1u, writer_->ping_frames().size());
10652}
10653
10654// Regression test for b/155757133
10655TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10656 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10657 return;
10658 }
10659 const size_t kMinRttMs = 40;
10660 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10661 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10662 QuicTime::Delta::Zero(), QuicTime::Zero());
10663 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -070010664 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040010665 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10666 // Discard INITIAL key.
10667 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10668 connection_.NeuterUnencryptedPackets();
10669 EXPECT_CALL(visitor_, GetHandshakeState())
10670 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10671
10672 ProcessPacket(2);
10673 ProcessPacket(3);
10674 ProcessPacket(4);
10675 // Process a packet containing stream frame followed by ACK of packets 1.
10676 QuicFrames frames;
10677 frames.push_back(QuicFrame(QuicStreamFrame(
10678 QuicUtils::GetFirstBidirectionalStreamId(
10679 connection_.version().transport_version, Perspective::IS_CLIENT),
10680 false, 0u, absl::string_view())));
10681 QuicAckFrame ack_frame = InitAckFrame(1);
10682 frames.push_back(QuicFrame(&ack_frame));
10683 // Receiving stream frame causes something to send.
10684 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10685 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
10686 // Verify now the queued ACK contains packet number 2.
10687 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10688 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10689 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10690 }));
10691 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10692 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10693}
10694
martinduke9e0811c2022-12-08 20:35:57 -080010695TEST_P(QuicConnectionTest, DoNotExtendIdleTimeOnUndecryptablePackets) {
Bence Békybac04052022-04-07 15:44:29 -040010696 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10697 QuicConfig config;
10698 connection_.SetFromConfig(config);
10699 // Subtract a second from the idle timeout on the client side.
10700 QuicTime initial_deadline =
10701 clock_.ApproximateNow() +
10702 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10703 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10704
10705 // Received an undecryptable packet.
10706 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080010707 peer_framer_.SetEncrypter(
10708 ENCRYPTION_FORWARD_SECURE,
10709 std::make_unique<quic::NullEncrypter>(Perspective::IS_CLIENT));
Bence Békybac04052022-04-07 15:44:29 -040010710 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10711 // Verify deadline does not get extended.
10712 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10713 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10714 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10715 clock_.AdvanceTime(delay);
10716 connection_.GetTimeoutAlarm()->Fire();
10717 // Verify connection gets closed.
10718 EXPECT_FALSE(connection_.connected());
10719}
10720
10721TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10722 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10723 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10724
10725 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10726 notifier_.WriteOrBufferWindowUpate(0, 0);
10727 }));
10728 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10729 ProcessDataPacket(1);
10730 // Verify ACK is bundled with WINDOW_UPDATE.
10731 EXPECT_FALSE(writer_->ack_frames().empty());
10732 EXPECT_FALSE(connection_.HasPendingAcks());
10733}
10734
10735TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10736 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10737 return;
10738 }
10739 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10740 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10741 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10742 }
10743 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010744 // Receives packet 1000 in initial data.
10745 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10746 EXPECT_TRUE(connection_.HasPendingAcks());
10747
martinduke9e0811c2022-12-08 20:35:57 -080010748 peer_framer_.SetEncrypter(
10749 ENCRYPTION_ZERO_RTT,
10750 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040010751 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080010752 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040010753 // Receives packet 1000 in application data.
10754 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
10755 EXPECT_TRUE(connection_.HasPendingAcks());
10756 // Verify ACK deadline does not change.
10757 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10758 connection_.GetAckAlarm()->deadline());
10759
10760 // Ack alarm fires early.
10761 // Verify the earliest ACK is flushed.
10762 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10763 connection_.GetAckAlarm()->Fire();
10764 EXPECT_TRUE(connection_.HasPendingAcks());
10765 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10766 connection_.GetAckAlarm()->deadline());
10767}
10768
10769TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
10770 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10771 return;
10772 }
10773 QuicConfig config;
10774 QuicTagVector connection_options;
10775 connection_options.push_back(kCBHD);
10776 config.SetConnectionOptionsToSend(connection_options);
10777 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10778 connection_.SetFromConfig(config);
10779 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080010780 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
10781 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -040010782 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10783 // Send stream data.
10784 SendStreamDataToPeer(
10785 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10786 0, FIN, nullptr);
10787 // Verify blackhole detection is in progress.
10788 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10789}
10790
10791TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
10792 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10793 return;
10794 }
10795 set_perspective(Perspective::IS_SERVER);
10796 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10797 if (version().SupportsAntiAmplificationLimit()) {
10798 QuicConnectionPeer::SetAddressValidated(&connection_);
10799 }
10800 QuicConfig config;
10801 QuicTagVector connection_options;
10802 connection_options.push_back(kCBHD);
10803 config.SetInitialReceivedConnectionOptions(connection_options);
10804 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10805 connection_.SetFromConfig(config);
10806 EXPECT_CALL(visitor_, GetHandshakeState())
10807 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10808 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10809 // Send stream data.
10810 SendStreamDataToPeer(
10811 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10812 0, FIN, nullptr);
10813 // Verify blackhole detection is disabled.
10814 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10815}
10816
Bence Békybac04052022-04-07 15:44:29 -040010817// Regresstion test for b/158491591.
10818TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
10819 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10820 return;
10821 }
Bence Békybac04052022-04-07 15:44:29 -040010822 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010823 connection_.SetEncrypter(
10824 ENCRYPTION_HANDSHAKE,
10825 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010826 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10827 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10828 QuicConfig config;
10829 QuicTagVector connection_options;
10830 connection_options.push_back(k5RTO);
10831 config.SetConnectionOptionsToSend(connection_options);
10832 QuicConfigPeer::SetNegotiated(&config, true);
fayang59e518a2022-11-29 11:16:45 -080010833 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10834 GetQuicReloadableFlag(
10835 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040010836 EXPECT_CALL(visitor_, GetHandshakeState())
10837 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10838 }
10839 if (connection_.version().UsesTls()) {
10840 QuicConfigPeer::SetReceivedOriginalConnectionId(
10841 &config, connection_.connection_id());
10842 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10843 &config, connection_.connection_id());
10844 }
10845 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10846 connection_.SetFromConfig(config);
10847
10848 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
fayang59e518a2022-11-29 11:16:45 -080010849 if (GetQuicReloadableFlag(
10850 quic_no_path_degrading_before_handshake_confirmed)) {
10851 // No blackhole detection before handshake confirmed.
10852 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10853 } else {
10854 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10855 }
Bence Békybac04052022-04-07 15:44:29 -040010856 // Discard handshake keys.
fayang59e518a2022-11-29 11:16:45 -080010857 EXPECT_CALL(visitor_, GetHandshakeState())
10858 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040010859 connection_.OnHandshakeComplete();
fayang59e518a2022-11-29 11:16:45 -080010860 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10861 GetQuicReloadableFlag(
10862 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040010863 // Verify blackhole detection stops.
10864 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10865 } else {
10866 // Problematic: although there is nothing in flight, blackhole detection is
10867 // still in progress.
10868 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10869 }
10870}
10871
10872TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
10873 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10874 return;
10875 }
10876 // SetFromConfig is always called after construction from InitializeSession.
10877 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10878 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10879 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10880 QuicConfig config;
10881 connection_.SetFromConfig(config);
10882 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10883 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040010884
martinduke9e0811c2022-12-08 20:35:57 -080010885 peer_framer_.SetEncrypter(
10886 ENCRYPTION_HANDSHAKE,
10887 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10888 peer_framer_.SetEncrypter(
10889 ENCRYPTION_FORWARD_SECURE,
10890 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010891
10892 for (uint64_t i = 1; i <= 3; ++i) {
10893 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10894 }
10895 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10896 for (uint64_t j = 5; j <= 7; ++j) {
10897 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10898 }
10899 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10900 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10901 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080010902 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010903 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080010904 connection_.SetEncrypter(
10905 ENCRYPTION_HANDSHAKE,
10906 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010907 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10908 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
10909 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10910 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
10911 }
10912 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10913 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10914
martinduke9e0811c2022-12-08 20:35:57 -080010915 SetDecrypter(
10916 ENCRYPTION_FORWARD_SECURE,
10917 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010918 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10919 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080010920 connection_.SetEncrypter(
10921 ENCRYPTION_FORWARD_SECURE,
10922 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010923 // Verify the 1-RTT packet gets processed.
10924 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
10925 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10926 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10927}
10928
10929TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
10930 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10931 return;
10932 }
10933 set_perspective(Perspective::IS_SERVER);
10934 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10935 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10936 }
10937 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010938 // Receives packet 1000 in initial data.
10939 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10940 EXPECT_TRUE(connection_.HasPendingAcks());
10941
Bence Békybac04052022-04-07 15:44:29 -040010942 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10943 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10944 QuicTime expected_pto_time =
10945 connection_.sent_packet_manager().GetRetransmissionTime();
10946
10947 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10948 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10949 std::make_unique<TaggingEncrypter>(0x02));
10950 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10951 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10952 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10953 // Verify PTO time does not change.
10954 EXPECT_EQ(expected_pto_time,
10955 connection_.sent_packet_manager().GetRetransmissionTime());
10956
10957 // Receives packet 1001 in initial data.
10958 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
10959 EXPECT_TRUE(connection_.HasPendingAcks());
10960 // Receives packet 1002 in initial data.
10961 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
10962 EXPECT_FALSE(writer_->ack_frames().empty());
10963 // Verify CRYPTO frame is bundled with INITIAL ACK.
10964 EXPECT_FALSE(writer_->crypto_frames().empty());
10965 // Verify PTO time changes.
10966 EXPECT_NE(expected_pto_time,
10967 connection_.sent_packet_manager().GetRetransmissionTime());
10968}
10969
10970TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
10971 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10972 return;
10973 }
10974 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
10975 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10976 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10977 }
10978 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
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 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080010984 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
10985 peer_framer_.SetEncrypter(
10986 ENCRYPTION_HANDSHAKE,
10987 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010988 // Receives packet 1000 in handshake data.
10989 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
10990 EXPECT_TRUE(connection_.HasPendingAcks());
10991 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10992 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10993
10994 // Receives packet 1001 in handshake data.
10995 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
10996 EXPECT_TRUE(connection_.HasPendingAcks());
10997 // Receives packet 1002 in handshake data.
10998 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
10999 EXPECT_FALSE(writer_->ack_frames().empty());
11000 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
11001 EXPECT_FALSE(writer_->crypto_frames().empty());
11002}
11003
11004// Regresstion test for b/156232673.
11005TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
11006 if (!connection_.version().CanSendCoalescedPackets()) {
11007 return;
11008 }
11009 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11010 {
11011 QuicConnection::ScopedPacketFlusher flusher(&connection_);
martinduke9e0811c2022-12-08 20:35:57 -080011012 connection_.SetEncrypter(
11013 ENCRYPTION_HANDSHAKE,
11014 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
11015 connection_.SetEncrypter(
11016 ENCRYPTION_FORWARD_SECURE,
11017 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040011018 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11019 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
11020 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11021 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
11022 // Verify soft max packet length gets resumed and handshake packet gets
11023 // successfully sent.
11024 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
11025 }
11026}
11027
11028// Regression test for b/160790422.
11029TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
11030 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11031 return;
11032 }
11033 set_perspective(Perspective::IS_SERVER);
11034 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11035 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11036 }
11037 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040011038 // Receives packet 1000 in initial data.
11039 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11040 EXPECT_TRUE(connection_.HasPendingAcks());
11041
Bence Békybac04052022-04-07 15:44:29 -040011042 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11043 // Send INITIAL 1.
11044 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11045 QuicTime expected_pto_time =
11046 connection_.sent_packet_manager().GetRetransmissionTime();
11047
11048 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martinduke9e0811c2022-12-08 20:35:57 -080011049 connection_.SetEncrypter(
11050 ENCRYPTION_HANDSHAKE,
11051 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011052 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11053 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11054 // Send HANDSHAKE 2 and 3.
11055 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11056 connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
11057 // Verify PTO time does not change.
11058 EXPECT_EQ(expected_pto_time,
11059 connection_.sent_packet_manager().GetRetransmissionTime());
11060
11061 // Receives ACK for HANDSHAKE 2.
11062 QuicFrames frames;
11063 auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
11064 frames.push_back(QuicFrame(&ack_frame));
martindukeba002452023-03-21 08:10:46 -070011065 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040011066 ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
11067 // Discard INITIAL key.
11068 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11069 connection_.NeuterUnencryptedPackets();
11070 // Receives PING from peer.
11071 frames.clear();
11072 frames.push_back(QuicFrame(QuicPingFrame()));
11073 frames.push_back(QuicFrame(QuicPaddingFrame(3)));
11074 ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
11075 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
11076 connection_.GetAckAlarm()->deadline());
11077 // Fire ACK alarm.
11078 clock_.AdvanceTime(kAlarmGranularity);
11079 connection_.GetAckAlarm()->Fire();
11080 EXPECT_FALSE(writer_->ack_frames().empty());
11081 // Verify handshake data gets retransmitted early.
11082 EXPECT_FALSE(writer_->crypto_frames().empty());
11083}
11084
11085// Regression test for b/161228202
11086TEST_P(QuicConnectionTest, InflatedRttSample) {
11087 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11088 return;
11089 }
11090 // 30ms RTT.
11091 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
11092 set_perspective(Perspective::IS_SERVER);
11093 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
Bence Békybac04052022-04-07 15:44:29 -040011094 // Receives packet 1000 in initial data.
11095 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11096 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11097 }
11098 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11099 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11100 EXPECT_TRUE(connection_.HasPendingAcks());
11101
Bence Békybac04052022-04-07 15:44:29 -040011102 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11103 // Send INITIAL 1.
11104 std::string initial_crypto_data(512, 'a');
11105 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11106 ENCRYPTION_INITIAL);
11107 ASSERT_TRUE(connection_.sent_packet_manager()
11108 .GetRetransmissionTime()
11109 .IsInitialized());
11110 QuicTime::Delta pto_timeout =
11111 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11112 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011113 connection_.SetEncrypter(
11114 ENCRYPTION_HANDSHAKE,
11115 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011116 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11117 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11118 std::string handshake_crypto_data(1024, 'a');
11119 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11120 ENCRYPTION_HANDSHAKE);
11121
11122 // INITIAL 1 gets lost and PTO fires.
11123 clock_.AdvanceTime(pto_timeout);
11124 connection_.GetRetransmissionAlarm()->Fire();
11125
11126 clock_.AdvanceTime(kTestRTT);
11127 // Assume retransmitted INITIAL gets received.
11128 QuicFrames frames;
11129 auto ack_frame = InitAckFrame({{QuicPacketNumber(4), QuicPacketNumber(5)}});
11130 frames.push_back(QuicFrame(&ack_frame));
martindukeba002452023-03-21 08:10:46 -070011131 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040011132 .Times(AnyNumber());
11133 ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
11134 EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
11135 // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
11136 frames.clear();
11137 // HANDSHAKE 5 is also processed.
11138 QuicAckFrame ack_frame2 =
11139 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
11140 {QuicPacketNumber(5), QuicPacketNumber(6)}});
11141 ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
11142 frames.push_back(QuicFrame(&ack_frame2));
11143 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
11144 // Verify RTT inflation gets mitigated.
11145 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
11146}
11147
11148// Regression test for b/161228202
martinduke9e0811c2022-12-08 20:35:57 -080011149TEST_P(QuicConnectionTest, CoalescingPacketCausesInfiniteLoop) {
Bence Békybac04052022-04-07 15:44:29 -040011150 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11151 return;
11152 }
11153 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040011154 // Receives packet 1000 in initial data.
11155 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11156 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11157 }
11158 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11159
11160 // Set anti amplification factor to 2, such that RetransmitDataOfSpaceIfAny
11161 // makes no forward progress and causes infinite loop.
birenroyef686222022-09-12 11:34:34 -070011162 SetQuicFlag(quic_anti_amplification_factor, 2);
Bence Békybac04052022-04-07 15:44:29 -040011163
11164 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11165 EXPECT_TRUE(connection_.HasPendingAcks());
11166
Bence Békybac04052022-04-07 15:44:29 -040011167 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11168 // Send INITIAL 1.
11169 std::string initial_crypto_data(512, 'a');
11170 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11171 ENCRYPTION_INITIAL);
11172 ASSERT_TRUE(connection_.sent_packet_manager()
11173 .GetRetransmissionTime()
11174 .IsInitialized());
11175 QuicTime::Delta pto_timeout =
11176 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11177 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011178 connection_.SetEncrypter(
11179 ENCRYPTION_HANDSHAKE,
11180 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011181 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11182 // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
11183 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11184 std::string handshake_crypto_data(1024, 'a');
11185 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11186 ENCRYPTION_HANDSHAKE);
11187
11188 // INITIAL 1 gets lost and PTO fires.
11189 clock_.AdvanceTime(pto_timeout);
11190 connection_.GetRetransmissionAlarm()->Fire();
11191}
11192
11193TEST_P(QuicConnectionTest, ClientAckDelayForAsyncPacketProcessing) {
11194 if (!version().HasIetfQuicFrames()) {
11195 return;
11196 }
11197 // SetFromConfig is always called after construction from InitializeSession.
11198 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11199 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11200 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11201 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11202 connection_.NeuterUnencryptedPackets();
11203 }));
11204 QuicConfig config;
11205 connection_.SetFromConfig(config);
11206 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080011207 peer_framer_.SetEncrypter(
11208 ENCRYPTION_HANDSHAKE,
11209 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011210 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11211
11212 // Received undecryptable HANDSHAKE 2.
11213 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11214 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11215 // Received INITIAL 4 (which is retransmission of INITIAL 1) after 100ms.
11216 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
11217 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL);
11218 // Generate HANDSHAKE key.
11219 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080011220 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011221 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080011222 connection_.SetEncrypter(
11223 ENCRYPTION_HANDSHAKE,
11224 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011225 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11226 // Verify HANDSHAKE packet gets processed.
fayangfea655c2022-05-17 08:19:12 -070011227 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -040011228 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
fayangfea655c2022-05-17 08:19:12 -070011229 // Verify immediate ACK has been sent out when flush went out of scope.
11230 ASSERT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -040011231 ASSERT_FALSE(writer_->ack_frames().empty());
fayangfea655c2022-05-17 08:19:12 -070011232 // Verify the ack_delay_time in the sent HANDSHAKE ACK frame is 100ms.
11233 EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
Bence Békybac04052022-04-07 15:44:29 -040011234 writer_->ack_frames()[0].ack_delay_time);
11235 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
11236}
11237
11238TEST_P(QuicConnectionTest, TestingLiveness) {
11239 const size_t kMinRttMs = 40;
11240 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11241 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11242 QuicTime::Delta::Zero(), QuicTime::Zero());
11243 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11244 QuicConfig config;
11245
11246 CryptoHandshakeMessage msg;
11247 std::string error_details;
11248 QuicConfig client_config;
11249 client_config.SetInitialStreamFlowControlWindowToSend(
11250 kInitialStreamFlowControlWindowForTest);
11251 client_config.SetInitialSessionFlowControlWindowToSend(
11252 kInitialSessionFlowControlWindowForTest);
11253 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11254 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11255 const QuicErrorCode error =
11256 config.ProcessPeerHello(msg, CLIENT, &error_details);
11257 EXPECT_THAT(error, IsQuicNoError());
11258
11259 if (connection_.version().UsesTls()) {
11260 QuicConfigPeer::SetReceivedOriginalConnectionId(
11261 &config, connection_.connection_id());
11262 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11263 &config, connection_.connection_id());
11264 }
11265
11266 connection_.SetFromConfig(config);
11267 connection_.OnHandshakeComplete();
11268 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11269 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11270 EXPECT_FALSE(connection_.MaybeTestLiveness());
11271
haoyuewang7b43efb2022-04-20 16:26:03 -070011272 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040011273 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11274 // Advance time to near the idle timeout.
11275 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11276 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11277 EXPECT_TRUE(connection_.MaybeTestLiveness());
11278 // Verify idle deadline does not change.
haoyuewang7b43efb2022-04-20 16:26:03 -070011279 EXPECT_EQ(deadline, QuicConnectionPeer::GetIdleNetworkDeadline(&connection_));
Bence Békybac04052022-04-07 15:44:29 -040011280}
11281
fayang5783c332022-12-14 09:30:25 -080011282TEST_P(QuicConnectionTest, DisableLivenessTesting) {
11283 const size_t kMinRttMs = 40;
11284 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11285 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11286 QuicTime::Delta::Zero(), QuicTime::Zero());
11287 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11288 QuicConfig config;
11289
11290 CryptoHandshakeMessage msg;
11291 std::string error_details;
11292 QuicConfig client_config;
11293 client_config.SetInitialStreamFlowControlWindowToSend(
11294 kInitialStreamFlowControlWindowForTest);
11295 client_config.SetInitialSessionFlowControlWindowToSend(
11296 kInitialSessionFlowControlWindowForTest);
11297 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11298 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11299 const QuicErrorCode error =
11300 config.ProcessPeerHello(msg, CLIENT, &error_details);
11301 EXPECT_THAT(error, IsQuicNoError());
11302
11303 if (connection_.version().UsesTls()) {
11304 QuicConfigPeer::SetReceivedOriginalConnectionId(
11305 &config, connection_.connection_id());
11306 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11307 &config, connection_.connection_id());
11308 }
11309
11310 connection_.SetFromConfig(config);
11311 connection_.OnHandshakeComplete();
11312 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11313 connection_.DisableLivenessTesting();
11314 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11315 EXPECT_FALSE(connection_.MaybeTestLiveness());
11316
11317 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
11318 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11319 // Advance time to near the idle timeout.
11320 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11322 EXPECT_FALSE(connection_.MaybeTestLiveness());
11323}
11324
Bence Békybac04052022-04-07 15:44:29 -040011325TEST_P(QuicConnectionTest, SilentIdleTimeout) {
11326 set_perspective(Perspective::IS_SERVER);
11327 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11328 if (version().SupportsAntiAmplificationLimit()) {
11329 QuicConnectionPeer::SetAddressValidated(&connection_);
11330 }
11331
11332 QuicConfig config;
11333 QuicConfigPeer::SetNegotiated(&config, true);
11334 if (connection_.version().UsesTls()) {
11335 QuicConfigPeer::SetReceivedOriginalConnectionId(
11336 &config, connection_.connection_id());
11337 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
11338 QuicConnectionId());
11339 }
11340 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11341 connection_.SetFromConfig(config);
11342
11343 EXPECT_TRUE(connection_.connected());
11344 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11345
11346 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
11347 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
11348 }
11349 EXPECT_CALL(visitor_,
11350 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11351 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11352 connection_.GetTimeoutAlarm()->Fire();
11353 // Verify the connection close packets get serialized and added to
11354 // termination packets list.
11355 EXPECT_NE(nullptr,
11356 QuicConnectionPeer::GetConnectionClosePacket(&connection_));
11357}
11358
martinduke9e0811c2022-12-08 20:35:57 -080011359TEST_P(QuicConnectionTest, DoNotSendPing) {
Bence Békybac04052022-04-07 15:44:29 -040011360 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11361 connection_.OnHandshakeComplete();
11362 EXPECT_TRUE(connection_.connected());
11363 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11364 .WillRepeatedly(Return(true));
11365 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
11366 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11367
11368 SendStreamDataToPeer(
11369 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
11370 "GET /", 0, FIN, nullptr);
11371 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11372 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11373 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
11374 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11375
11376 // Now recevie an ACK and response of the previous packet, which will move the
11377 // ping alarm forward.
11378 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11379 QuicFrames frames;
11380 QuicAckFrame ack_frame = InitAckFrame(1);
11381 frames.push_back(QuicFrame(&ack_frame));
11382 frames.push_back(QuicFrame(QuicStreamFrame(
11383 GetNthClientInitiatedStreamId(0, connection_.transport_version()), true,
11384 0u, absl::string_view())));
11385 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
martindukeba002452023-03-21 08:10:46 -070011386 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040011387 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11388 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
11389 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11390 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11391 // The ping timer is set slightly less than 15 seconds in the future, because
11392 // of the 1s ping timer alarm granularity.
11393 EXPECT_EQ(
11394 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
11395 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11396
11397 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
11398 // Suppose now ShouldKeepConnectionAlive returns false.
11399 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11400 .WillRepeatedly(Return(false));
11401 // Verify PING does not get sent.
11402 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11403 connection_.GetPingAlarm()->Fire();
11404}
11405
11406// Regression test for b/159698337
11407TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) {
11408 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11409 return;
11410 }
11411 // Finish handshake.
11412 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11413 notifier_.NeuterUnencryptedData();
11414 connection_.NeuterUnencryptedPackets();
11415 connection_.OnHandshakeComplete();
11416 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080011417 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040011418
11419 std::string data(1200, 'a');
11420 // Send data packets 1 - 5.
11421 for (size_t i = 0; i < 5; ++i) {
11422 SendStreamDataToPeer(
11423 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
11424 i * 1200, i == 4 ? FIN : NO_FIN, nullptr);
11425 }
11426 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
11427
martindukeba002452023-03-21 08:10:46 -070011428 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
11429 .Times(3);
Bence Békybac04052022-04-07 15:44:29 -040011430
11431 // ACK packet 5 and 1 and 2 are detected lost.
11432 QuicAckFrame frame =
11433 InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}});
11434 LostPacketVector lost_packets;
11435 lost_packets.push_back(
11436 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
11437 lost_packets.push_back(
11438 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
11439 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11440 .Times(AnyNumber())
11441 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
awillia202240c2024-07-08 09:47:00 -070011442 Return(LossDetectionInterface::DetectionStats())))
11443 .WillRepeatedly(DoDefault());
11444 ;
Bence Békybac04052022-04-07 15:44:29 -040011445 ProcessAckPacket(1, &frame);
11446 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11447 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
11448 EXPECT_TRUE(retransmission_alarm->IsSet());
11449
11450 // ACK packet 1 - 5 and 7.
11451 QuicAckFrame frame2 =
11452 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)},
11453 {QuicPacketNumber(7), QuicPacketNumber(8)}});
11454 ProcessAckPacket(2, &frame2);
11455 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11456
11457 // ACK packet 7 again and assume packet 6 is detected lost.
11458 QuicAckFrame frame3 =
11459 InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}});
11460 lost_packets.clear();
11461 lost_packets.push_back(
11462 LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize));
11463 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11464 .Times(AnyNumber())
11465 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11466 Return(LossDetectionInterface::DetectionStats())));
11467 ProcessAckPacket(3, &frame3);
11468 // Make sure loss detection is cancelled even there is no new acked packets.
11469 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11470}
11471
11472TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) {
11473 EXPECT_TRUE(connection_.connected());
11474 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11475 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
11476 QuicTime::Delta::Zero(), QuicTime::Zero());
11477
11478 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11479 QuicConfig config;
11480 config.SetClientConnectionOptions(QuicTagVector{kFIDT});
11481 QuicConfigPeer::SetNegotiated(&config, true);
11482 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11483 EXPECT_CALL(visitor_, GetHandshakeState())
11484 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11485 }
11486 if (connection_.version().UsesTls()) {
11487 QuicConfigPeer::SetReceivedOriginalConnectionId(
11488 &config, connection_.connection_id());
11489 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11490 &config, connection_.connection_id());
11491 }
11492 connection_.SetFromConfig(config);
11493
11494 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11495 // Send a packet close to timeout.
11496 QuicTime::Delta timeout =
11497 connection_.GetTimeoutAlarm()->deadline() - clock_.Now();
11498 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1));
11499 // Send stream data.
11500 SendStreamDataToPeer(
11501 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11502 0, FIN, nullptr);
11503 // Verify this sent packet does not extend idle timeout since 1s is > PTO
11504 // delay.
11505 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11506 EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
11507 connection_.GetTimeoutAlarm()->deadline() - clock_.Now());
11508
11509 // Received an ACK 100ms later.
11510 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100));
11511 QuicAckFrame ack = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070011512 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040011513 ProcessAckPacket(1, &ack);
11514 // Verify idle timeout gets extended.
11515 EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline());
11516}
11517
11518// Regression test for b/166255274
11519TEST_P(QuicConnectionTest,
11520 ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) {
11521 if (!connection_.version().CanSendCoalescedPackets()) {
11522 return;
11523 }
Bence Békybac04052022-04-07 15:44:29 -040011524 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11525 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11526 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11527 EXPECT_TRUE(connection_.HasPendingAcks());
11528 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11529 std::make_unique<TaggingEncrypter>(0x02));
11530 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11531 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11532 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11533 connection_.NeuterUnencryptedPackets();
11534 }));
11535 {
11536 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11537 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11538 // Verify the packet is on hold.
11539 EXPECT_EQ(0u, writer_->packets_write_attempts());
11540 // Flush pending ACKs.
11541 connection_.GetAckAlarm()->Fire();
11542 }
11543 EXPECT_FALSE(connection_.packet_creator().HasPendingFrames());
11544 // The ACK frame is deleted along with initial_packet_ in coalescer. Sending
11545 // connection close would cause this (released) ACK frame be serialized (and
11546 // crashes).
11547 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11548 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
11549 EXPECT_TRUE(connection_.connected());
11550}
11551
11552TEST_P(QuicConnectionTest, PathValidationOnNewSocketSuccess) {
danzh87605712022-04-11 14:36:39 -070011553 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011554 return;
11555 }
11556 PathProbeTestInit(Perspective::IS_CLIENT);
11557 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11558 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11559 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11561 .Times(AtLeast(1u))
11562 .WillOnce(Invoke([&]() {
11563 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11564 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11565 EXPECT_EQ(1u, new_writer.padding_frames().size());
11566 EXPECT_EQ(kNewSelfAddress.host(),
11567 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070011568 }))
11569 .WillRepeatedly(DoDefault());
11570 ;
Bence Békybac04052022-04-07 15:44:29 -040011571 bool success = false;
11572 connection_.ValidatePath(
11573 std::make_unique<TestQuicPathValidationContext>(
11574 kNewSelfAddress, connection_.peer_address(), &new_writer),
11575 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011576 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11577 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011578 EXPECT_EQ(0u, writer_->packets_write_attempts());
11579
11580 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011581 frames.push_back(QuicFrame(QuicPathResponseFrame(
Bence Békybac04052022-04-07 15:44:29 -040011582 99, new_writer.path_challenge_frames().front().data_buffer)));
11583 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
11584 ENCRYPTION_FORWARD_SECURE);
11585 EXPECT_TRUE(success);
11586}
11587
danzh90315e82023-06-08 14:09:49 -070011588TEST_P(QuicConnectionTest, PathValidationOnNewSocketWriteBlocked) {
11589 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11590 return;
11591 }
11592 PathProbeTestInit(Perspective::IS_CLIENT);
11593 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11594 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11595 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11596 new_writer.SetWriteBlocked();
11597 bool success = false;
11598 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11599 connection_.ValidatePath(
11600 std::make_unique<TestQuicPathValidationContext>(
11601 kNewSelfAddress, connection_.peer_address(), &new_writer),
11602 std::make_unique<TestValidationResultDelegate>(
11603 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11604 PathValidationReason::kReasonUnknown);
11605 EXPECT_EQ(0u, new_writer.packets_write_attempts());
11606 EXPECT_TRUE(connection_.HasPendingPathValidation());
11607
11608 new_writer.SetWritable();
11609 // Retry after time out.
11610 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11611 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11612 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11613 .WillOnce(Invoke([&]() {
11614 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11615 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11616 EXPECT_EQ(1u, new_writer.padding_frames().size());
11617 EXPECT_EQ(kNewSelfAddress.host(),
11618 new_writer.last_write_source_address());
11619 }));
11620 static_cast<TestAlarmFactory::TestAlarm*>(
11621 QuicPathValidatorPeer::retry_timer(
11622 QuicConnectionPeer::path_validator(&connection_)))
11623 ->Fire();
11624 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11625
11626 QuicFrames frames;
11627 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
11628 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
11629 new_writer.SetWriteBlocked();
11630 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11631 .WillRepeatedly(Invoke([&] {
11632 // Packets other than PATH_RESPONSE may be sent over the default writer.
11633 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11634 EXPECT_TRUE(new_writer.path_response_frames().empty());
11635 EXPECT_EQ(1u, writer_->packets_write_attempts());
11636 }));
11637 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
11638 connection_.peer_address(),
11639 ENCRYPTION_FORWARD_SECURE);
11640 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11641}
11642
Bence Békybac04052022-04-07 15:44:29 -040011643TEST_P(QuicConnectionTest, NewPathValidationCancelsPreviousOne) {
danzh87605712022-04-11 14:36:39 -070011644 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011645 return;
11646 }
11647 PathProbeTestInit(Perspective::IS_CLIENT);
11648 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11649 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11650 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11651 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11652 .Times(AtLeast(1u))
11653 .WillOnce(Invoke([&]() {
11654 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11655 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11656 EXPECT_EQ(1u, new_writer.padding_frames().size());
11657 EXPECT_EQ(kNewSelfAddress.host(),
11658 new_writer.last_write_source_address());
11659 }));
11660 bool success = true;
11661 connection_.ValidatePath(
11662 std::make_unique<TestQuicPathValidationContext>(
11663 kNewSelfAddress, connection_.peer_address(), &new_writer),
11664 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011665 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11666 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011667 EXPECT_EQ(0u, writer_->packets_write_attempts());
11668
11669 // Start another path validation request.
11670 const QuicSocketAddress kNewSelfAddress2(QuicIpAddress::Any4(), 12346);
11671 EXPECT_NE(kNewSelfAddress2, connection_.self_address());
11672 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
Bence Békybac04052022-04-07 15:44:29 -040011673 bool success2 = false;
11674 connection_.ValidatePath(
11675 std::make_unique<TestQuicPathValidationContext>(
11676 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
11677 std::make_unique<TestValidationResultDelegate>(
11678 &connection_, kNewSelfAddress2, connection_.peer_address(),
renjietange499db42023-01-17 15:42:33 -080011679 &success2),
11680 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011681 EXPECT_FALSE(success);
danzh7c0ef5f2023-06-08 12:10:35 -070011682 // There is no pening path validation as there is no available connection ID.
11683 EXPECT_FALSE(connection_.HasPendingPathValidation());
Bence Békybac04052022-04-07 15:44:29 -040011684}
11685
11686// Regression test for b/182571515.
11687TEST_P(QuicConnectionTest, PathValidationRetry) {
danzh87605712022-04-11 14:36:39 -070011688 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011689 return;
11690 }
11691 PathProbeTestInit(Perspective::IS_CLIENT);
11692
11693 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11694 .Times(2u)
11695 .WillRepeatedly(Invoke([&]() {
11696 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11697 EXPECT_EQ(1u, writer_->padding_frames().size());
11698 }));
11699 bool success = true;
11700 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11701 connection_.self_address(),
11702 connection_.peer_address(), writer_.get()),
11703 std::make_unique<TestValidationResultDelegate>(
11704 &connection_, connection_.self_address(),
renjietange499db42023-01-17 15:42:33 -080011705 connection_.peer_address(), &success),
11706 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011707 EXPECT_EQ(1u, writer_->packets_write_attempts());
11708 EXPECT_TRUE(connection_.HasPendingPathValidation());
11709
11710 // Retry after time out.
11711 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11712 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11713 static_cast<TestAlarmFactory::TestAlarm*>(
11714 QuicPathValidatorPeer::retry_timer(
11715 QuicConnectionPeer::path_validator(&connection_)))
11716 ->Fire();
11717 EXPECT_EQ(2u, writer_->packets_write_attempts());
11718}
11719
11720TEST_P(QuicConnectionTest, PathValidationReceivesStatelessReset) {
danzh87605712022-04-11 14:36:39 -070011721 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011722 return;
11723 }
11724 PathProbeTestInit(Perspective::IS_CLIENT);
11725 QuicConfig config;
11726 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
11727 kTestStatelessResetToken);
11728 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11729 connection_.SetFromConfig(config);
11730 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11731 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11732 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11733 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11734 .Times(AtLeast(1u))
11735 .WillOnce(Invoke([&]() {
11736 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11737 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11738 EXPECT_EQ(1u, new_writer.padding_frames().size());
11739 EXPECT_EQ(kNewSelfAddress.host(),
11740 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070011741 }))
11742 .WillRepeatedly(DoDefault());
11743 ;
Bence Békybac04052022-04-07 15:44:29 -040011744 bool success = true;
11745 connection_.ValidatePath(
11746 std::make_unique<TestQuicPathValidationContext>(
11747 kNewSelfAddress, connection_.peer_address(), &new_writer),
11748 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011749 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11750 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011751 EXPECT_EQ(0u, writer_->packets_write_attempts());
11752 EXPECT_TRUE(connection_.HasPendingPathValidation());
11753
11754 std::unique_ptr<QuicEncryptedPacket> packet(
11755 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
11756 /*received_packet_length=*/100,
11757 kTestStatelessResetToken));
11758 std::unique_ptr<QuicReceivedPacket> received(
11759 ConstructReceivedPacket(*packet, QuicTime::Zero()));
11760 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
11761 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
11762 EXPECT_FALSE(connection_.HasPendingPathValidation());
11763 EXPECT_FALSE(success);
11764}
11765
11766// Tests that PATH_CHALLENGE is dropped if it is sent via a blocked alternative
11767// writer.
11768TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedNewSocket) {
danzh7c0ef5f2023-06-08 12:10:35 -070011769 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011770 return;
11771 }
11772 PathProbeTestInit(Perspective::IS_CLIENT);
11773 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11774 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11775 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11776 new_writer.BlockOnNextWrite();
11777 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
11778 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11779 .Times(AtLeast(1))
11780 .WillOnce(Invoke([&]() {
11781 // Even though the socket is blocked, the PATH_CHALLENGE should still be
11782 // treated as sent.
11783 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11784 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11785 EXPECT_EQ(1u, new_writer.padding_frames().size());
11786 EXPECT_EQ(kNewSelfAddress.host(),
11787 new_writer.last_write_source_address());
awillia202240c2024-07-08 09:47:00 -070011788 }))
11789 .WillRepeatedly(DoDefault());
11790 ;
Bence Békybac04052022-04-07 15:44:29 -040011791 bool success = false;
11792 connection_.ValidatePath(
11793 std::make_unique<TestQuicPathValidationContext>(
11794 kNewSelfAddress, connection_.peer_address(), &new_writer),
11795 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011796 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11797 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011798 EXPECT_EQ(0u, writer_->packets_write_attempts());
11799
11800 new_writer.SetWritable();
11801 // Write event on the default socket shouldn't make any difference.
11802 connection_.OnCanWrite();
11803 // A NEW_CONNECTION_ID frame is received in PathProbeTestInit and OnCanWrite
11804 // will write a acking packet.
11805 EXPECT_EQ(1u, writer_->packets_write_attempts());
11806 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11807}
11808
11809// Tests that PATH_CHALLENGE is dropped if it is sent via the default writer
11810// and the writer is blocked.
11811TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedDefaultSocket) {
danzh87605712022-04-11 14:36:39 -070011812 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011813 return;
11814 }
11815 PathProbeTestInit(Perspective::IS_SERVER);
11816 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11817 writer_->BlockOnNextWrite();
11818 // 1st time is after writer returns WRITE_STATUS_BLOCKED. 2nd time is in
11819 // ShouldGeneratePacket().
11820 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(2));
11821 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
11822 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11823 .Times(AtLeast(1u))
11824 .WillOnce(Invoke([&]() {
11825 // This packet isn't sent actually, instead it is buffered in the
11826 // connection.
11827 EXPECT_EQ(1u, writer_->packets_write_attempts());
danzh4d58dae2023-06-06 11:13:10 -070011828 EXPECT_EQ(1u, writer_->path_response_frames().size());
11829 EXPECT_EQ(0,
11830 memcmp(&path_challenge_payload,
11831 &writer_->path_response_frames().front().data_buffer,
11832 sizeof(path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040011833 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11834 EXPECT_EQ(1u, writer_->padding_frames().size());
11835 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11836 }))
11837 .WillRepeatedly(Invoke([&]() {
11838 // Only one PATH_CHALLENGE should be sent out.
11839 EXPECT_EQ(0u, writer_->path_challenge_frames().size());
11840 }));
danzh4d58dae2023-06-06 11:13:10 -070011841 // Receiving a PATH_CHALLENGE from the new peer address should trigger address
11842 // validation.
11843 QuicFrames frames;
11844 frames.push_back(
11845 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
11846 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11847 ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040011848 EXPECT_EQ(1u, writer_->packets_write_attempts());
11849
11850 // Try again with the new socket blocked from the beginning. The 2nd
11851 // PATH_CHALLENGE shouldn't be serialized, but be dropped.
11852 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11853 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11854 static_cast<TestAlarmFactory::TestAlarm*>(
11855 QuicPathValidatorPeer::retry_timer(
11856 QuicConnectionPeer::path_validator(&connection_)))
11857 ->Fire();
11858
11859 // No more write attempt should be made.
11860 EXPECT_EQ(1u, writer_->packets_write_attempts());
11861
11862 writer_->SetWritable();
11863 // OnCanWrite() should actually write out the 1st PATH_CHALLENGE packet
11864 // buffered earlier, thus incrementing the write counter. It may also send
11865 // ACKs to previously received packets.
11866 connection_.OnCanWrite();
11867 EXPECT_LE(2u, writer_->packets_write_attempts());
11868}
11869
11870// Tests that write error on the alternate socket should be ignored.
11871TEST_P(QuicConnectionTest, SendPathChallengeFailOnNewSocket) {
danzh87605712022-04-11 14:36:39 -070011872 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011873 return;
11874 }
11875 PathProbeTestInit(Perspective::IS_CLIENT);
11876 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11877 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11878 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11879 new_writer.SetShouldWriteFail();
11880 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11881 .Times(0);
11882 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11883
11884 bool success = false;
11885 connection_.ValidatePath(
11886 std::make_unique<TestQuicPathValidationContext>(
11887 kNewSelfAddress, connection_.peer_address(), &new_writer),
11888 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011889 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
11890 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011891 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11892 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11893 EXPECT_EQ(1u, new_writer.padding_frames().size());
11894 EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address());
11895
11896 EXPECT_EQ(0u, writer_->packets_write_attempts());
11897 // Regardless of the write error, the connection should still be connected.
11898 EXPECT_TRUE(connection_.connected());
11899}
11900
11901// Tests that write error while sending PATH_CHALLANGE from the default socket
11902// should close the connection.
11903TEST_P(QuicConnectionTest, SendPathChallengeFailOnDefaultPath) {
danzh87605712022-04-11 14:36:39 -070011904 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011905 return;
11906 }
11907 PathProbeTestInit(Perspective::IS_CLIENT);
11908
11909 writer_->SetShouldWriteFail();
11910 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11911 .WillOnce(
11912 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11913 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11914 }));
11915 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11916 {
11917 // Add a flusher to force flush, otherwise the frames will remain in the
11918 // packet creator.
11919 bool success = false;
11920 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11921 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11922 connection_.self_address(),
11923 connection_.peer_address(), writer_.get()),
11924 std::make_unique<TestValidationResultDelegate>(
11925 &connection_, connection_.self_address(),
renjietange499db42023-01-17 15:42:33 -080011926 connection_.peer_address(), &success),
11927 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011928 }
11929 EXPECT_EQ(1u, writer_->packets_write_attempts());
11930 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11931 EXPECT_EQ(1u, writer_->padding_frames().size());
11932 EXPECT_EQ(connection_.peer_address(), writer_->last_write_peer_address());
11933 EXPECT_FALSE(connection_.connected());
11934 // Closing connection should abandon ongoing path validation.
11935 EXPECT_FALSE(connection_.HasPendingPathValidation());
11936}
11937
11938TEST_P(QuicConnectionTest, SendPathChallengeFailOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011939 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011940 return;
11941 }
11942 PathProbeTestInit(Perspective::IS_CLIENT);
11943
11944 writer_->SetShouldWriteFail();
11945 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11946 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11947 .WillOnce(
11948 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11949 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11950 }));
11951 // Sending PATH_CHALLENGE to trigger a flush write which will fail and close
11952 // the connection.
11953 bool success = false;
11954 connection_.ValidatePath(
11955 std::make_unique<TestQuicPathValidationContext>(
11956 connection_.self_address(), kNewPeerAddress, writer_.get()),
11957 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011958 &connection_, connection_.self_address(), kNewPeerAddress, &success),
11959 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011960
11961 EXPECT_EQ(1u, writer_->packets_write_attempts());
11962 EXPECT_FALSE(connection_.HasPendingPathValidation());
11963 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11964 EXPECT_EQ(1u, writer_->padding_frames().size());
11965 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11966 EXPECT_FALSE(connection_.connected());
11967}
11968
11969TEST_P(QuicConnectionTest,
11970 SendPathChallengeFailPacketTooBigOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011971 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011972 return;
11973 }
11974 PathProbeTestInit(Perspective::IS_CLIENT);
11975 // Make sure there is no outstanding ACK_FRAME to write.
11976 connection_.OnCanWrite();
11977 uint32_t num_packets_write_attempts = writer_->packets_write_attempts();
11978
11979 writer_->SetShouldWriteFail();
11980 writer_->SetWriteError(*writer_->MessageTooBigErrorCode());
11981 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11982 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11983 .Times(0u);
11984 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11985 // Sending PATH_CHALLENGE to trigger a flush write which will fail with
11986 // MSG_TOO_BIG.
11987 bool success = false;
11988 connection_.ValidatePath(
11989 std::make_unique<TestQuicPathValidationContext>(
11990 connection_.self_address(), kNewPeerAddress, writer_.get()),
11991 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080011992 &connection_, connection_.self_address(), kNewPeerAddress, &success),
11993 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040011994 EXPECT_TRUE(connection_.HasPendingPathValidation());
11995 // Connection shouldn't be closed.
11996 EXPECT_TRUE(connection_.connected());
11997 EXPECT_EQ(++num_packets_write_attempts, writer_->packets_write_attempts());
11998 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11999 EXPECT_EQ(1u, writer_->padding_frames().size());
12000 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12001}
12002
12003// Check that if there are two PATH_CHALLENGE frames in the packet, the latter
12004// one is ignored.
12005TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) {
12006 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12007 return;
12008 }
12009 PathProbeTestInit(Perspective::IS_SERVER);
12010
12011 QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7};
12012 QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15};
12013 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070012014 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer1)));
12015 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer2)));
Bence Békybac04052022-04-07 15:44:29 -040012016 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12017 /*port=*/23456);
12018
12019 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
12020
12021 // Expect 2 packets to be sent: the first are padded PATH_RESPONSE(s) to the
12022 // alternative peer address. The 2nd is a ACK-only packet to the original
12023 // peer address.
12024 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12025 .Times(2)
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012026 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012027 EXPECT_EQ(1u, writer_->path_response_frames().size());
12028 // The final check is to ensure that the random data in the response
12029 // matches the random data from the challenge.
12030 EXPECT_EQ(0,
12031 memcmp(path_frame_buffer1.data(),
12032 &(writer_->path_response_frames().front().data_buffer),
12033 sizeof(path_frame_buffer1)));
12034 EXPECT_EQ(1u, writer_->padding_frames().size());
12035 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12036 }))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012037 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012038 // The last write of ACK-only packet should still use the old peer
12039 // address.
12040 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12041 }));
12042 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12043 ENCRYPTION_FORWARD_SECURE);
12044}
12045
12046TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) {
12047 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12048 return;
12049 }
12050 PathProbeTestInit(Perspective::IS_SERVER);
12051
12052 QuicFrames frames;
12053 frames.push_back(QuicFrame(frame1_));
12054 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012055 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
fayang161ce6e2022-07-01 18:02:11 -070012056 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
Bence Békybac04052022-04-07 15:44:29 -040012057 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
12058 /*port=*/23456);
12059
12060 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
danzh4d58dae2023-06-06 11:13:10 -070012061 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040012062 EXPECT_CALL(visitor_, OnStreamFrame(_))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012063 .WillOnce(Invoke([=, this](const QuicStreamFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040012064 // Send some data on the stream. The STREAM_FRAME should be built into
12065 // one packet together with the latter PATH_RESPONSE and PATH_CHALLENGE.
12066 const std::string data{"response body"};
12067 connection_.producer()->SaveStreamData(frame.stream_id, data);
12068 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12069 NO_FIN);
12070 }));
danzh4d58dae2023-06-06 11:13:10 -070012071 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040012072 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12073 ENCRYPTION_FORWARD_SECURE);
12074
12075 // Verify that this packet contains a STREAM_FRAME and a
12076 // PATH_RESPONSE_FRAME.
12077 EXPECT_EQ(1u, writer_->stream_frames().size());
12078 EXPECT_EQ(1u, writer_->path_response_frames().size());
danzh4d58dae2023-06-06 11:13:10 -070012079 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012080 // The final check is to ensure that the random data in the response
12081 // matches the random data from the challenge.
12082 EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
12083 &(writer_->path_response_frames().front().data_buffer),
12084 sizeof(path_frame_buffer)));
danzh4d58dae2023-06-06 11:13:10 -070012085 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012086 EXPECT_EQ(1u, writer_->padding_frames().size());
12087 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
danzh4d58dae2023-06-06 11:13:10 -070012088 EXPECT_TRUE(connection_.HasPendingPathValidation());
Bence Békybac04052022-04-07 15:44:29 -040012089}
12090
12091TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) {
12092 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12093 return;
12094 }
12095 PathProbeTestInit(Perspective::IS_SERVER);
12096
12097 QuicFrames frames;
12098 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012099 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012100 // PATH_RESPONSE should be flushed out before the rest packet is parsed.
12101 frames.push_back(QuicFrame(frame1_));
12102 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
12103 /*port=*/23456);
12104 QuicByteCount received_packet_size;
12105 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12106 .Times(AtLeast(1u))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012107 .WillOnce(Invoke([=, this, &received_packet_size]() {
Bence Békybac04052022-04-07 15:44:29 -040012108 // Verify that this packet contains a PATH_RESPONSE_FRAME.
12109 EXPECT_EQ(0u, writer_->stream_frames().size());
12110 EXPECT_EQ(1u, writer_->path_response_frames().size());
12111 // The final check is to ensure that the random data in the response
12112 // matches the random data from the challenge.
12113 EXPECT_EQ(0,
12114 memcmp(path_frame_buffer.data(),
12115 &(writer_->path_response_frames().front().data_buffer),
12116 sizeof(path_frame_buffer)));
danzh4d58dae2023-06-06 11:13:10 -070012117 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040012118 EXPECT_EQ(1u, writer_->padding_frames().size());
12119 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12120 received_packet_size =
12121 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_);
12122 }));
12123 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
danzh4d58dae2023-06-06 11:13:10 -070012124 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0u);
Bence Békybac04052022-04-07 15:44:29 -040012125 EXPECT_CALL(visitor_, OnStreamFrame(_))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012126 .WillOnce(Invoke([=, this](const QuicStreamFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040012127 // Send some data on the stream. The STREAM_FRAME should be built into a
12128 // new packet but throttled by anti-amplifciation limit.
12129 const std::string data{"response body"};
12130 connection_.producer()->SaveStreamData(frame.stream_id, data);
12131 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12132 NO_FIN);
12133 }));
12134
12135 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12136 ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040012137 EXPECT_TRUE(connection_.HasPendingPathValidation());
12138 EXPECT_EQ(0u,
12139 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
12140 EXPECT_EQ(
12141 received_packet_size,
12142 QuicConnectionPeer::BytesReceivedBeforeAddressValidation(&connection_));
12143}
12144
12145// Tests that a PATH_CHALLENGE is received in between other frames in an out of
12146// order packet.
12147TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) {
12148 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12149 return;
12150 }
12151 PathProbeTestInit(Perspective::IS_SERVER);
12152
12153 QuicFrames frames;
12154 frames.push_back(QuicFrame(frame1_));
12155 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012156 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012157 frames.push_back(QuicFrame(frame2_));
12158 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12159 /*port=*/23456);
12160
12161 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12162 EXPECT_CALL(visitor_, OnStreamFrame(_))
12163 .Times(2)
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012164 .WillRepeatedly(Invoke([=, this](const QuicStreamFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040012165 // Send some data on the stream. The STREAM_FRAME should be built into
12166 // one packet together with the latter PATH_RESPONSE.
12167 const std::string data{"response body"};
12168 connection_.producer()->SaveStreamData(frame.stream_id, data);
12169 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12170 NO_FIN);
12171 }));
12172 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012173 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012174 // Verify that this packet contains a STREAM_FRAME and is sent to the
12175 // original peer address.
12176 EXPECT_EQ(1u, writer_->stream_frames().size());
12177 // No connection migration should happen because the packet is received
12178 // out of order.
12179 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12180 }))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012181 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012182 EXPECT_EQ(1u, writer_->path_response_frames().size());
12183 // The final check is to ensure that the random data in the response
12184 // matches the random data from the challenge.
12185 EXPECT_EQ(0,
12186 memcmp(path_frame_buffer.data(),
12187 &(writer_->path_response_frames().front().data_buffer),
12188 sizeof(path_frame_buffer)));
12189 EXPECT_EQ(1u, writer_->padding_frames().size());
12190 // PATH_RESPONSE should be sent in another packet to a different peer
12191 // address.
12192 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12193 }))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012194 .WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040012195 // Verify that this packet contains a STREAM_FRAME and is sent to the
12196 // original peer address.
12197 EXPECT_EQ(1u, writer_->stream_frames().size());
12198 // No connection migration should happen because the packet is received
12199 // out of order.
12200 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12201 }));
12202 // Lower the packet number so that receiving this packet shouldn't trigger
12203 // peer migration.
12204 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12205 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12206 ENCRYPTION_FORWARD_SECURE);
12207}
12208
12209// Tests that a PATH_CHALLENGE is cached if its PATH_RESPONSE can't be sent.
danzh90315e82023-06-08 14:09:49 -070012210TEST_P(QuicConnectionTest, FailToWritePathResponseAtServer) {
Bence Békybac04052022-04-07 15:44:29 -040012211 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12212 return;
12213 }
12214 PathProbeTestInit(Perspective::IS_SERVER);
12215
12216 QuicFrames frames;
12217 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012218 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012219 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12220 /*port=*/23456);
12221
12222 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12223 // Lower the packet number so that receiving this packet shouldn't trigger
12224 // peer migration.
12225 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12226 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
12227 writer_->SetWriteBlocked();
12228 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12229 ENCRYPTION_FORWARD_SECURE);
12230}
12231
12232// Regression test for b/168101557.
12233TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) {
12234 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12235 return;
12236 }
12237 set_perspective(Perspective::IS_SERVER);
12238 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
12239 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12240 }
12241 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040012242 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12243 EXPECT_TRUE(connection_.HasPendingAcks());
12244
Bence Békybac04052022-04-07 15:44:29 -040012245 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12246 // Send INITIAL 1.
12247 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12248
martinduke9e0811c2022-12-08 20:35:57 -080012249 connection_.SetEncrypter(
12250 ENCRYPTION_HANDSHAKE,
12251 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012252 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12253 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080012254 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012255 // Send HANDSHAKE packets.
12256 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
12257 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12258
martinduke9e0811c2022-12-08 20:35:57 -080012259 connection_.SetEncrypter(
12260 ENCRYPTION_FORWARD_SECURE,
12261 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012262 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12263 // Send half RTT packet.
12264 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12265
12266 // Receives HANDSHAKE 1.
martinduke9e0811c2022-12-08 20:35:57 -080012267 peer_framer_.SetEncrypter(
12268 ENCRYPTION_HANDSHAKE,
12269 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012270 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
12271 // Discard INITIAL key.
12272 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12273 connection_.NeuterUnencryptedPackets();
12274 // Verify there is pending ACK.
12275 ASSERT_TRUE(connection_.HasPendingAcks());
12276 // Set the send alarm.
12277 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
12278
12279 // Fire ACK alarm.
12280 connection_.GetAckAlarm()->Fire();
12281 // Verify 1-RTT packet is coalesced with handshake packet.
12282 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12283 connection_.GetSendAlarm()->Fire();
12284
12285 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12286 connection_.GetRetransmissionAlarm()->Fire();
12287 // Verify a handshake packet gets PTOed and 1-RTT packet gets coalesced.
12288 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12289}
12290
12291// Regression test for b/168294218.
12292TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) {
12293 if (!connection_.version().CanSendCoalescedPackets()) {
12294 return;
12295 }
12296 SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true);
12297 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
12298 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12299 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12300 connection_.NeuterUnencryptedPackets();
12301 }));
12302 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12303
12304 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
12305 {
12306 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040012307 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
12308 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080012309 connection_.SetEncrypter(
12310 ENCRYPTION_HANDSHAKE,
12311 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012312 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12313 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
12314 // Verify this packet is on hold.
12315 EXPECT_EQ(0u, writer_->packets_write_attempts());
12316 }
12317 EXPECT_TRUE(connection_.connected());
12318}
12319
12320// Regresstion test for b/168294218
12321TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) {
12322 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12323 return;
12324 }
12325 // Not defer send in response to packet.
12326 connection_.set_defer_send_in_response_to_packets(false);
12327 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12328 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12329 connection_.NeuterUnencryptedPackets();
12330 }));
12331 EXPECT_CALL(visitor_, OnCryptoFrame(_))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070012332 .WillRepeatedly(Invoke([=, this](const QuicCryptoFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040012333 if (frame.level == ENCRYPTION_HANDSHAKE) {
12334 // 0-RTT gets rejected.
12335 connection_.MarkZeroRttPacketsForRetransmission(0);
12336 // Send Crypto data.
martinduke9e0811c2022-12-08 20:35:57 -080012337 connection_.SetEncrypter(
12338 ENCRYPTION_HANDSHAKE,
12339 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012340 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12341 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080012342 connection_.SetEncrypter(
12343 ENCRYPTION_FORWARD_SECURE,
12344 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012345 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12346 // Advance INITIAL ack delay to trigger initial ACK to be sent AFTER
12347 // the retransmission of rejected 0-RTT packets while the HANDSHAKE
12348 // packet is still in the coalescer, such that the INITIAL key gets
12349 // dropped between SendAllPendingAcks and actually send the ack frame,
12350 // bummer.
12351 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12352 }
12353 }));
Bence Békybac04052022-04-07 15:44:29 -040012354 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12355 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080012356 connection_.SetEncrypter(
12357 ENCRYPTION_ZERO_RTT,
12358 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040012359 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12360 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12361
12362 QuicAckFrame frame1 = InitAckFrame(1);
12363 // Received ACK for packet 1.
martindukeba002452023-03-21 08:10:46 -070012364 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012365 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
12366 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12367
12368 // Fire retransmission alarm.
12369 connection_.GetRetransmissionAlarm()->Fire();
12370
12371 QuicFrames frames1;
12372 frames1.push_back(QuicFrame(&crypto_frame_));
12373 QuicFrames frames2;
12374 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12375 absl::string_view(data1));
12376 frames2.push_back(QuicFrame(&crypto_frame));
12377 ProcessCoalescedPacket(
12378 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
12379}
12380
12381TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) {
12382 if (!connection_.version().UsesTls()) {
12383 return;
12384 }
12385 MockQuicConnectionDebugVisitor debug_visitor;
12386 connection_.set_debug_visitor(&debug_visitor);
Bence Békybac04052022-04-07 15:44:29 -040012387 connection_.SendCryptoStreamData();
12388 // Send 0-RTT packet.
12389 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
12390 std::make_unique<TaggingEncrypter>(0x02));
12391 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12392 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12393 connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN);
12394 // Received ACK for packet 1, HANDSHAKE packet and 1-RTT ACK.
martindukeba002452023-03-21 08:10:46 -070012395 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040012396 .Times(AnyNumber());
12397 QuicFrames frames1;
12398 QuicAckFrame ack_frame1 = InitAckFrame(1);
12399 frames1.push_back(QuicFrame(&ack_frame1));
12400
12401 QuicFrames frames2;
12402 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12403 absl::string_view(data1));
12404 frames2.push_back(QuicFrame(&crypto_frame));
12405 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12406 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
12407 ProcessCoalescedPacket(
12408 {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}});
12409
12410 QuicFrames frames3;
12411 QuicAckFrame ack_frame2 =
12412 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
12413 frames3.push_back(QuicFrame(&ack_frame2));
12414 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1);
12415 ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}});
12416
12417 QuicFrames frames4;
12418 QuicAckFrame ack_frame3 =
12419 InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}});
12420 frames4.push_back(QuicFrame(&ack_frame3));
12421 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12422 ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}});
12423}
12424
12425TEST_P(QuicConnectionTest, InitiateKeyUpdate) {
12426 if (!connection_.version().UsesTls()) {
12427 return;
12428 }
12429
12430 TransportParameters params;
12431 QuicConfig config;
12432 std::string error_details;
12433 EXPECT_THAT(config.ProcessTransportParameters(
12434 params, /* is_resumption = */ false, &error_details),
12435 IsQuicNoError());
12436 QuicConfigPeer::SetNegotiated(&config, true);
12437 if (connection_.version().UsesTls()) {
12438 QuicConfigPeer::SetReceivedOriginalConnectionId(
12439 &config, connection_.connection_id());
12440 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12441 &config, connection_.connection_id());
12442 }
12443 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12444 connection_.SetFromConfig(config);
12445
12446 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12447
12448 MockFramerVisitor peer_framer_visitor_;
12449 peer_framer_.set_visitor(&peer_framer_visitor_);
12450
martinduke9e0811c2022-12-08 20:35:57 -080012451 uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012452 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12453 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012454 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012455 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012456 std::make_unique<StrictTaggingDecrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012457 EXPECT_CALL(visitor_, GetHandshakeState())
12458 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12459 connection_.OnHandshakeComplete();
12460
12461 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012462 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012463
12464 // Key update should still not be allowed, since no packet has been acked
12465 // from the current key phase.
12466 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12467 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12468
12469 // Send packet 1.
12470 QuicPacketNumber last_packet;
12471 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12472 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12473
12474 // Key update should still not be allowed, even though a packet was sent in
12475 // the current key phase it hasn't been acked yet.
12476 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12477 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12478
12479 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12480 // Receive ack for packet 1.
martindukeba002452023-03-21 08:10:46 -070012481 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012482 QuicAckFrame frame1 = InitAckFrame(1);
12483 ProcessAckPacket(&frame1);
12484
12485 // OnDecryptedFirstPacketInKeyPhase is called even on the first key phase,
12486 // so discard_previous_keys_alarm_ should be set now.
12487 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12488 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12489
martinduke9e0811c2022-12-08 20:35:57 -080012490 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012491 // Key update should now be allowed.
12492 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012493 .WillOnce([&correct_tag]() {
12494 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12495 });
12496 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12497 .WillOnce([&correct_tag]() {
12498 return std::make_unique<TaggingEncrypter>(correct_tag);
12499 });
Bence Békybac04052022-04-07 15:44:29 -040012500 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12501 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12502 // discard_previous_keys_alarm_ should not be set until a packet from the new
12503 // key phase has been received. (The alarm that was set above should be
12504 // cleared if it hasn't fired before the next key update happened.)
12505 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12506 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12507
12508 // Pretend that peer accepts the key update.
12509 EXPECT_CALL(peer_framer_visitor_,
12510 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012511 .WillOnce([&correct_tag]() {
12512 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12513 });
Bence Békybac04052022-04-07 15:44:29 -040012514 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012515 .WillOnce([&correct_tag]() {
12516 return std::make_unique<TaggingEncrypter>(correct_tag);
12517 });
Bence Békybac04052022-04-07 15:44:29 -040012518 peer_framer_.SetKeyUpdateSupportForConnection(true);
12519 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12520
12521 // Another key update should not be allowed yet.
12522 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12523
12524 // Send packet 2.
12525 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12526 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12527 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12528 // Receive ack for packet 2.
martindukeba002452023-03-21 08:10:46 -070012529 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012530 QuicAckFrame frame2 = InitAckFrame(2);
12531 ProcessAckPacket(&frame2);
12532 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12533 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12534
martinduke9e0811c2022-12-08 20:35:57 -080012535 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012536 // Key update should be allowed again now that a packet has been acked from
12537 // the current key phase.
12538 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012539 .WillOnce([&correct_tag]() {
12540 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12541 });
12542 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12543 .WillOnce([&correct_tag]() {
12544 return std::make_unique<TaggingEncrypter>(correct_tag);
12545 });
Bence Békybac04052022-04-07 15:44:29 -040012546 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12547 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12548
12549 // Pretend that peer accepts the key update.
12550 EXPECT_CALL(peer_framer_visitor_,
12551 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012552 .WillOnce([&correct_tag]() {
12553 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12554 });
Bence Békybac04052022-04-07 15:44:29 -040012555 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012556 .WillOnce([&correct_tag]() {
12557 return std::make_unique<TaggingEncrypter>(correct_tag);
12558 });
Bence Békybac04052022-04-07 15:44:29 -040012559 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12560
12561 // Another key update should not be allowed yet.
12562 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12563
12564 // Send packet 3.
12565 SendStreamDataToPeer(3, "baz", 0, NO_FIN, &last_packet);
12566 EXPECT_EQ(QuicPacketNumber(3u), last_packet);
12567
12568 // Another key update should not be allowed yet.
12569 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12570 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12571
12572 // Receive ack for packet 3.
martindukeba002452023-03-21 08:10:46 -070012573 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012574 QuicAckFrame frame3 = InitAckFrame(3);
12575 ProcessAckPacket(&frame3);
12576 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12577 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12578
martinduke9e0811c2022-12-08 20:35:57 -080012579 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012580 // Key update should be allowed now.
12581 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012582 .WillOnce([&correct_tag]() {
12583 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12584 });
12585 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12586 .WillOnce([&correct_tag]() {
12587 return std::make_unique<TaggingEncrypter>(correct_tag);
12588 });
Bence Békybac04052022-04-07 15:44:29 -040012589 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12590 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12591 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12592 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12593}
12594
12595TEST_P(QuicConnectionTest, InitiateKeyUpdateApproachingConfidentialityLimit) {
12596 if (!connection_.version().UsesTls()) {
12597 return;
12598 }
12599
birenroyef686222022-09-12 11:34:34 -070012600 SetQuicFlag(quic_key_update_confidentiality_limit, 3U);
Bence Békybac04052022-04-07 15:44:29 -040012601
12602 std::string error_details;
12603 TransportParameters params;
12604 // Key update is enabled.
12605 QuicConfig config;
12606 EXPECT_THAT(config.ProcessTransportParameters(
12607 params, /* is_resumption = */ false, &error_details),
12608 IsQuicNoError());
12609 QuicConfigPeer::SetNegotiated(&config, true);
12610 if (connection_.version().UsesTls()) {
12611 QuicConfigPeer::SetReceivedOriginalConnectionId(
12612 &config, connection_.connection_id());
12613 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12614 &config, connection_.connection_id());
12615 }
12616 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12617 connection_.SetFromConfig(config);
12618
12619 MockFramerVisitor peer_framer_visitor_;
12620 peer_framer_.set_visitor(&peer_framer_visitor_);
12621
martinduke9e0811c2022-12-08 20:35:57 -080012622 uint8_t current_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012623
12624 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12625 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12626 std::make_unique<TaggingEncrypter>(current_tag));
12627 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12628 std::make_unique<StrictTaggingDecrypter>(current_tag));
12629 EXPECT_CALL(visitor_, GetHandshakeState())
12630 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12631 connection_.OnHandshakeComplete();
12632
12633 peer_framer_.SetKeyUpdateSupportForConnection(true);
12634 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12635 std::make_unique<TaggingEncrypter>(current_tag));
12636
12637 const QuicConnectionStats& stats = connection_.GetStats();
12638
12639 for (int packet_num = 1; packet_num <= 8; ++packet_num) {
12640 if (packet_num == 3 || packet_num == 6) {
12641 current_tag++;
12642 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12643 .WillOnce([current_tag]() {
12644 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12645 });
12646 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12647 .WillOnce([current_tag]() {
12648 return std::make_unique<TaggingEncrypter>(current_tag);
12649 });
12650 EXPECT_CALL(visitor_,
12651 OnKeyUpdate(KeyUpdateReason::kLocalKeyUpdateLimitOverride));
12652 }
12653 // Send packet.
12654 QuicPacketNumber last_packet;
12655 SendStreamDataToPeer(packet_num, "foo", 0, NO_FIN, &last_packet);
12656 EXPECT_EQ(QuicPacketNumber(packet_num), last_packet);
12657 if (packet_num >= 6) {
12658 EXPECT_EQ(2U, stats.key_update_count);
12659 } else if (packet_num >= 3) {
12660 EXPECT_EQ(1U, stats.key_update_count);
12661 } else {
12662 EXPECT_EQ(0U, stats.key_update_count);
12663 }
12664
12665 if (packet_num == 4 || packet_num == 7) {
12666 // Pretend that peer accepts the key update.
12667 EXPECT_CALL(peer_framer_visitor_,
12668 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12669 .WillOnce([current_tag]() {
12670 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12671 });
12672 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12673 .WillOnce([current_tag]() {
12674 return std::make_unique<TaggingEncrypter>(current_tag);
12675 });
12676 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12677 }
12678 // Receive ack for packet.
martindukeba002452023-03-21 08:10:46 -070012679 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012680 QuicAckFrame frame1 = InitAckFrame(packet_num);
12681 ProcessAckPacket(&frame1);
12682 }
12683}
12684
12685TEST_P(QuicConnectionTest,
12686 CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed) {
12687 if (!connection_.version().UsesTls()) {
12688 return;
12689 }
12690
12691 // Set key update confidentiality limit to 1 packet.
birenroyef686222022-09-12 11:34:34 -070012692 SetQuicFlag(quic_key_update_confidentiality_limit, 1U);
Bence Békybac04052022-04-07 15:44:29 -040012693 // Use confidentiality limit for connection close of 3 packets.
12694 constexpr size_t kConfidentialityLimit = 3U;
12695
12696 std::string error_details;
12697 TransportParameters params;
12698 // Key update is enabled.
12699 QuicConfig config;
12700 EXPECT_THAT(config.ProcessTransportParameters(
12701 params, /* is_resumption = */ false, &error_details),
12702 IsQuicNoError());
12703 QuicConfigPeer::SetNegotiated(&config, true);
12704 if (connection_.version().UsesTls()) {
12705 QuicConfigPeer::SetReceivedOriginalConnectionId(
12706 &config, connection_.connection_id());
12707 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12708 &config, connection_.connection_id());
12709 }
12710 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12711 connection_.SetFromConfig(config);
12712
12713 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12714 connection_.SetEncrypter(
12715 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012716 std::make_unique<TaggingEncrypterWithConfidentialityLimit>(
12717 ENCRYPTION_FORWARD_SECURE, kConfidentialityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012718 EXPECT_CALL(visitor_, GetHandshakeState())
12719 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12720 connection_.OnHandshakeComplete();
12721
12722 QuicPacketNumber last_packet;
12723 // Send 3 packets without receiving acks for any of them. Key update will not
12724 // be allowed, so the confidentiality limit should be reached, forcing the
12725 // connection to be closed.
12726 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12727 EXPECT_TRUE(connection_.connected());
12728 SendStreamDataToPeer(2, "foo", 0, NO_FIN, &last_packet);
12729 EXPECT_TRUE(connection_.connected());
12730 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12731 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
12732 EXPECT_FALSE(connection_.connected());
12733 const QuicConnectionStats& stats = connection_.GetStats();
12734 EXPECT_EQ(0U, stats.key_update_count);
12735 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12736}
12737
12738TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitDuringHandshake) {
12739 if (!connection_.version().UsesTls()) {
12740 return;
12741 }
12742
martinduke9e0811c2022-12-08 20:35:57 -080012743 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012744 constexpr uint8_t wrong_tag = 0xFE;
12745 constexpr QuicPacketCount kIntegrityLimit = 3;
12746
12747 SetDecrypter(ENCRYPTION_HANDSHAKE,
12748 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12749 correct_tag, kIntegrityLimit));
12750 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12751 std::make_unique<TaggingEncrypter>(correct_tag));
12752 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12753 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12754 std::make_unique<TaggingEncrypter>(wrong_tag));
12755 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12756 EXPECT_TRUE(connection_.connected());
12757 if (i == kIntegrityLimit) {
12758 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12759 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
12760 }
12761 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12762 EXPECT_EQ(
12763 i, connection_.GetStats().num_failed_authentication_packets_received);
12764 }
12765 EXPECT_FALSE(connection_.connected());
12766 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12767}
12768
12769TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAfterHandshake) {
12770 if (!connection_.version().UsesTls()) {
12771 return;
12772 }
12773
martinduke9e0811c2022-12-08 20:35:57 -080012774 constexpr uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012775 constexpr uint8_t wrong_tag = 0xFE;
12776 constexpr QuicPacketCount kIntegrityLimit = 3;
12777
Bence Békybac04052022-04-07 15:44:29 -040012778 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12779 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12780 correct_tag, kIntegrityLimit));
12781 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12782 std::make_unique<TaggingEncrypter>(correct_tag));
12783 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12784 EXPECT_CALL(visitor_, GetHandshakeState())
12785 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12786 connection_.OnHandshakeComplete();
12787 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12788 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12789 std::make_unique<TaggingEncrypter>(wrong_tag));
12790 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12791 EXPECT_TRUE(connection_.connected());
12792 if (i == kIntegrityLimit) {
12793 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12794 }
12795 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12796 EXPECT_EQ(
12797 i, connection_.GetStats().num_failed_authentication_packets_received);
12798 }
12799 EXPECT_FALSE(connection_.connected());
12800 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12801}
12802
12803TEST_P(QuicConnectionTest,
12804 CloseConnectionOnIntegrityLimitAcrossEncryptionLevels) {
12805 if (!connection_.version().UsesTls()) {
12806 return;
12807 }
12808
martinduke9e0811c2022-12-08 20:35:57 -080012809 uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012810 constexpr uint8_t wrong_tag = 0xFE;
12811 constexpr QuicPacketCount kIntegrityLimit = 4;
12812
Bence Békybac04052022-04-07 15:44:29 -040012813 SetDecrypter(ENCRYPTION_HANDSHAKE,
12814 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12815 correct_tag, kIntegrityLimit));
12816 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12817 std::make_unique<TaggingEncrypter>(correct_tag));
12818 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12819 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12820 std::make_unique<TaggingEncrypter>(wrong_tag));
12821 for (uint64_t i = 1; i <= 2; ++i) {
12822 EXPECT_TRUE(connection_.connected());
12823 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12824 EXPECT_EQ(
12825 i, connection_.GetStats().num_failed_authentication_packets_received);
12826 }
12827
martinduke9e0811c2022-12-08 20:35:57 -080012828 correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012829 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12830 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12831 correct_tag, kIntegrityLimit));
12832 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12833 std::make_unique<TaggingEncrypter>(correct_tag));
12834 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12835 EXPECT_CALL(visitor_, GetHandshakeState())
12836 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12837 connection_.OnHandshakeComplete();
12838 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12839 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
12840 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12841 std::make_unique<TaggingEncrypter>(wrong_tag));
12842 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12843 EXPECT_TRUE(connection_.connected());
12844 if (i == kIntegrityLimit) {
12845 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12846 }
12847 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12848 EXPECT_EQ(
12849 i, connection_.GetStats().num_failed_authentication_packets_received);
12850 }
12851 EXPECT_FALSE(connection_.connected());
12852 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12853}
12854
12855TEST_P(QuicConnectionTest, IntegrityLimitDoesNotApplyWithoutDecryptionKey) {
12856 if (!connection_.version().UsesTls()) {
12857 return;
12858 }
12859
martinduke9e0811c2022-12-08 20:35:57 -080012860 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012861 constexpr uint8_t wrong_tag = 0xFE;
12862 constexpr QuicPacketCount kIntegrityLimit = 3;
12863
Bence Békybac04052022-04-07 15:44:29 -040012864 SetDecrypter(ENCRYPTION_HANDSHAKE,
12865 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12866 correct_tag, kIntegrityLimit));
12867 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12868 std::make_unique<TaggingEncrypter>(correct_tag));
12869 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12870 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
12871
12872 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12873 std::make_unique<TaggingEncrypter>(wrong_tag));
12874 for (uint64_t i = 1; i <= kIntegrityLimit * 2; ++i) {
12875 EXPECT_TRUE(connection_.connected());
12876 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12877 EXPECT_EQ(
12878 0u, connection_.GetStats().num_failed_authentication_packets_received);
12879 }
12880 EXPECT_TRUE(connection_.connected());
12881}
12882
12883TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossKeyPhases) {
12884 if (!connection_.version().UsesTls()) {
12885 return;
12886 }
12887
12888 constexpr QuicPacketCount kIntegrityLimit = 4;
12889
12890 TransportParameters params;
12891 QuicConfig config;
12892 std::string error_details;
12893 EXPECT_THAT(config.ProcessTransportParameters(
12894 params, /* is_resumption = */ false, &error_details),
12895 IsQuicNoError());
12896 QuicConfigPeer::SetNegotiated(&config, true);
12897 if (connection_.version().UsesTls()) {
12898 QuicConfigPeer::SetReceivedOriginalConnectionId(
12899 &config, connection_.connection_id());
12900 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12901 &config, connection_.connection_id());
12902 }
12903 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12904 connection_.SetFromConfig(config);
12905
12906 MockFramerVisitor peer_framer_visitor_;
12907 peer_framer_.set_visitor(&peer_framer_visitor_);
12908
Bence Békybac04052022-04-07 15:44:29 -040012909 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12910 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12911 std::make_unique<TaggingEncrypter>(0x01));
12912 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12913 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
martinduke9e0811c2022-12-08 20:35:57 -080012914 ENCRYPTION_FORWARD_SECURE, kIntegrityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012915 EXPECT_CALL(visitor_, GetHandshakeState())
12916 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12917 connection_.OnHandshakeComplete();
12918 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12919
12920 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12921 std::make_unique<TaggingEncrypter>(0xFF));
12922 for (uint64_t i = 1; i <= 2; ++i) {
12923 EXPECT_TRUE(connection_.connected());
12924 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12925 EXPECT_EQ(
12926 i, connection_.GetStats().num_failed_authentication_packets_received);
12927 }
12928
martinduke9e0811c2022-12-08 20:35:57 -080012929 peer_framer_.SetEncrypter(
12930 ENCRYPTION_FORWARD_SECURE,
12931 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012932 // Send packet 1.
12933 QuicPacketNumber last_packet;
12934 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12935 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12936 // Receive ack for packet 1.
martindukeba002452023-03-21 08:10:46 -070012937 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012938 QuicAckFrame frame1 = InitAckFrame(1);
12939 ProcessAckPacket(&frame1);
12940 // Key update should now be allowed, initiate it.
12941 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12942 .WillOnce([kIntegrityLimit]() {
12943 return std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12944 0x02, kIntegrityLimit);
12945 });
12946 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12947 return std::make_unique<TaggingEncrypter>(0x02);
12948 });
12949 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12950 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12951
12952 // Pretend that peer accepts the key update.
12953 EXPECT_CALL(peer_framer_visitor_,
12954 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12955 .WillOnce(
12956 []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
12957 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12958 .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); });
12959 peer_framer_.SetKeyUpdateSupportForConnection(true);
12960 peer_framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests);
12961
12962 // Send packet 2.
12963 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12964 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12965 // Receive ack for packet 2.
martindukeba002452023-03-21 08:10:46 -070012966 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040012967 QuicAckFrame frame2 = InitAckFrame(2);
12968 ProcessAckPacket(&frame2);
12969
12970 EXPECT_EQ(2u,
12971 connection_.GetStats().num_failed_authentication_packets_received);
12972
12973 // Do two more undecryptable packets. Integrity limit should be reached.
12974 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12975 std::make_unique<TaggingEncrypter>(0xFF));
12976 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12977 EXPECT_TRUE(connection_.connected());
12978 if (i == kIntegrityLimit) {
12979 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12980 }
12981 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12982 EXPECT_EQ(
12983 i, connection_.GetStats().num_failed_authentication_packets_received);
12984 }
12985 EXPECT_FALSE(connection_.connected());
12986 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12987}
12988
12989TEST_P(QuicConnectionTest, SendAckFrequencyFrame) {
12990 if (!version().HasIetfQuicFrames()) {
12991 return;
12992 }
12993 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12994 set_perspective(Perspective::IS_SERVER);
martindukeba002452023-03-21 08:10:46 -070012995 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040012996 .Times(AnyNumber());
12997 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12998
12999 QuicConfig config;
13000 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13001 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13002 connection_.SetFromConfig(config);
13003 QuicConnectionPeer::SetAddressValidated(&connection_);
13004 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13005 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
13006
13007 connection_.OnHandshakeComplete();
13008
13009 writer_->SetWritable();
13010 QuicPacketCreatorPeer::SetPacketNumber(creator_, 99);
13011 // Send packet 100
13012 SendStreamDataToPeer(/*id=*/1, "foo", /*offset=*/0, NO_FIN, nullptr);
13013
13014 QuicAckFrequencyFrame captured_frame;
13015 EXPECT_CALL(visitor_, SendAckFrequency(_))
13016 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
13017 captured_frame = frame;
13018 }));
13019 // Send packet 101.
13020 SendStreamDataToPeer(/*id=*/1, "bar", /*offset=*/3, NO_FIN, nullptr);
13021
13022 EXPECT_EQ(captured_frame.packet_tolerance, 10u);
13023 EXPECT_EQ(captured_frame.max_ack_delay,
wub349df3d2024-04-26 11:37:32 -070013024 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040013025
13026 // Sending packet 102 does not trigger sending another AckFrequencyFrame.
13027 SendStreamDataToPeer(/*id=*/1, "baz", /*offset=*/6, NO_FIN, nullptr);
13028}
13029
13030TEST_P(QuicConnectionTest, SendAckFrequencyFrameUponHandshakeCompletion) {
13031 if (!version().HasIetfQuicFrames()) {
13032 return;
13033 }
13034 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13035 set_perspective(Perspective::IS_SERVER);
martindukeba002452023-03-21 08:10:46 -070013036 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040013037 .Times(AnyNumber());
13038 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
13039
13040 QuicConfig config;
13041 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13042 QuicTagVector quic_tag_vector;
13043 // Enable sending AckFrequency upon handshake completion.
13044 quic_tag_vector.push_back(kAFF2);
13045 QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector);
13046 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13047 connection_.SetFromConfig(config);
13048 QuicConnectionPeer::SetAddressValidated(&connection_);
13049 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13050 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
13051
13052 QuicAckFrequencyFrame captured_frame;
13053 EXPECT_CALL(visitor_, SendAckFrequency(_))
13054 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
13055 captured_frame = frame;
13056 }));
13057
13058 connection_.OnHandshakeComplete();
13059
13060 EXPECT_EQ(captured_frame.packet_tolerance, 2u);
13061 EXPECT_EQ(captured_frame.max_ack_delay,
wub349df3d2024-04-26 11:37:32 -070013062 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040013063}
13064
13065TEST_P(QuicConnectionTest, FastRecoveryOfLostServerHello) {
13066 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
13067 return;
13068 }
13069 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13070 QuicConfig config;
13071 connection_.SetFromConfig(config);
13072
Bence Békybac04052022-04-07 15:44:29 -040013073 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13074 connection_.SendCryptoStreamData();
13075 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13076
13077 // Assume ServerHello gets lost.
13078 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13079 std::make_unique<TaggingEncrypter>(0x02));
13080 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13081 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
13082 // Shorten PTO for fast recovery from lost ServerHello.
13083 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
13084 connection_.GetRetransmissionAlarm()->deadline());
13085}
13086
13087TEST_P(QuicConnectionTest, ServerHelloGetsReordered) {
13088 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
13089 return;
13090 }
13091 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13092 QuicConfig config;
13093 connection_.SetFromConfig(config);
13094 EXPECT_CALL(visitor_, OnCryptoFrame(_))
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070013095 .WillRepeatedly(Invoke([=, this](const QuicCryptoFrame& frame) {
Bence Békybac04052022-04-07 15:44:29 -040013096 if (frame.level == ENCRYPTION_INITIAL) {
13097 // Install handshake read keys.
martinduke9e0811c2022-12-08 20:35:57 -080013098 SetDecrypter(
13099 ENCRYPTION_HANDSHAKE,
13100 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
13101 connection_.SetEncrypter(
13102 ENCRYPTION_HANDSHAKE,
13103 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040013104 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
13105 }
13106 }));
13107
Bence Békybac04052022-04-07 15:44:29 -040013108 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13109 connection_.SendCryptoStreamData();
13110 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13111
13112 // Assume ServerHello gets reordered.
13113 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13114 std::make_unique<TaggingEncrypter>(0x02));
13115 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13116 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
13117 // Verify fast recovery is not enabled.
13118 EXPECT_EQ(connection_.sent_packet_manager().GetRetransmissionTime(),
13119 connection_.GetRetransmissionAlarm()->deadline());
13120}
13121
13122TEST_P(QuicConnectionTest, MigratePath) {
danzh7c0ef5f2023-06-08 12:10:35 -070013123 connection_.CreateConnectionIdManager();
13124 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13125 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -040013126 EXPECT_CALL(visitor_, GetHandshakeState())
13127 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13128 EXPECT_CALL(visitor_, OnPathDegrading());
13129 connection_.OnPathDegradingDetected();
13130 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13131 EXPECT_NE(kNewSelfAddress, connection_.self_address());
13132
13133 // Buffer a packet.
13134 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
13135 writer_->SetWriteBlocked();
13136 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
13137 EXPECT_EQ(1u, connection_.NumQueuedPackets());
13138
danzh7c0ef5f2023-06-08 12:10:35 -070013139 if (version().HasIetfQuicFrames()) {
13140 QuicNewConnectionIdFrame frame;
13141 frame.connection_id = TestConnectionId(1234);
13142 ASSERT_NE(frame.connection_id, connection_.connection_id());
13143 frame.stateless_reset_token =
13144 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13145 frame.retire_prior_to = 0u;
13146 frame.sequence_number = 1u;
13147 connection_.OnNewConnectionIdFrame(frame);
13148 }
13149
Bence Békybac04052022-04-07 15:44:29 -040013150 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13151 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
danzh7c0ef5f2023-06-08 12:10:35 -070013152 EXPECT_TRUE(connection_.MigratePath(kNewSelfAddress,
13153 connection_.peer_address(), &new_writer,
13154 /*owns_writer=*/false));
Bence Békybac04052022-04-07 15:44:29 -040013155
13156 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13157 EXPECT_EQ(&new_writer, QuicConnectionPeer::GetWriter(&connection_));
13158 EXPECT_FALSE(connection_.IsPathDegrading());
13159 // Buffered packet on the old path should be discarded.
danzh7c0ef5f2023-06-08 12:10:35 -070013160 if (version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040013161 EXPECT_EQ(0u, connection_.NumQueuedPackets());
13162 } else {
13163 EXPECT_EQ(1u, connection_.NumQueuedPackets());
13164 }
13165}
13166
13167TEST_P(QuicConnectionTest, MigrateToNewPathDuringProbing) {
danzh87605712022-04-11 14:36:39 -070013168 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040013169 return;
13170 }
13171 PathProbeTestInit(Perspective::IS_CLIENT);
13172 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13173 EXPECT_NE(kNewSelfAddress, connection_.self_address());
13174 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13175 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13176 bool success = false;
13177 connection_.ValidatePath(
13178 std::make_unique<TestQuicPathValidationContext>(
13179 kNewSelfAddress, connection_.peer_address(), &new_writer),
13180 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080013181 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
13182 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040013183 EXPECT_TRUE(connection_.HasPendingPathValidation());
13184 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13185 &connection_, kNewSelfAddress, connection_.peer_address()));
13186
13187 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
13188 &new_writer, /*owns_writer=*/false);
13189 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13190 EXPECT_TRUE(connection_.HasPendingPathValidation());
13191 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13192 &connection_, kNewSelfAddress, connection_.peer_address()));
13193}
13194
renjietang89540a62022-12-01 14:46:26 -080013195TEST_P(QuicConnectionTest, MultiPortConnection) {
renjietangfca5c772022-08-25 13:48:21 -070013196 set_perspective(Perspective::IS_CLIENT);
13197 QuicConfig config;
renjietang89540a62022-12-01 14:46:26 -080013198 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
renjietangfca5c772022-08-25 13:48:21 -070013199 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13200 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013201 if (!version().HasIetfQuicFrames()) {
renjietangfca5c772022-08-25 13:48:21 -070013202 return;
13203 }
13204 connection_.CreateConnectionIdManager();
13205 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13206 connection_.OnHandshakeComplete();
13207
renjietang864fbda2022-09-08 10:50:07 -070013208 EXPECT_CALL(visitor_, OnPathDegrading());
13209 connection_.OnPathDegradingDetected();
13210
renjietangfca5c772022-08-25 13:48:21 -070013211 auto self_address = connection_.self_address();
13212 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13213 self_address.port() + 1);
13214 EXPECT_NE(kNewSelfAddress, self_address);
13215 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13216
renjietang89540a62022-12-01 14:46:26 -080013217 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
renjietangfca5c772022-08-25 13:48:21 -070013218 QuicNewConnectionIdFrame frame;
13219 frame.connection_id = TestConnectionId(1234);
13220 ASSERT_NE(frame.connection_id, connection_.connection_id());
13221 frame.stateless_reset_token =
13222 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13223 frame.retire_prior_to = 0u;
13224 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013225 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013226 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13227 observer->OnMultiPortPathContextAvailable(
13228 std::move(std::make_unique<TestQuicPathValidationContext>(
13229 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013230 }));
renjietangfca5c772022-08-25 13:48:21 -070013231 connection_.OnNewConnectionIdFrame(frame);
13232 EXPECT_TRUE(connection_.HasPendingPathValidation());
13233 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13234 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013235 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13236 EXPECT_FALSE(alt_path->validated);
renjietange499db42023-01-17 15:42:33 -080013237 EXPECT_EQ(PathValidationReason::kMultiPort,
13238 QuicConnectionPeer::path_validator(&connection_)
13239 ->GetPathValidationReason());
13240
13241 // Suppose the server retransmits the NEW_CID frame, the client will receive
13242 // the same frame again. It should be ignored.
13243 // Regression test of crbug.com/1406762
13244 connection_.OnNewConnectionIdFrame(frame);
renjietangfca5c772022-08-25 13:48:21 -070013245
renjietang864fbda2022-09-08 10:50:07 -070013246 // 30ms RTT.
13247 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13248 // Fake a response delay.
13249 clock_.AdvanceTime(kTestRTT);
13250
renjietangfca5c772022-08-25 13:48:21 -070013251 QuicFrames frames;
13252 frames.push_back(QuicFrame(QuicPathResponseFrame(
renjietang89540a62022-12-01 14:46:26 -080013253 99, new_writer.path_challenge_frames().back().data_buffer)));
renjietangfca5c772022-08-25 13:48:21 -070013254 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13255 ENCRYPTION_FORWARD_SECURE);
13256 // No migration should happen and the alternative path should still be alive.
13257 EXPECT_FALSE(connection_.HasPendingPathValidation());
13258 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13259 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013260 EXPECT_TRUE(alt_path->validated);
renjietang864fbda2022-09-08 10:50:07 -070013261 auto stats = connection_.multi_port_stats();
renjietang201bfa52023-04-24 18:12:27 -070013262 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietangbb4f6842024-02-12 14:25:06 -080013263 EXPECT_EQ(1, stats->num_successful_probes);
13264 EXPECT_EQ(1, stats->num_client_probing_attempts);
martinduke525723b2024-09-12 13:25:06 -070013265 EXPECT_EQ(1, connection_.GetStats().num_client_probing_attempts);
renjietang864fbda2022-09-08 10:50:07 -070013266 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13267 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13268 EXPECT_EQ(kTestRTT,
13269 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13270
renjietang785c7cb2023-08-21 09:10:25 -070013271 // Receiving the retransmitted NEW_CID frame now should still have no effect.
renjietang39a1add2023-10-26 12:51:57 -070013272 EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0);
13273 connection_.OnNewConnectionIdFrame(frame);
renjietang785c7cb2023-08-21 09:10:25 -070013274
renjietang89540a62022-12-01 14:46:26 -080013275 // When there's no active request, the probing shouldn't happen. But the
13276 // probing context should be saved.
13277 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
13278 connection_.GetMultiPortProbingAlarm()->Fire();
13279 EXPECT_FALSE(connection_.HasPendingPathValidation());
13280 EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13281
13282 // Simulate the situation where a new request stream is created.
13283 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13284 .WillRepeatedly(Return(true));
13285 random_generator_.ChangeValue();
13286 connection_.MaybeProbeMultiPortPath();
13287 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13288 &connection_, kNewSelfAddress, connection_.peer_address()));
13289 EXPECT_TRUE(alt_path->validated);
13290 // Fake a response delay.
13291 clock_.AdvanceTime(kTestRTT);
13292 QuicFrames frames2;
13293 frames2.push_back(QuicFrame(QuicPathResponseFrame(
13294 99, new_writer.path_challenge_frames().back().data_buffer)));
13295 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress, kPeerAddress,
13296 ENCRYPTION_FORWARD_SECURE);
13297 // No migration should happen and the alternative path should still be alive.
13298 EXPECT_FALSE(connection_.HasPendingPathValidation());
13299 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13300 &connection_, kNewSelfAddress, connection_.peer_address()));
13301 EXPECT_TRUE(alt_path->validated);
renjietang201bfa52023-04-24 18:12:27 -070013302 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013303 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13304 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13305 EXPECT_EQ(kTestRTT,
13306 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13307
renjietang546e3962023-09-01 10:51:19 -070013308 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
13309 QuicConnectionPeer::OnForwardProgressMade(&connection_);
13310
renjietang89540a62022-12-01 14:46:26 -080013311 EXPECT_TRUE(connection_.GetMultiPortProbingAlarm()->IsSet());
13312 // Since there's already a scheduled probing alarm, manual calls won't have
13313 // any effect.
13314 connection_.MaybeProbeMultiPortPath();
13315 EXPECT_FALSE(connection_.HasPendingPathValidation());
13316
renjietang546e3962023-09-01 10:51:19 -070013317 // Since kMPQM is not set, migration shouldn't happen
13318 EXPECT_CALL(visitor_, OnPathDegrading());
13319 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0);
13320 connection_.OnPathDegradingDetected();
13321 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13322 &connection_, kNewSelfAddress, connection_.peer_address()));
13323
renjietang89540a62022-12-01 14:46:26 -080013324 // Simulate the case where the path validation fails after retries.
renjietangfca5c772022-08-25 13:48:21 -070013325 connection_.GetMultiPortProbingAlarm()->Fire();
13326 EXPECT_TRUE(connection_.HasPendingPathValidation());
13327 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13328 &connection_, kNewSelfAddress, connection_.peer_address()));
13329 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13330 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13331 static_cast<TestAlarmFactory::TestAlarm*>(
13332 QuicPathValidatorPeer::retry_timer(
13333 QuicConnectionPeer::path_validator(&connection_)))
13334 ->Fire();
13335 }
13336
13337 EXPECT_FALSE(connection_.HasPendingPathValidation());
13338 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13339 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang546e3962023-09-01 10:51:19 -070013340 EXPECT_EQ(2, connection_.GetStats().num_path_degrading);
renjietang864fbda2022-09-08 10:50:07 -070013341 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13342 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_not_degrading);
martinduke525723b2024-09-12 13:25:06 -070013343 EXPECT_EQ(0, connection_.GetStats().num_stateless_resets_on_alternate_path);
renjietangfca5c772022-08-25 13:48:21 -070013344}
13345
renjietang89540a62022-12-01 14:46:26 -080013346TEST_P(QuicConnectionTest, TooManyMultiPortPathCreations) {
13347 set_perspective(Perspective::IS_CLIENT);
13348 QuicConfig config;
renjietang89540a62022-12-01 14:46:26 -080013349 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13350 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13351 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013352 if (!version().HasIetfQuicFrames()) {
renjietang89540a62022-12-01 14:46:26 -080013353 return;
13354 }
13355 connection_.CreateConnectionIdManager();
13356 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13357 connection_.OnHandshakeComplete();
13358
13359 EXPECT_CALL(visitor_, OnPathDegrading());
13360 connection_.OnPathDegradingDetected();
13361
13362 auto self_address = connection_.self_address();
13363 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13364 self_address.port() + 1);
13365 EXPECT_NE(kNewSelfAddress, self_address);
13366 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13367
13368 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13369 .WillRepeatedly(Return(true));
13370
QUICHE teame2a24ee2024-01-09 06:34:35 -080013371 {
13372 QuicNewConnectionIdFrame frame;
13373 frame.connection_id = TestConnectionId(1234);
13374 ASSERT_NE(frame.connection_id, connection_.connection_id());
13375 frame.stateless_reset_token =
13376 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13377 frame.retire_prior_to = 0u;
13378 frame.sequence_number = 1u;
13379 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13380 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13381 observer->OnMultiPortPathContextAvailable(
13382 std::move(std::make_unique<TestQuicPathValidationContext>(
13383 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13384 }));
13385 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13386 }
renjietang89540a62022-12-01 14:46:26 -080013387 EXPECT_TRUE(connection_.HasPendingPathValidation());
13388 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13389 &connection_, kNewSelfAddress, connection_.peer_address()));
13390 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13391 EXPECT_FALSE(alt_path->validated);
13392
13393 EXPECT_TRUE(connection_.HasPendingPathValidation());
13394 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13395 &connection_, kNewSelfAddress, connection_.peer_address()));
13396 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13397 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13398 static_cast<TestAlarmFactory::TestAlarm*>(
13399 QuicPathValidatorPeer::retry_timer(
13400 QuicConnectionPeer::path_validator(&connection_)))
13401 ->Fire();
13402 }
13403
13404 auto stats = connection_.multi_port_stats();
13405 EXPECT_FALSE(connection_.HasPendingPathValidation());
13406 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13407 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang201bfa52023-04-24 18:12:27 -070013408 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013409 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13410
13411 uint64_t connection_id = 1235;
13412 for (size_t i = 0; i < kMaxNumMultiPortPaths - 1; ++i) {
13413 QuicNewConnectionIdFrame frame;
13414 frame.connection_id = TestConnectionId(connection_id + i);
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 = i + 2;
QUICHE team107316f2023-05-03 09:04:11 -070013420 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013421 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13422 observer->OnMultiPortPathContextAvailable(
13423 std::move(std::make_unique<TestQuicPathValidationContext>(
13424 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013425 }));
renjietang89540a62022-12-01 14:46:26 -080013426 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13427 EXPECT_TRUE(connection_.HasPendingPathValidation());
13428 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13429 &connection_, kNewSelfAddress, connection_.peer_address()));
13430 EXPECT_FALSE(alt_path->validated);
13431
13432 for (size_t j = 0; j < QuicPathValidator::kMaxRetryTimes + 1; ++j) {
13433 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13434 static_cast<TestAlarmFactory::TestAlarm*>(
13435 QuicPathValidatorPeer::retry_timer(
13436 QuicConnectionPeer::path_validator(&connection_)))
13437 ->Fire();
13438 }
13439
13440 EXPECT_FALSE(connection_.HasPendingPathValidation());
13441 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13442 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang201bfa52023-04-24 18:12:27 -070013443 EXPECT_EQ(1, connection_.GetStats().num_path_degrading);
renjietang89540a62022-12-01 14:46:26 -080013444 EXPECT_EQ(i + 2, stats->num_multi_port_probe_failures_when_path_degrading);
13445 }
13446
13447 // The 6th attemp should fail.
13448 QuicNewConnectionIdFrame frame2;
13449 frame2.connection_id = TestConnectionId(1239);
13450 ASSERT_NE(frame2.connection_id, connection_.connection_id());
13451 frame2.stateless_reset_token =
13452 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
13453 frame2.retire_prior_to = 0u;
13454 frame2.sequence_number = 6u;
13455 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame2));
13456 EXPECT_FALSE(connection_.HasPendingPathValidation());
13457 EXPECT_EQ(kMaxNumMultiPortPaths,
13458 stats->num_multi_port_probe_failures_when_path_degrading);
13459}
13460
renjietang4ca6b842023-06-05 08:00:57 -070013461TEST_P(QuicConnectionTest, MultiPortPathReceivesStatelessReset) {
13462 set_perspective(Perspective::IS_CLIENT);
13463 QuicConfig config;
13464 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
13465 kTestStatelessResetToken);
13466 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13467 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13468 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013469 if (!version().HasIetfQuicFrames()) {
renjietang4ca6b842023-06-05 08:00:57 -070013470 return;
13471 }
13472 connection_.CreateConnectionIdManager();
13473 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13474 connection_.OnHandshakeComplete();
13475
13476 EXPECT_CALL(visitor_, OnPathDegrading());
13477 connection_.OnPathDegradingDetected();
13478
13479 auto self_address = connection_.self_address();
13480 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13481 self_address.port() + 1);
13482 EXPECT_NE(kNewSelfAddress, self_address);
13483 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13484
13485 QuicNewConnectionIdFrame frame;
13486 frame.connection_id = TestConnectionId(1234);
13487 ASSERT_NE(frame.connection_id, connection_.connection_id());
13488 frame.stateless_reset_token =
13489 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13490 frame.retire_prior_to = 0u;
13491 frame.sequence_number = 1u;
13492 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
13493 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13494 observer->OnMultiPortPathContextAvailable(
13495 std::move(std::make_unique<TestQuicPathValidationContext>(
13496 kNewSelfAddress, connection_.peer_address(), &new_writer)));
13497 }));
13498 connection_.OnNewConnectionIdFrame(frame);
13499 EXPECT_TRUE(connection_.HasPendingPathValidation());
13500 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13501 &connection_, kNewSelfAddress, connection_.peer_address()));
13502 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13503 EXPECT_FALSE(alt_path->validated);
13504 EXPECT_EQ(PathValidationReason::kMultiPort,
13505 QuicConnectionPeer::path_validator(&connection_)
13506 ->GetPathValidationReason());
13507
13508 std::unique_ptr<QuicEncryptedPacket> packet(
13509 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
13510 /*received_packet_length=*/100,
13511 kTestStatelessResetToken));
13512 std::unique_ptr<QuicReceivedPacket> received(
13513 ConstructReceivedPacket(*packet, QuicTime::Zero()));
13514 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
13515 .Times(0);
13516 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
martinduke525723b2024-09-12 13:25:06 -070013517 EXPECT_EQ(connection_.GetStats().num_client_probing_attempts, 1);
13518 EXPECT_EQ(connection_.GetStats().num_stateless_resets_on_alternate_path, 1);
renjietang4ca6b842023-06-05 08:00:57 -070013519}
13520
renjietangc60dcb72023-06-06 13:00:51 -070013521// Test that if the client's active migration is disabled, multi-port will not
13522// be attempted.
13523TEST_P(QuicConnectionTest, MultiPortPathRespectsActiveMigrationConfig) {
danzh7c0ef5f2023-06-08 12:10:35 -070013524 if (!version().HasIetfQuicFrames()) {
13525 return;
13526 }
renjietangc60dcb72023-06-06 13:00:51 -070013527 set_perspective(Perspective::IS_CLIENT);
13528 QuicConfig config;
13529 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
13530 kTestStatelessResetToken);
13531 QuicConfigPeer::SetReceivedDisableConnectionMigration(&config);
13532 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13533 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13534 connection_.SetFromConfig(config);
renjietangc60dcb72023-06-06 13:00:51 -070013535 connection_.CreateConnectionIdManager();
13536 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13537 connection_.OnHandshakeComplete();
13538
13539 EXPECT_CALL(visitor_, OnPathDegrading());
13540 connection_.OnPathDegradingDetected();
13541
13542 QuicNewConnectionIdFrame frame;
13543 frame.connection_id = TestConnectionId(1234);
13544 ASSERT_NE(frame.connection_id, connection_.connection_id());
13545 frame.stateless_reset_token =
13546 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13547 frame.retire_prior_to = 0u;
13548 frame.sequence_number = 1u;
13549 EXPECT_CALL(visitor_, CreateContextForMultiPortPath).Times(0);
13550 connection_.OnNewConnectionIdFrame(frame);
13551 EXPECT_FALSE(connection_.HasPendingPathValidation());
13552}
13553
renjietang5ba0e1b2023-03-14 13:08:03 -070013554// Verify that when multi-port is enabled and path degrading is triggered, if
13555// the alt-path is not ready, nothing happens.
13556TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsNotReady) {
13557 set_perspective(Perspective::IS_CLIENT);
13558 QuicConfig config;
renjietang5ba0e1b2023-03-14 13:08:03 -070013559 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13560 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13561 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013562 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070013563 return;
13564 }
13565 connection_.CreateConnectionIdManager();
13566 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13567 connection_.OnHandshakeComplete();
13568
13569 auto self_address = connection_.self_address();
13570 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13571 self_address.port() + 1);
13572 EXPECT_NE(kNewSelfAddress, self_address);
13573 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13574
13575 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13576 .WillRepeatedly(Return(true));
13577
13578 QuicNewConnectionIdFrame frame;
13579 frame.connection_id = TestConnectionId(1234);
13580 ASSERT_NE(frame.connection_id, connection_.connection_id());
13581 frame.stateless_reset_token =
13582 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13583 frame.retire_prior_to = 0u;
13584 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013585 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013586 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13587 observer->OnMultiPortPathContextAvailable(
13588 std::move(std::make_unique<TestQuicPathValidationContext>(
13589 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013590 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070013591 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13592 EXPECT_TRUE(connection_.HasPendingPathValidation());
13593 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13594 &connection_, kNewSelfAddress, connection_.peer_address()));
13595 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13596 EXPECT_FALSE(alt_path->validated);
13597
13598 // The alt path is not ready, path degrading doesn't do anything.
13599 EXPECT_CALL(visitor_, OnPathDegrading());
13600 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_)).Times(0);
13601 connection_.OnPathDegradingDetected();
13602
13603 // 30ms RTT.
13604 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13605 // Fake a response delay.
13606 clock_.AdvanceTime(kTestRTT);
13607
13608 // Even if the alt path is validated after path degrading, nothing should
13609 // happen.
13610 QuicFrames frames;
13611 frames.push_back(QuicFrame(QuicPathResponseFrame(
13612 99, new_writer.path_challenge_frames().back().data_buffer)));
13613 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13614 ENCRYPTION_FORWARD_SECURE);
13615 // No migration should happen and the alternative path should still be alive.
13616 EXPECT_FALSE(connection_.HasPendingPathValidation());
13617 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13618 &connection_, kNewSelfAddress, connection_.peer_address()));
13619 EXPECT_TRUE(alt_path->validated);
13620}
13621
13622// Verify that when multi-port is enabled and path degrading is triggered, if
13623// the alt-path is ready and not probing, it should be migrated.
13624TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndNotProbing) {
13625 EXPECT_CALL(visitor_, GetHandshakeState())
13626 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13627 set_perspective(Perspective::IS_CLIENT);
13628 QuicConfig config;
renjietang546e3962023-09-01 10:51:19 -070013629 config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
renjietang5ba0e1b2023-03-14 13:08:03 -070013630 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13631 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013632 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070013633 return;
13634 }
13635 connection_.CreateConnectionIdManager();
13636 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13637 connection_.OnHandshakeComplete();
13638
13639 auto self_address = connection_.self_address();
13640 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13641 self_address.port() + 1);
13642 EXPECT_NE(kNewSelfAddress, self_address);
13643 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13644
13645 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13646 .WillRepeatedly(Return(true));
13647
13648 QuicNewConnectionIdFrame frame;
13649 frame.connection_id = TestConnectionId(1234);
13650 ASSERT_NE(frame.connection_id, connection_.connection_id());
13651 frame.stateless_reset_token =
13652 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13653 frame.retire_prior_to = 0u;
13654 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013655 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013656 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13657 observer->OnMultiPortPathContextAvailable(
13658 std::move(std::make_unique<TestQuicPathValidationContext>(
13659 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013660 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070013661 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13662 EXPECT_TRUE(connection_.HasPendingPathValidation());
13663 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13664 &connection_, kNewSelfAddress, connection_.peer_address()));
13665 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13666 EXPECT_FALSE(alt_path->validated);
13667
13668 // 30ms RTT.
13669 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13670 // Fake a response delay.
13671 clock_.AdvanceTime(kTestRTT);
13672
13673 // Even if the alt path is validated after path degrading, nothing should
13674 // happen.
13675 QuicFrames frames;
13676 frames.push_back(QuicFrame(QuicPathResponseFrame(
13677 99, new_writer.path_challenge_frames().back().data_buffer)));
13678 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13679 ENCRYPTION_FORWARD_SECURE);
13680 // No migration should happen and the alternative path should still be alive.
13681 EXPECT_FALSE(connection_.HasPendingPathValidation());
13682 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13683 &connection_, kNewSelfAddress, connection_.peer_address()));
13684 EXPECT_TRUE(alt_path->validated);
13685
13686 // Trigger path degrading and the connection should attempt to migrate.
13687 EXPECT_CALL(visitor_, OnPathDegrading());
13688 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0);
13689 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_))
13690 .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) {
13691 EXPECT_EQ(context->self_address(), kNewSelfAddress);
13692 connection_.MigratePath(context->self_address(),
13693 context->peer_address(), context->WriterToUse(),
13694 /*owns_writer=*/false);
13695 }));
13696 connection_.OnPathDegradingDetected();
13697}
13698
13699// Verify that when multi-port is enabled and path degrading is triggered, if
13700// the alt-path is probing, the probing should be cancelled and the path should
13701// be migrated.
13702TEST_P(QuicConnectionTest, PathDegradingWhenAltPathIsReadyAndProbing) {
13703 EXPECT_CALL(visitor_, GetHandshakeState())
13704 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
13705 set_perspective(Perspective::IS_CLIENT);
13706 QuicConfig config;
renjietang546e3962023-09-01 10:51:19 -070013707 config.SetClientConnectionOptions(QuicTagVector{kMPQC, kMPQM});
renjietang5ba0e1b2023-03-14 13:08:03 -070013708 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13709 connection_.SetFromConfig(config);
danzh7c0ef5f2023-06-08 12:10:35 -070013710 if (!version().HasIetfQuicFrames()) {
renjietang5ba0e1b2023-03-14 13:08:03 -070013711 return;
13712 }
13713 connection_.CreateConnectionIdManager();
13714 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13715 connection_.OnHandshakeComplete();
13716
13717 auto self_address = connection_.self_address();
13718 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13719 self_address.port() + 1);
13720 EXPECT_NE(kNewSelfAddress, self_address);
13721 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13722
13723 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13724 .WillRepeatedly(Return(true));
13725
13726 QuicNewConnectionIdFrame frame;
13727 frame.connection_id = TestConnectionId(1234);
13728 ASSERT_NE(frame.connection_id, connection_.connection_id());
13729 frame.stateless_reset_token =
13730 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13731 frame.retire_prior_to = 0u;
13732 frame.sequence_number = 1u;
QUICHE team107316f2023-05-03 09:04:11 -070013733 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070013734 .WillRepeatedly(testing::WithArgs<0>([&](auto&& observer) {
13735 observer->OnMultiPortPathContextAvailable(
13736 std::move(std::make_unique<TestQuicPathValidationContext>(
13737 kNewSelfAddress, connection_.peer_address(), &new_writer)));
QUICHE team107316f2023-05-03 09:04:11 -070013738 }));
renjietang5ba0e1b2023-03-14 13:08:03 -070013739 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13740 EXPECT_TRUE(connection_.HasPendingPathValidation());
13741 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13742 &connection_, kNewSelfAddress, connection_.peer_address()));
13743 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13744 EXPECT_FALSE(alt_path->validated);
13745
13746 // 30ms RTT.
13747 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13748 // Fake a response delay.
13749 clock_.AdvanceTime(kTestRTT);
13750
13751 // Even if the alt path is validated after path degrading, nothing should
13752 // happen.
13753 QuicFrames frames;
13754 frames.push_back(QuicFrame(QuicPathResponseFrame(
13755 99, new_writer.path_challenge_frames().back().data_buffer)));
13756 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13757 ENCRYPTION_FORWARD_SECURE);
13758 // No migration should happen and the alternative path should still be alive.
13759 EXPECT_FALSE(connection_.HasPendingPathValidation());
13760 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13761 &connection_, kNewSelfAddress, connection_.peer_address()));
13762 EXPECT_TRUE(alt_path->validated);
13763
13764 random_generator_.ChangeValue();
13765 connection_.GetMultiPortProbingAlarm()->Fire();
13766 EXPECT_TRUE(connection_.HasPendingPathValidation());
13767 EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13768
13769 // Trigger path degrading and the connection should attempt to migrate.
13770 EXPECT_CALL(visitor_, OnPathDegrading());
13771 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(0);
13772 EXPECT_CALL(visitor_, MigrateToMultiPortPath(_))
13773 .WillOnce(Invoke([&](std::unique_ptr<QuicPathValidationContext> context) {
13774 EXPECT_EQ(context->self_address(), kNewSelfAddress);
13775 connection_.MigratePath(context->self_address(),
13776 context->peer_address(), context->WriterToUse(),
13777 /*owns_writer=*/false);
13778 }));
13779 connection_.OnPathDegradingDetected();
13780 EXPECT_FALSE(connection_.HasPendingPathValidation());
13781 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
13782 EXPECT_FALSE(QuicPathValidatorPeer::retry_timer(path_validator)->IsSet());
13783}
13784
Bence Békybac04052022-04-07 15:44:29 -040013785TEST_P(QuicConnectionTest, SingleAckInPacket) {
13786 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13787 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13788 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13789 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13790 connection_.NeuterUnencryptedPackets();
13791 connection_.OnHandshakeComplete();
13792 EXPECT_CALL(visitor_, GetHandshakeState())
13793 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13794
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070013795 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040013796 connection_.SendStreamData3();
13797 connection_.CloseConnection(
13798 QUIC_INTERNAL_ERROR, "error",
13799 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
13800 }));
13801 QuicFrames frames;
13802 frames.push_back(QuicFrame(frame1_));
13803 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
13804 ENCRYPTION_FORWARD_SECURE);
13805 ASSERT_FALSE(writer_->ack_frames().empty());
13806 EXPECT_EQ(1u, writer_->ack_frames().size());
13807}
13808
13809TEST_P(QuicConnectionTest,
13810 ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey) {
13811 if (!connection_.version().UsesTls()) {
13812 return;
13813 }
13814
13815 set_perspective(Perspective::IS_SERVER);
13816 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080013817 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040013818
13819 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13820 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13821
13822 // Finish handshake.
13823 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13824 notifier_.NeuterUnencryptedData();
13825 connection_.NeuterUnencryptedPackets();
13826 connection_.OnHandshakeComplete();
13827 EXPECT_CALL(visitor_, GetHandshakeState())
13828 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13829
13830 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13831 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13832 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13833
13834 // 0-RTT packet received out of order should be decoded since the decrypter
13835 // is temporarily retained.
13836 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13837 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13838 EXPECT_EQ(
13839 0u,
13840 connection_.GetStats()
13841 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13842
13843 // Simulate the timeout for discarding 0-RTT keys passing.
13844 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
13845
13846 // Another 0-RTT packet received now should not be decoded.
13847 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13848 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
13849 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13850 EXPECT_EQ(
13851 1u,
13852 connection_.GetStats()
13853 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13854
13855 // The |discard_zero_rtt_decryption_keys_alarm_| should only be set on the
13856 // first 1-RTT packet received.
13857 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13858 ProcessDataPacketAtLevel(5, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13859 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13860}
13861
13862TEST_P(QuicConnectionTest, NewTokenFrameInstigateAcks) {
13863 if (!version().HasIetfQuicFrames()) {
13864 return;
13865 }
13866 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13867
13868 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13869 EXPECT_CALL(visitor_, OnNewTokenReceived(_));
13870 ProcessFramePacket(QuicFrame(new_token));
13871
13872 // Ensure that this has caused the ACK alarm to be set.
13873 EXPECT_TRUE(connection_.HasPendingAcks());
13874}
13875
13876TEST_P(QuicConnectionTest, ServerClosesConnectionOnNewTokenFrame) {
13877 if (!version().HasIetfQuicFrames()) {
13878 return;
13879 }
13880 set_perspective(Perspective::IS_SERVER);
13881 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13882 EXPECT_CALL(visitor_, OnNewTokenReceived(_)).Times(0);
13883 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13884 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13885 ProcessFramePacket(QuicFrame(new_token));
13886 EXPECT_FALSE(connection_.connected());
13887}
13888
13889TEST_P(QuicConnectionTest, OverrideRetryTokenWithRetryPacket) {
13890 if (!version().HasIetfQuicFrames()) {
13891 return;
13892 }
13893 std::string address_token = "TestAddressToken";
13894 connection_.SetSourceAddressTokenToSend(address_token);
13895 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13896 QuicConnectionPeer::GetPacketCreator(&connection_)),
13897 address_token);
13898 // Passes valid retry and verify token gets overridden.
13899 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13900 /*missing_original_id_in_config=*/false,
13901 /*wrong_original_id_in_config=*/false,
13902 /*missing_retry_id_in_config=*/false,
13903 /*wrong_retry_id_in_config=*/false);
13904}
13905
13906TEST_P(QuicConnectionTest, DonotOverrideRetryTokenWithAddressToken) {
13907 if (!version().HasIetfQuicFrames()) {
13908 return;
13909 }
13910 // Passes valid retry and verify token gets overridden.
13911 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13912 /*missing_original_id_in_config=*/false,
13913 /*wrong_original_id_in_config=*/false,
13914 /*missing_retry_id_in_config=*/false,
13915 /*wrong_retry_id_in_config=*/false);
13916 std::string retry_token = QuicPacketCreatorPeer::GetRetryToken(
13917 QuicConnectionPeer::GetPacketCreator(&connection_));
13918
13919 std::string address_token = "TestAddressToken";
13920 connection_.SetSourceAddressTokenToSend(address_token);
13921 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13922 QuicConnectionPeer::GetPacketCreator(&connection_)),
13923 retry_token);
13924}
13925
13926TEST_P(QuicConnectionTest,
13927 ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt) {
13928 if (!connection_.version().UsesTls()) {
13929 return;
13930 }
13931
13932 // The code that checks for this error piggybacks on some book-keeping state
13933 // kept for key update, so enable key update for the test.
13934 std::string error_details;
13935 TransportParameters params;
13936 QuicConfig config;
13937 EXPECT_THAT(config.ProcessTransportParameters(
13938 params, /* is_resumption = */ false, &error_details),
13939 IsQuicNoError());
13940 QuicConfigPeer::SetNegotiated(&config, true);
13941 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
13942 connection_.connection_id());
13943 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
13944 &config, connection_.connection_id());
13945 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13946 connection_.SetFromConfig(config);
13947
13948 set_perspective(Perspective::IS_SERVER);
13949 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080013950 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040013951
13952 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13953 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13954
13955 // Finish handshake.
13956 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13957 notifier_.NeuterUnencryptedData();
13958 connection_.NeuterUnencryptedPackets();
13959 connection_.OnHandshakeComplete();
13960 EXPECT_CALL(visitor_, GetHandshakeState())
13961 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13962
13963 // Decrypt a 1-RTT packet.
13964 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13965 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13966 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13967
13968 // 0-RTT packet with higher packet number than a 1-RTT packet is invalid and
13969 // should cause the connection to be closed.
13970 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13971 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13972 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13973 EXPECT_FALSE(connection_.connected());
13974 TestConnectionCloseQuicErrorCode(
13975 QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
13976}
13977
13978// Regression test for b/177312785
13979TEST_P(QuicConnectionTest, PeerMigrateBeforeHandshakeConfirm) {
13980 if (!VersionHasIetfQuicFrames(version().transport_version)) {
13981 return;
13982 }
13983 set_perspective(Perspective::IS_SERVER);
13984 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
13985 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
13986 EXPECT_CALL(visitor_, GetHandshakeState())
13987 .WillRepeatedly(Return(HANDSHAKE_START));
13988
13989 // Clear direct_peer_address.
13990 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
13991 // Clear effective_peer_address, it is the same as direct_peer_address for
13992 // this test.
13993 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
13994 QuicSocketAddress());
13995 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
13996
13997 const QuicSocketAddress kNewPeerAddress =
13998 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
13999 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
14000 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
14001 ENCRYPTION_INITIAL);
14002 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14003 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14004
14005 // Process another packet with a different peer address on server side will
14006 // close connection.
14007 QuicAckFrame frame = InitAckFrame(1);
14008 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14009 EXPECT_CALL(visitor_,
14010 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
14011 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
14012
martindukeba002452023-03-21 08:10:46 -070014013 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
14014 .Times(0);
Bence Békybac04052022-04-07 15:44:29 -040014015 ProcessFramePacketWithAddresses(QuicFrame(&frame), kSelfAddress,
14016 kNewPeerAddress, ENCRYPTION_INITIAL);
14017 EXPECT_FALSE(connection_.connected());
14018}
14019
14020// Regresstion test for b/175685916
14021TEST_P(QuicConnectionTest, TryToFlushAckWithAckQueued) {
14022 if (!version().HasIetfQuicFrames()) {
14023 return;
14024 }
14025 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
14026 set_perspective(Perspective::IS_SERVER);
14027
14028 QuicConfig config;
14029 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
14030 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14031 connection_.SetFromConfig(config);
14032 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14033 connection_.OnHandshakeComplete();
14034 QuicPacketCreatorPeer::SetPacketNumber(creator_, 200);
14035
14036 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
14037 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14038 // Sending ACK_FREQUENCY bundles ACK. QuicConnectionPeer::SendPing
14039 // will try to bundle ACK but there is no pending ACK.
14040 EXPECT_CALL(visitor_, SendAckFrequency(_))
14041 .WillOnce(Invoke(&notifier_,
14042 &SimpleSessionNotifier::WriteOrBufferAckFrequency));
14043 QuicConnectionPeer::SendPing(&connection_);
14044}
14045
14046TEST_P(QuicConnectionTest, PathChallengeBeforePeerIpAddressChangeAtServer) {
14047 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070014048 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014049 return;
14050 }
14051 PathProbeTestInit(Perspective::IS_SERVER);
14052 SetClientConnectionId(TestConnectionId(1));
14053 connection_.CreateConnectionIdManager();
14054
14055 QuicConnectionId server_cid0 = connection_.connection_id();
14056 QuicConnectionId client_cid0 = connection_.client_connection_id();
14057 QuicConnectionId client_cid1 = TestConnectionId(2);
14058 QuicConnectionId server_cid1;
14059 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014060 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014061 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14062 .WillOnce(Return(TestConnectionId(456)));
14063 }
haoyuewangada6b822022-06-23 13:41:18 -070014064 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14065 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14066 server_cid1 = cid;
14067 return true;
14068 }));
Bence Békybac04052022-04-07 15:44:29 -040014069 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14070 connection_.MaybeSendConnectionIdToClient();
14071 // Receives new client CID from client.
14072 QuicNewConnectionIdFrame new_cid_frame;
14073 new_cid_frame.connection_id = client_cid1;
14074 new_cid_frame.sequence_number = 1u;
14075 new_cid_frame.retire_prior_to = 0u;
14076 connection_.OnNewConnectionIdFrame(new_cid_frame);
14077 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14078 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14079 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14080
14081 peer_creator_.SetServerConnectionId(server_cid1);
14082 const QuicSocketAddress kNewPeerAddress =
14083 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
14084 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14085 QuicFrames frames1;
14086 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014087 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014088 QuicPathFrameBuffer payload;
14089 EXPECT_CALL(*send_algorithm_,
14090 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14091 .Times(AtLeast(1))
14092 .WillOnce(Invoke([&]() {
14093 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14094 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14095 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14096 EXPECT_FALSE(writer_->path_response_frames().empty());
14097 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14098 payload = writer_->path_challenge_frames().front().data_buffer;
awillia202240c2024-07-08 09:47:00 -070014099 }))
14100 .WillRepeatedly(DoDefault());
14101 ;
Bence Békybac04052022-04-07 15:44:29 -040014102 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14103 ENCRYPTION_FORWARD_SECURE);
14104 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14105 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14106 EXPECT_TRUE(connection_.HasPendingPathValidation());
14107 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14108 const auto* alternative_path =
14109 QuicConnectionPeer::GetAlternativePath(&connection_);
14110 EXPECT_EQ(default_path->client_connection_id, client_cid0);
14111 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14112 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14113 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14114 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14115 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14116
14117 // Process another packet with a different peer address on server side will
14118 // start connection migration.
14119 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014120 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040014121 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14122 }));
14123 // IETF QUIC send algorithm should be changed to a different object, so no
14124 // OnPacketSent() called on the old send algorithm.
14125 EXPECT_CALL(*send_algorithm_,
14126 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14127 .Times(0);
14128 QuicFrames frames2;
14129 frames2.push_back(QuicFrame(frame2_));
14130 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14131 ENCRYPTION_FORWARD_SECURE);
14132 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14133 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14134 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
14135 connection_.active_effective_peer_migration_type());
14136 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14137 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
14138 send_algorithm_);
14139 // Switch to use the mock send algorithm.
14140 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14141 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14142 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14143 .WillRepeatedly(Return(kDefaultTCPMSS));
14144 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14145 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14146 .Times(AnyNumber())
14147 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14148 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14149 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14150 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14151 connection_.SetSendAlgorithm(send_algorithm_);
14152 EXPECT_EQ(default_path->client_connection_id, client_cid1);
14153 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14154 // The previous default path is kept as alternative path before reverse path
14155 // validation finishes.
14156 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
14157 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
14158 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
14159 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
14160
14161 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14162 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14163 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
14164 connection_.active_effective_peer_migration_type());
14165 EXPECT_EQ(1u, connection_.GetStats()
14166 .num_peer_migration_to_proactively_validated_address);
14167
14168 // The PATH_CHALLENGE and PATH_RESPONSE is expanded upto the max packet size
14169 // which may exceeds the anti-amplification limit. Verify server is throttled
14170 // by anti-amplification limit.
14171 connection_.SendCryptoDataWithString("foo", 0);
14172 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
14173
14174 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
14175 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070014176 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040014177 EXPECT_CALL(visitor_, MaybeSendAddressToken());
14178 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14179 .Times(testing::AtLeast(1u));
14180 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
14181 ENCRYPTION_FORWARD_SECURE);
14182 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
14183 // Verify that alternative_path_ is cleared and the peer CID is retired.
14184 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14185 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14186 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14187 auto* retire_peer_issued_cid_alarm =
14188 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14189 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14190 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14191 retire_peer_issued_cid_alarm->Fire();
14192
14193 // Verify the anti-amplification limit is lifted by sending a packet larger
14194 // than the anti-amplification limit.
14195 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
14196 EXPECT_CALL(*send_algorithm_, PacingRate(_))
14197 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14198 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
14199 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -070014200 EXPECT_EQ(1u, connection_.num_unlinkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -040014201}
14202
14203TEST_P(QuicConnectionTest,
14204 PathValidationSucceedsBeforePeerIpAddressChangeAtServer) {
14205 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070014206 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014207 return;
14208 }
14209 PathProbeTestInit(Perspective::IS_SERVER);
14210 connection_.CreateConnectionIdManager();
14211
14212 QuicConnectionId server_cid0 = connection_.connection_id();
14213 QuicConnectionId server_cid1;
14214 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014215 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014216 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14217 .WillOnce(Return(TestConnectionId(456)));
14218 }
haoyuewangada6b822022-06-23 13:41:18 -070014219 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14220 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14221 server_cid1 = cid;
14222 return true;
14223 }));
Bence Békybac04052022-04-07 15:44:29 -040014224 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14225 connection_.MaybeSendConnectionIdToClient();
14226 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14227 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14228
14229 // Receive probing packet with new peer address.
14230 peer_creator_.SetServerConnectionId(server_cid1);
14231 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14232 /*port=*/23456);
14233 QuicPathFrameBuffer payload;
14234 EXPECT_CALL(*send_algorithm_,
14235 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14236 .WillOnce(Invoke([&]() {
14237 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14238 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14239 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14240 EXPECT_FALSE(writer_->path_response_frames().empty());
14241 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14242 payload = writer_->path_challenge_frames().front().data_buffer;
14243 }))
14244 .WillRepeatedly(Invoke([&]() {
14245 // Only start reverse path validation once.
14246 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14247 }));
14248 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14249 QuicFrames frames1;
14250 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014251 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014252 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14253 ENCRYPTION_FORWARD_SECURE);
14254 EXPECT_TRUE(connection_.HasPendingPathValidation());
14255 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14256 const auto* alternative_path =
14257 QuicConnectionPeer::GetAlternativePath(&connection_);
14258 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14259 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14260 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14261
14262 // Receive PATH_RESPONSE should mark the new peer address validated.
14263 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070014264 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040014265 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
14266 ENCRYPTION_FORWARD_SECURE);
14267
14268 // Process another packet with a newer peer address with the same port will
14269 // start connection migration.
14270 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14271 // IETF QUIC send algorithm should be changed to a different object, so no
14272 // OnPacketSent() called on the old send algorithm.
14273 EXPECT_CALL(*send_algorithm_,
14274 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14275 .Times(0);
14276 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14277 /*port=*/34567);
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014278 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040014279 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
14280 }));
14281 EXPECT_CALL(visitor_, MaybeSendAddressToken());
14282 QuicFrames frames2;
14283 frames2.push_back(QuicFrame(frame2_));
14284 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewerPeerAddress,
14285 ENCRYPTION_FORWARD_SECURE);
14286 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
14287 EXPECT_EQ(kNewerPeerAddress, connection_.effective_peer_address());
14288 // Since the newer address has the same IP as the previously validated probing
14289 // address. The peer migration becomes validated immediately.
14290 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
14291 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14292 EXPECT_EQ(1u, connection_.GetStats()
14293 .num_peer_migration_to_proactively_validated_address);
14294 EXPECT_FALSE(connection_.HasPendingPathValidation());
14295 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
14296 send_algorithm_);
14297
14298 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14299 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
14300 // Verify that alternative_path_ is cleared.
14301 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14302 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14303
14304 // Switch to use the mock send algorithm.
14305 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14306 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14307 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14308 .WillRepeatedly(Return(kDefaultTCPMSS));
14309 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14310 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14311 .Times(AnyNumber())
14312 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14313 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14314 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14315 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14316 connection_.SetSendAlgorithm(send_algorithm_);
14317
14318 // Verify the server is not throttled by the anti-amplification limit by
14319 // sending a packet larger than the anti-amplification limit.
14320 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
14321 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
14322 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
14323}
14324
danzhb37451f2022-04-19 08:18:54 -070014325// Regression test of b/228645208.
14326TEST_P(QuicConnectionTest, NoNonProbingFrameOnAlternativePath) {
danzh7c0ef5f2023-06-08 12:10:35 -070014327 if (!version().HasIetfQuicFrames()) {
danzhb37451f2022-04-19 08:18:54 -070014328 return;
14329 }
14330
14331 PathProbeTestInit(Perspective::IS_SERVER);
14332 SetClientConnectionId(TestConnectionId(1));
14333 connection_.CreateConnectionIdManager();
14334
14335 QuicConnectionId server_cid0 = connection_.connection_id();
14336 QuicConnectionId client_cid0 = connection_.client_connection_id();
14337 QuicConnectionId client_cid1 = TestConnectionId(2);
14338 QuicConnectionId server_cid1;
14339 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014340 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014341 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14342 .WillOnce(Return(TestConnectionId(456)));
14343 }
haoyuewangada6b822022-06-23 13:41:18 -070014344 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14345 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
14346 server_cid1 = cid;
14347 return true;
14348 }));
danzhb37451f2022-04-19 08:18:54 -070014349 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14350 connection_.MaybeSendConnectionIdToClient();
14351 // Receives new client CID from client.
14352 QuicNewConnectionIdFrame new_cid_frame;
14353 new_cid_frame.connection_id = client_cid1;
14354 new_cid_frame.sequence_number = 1u;
14355 new_cid_frame.retire_prior_to = 0u;
14356 connection_.OnNewConnectionIdFrame(new_cid_frame);
14357 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14358 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14359 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14360
14361 peer_creator_.SetServerConnectionId(server_cid1);
14362 const QuicSocketAddress kNewPeerAddress =
14363 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
14364 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14365 QuicFrames frames1;
14366 frames1.push_back(
14367 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
danzhb37451f2022-04-19 08:18:54 -070014368 EXPECT_CALL(*send_algorithm_,
14369 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14370 .Times(AtLeast(1))
14371 .WillOnce(Invoke([&]() {
14372 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14373 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14374 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14375 EXPECT_FALSE(writer_->path_response_frames().empty());
14376 EXPECT_FALSE(writer_->path_challenge_frames().empty());
awillia202240c2024-07-08 09:47:00 -070014377 }))
14378 .WillRepeatedly(DoDefault());
danzhb37451f2022-04-19 08:18:54 -070014379 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14380 ENCRYPTION_FORWARD_SECURE);
14381 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14382 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14383 EXPECT_TRUE(connection_.HasPendingPathValidation());
14384 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14385 const auto* alternative_path =
14386 QuicConnectionPeer::GetAlternativePath(&connection_);
14387 EXPECT_EQ(default_path->client_connection_id, client_cid0);
14388 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14389 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14390 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14391 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14392 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14393
14394 // Process non-probing packets on the default path.
14395 peer_creator_.SetServerConnectionId(server_cid0);
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014396 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillRepeatedly(Invoke([=, this]() {
danzhb37451f2022-04-19 08:18:54 -070014397 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14398 }));
14399 // Receives packets 3 - 39 to send 19 ACK-only packets, which will force the
14400 // connection to reach |kMaxConsecutiveNonRetransmittablePackets| while
14401 // sending the next ACK.
14402 for (size_t i = 3; i <= 39; ++i) {
14403 ProcessDataPacket(i);
14404 }
14405 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14406 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14407
14408 EXPECT_TRUE(connection_.HasPendingAcks());
14409 QuicTime ack_time = connection_.GetAckAlarm()->deadline();
14410 QuicTime path_validation_retry_time =
14411 connection_.GetRetryTimeout(kNewPeerAddress, writer_.get());
14412 // Advance time to simultaneously fire path validation retry and ACK alarms.
14413 clock_.AdvanceTime(std::max(ack_time, path_validation_retry_time) -
14414 clock_.ApproximateNow());
14415
14416 // The 20th ACK should bundle with a WINDOW_UPDATE frame.
14417 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
14418 .WillOnce(Invoke([this]() {
14419 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
14420 }));
martindukee6444ef2022-09-23 12:32:23 -070014421 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14422 .WillOnce(Invoke([&]() {
14423 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14424 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14425 // Retry path validation shouldn't bundle ACK.
14426 EXPECT_TRUE(writer_->ack_frames().empty());
14427 }))
14428 .WillOnce(Invoke([&]() {
14429 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
14430 EXPECT_FALSE(writer_->ack_frames().empty());
14431 EXPECT_FALSE(writer_->window_update_frames().empty());
14432 }));
14433 static_cast<TestAlarmFactory::TestAlarm*>(
14434 QuicPathValidatorPeer::retry_timer(
14435 QuicConnectionPeer::path_validator(&connection_)))
14436 ->Fire();
danzhb37451f2022-04-19 08:18:54 -070014437}
14438
haoyuewangada6b822022-06-23 13:41:18 -070014439TEST_P(QuicConnectionTest, DoNotIssueNewCidIfVisitorSaysNo) {
14440 set_perspective(Perspective::IS_SERVER);
danzh7c0ef5f2023-06-08 12:10:35 -070014441 if (!version().HasIetfQuicFrames()) {
haoyuewangada6b822022-06-23 13:41:18 -070014442 return;
14443 }
14444
14445 connection_.CreateConnectionIdManager();
14446
14447 QuicConnectionId server_cid0 = connection_.connection_id();
14448 QuicConnectionId client_cid1 = TestConnectionId(2);
14449 QuicConnectionId server_cid1;
14450 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014451 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014452 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14453 .WillOnce(Return(TestConnectionId(456)));
14454 }
haoyuewangada6b822022-06-23 13:41:18 -070014455 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(false));
haoyuewangc0d96f52023-06-08 11:24:28 -070014456 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(0);
haoyuewangada6b822022-06-23 13:41:18 -070014457 connection_.MaybeSendConnectionIdToClient();
14458}
14459
Bence Békybac04052022-04-07 15:44:29 -040014460TEST_P(QuicConnectionTest,
14461 ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer) {
14462 PathProbeTestInit(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -070014463 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014464 return;
14465 }
14466
14467 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14468 /*port=*/23456);
14469
14470 // Process a packet with a new peer address will start connection migration.
14471 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14472 // IETF QUIC send algorithm should be changed to a different object, so no
14473 // OnPacketSent() called on the old send algorithm.
14474 EXPECT_CALL(*send_algorithm_,
14475 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14476 .Times(0);
QUICHE teamf8ca4ff2024-07-17 12:06:18 -070014477 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=, this]() {
Bence Békybac04052022-04-07 15:44:29 -040014478 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14479 }));
14480 QuicFrames frames2;
14481 frames2.push_back(QuicFrame(frame2_));
14482 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14483 ENCRYPTION_FORWARD_SECURE);
14484 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14485 EXPECT_TRUE(connection_.HasPendingPathValidation());
14486
14487 // Switch to use the mock send algorithm.
14488 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14489 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14490 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14491 .WillRepeatedly(Return(kDefaultTCPMSS));
14492 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14493 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14494 .Times(AnyNumber())
14495 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14496 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14497 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14498 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14499 connection_.SetSendAlgorithm(send_algorithm_);
14500
14501 // Receive probing packet with a newer peer address shouldn't override the
14502 // on-going path validation.
14503 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14504 /*port=*/34567);
14505 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14506 .WillOnce(Invoke([&]() {
14507 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14508 EXPECT_FALSE(writer_->path_response_frames().empty());
14509 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14510 }));
14511 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14512 QuicFrames frames1;
14513 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014514 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014515 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewerPeerAddress,
14516 ENCRYPTION_FORWARD_SECURE);
14517 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14518 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14519 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14520 EXPECT_TRUE(connection_.HasPendingPathValidation());
14521}
14522
14523TEST_P(QuicConnectionTest,
14524 PathValidationFailedOnClientDueToLackOfServerConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070014525 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014526 return;
14527 }
14528 PathProbeTestInit(Perspective::IS_CLIENT,
14529 /*receive_new_server_connection_id=*/false);
14530
14531 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14532 /*port=*/34567);
14533
14534 bool success;
14535 connection_.ValidatePath(
14536 std::make_unique<TestQuicPathValidationContext>(
14537 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14538 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014539 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
14540 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014541
14542 EXPECT_FALSE(success);
14543}
14544
14545TEST_P(QuicConnectionTest,
14546 PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime) {
danzh7c0ef5f2023-06-08 12:10:35 -070014547 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014548 return;
14549 }
14550 PathProbeTestInit(Perspective::IS_CLIENT,
14551 /*receive_new_server_connection_id=*/false);
14552 SetClientConnectionId(TestConnectionId(1));
14553
14554 // Make sure server connection ID is available for the 1st validation.
14555 QuicConnectionId server_cid0 = connection_.connection_id();
14556 QuicConnectionId server_cid1 = TestConnectionId(2);
14557 QuicConnectionId server_cid2 = TestConnectionId(4);
14558 QuicConnectionId client_cid1;
14559 QuicNewConnectionIdFrame frame1;
14560 frame1.connection_id = server_cid1;
14561 frame1.sequence_number = 1u;
14562 frame1.retire_prior_to = 0u;
14563 frame1.stateless_reset_token =
14564 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14565 connection_.OnNewConnectionIdFrame(frame1);
14566 const auto* packet_creator =
14567 QuicConnectionPeer::GetPacketCreator(&connection_);
14568 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid0);
14569
14570 // Client will issue a new client connection ID to server.
martinduke08e3ff82022-10-18 09:06:26 -070014571 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14572 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014573 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14574 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14575 client_cid1 = frame.connection_id;
14576 }));
14577
14578 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14579 ASSERT_NE(kSelfAddress1, connection_.self_address());
14580 bool success1;
14581 connection_.ValidatePath(
14582 std::make_unique<TestQuicPathValidationContext>(
14583 kSelfAddress1, connection_.peer_address(), writer_.get()),
14584 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014585 &connection_, kSelfAddress1, connection_.peer_address(), &success1),
14586 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014587
14588 // Migrate upon 1st validation success.
14589 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14590 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14591 &new_writer, /*owns_writer=*/false));
14592 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14593 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14594 EXPECT_EQ(default_path->client_connection_id, client_cid1);
14595 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14596 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14597 const auto* alternative_path =
14598 QuicConnectionPeer::GetAlternativePath(&connection_);
14599 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14600 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14601 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14602 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid1);
14603
14604 // Client will retire server connection ID on old default_path.
14605 auto* retire_peer_issued_cid_alarm =
14606 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14607 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14608 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14609 retire_peer_issued_cid_alarm->Fire();
14610
14611 // Another server connection ID is available to client.
14612 QuicNewConnectionIdFrame frame2;
14613 frame2.connection_id = server_cid2;
14614 frame2.sequence_number = 2u;
14615 frame2.retire_prior_to = 1u;
14616 frame2.stateless_reset_token =
14617 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14618 connection_.OnNewConnectionIdFrame(frame2);
14619
14620 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14621 /*port=*/45678);
14622 bool success2;
14623 connection_.ValidatePath(
14624 std::make_unique<TestQuicPathValidationContext>(
14625 kSelfAddress2, connection_.peer_address(), writer_.get()),
14626 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014627 &connection_, kSelfAddress2, connection_.peer_address(), &success2),
14628 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014629 // Since server does not retire any client connection ID yet, 2nd validation
14630 // would fail due to lack of client connection ID.
14631 EXPECT_FALSE(success2);
14632}
14633
14634TEST_P(QuicConnectionTest, ServerConnectionIdRetiredUponPathValidationFailure) {
danzh7c0ef5f2023-06-08 12:10:35 -070014635 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014636 return;
14637 }
14638 PathProbeTestInit(Perspective::IS_CLIENT);
14639
14640 // Make sure server connection ID is available for validation.
14641 QuicNewConnectionIdFrame frame;
14642 frame.connection_id = TestConnectionId(2);
14643 frame.sequence_number = 1u;
14644 frame.retire_prior_to = 0u;
14645 frame.stateless_reset_token =
14646 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14647 connection_.OnNewConnectionIdFrame(frame);
14648
14649 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14650 /*port=*/34567);
14651 bool success;
14652 connection_.ValidatePath(
14653 std::make_unique<TestQuicPathValidationContext>(
14654 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14655 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080014656 &connection_, kNewSelfAddress, connection_.peer_address(), &success),
14657 PathValidationReason::kReasonUnknown);
Bence Békybac04052022-04-07 15:44:29 -040014658
14659 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
14660 path_validator->CancelPathValidation();
14661 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14662 EXPECT_FALSE(success);
14663 const auto* alternative_path =
14664 QuicConnectionPeer::GetAlternativePath(&connection_);
14665 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14666 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14667 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14668
14669 // Client will retire server connection ID on alternative_path.
14670 auto* retire_peer_issued_cid_alarm =
14671 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14672 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14673 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
14674 retire_peer_issued_cid_alarm->Fire();
14675}
14676
14677TEST_P(QuicConnectionTest,
14678 MigratePathDirectlyFailedDueToLackOfServerConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070014679 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014680 return;
14681 }
14682 PathProbeTestInit(Perspective::IS_CLIENT,
14683 /*receive_new_server_connection_id=*/false);
14684 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14685 ASSERT_NE(kSelfAddress1, connection_.self_address());
14686
14687 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14688 ASSERT_FALSE(connection_.MigratePath(kSelfAddress1,
14689 connection_.peer_address(), &new_writer,
14690 /*owns_writer=*/false));
14691}
14692
14693TEST_P(QuicConnectionTest,
14694 MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime) {
danzh7c0ef5f2023-06-08 12:10:35 -070014695 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014696 return;
14697 }
14698 PathProbeTestInit(Perspective::IS_CLIENT,
14699 /*receive_new_server_connection_id=*/false);
14700 SetClientConnectionId(TestConnectionId(1));
14701
14702 // Make sure server connection ID is available for the 1st migration.
14703 QuicNewConnectionIdFrame frame1;
14704 frame1.connection_id = TestConnectionId(2);
14705 frame1.sequence_number = 1u;
14706 frame1.retire_prior_to = 0u;
14707 frame1.stateless_reset_token =
14708 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14709 connection_.OnNewConnectionIdFrame(frame1);
14710
14711 // Client will issue a new client connection ID to server.
14712 QuicConnectionId new_client_connection_id;
martinduke08e3ff82022-10-18 09:06:26 -070014713 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14714 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014715 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14716 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14717 new_client_connection_id = frame.connection_id;
14718 }));
14719
14720 // 1st migration is successful.
14721 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14722 ASSERT_NE(kSelfAddress1, connection_.self_address());
14723 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14724 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14725 &new_writer,
14726 /*owns_writer=*/false));
14727 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14728 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14729 EXPECT_EQ(default_path->client_connection_id, new_client_connection_id);
14730 EXPECT_EQ(default_path->server_connection_id, frame1.connection_id);
14731 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14732
14733 // Client will retire server connection ID on old default_path.
14734 auto* retire_peer_issued_cid_alarm =
14735 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14736 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14737 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14738 retire_peer_issued_cid_alarm->Fire();
14739
14740 // Another server connection ID is available to client.
14741 QuicNewConnectionIdFrame frame2;
14742 frame2.connection_id = TestConnectionId(4);
14743 frame2.sequence_number = 2u;
14744 frame2.retire_prior_to = 1u;
14745 frame2.stateless_reset_token =
14746 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14747 connection_.OnNewConnectionIdFrame(frame2);
14748
14749 // Since server does not retire any client connection ID yet, 2nd migration
14750 // would fail due to lack of client connection ID.
14751 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14752 /*port=*/45678);
14753 auto new_writer2 = std::make_unique<TestPacketWriter>(version(), &clock_,
14754 Perspective::IS_CLIENT);
14755 ASSERT_FALSE(connection_.MigratePath(
14756 kSelfAddress2, connection_.peer_address(), new_writer2.release(),
14757 /*owns_writer=*/true));
14758}
14759
14760TEST_P(QuicConnectionTest,
14761 CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID) {
14762 if (!version().HasIetfQuicFrames()) {
14763 return;
14764 }
14765 set_perspective(Perspective::IS_SERVER);
14766 ASSERT_TRUE(connection_.client_connection_id().IsEmpty());
14767
14768 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14769 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14770 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14771 QuicNewConnectionIdFrame frame;
14772 frame.sequence_number = 1u;
14773 frame.connection_id = TestConnectionId(1);
14774 frame.stateless_reset_token =
14775 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14776 frame.retire_prior_to = 0u;
14777
14778 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14779
14780 EXPECT_FALSE(connection_.connected());
14781 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14782 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14783}
14784
14785TEST_P(QuicConnectionTest, NewConnectionIdFrameResultsInError) {
14786 if (!version().HasIetfQuicFrames()) {
14787 return;
14788 }
14789 connection_.CreateConnectionIdManager();
14790 ASSERT_FALSE(connection_.connection_id().IsEmpty());
14791
14792 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14793 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14794 QuicNewConnectionIdFrame frame;
14795 frame.sequence_number = 1u;
14796 frame.connection_id = connection_id_; // Reuses connection ID casuing error.
14797 frame.stateless_reset_token =
14798 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14799 frame.retire_prior_to = 0u;
14800
14801 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14802
14803 EXPECT_FALSE(connection_.connected());
14804 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14805 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14806}
14807
14808TEST_P(QuicConnectionTest,
14809 ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14810 if (!version().HasIetfQuicFrames()) {
14811 return;
14812 }
14813 connection_.CreateConnectionIdManager();
14814
14815 QuicNewConnectionIdFrame frame;
14816 frame.sequence_number = 1u;
14817 frame.connection_id = TestConnectionId(1);
14818 frame.stateless_reset_token =
14819 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14820 frame.retire_prior_to = 0u;
14821
14822 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14823 auto* retire_peer_issued_cid_alarm =
14824 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14825 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14826
14827 frame.sequence_number = 2u;
14828 frame.connection_id = TestConnectionId(2);
14829 frame.stateless_reset_token =
14830 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14831 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14832
14833 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14834 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14835 EXPECT_EQ(connection_.connection_id(), connection_id_);
14836
14837 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14838 retire_peer_issued_cid_alarm->Fire();
14839 EXPECT_EQ(connection_.connection_id(), TestConnectionId(2));
14840 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14841 TestConnectionId(2));
14842}
14843
14844TEST_P(QuicConnectionTest,
14845 ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14846 if (!version().HasIetfQuicFrames()) {
14847 return;
14848 }
14849 set_perspective(Perspective::IS_SERVER);
14850 SetClientConnectionId(TestConnectionId(0));
14851
14852 QuicNewConnectionIdFrame frame;
14853 frame.sequence_number = 1u;
14854 frame.connection_id = TestConnectionId(1);
14855 frame.stateless_reset_token =
14856 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14857 frame.retire_prior_to = 0u;
14858
14859 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14860 auto* retire_peer_issued_cid_alarm =
14861 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14862 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14863
14864 frame.sequence_number = 2u;
14865 frame.connection_id = TestConnectionId(2);
14866 frame.stateless_reset_token =
14867 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14868 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14869
14870 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14871 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14872 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14873
14874 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14875 retire_peer_issued_cid_alarm->Fire();
14876 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14877 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14878 TestConnectionId(2));
14879}
14880
14881TEST_P(
14882 QuicConnectionTest,
14883 ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame) {
danzhaf2e52a2022-04-20 07:37:03 -070014884 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014885 return;
14886 }
14887 PathProbeTestInit(Perspective::IS_SERVER);
14888 SetClientConnectionId(TestConnectionId(0));
14889
14890 // Populate alternative_path_ with probing packet.
14891 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
14892
14893 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
14894 QuicEncryptedPacket(probing_packet->encrypted_buffer,
14895 probing_packet->encrypted_length),
14896 clock_.Now()));
14897 QuicIpAddress new_host;
14898 new_host.FromString("1.1.1.1");
14899 ProcessReceivedPacket(kSelfAddress,
14900 QuicSocketAddress(new_host, /*port=*/23456), *received);
14901
14902 EXPECT_EQ(
14903 TestConnectionId(0),
14904 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14905
14906 QuicNewConnectionIdFrame frame;
14907 frame.sequence_number = 1u;
14908 frame.connection_id = TestConnectionId(1);
14909 frame.stateless_reset_token =
14910 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14911 frame.retire_prior_to = 0u;
14912
14913 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14914 auto* retire_peer_issued_cid_alarm =
14915 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14916 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14917
14918 frame.sequence_number = 2u;
14919 frame.connection_id = TestConnectionId(2);
14920 frame.stateless_reset_token =
14921 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14922 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14923
14924 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14925 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14926 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14927
14928 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14929 retire_peer_issued_cid_alarm->Fire();
14930 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14931 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14932 TestConnectionId(2));
14933 // Clean up alternative path connection ID.
14934 EXPECT_EQ(
14935 TestConnectionId(2),
14936 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14937}
14938
14939TEST_P(QuicConnectionTest,
14940 CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued) {
danzh7c0ef5f2023-06-08 12:10:35 -070014941 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014942 return;
14943 }
14944 set_perspective(Perspective::IS_SERVER);
14945
14946 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14947 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14948 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14949 QuicRetireConnectionIdFrame frame;
14950 frame.sequence_number = 1u;
14951
14952 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14953
14954 EXPECT_FALSE(connection_.connected());
14955 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14956 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14957}
14958
14959TEST_P(QuicConnectionTest, RetireConnectionIdFrameResultsInError) {
danzh7c0ef5f2023-06-08 12:10:35 -070014960 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014961 return;
14962 }
14963 set_perspective(Perspective::IS_SERVER);
14964 connection_.CreateConnectionIdManager();
14965
martinduke08e3ff82022-10-18 09:06:26 -070014966 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014967 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14968 .WillOnce(Return(TestConnectionId(456)));
14969 }
danzh7c0ef5f2023-06-08 12:10:35 -070014970 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
Bence Békybac04052022-04-07 15:44:29 -040014971 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14972 connection_.MaybeSendConnectionIdToClient();
14973
14974 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14975 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14976 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14977 QuicRetireConnectionIdFrame frame;
14978 frame.sequence_number = 2u; // The corresponding ID is never issued.
14979
14980 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14981
14982 EXPECT_FALSE(connection_.connected());
14983 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14984 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14985}
14986
14987TEST_P(QuicConnectionTest,
14988 ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore) {
14989 if (!version().HasIetfQuicFrames()) {
14990 return;
14991 }
14992 set_perspective(Perspective::IS_SERVER);
14993 connection_.CreateConnectionIdManager();
14994
14995 auto* retire_self_issued_cid_alarm =
14996 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14997 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14998
14999 QuicConnectionId cid0 = connection_id_;
15000 QuicRetireConnectionIdFrame frame;
15001 frame.sequence_number = 0u;
danzh7c0ef5f2023-06-08 12:10:35 -070015002
15003 if (!connection_.connection_id().IsEmpty()) {
15004 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(cid0))
15005 .WillOnce(Return(TestConnectionId(456)));
15006 EXPECT_CALL(connection_id_generator_,
15007 GenerateNextConnectionId(TestConnectionId(456)))
15008 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040015009 }
danzh7c0ef5f2023-06-08 12:10:35 -070015010 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
15011 .Times(2)
15012 .WillRepeatedly(Return(true));
15013 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -040015014 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(frame));
15015}
15016
15017TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionId) {
danzh7c0ef5f2023-06-08 12:10:35 -070015018 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040015019 return;
15020 }
15021 set_perspective(Perspective::IS_SERVER);
15022 connection_.CreateConnectionIdManager();
15023 QuicConnectionId recorded_cid;
haoyuewangada6b822022-06-23 13:41:18 -070015024 auto cid_recorder = [&recorded_cid](const QuicConnectionId& cid) -> bool {
Bence Békybac04052022-04-07 15:44:29 -040015025 recorded_cid = cid;
haoyuewangada6b822022-06-23 13:41:18 -070015026 return true;
Bence Békybac04052022-04-07 15:44:29 -040015027 };
15028 QuicConnectionId cid0 = connection_id_;
15029 QuicConnectionId cid1;
15030 QuicConnectionId cid2;
15031 EXPECT_EQ(connection_.connection_id(), cid0);
15032 EXPECT_EQ(connection_.GetOneActiveServerConnectionId(), cid0);
15033
15034 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke08e3ff82022-10-18 09:06:26 -070015035 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070015036 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
15037 .WillOnce(Return(TestConnectionId(456)));
15038 }
haoyuewangada6b822022-06-23 13:41:18 -070015039 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040015040 .WillOnce(Invoke(cid_recorder));
15041 EXPECT_CALL(visitor_, SendNewConnectionId(_));
15042 connection_.MaybeSendConnectionIdToClient();
15043 cid1 = recorded_cid;
15044
15045 auto* retire_self_issued_cid_alarm =
15046 connection_.GetRetireSelfIssuedConnectionIdAlarm();
15047 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
15048
15049 // Generate three packets with different connection IDs that will arrive out
15050 // of order (2, 1, 3) later.
15051 char buffers[3][kMaxOutgoingPacketSize];
15052 // Destination connection ID of packet1 is cid0.
15053 auto packet1 =
15054 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
15055 buffers[0], kMaxOutgoingPacketSize);
15056 peer_creator_.SetServerConnectionId(cid1);
15057 auto retire_cid_frame = std::make_unique<QuicRetireConnectionIdFrame>();
15058 retire_cid_frame->sequence_number = 0u;
15059 // Destination connection ID of packet2 is cid1.
15060 auto packet2 = ConstructPacket({QuicFrame(retire_cid_frame.release())},
15061 ENCRYPTION_FORWARD_SECURE, buffers[1],
15062 kMaxOutgoingPacketSize);
15063 // Destination connection ID of packet3 is cid1.
15064 auto packet3 =
15065 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
15066 buffers[2], kMaxOutgoingPacketSize);
15067
15068 // Packet2 with RetireConnectionId frame trigers sending NewConnectionId
15069 // immediately.
martinduke08e3ff82022-10-18 09:06:26 -070015070 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070015071 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
15072 .WillOnce(Return(TestConnectionId(456)));
15073 }
haoyuewangada6b822022-06-23 13:41:18 -070015074 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040015075 .WillOnce(Invoke(cid_recorder));
15076 EXPECT_CALL(visitor_, SendNewConnectionId(_));
15077 peer_creator_.SetServerConnectionId(cid1);
15078 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet2);
15079 cid2 = recorded_cid;
15080 // cid0 is not retired immediately.
15081 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
15082 ElementsAre(cid0, cid1, cid2));
15083 ASSERT_TRUE(retire_self_issued_cid_alarm->IsSet());
15084 EXPECT_EQ(connection_.connection_id(), cid1);
15085 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
15086 connection_.GetOneActiveServerConnectionId() == cid1 ||
15087 connection_.GetOneActiveServerConnectionId() == cid2);
15088
15089 // Packet1 updates the connection ID on the default path but not the active
15090 // connection ID.
15091 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet1);
15092 EXPECT_EQ(connection_.connection_id(), cid0);
15093 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
15094 connection_.GetOneActiveServerConnectionId() == cid1 ||
15095 connection_.GetOneActiveServerConnectionId() == cid2);
15096
15097 // cid0 is retired when the retire CID alarm fires.
15098 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(cid0));
15099 retire_self_issued_cid_alarm->Fire();
15100 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
15101 ElementsAre(cid1, cid2));
15102 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
15103 connection_.GetOneActiveServerConnectionId() == cid2);
15104
15105 // Packet3 updates the connection ID on the default path.
15106 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet3);
15107 EXPECT_EQ(connection_.connection_id(), cid1);
15108 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
15109 connection_.GetOneActiveServerConnectionId() == cid2);
15110}
15111
15112TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoAlternativePath) {
15113 if (!version().HasIetfQuicFrames()) {
15114 return;
15115 }
15116 set_perspective(Perspective::IS_SERVER);
15117 connection_.CreateConnectionIdManager();
15118 connection_.set_client_connection_id(TestConnectionId(1));
15119
15120 // Set up the state after path probing.
15121 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15122 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
15123 QuicIpAddress new_host;
15124 new_host.FromString("12.12.12.12");
15125 alternative_path->self_address = default_path->self_address;
15126 alternative_path->peer_address = QuicSocketAddress(new_host, 12345);
15127 alternative_path->server_connection_id = TestConnectionId(3);
15128 ASSERT_TRUE(alternative_path->client_connection_id.IsEmpty());
15129 ASSERT_FALSE(alternative_path->stateless_reset_token.has_value());
15130
15131 QuicNewConnectionIdFrame frame;
15132 frame.sequence_number = 1u;
15133 frame.connection_id = TestConnectionId(5);
15134 frame.stateless_reset_token =
15135 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15136 frame.retire_prior_to = 0u;
15137 // New ID is patched onto the alternative path when the needed
15138 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
15139 connection_.OnNewConnectionIdFrame(frame);
15140
15141 ASSERT_EQ(alternative_path->client_connection_id, frame.connection_id);
15142 ASSERT_EQ(alternative_path->stateless_reset_token,
15143 frame.stateless_reset_token);
15144}
15145
15146TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoDefaultPath) {
15147 if (!version().HasIetfQuicFrames()) {
15148 return;
15149 }
15150 set_perspective(Perspective::IS_SERVER);
15151 connection_.CreateConnectionIdManager();
15152 connection_.set_client_connection_id(TestConnectionId(1));
15153
15154 // Set up the state after peer migration without probing.
15155 auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
15156 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
15157 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
15158 *alternative_path = std::move(*default_path);
15159 QuicIpAddress new_host;
15160 new_host.FromString("12.12.12.12");
15161 default_path->self_address = default_path->self_address;
15162 default_path->peer_address = QuicSocketAddress(new_host, 12345);
15163 default_path->server_connection_id = TestConnectionId(3);
15164 packet_creator->SetDefaultPeerAddress(default_path->peer_address);
15165 packet_creator->SetServerConnectionId(default_path->server_connection_id);
15166 packet_creator->SetClientConnectionId(default_path->client_connection_id);
15167
15168 ASSERT_FALSE(default_path->validated);
15169 ASSERT_TRUE(default_path->client_connection_id.IsEmpty());
15170 ASSERT_FALSE(default_path->stateless_reset_token.has_value());
15171
15172 QuicNewConnectionIdFrame frame;
15173 frame.sequence_number = 1u;
15174 frame.connection_id = TestConnectionId(5);
15175 frame.stateless_reset_token =
15176 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
15177 frame.retire_prior_to = 0u;
15178 // New ID is patched onto the default path when the needed
15179 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
15180 connection_.OnNewConnectionIdFrame(frame);
15181
15182 ASSERT_EQ(default_path->client_connection_id, frame.connection_id);
15183 ASSERT_EQ(default_path->stateless_reset_token, frame.stateless_reset_token);
15184 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), frame.connection_id);
15185}
15186
15187TEST_P(QuicConnectionTest, ShouldGeneratePacketBlockedByMissingConnectionId) {
15188 if (!version().HasIetfQuicFrames()) {
15189 return;
15190 }
15191 set_perspective(Perspective::IS_SERVER);
15192 connection_.set_client_connection_id(TestConnectionId(1));
15193 connection_.CreateConnectionIdManager();
15194 if (version().SupportsAntiAmplificationLimit()) {
15195 QuicConnectionPeer::SetAddressValidated(&connection_);
15196 }
15197
15198 ASSERT_TRUE(
15199 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
15200
15201 QuicPacketCreator* packet_creator =
15202 QuicConnectionPeer::GetPacketCreator(&connection_);
15203 QuicIpAddress peer_host1;
15204 peer_host1.FromString("12.12.12.12");
15205 QuicSocketAddress peer_address1(peer_host1, 1235);
15206
15207 {
15208 // No connection ID is available as context is created without any.
15209 QuicPacketCreator::ScopedPeerAddressContext context(
15210 packet_creator, peer_address1, EmptyQuicConnectionId(),
danzh7c0ef5f2023-06-08 12:10:35 -070015211 EmptyQuicConnectionId());
Bence Békybac04052022-04-07 15:44:29 -040015212 ASSERT_FALSE(connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
15213 NOT_HANDSHAKE));
15214 }
15215 ASSERT_TRUE(
15216 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
15217}
15218
15219// Regression test for b/182571515
15220TEST_P(QuicConnectionTest, LostDataThenGetAcknowledged) {
15221 set_perspective(Perspective::IS_SERVER);
danzh4d58dae2023-06-06 11:13:10 -070015222 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -070015223 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040015224 return;
15225 }
15226
15227 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
15228 if (version().SupportsAntiAmplificationLimit()) {
15229 QuicConnectionPeer::SetAddressValidated(&connection_);
15230 }
15231 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15232 // Discard INITIAL key.
15233 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15234 connection_.NeuterUnencryptedPackets();
15235 EXPECT_CALL(visitor_, GetHandshakeState())
15236 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
15237
15238 QuicPacketNumber last_packet;
15239 // Send packets 1 to 4.
15240 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
15241 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 2
15242 SendStreamDataToPeer(3, "foo", 6, NO_FIN, &last_packet); // Packet 3
15243 SendStreamDataToPeer(3, "foo", 9, NO_FIN, &last_packet); // Packet 4
15244
15245 // Process a PING packet to set peer address.
15246 ProcessFramePacket(QuicFrame(QuicPingFrame()));
15247
15248 // Process a packet containing a STREAM_FRAME and an ACK with changed peer
15249 // address.
15250 QuicFrames frames;
15251 frames.push_back(QuicFrame(frame1_));
15252 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}});
15253 frames.push_back(QuicFrame(&ack));
15254
Bence Békybac04052022-04-07 15:44:29 -040015255 // Invoke OnCanWrite.
Bence Békybac04052022-04-07 15:44:29 -040015256 QuicIpAddress ip_address;
15257 ASSERT_TRUE(ip_address.FromString("127.0.52.223"));
vasilvvac2e30d2022-06-02 14:26:59 -070015258 EXPECT_QUIC_BUG(
15259 {
15260 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(1);
15261 EXPECT_CALL(visitor_, OnStreamFrame(_))
15262 .WillOnce(InvokeWithoutArgs(&notifier_,
15263 &SimpleSessionNotifier::OnCanWrite));
15264 ProcessFramesPacketWithAddresses(frames, kSelfAddress,
15265 QuicSocketAddress(ip_address, 1000),
15266 ENCRYPTION_FORWARD_SECURE);
15267 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
15268
15269 // Verify stream frame will not be retransmitted.
15270 EXPECT_TRUE(writer_->stream_frames().empty());
15271 },
15272 "Try to write mid packet processing");
Bence Békybac04052022-04-07 15:44:29 -040015273}
15274
15275TEST_P(QuicConnectionTest, PtoSendStreamData) {
15276 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15277 return;
15278 }
15279 set_perspective(Perspective::IS_SERVER);
15280 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
15281 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15282 }
15283 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015284 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15285 EXPECT_TRUE(connection_.HasPendingAcks());
15286
Bence Békybac04052022-04-07 15:44:29 -040015287 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15288 // Send INITIAL 1.
15289 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15290
martinduke9e0811c2022-12-08 20:35:57 -080015291 connection_.SetEncrypter(
15292 ENCRYPTION_HANDSHAKE,
15293 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015294 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15295 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015296 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015297 // Send HANDSHAKE packets.
15298 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15299 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15300
martinduke9e0811c2022-12-08 20:35:57 -080015301 connection_.SetEncrypter(
15302 ENCRYPTION_FORWARD_SECURE,
15303 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015304 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15305
15306 // Send half RTT packet with congestion control blocked.
15307 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
15308 connection_.SendStreamDataWithString(2, std::string(1500, 'a'), 0, NO_FIN);
15309
15310 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15311 connection_.GetRetransmissionAlarm()->Fire();
15312 // Verify INITIAL and HANDSHAKE get retransmitted.
martinduke9e0811c2022-12-08 20:35:57 -080015313 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015314}
15315
15316TEST_P(QuicConnectionTest, SendingZeroRttPacketsDoesNotPostponePTO) {
15317 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15318 return;
15319 }
Bence Békybac04052022-04-07 15:44:29 -040015320 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15321 // Send CHLO.
15322 connection_.SendCryptoStreamData();
15323 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15324 // Install 0-RTT keys.
15325 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15326 std::make_unique<TaggingEncrypter>(0x02));
15327 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15328
15329 // CHLO gets acknowledged after 10ms.
15330 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15331 QuicAckFrame frame1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070015332 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015333 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15334 // Verify PTO is still armed since address validation is not finished yet.
15335 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15336 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15337
15338 // Send 0-RTT packet.
15339 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15340 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15341 std::make_unique<TaggingEncrypter>(0x02));
15342 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15343 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15344 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15345 // PTO deadline should be unchanged.
15346 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15347}
15348
15349TEST_P(QuicConnectionTest, QueueingUndecryptablePacketsDoesntPostponePTO) {
15350 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15351 return;
15352 }
15353 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15354 QuicConfig config;
15355 config.set_max_undecryptable_packets(3);
15356 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040015357 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15358 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15359 // Send CHLO.
15360 connection_.SendCryptoStreamData();
15361
15362 // Send 0-RTT packet.
15363 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15364 std::make_unique<TaggingEncrypter>(0x02));
15365 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 // Receive an undecryptable packets.
15378 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15379 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15380 std::make_unique<TaggingEncrypter>(0xFF));
15381 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15382 // Verify PTO deadline is sooner.
15383 EXPECT_GT(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15384 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15385
15386 // PTO fires.
15387 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15388 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15389 connection_.GetRetransmissionAlarm()->Fire();
15390 // Verify PTO is still armed since address validation is not finished yet.
15391 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15392 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15393
15394 // Verify PTO deadline does not change.
15395 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15396 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15397}
15398
15399TEST_P(QuicConnectionTest, QueueUndecryptableHandshakePackets) {
15400 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15401 return;
15402 }
15403 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15404 QuicConfig config;
15405 config.set_max_undecryptable_packets(3);
15406 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040015407 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15408 connection_.RemoveDecrypter(ENCRYPTION_HANDSHAKE);
15409 // Send CHLO.
15410 connection_.SendCryptoStreamData();
15411
15412 // Send 0-RTT packet.
15413 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15414 std::make_unique<TaggingEncrypter>(0x02));
15415 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15416 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15417 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15418
15419 // Receive an undecryptable handshake packet.
15420 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15421 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15422 std::make_unique<TaggingEncrypter>(0xFF));
15423 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
15424 // Verify this handshake packet gets queued.
15425 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15426}
15427
15428TEST_P(QuicConnectionTest, PingNotSentAt0RTTLevelWhenInitialAvailable) {
15429 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15430 return;
15431 }
Bence Békybac04052022-04-07 15:44:29 -040015432 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15433 // Send CHLO.
15434 connection_.SendCryptoStreamData();
15435 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080015436 connection_.SetEncrypter(
15437 ENCRYPTION_ZERO_RTT,
15438 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015439 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15440 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15441
15442 // CHLO gets acknowledged after 10ms.
15443 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15444 QuicAckFrame frame1 = InitAckFrame(1);
martindukeba002452023-03-21 08:10:46 -070015445 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015446 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15447 // Verify PTO is still armed since address validation is not finished yet.
15448 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15449 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15450
15451 // PTO fires.
15452 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15453 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15454 connection_.GetRetransmissionAlarm()->Fire();
15455 // Verify the PING gets sent in ENCRYPTION_INITIAL.
martinduke9e0811c2022-12-08 20:35:57 -080015456 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015457}
15458
15459TEST_P(QuicConnectionTest, AckElicitingFrames) {
danzh7c0ef5f2023-06-08 12:10:35 -070015460 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040015461 return;
15462 }
martinduke08e3ff82022-10-18 09:06:26 -070015463 EXPECT_CALL(connection_id_generator_,
15464 GenerateNextConnectionId(TestConnectionId(12)))
15465 .WillOnce(Return(TestConnectionId(456)));
15466 EXPECT_CALL(connection_id_generator_,
15467 GenerateNextConnectionId(TestConnectionId(456)))
15468 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040015469 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
15470 EXPECT_CALL(visitor_, OnRstStream(_));
15471 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
15472 EXPECT_CALL(visitor_, OnBlockedFrame(_));
15473 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
15474 EXPECT_CALL(visitor_, OnStreamFrame(_));
martindukeba002452023-03-21 08:10:46 -070015475 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015476 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_));
15477 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_));
15478 EXPECT_CALL(visitor_, OnStopSendingFrame(_));
15479 EXPECT_CALL(visitor_, OnMessageReceived(""));
15480 EXPECT_CALL(visitor_, OnNewTokenReceived(""));
15481
15482 SetClientConnectionId(TestConnectionId(12));
15483 connection_.CreateConnectionIdManager();
15484 QuicConnectionPeer::GetSelfIssuedConnectionIdManager(&connection_)
15485 ->MaybeSendNewConnectionIds();
15486 connection_.set_can_receive_ack_frequency_frame();
15487
15488 QuicAckFrame ack_frame = InitAckFrame(1);
15489 QuicRstStreamFrame rst_stream_frame;
15490 QuicWindowUpdateFrame window_update_frame;
15491 QuicPathChallengeFrame path_challenge_frame;
15492 QuicNewConnectionIdFrame new_connection_id_frame;
renjietang785c7cb2023-08-21 09:10:25 -070015493 new_connection_id_frame.sequence_number = 1u;
Bence Békybac04052022-04-07 15:44:29 -040015494 QuicRetireConnectionIdFrame retire_connection_id_frame;
15495 retire_connection_id_frame.sequence_number = 1u;
15496 QuicStopSendingFrame stop_sending_frame;
15497 QuicPathResponseFrame path_response_frame;
15498 QuicMessageFrame message_frame;
15499 QuicNewTokenFrame new_token_frame;
15500 QuicAckFrequencyFrame ack_frequency_frame;
vasilvv60a22a62024-02-05 08:26:22 -080015501 QuicResetStreamAtFrame reset_stream_at_frame;
Bence Békybac04052022-04-07 15:44:29 -040015502 QuicBlockedFrame blocked_frame;
15503 size_t packet_number = 1;
15504
15505 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
vasilvv60a22a62024-02-05 08:26:22 -080015506 QuicFramer* framer = const_cast<QuicFramer*>(&connection_.framer());
15507 framer->set_process_reset_stream_at(true);
15508 peer_framer_.set_process_reset_stream_at(true);
Bence Békybac04052022-04-07 15:44:29 -040015509
15510 for (uint8_t i = 0; i < NUM_FRAME_TYPES; ++i) {
15511 QuicFrameType frame_type = static_cast<QuicFrameType>(i);
15512 bool skipped = false;
15513 QuicFrame frame;
15514 QuicFrames frames;
15515 // Add some padding to fullfill the min size requirement of header
15516 // protection.
15517 frames.push_back(QuicFrame(QuicPaddingFrame(10)));
15518 switch (frame_type) {
15519 case PADDING_FRAME:
15520 frame = QuicFrame(QuicPaddingFrame(10));
15521 break;
15522 case MTU_DISCOVERY_FRAME:
15523 frame = QuicFrame(QuicMtuDiscoveryFrame());
15524 break;
15525 case PING_FRAME:
15526 frame = QuicFrame(QuicPingFrame());
15527 break;
15528 case MAX_STREAMS_FRAME:
15529 frame = QuicFrame(QuicMaxStreamsFrame());
15530 break;
15531 case STOP_WAITING_FRAME:
15532 // Not supported.
15533 skipped = true;
15534 break;
15535 case STREAMS_BLOCKED_FRAME:
15536 frame = QuicFrame(QuicStreamsBlockedFrame());
15537 break;
15538 case STREAM_FRAME:
15539 frame = QuicFrame(QuicStreamFrame());
15540 break;
15541 case HANDSHAKE_DONE_FRAME:
15542 frame = QuicFrame(QuicHandshakeDoneFrame());
15543 break;
15544 case ACK_FRAME:
15545 frame = QuicFrame(&ack_frame);
15546 break;
15547 case RST_STREAM_FRAME:
15548 frame = QuicFrame(&rst_stream_frame);
15549 break;
15550 case CONNECTION_CLOSE_FRAME:
15551 // Do not test connection close.
15552 skipped = true;
15553 break;
15554 case GOAWAY_FRAME:
15555 // Does not exist in IETF QUIC.
15556 skipped = true;
15557 break;
15558 case BLOCKED_FRAME:
15559 frame = QuicFrame(blocked_frame);
15560 break;
15561 case WINDOW_UPDATE_FRAME:
15562 frame = QuicFrame(window_update_frame);
15563 break;
15564 case PATH_CHALLENGE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015565 frame = QuicFrame(path_challenge_frame);
Bence Békybac04052022-04-07 15:44:29 -040015566 break;
15567 case STOP_SENDING_FRAME:
15568 frame = QuicFrame(stop_sending_frame);
15569 break;
15570 case NEW_CONNECTION_ID_FRAME:
15571 frame = QuicFrame(&new_connection_id_frame);
15572 break;
15573 case RETIRE_CONNECTION_ID_FRAME:
15574 frame = QuicFrame(&retire_connection_id_frame);
15575 break;
15576 case PATH_RESPONSE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015577 frame = QuicFrame(path_response_frame);
Bence Békybac04052022-04-07 15:44:29 -040015578 break;
15579 case MESSAGE_FRAME:
15580 frame = QuicFrame(&message_frame);
15581 break;
15582 case CRYPTO_FRAME:
15583 // CRYPTO_FRAME is ack eliciting is covered by other tests.
15584 skipped = true;
15585 break;
15586 case NEW_TOKEN_FRAME:
15587 frame = QuicFrame(&new_token_frame);
15588 break;
15589 case ACK_FREQUENCY_FRAME:
15590 frame = QuicFrame(&ack_frequency_frame);
15591 break;
vasilvv60a22a62024-02-05 08:26:22 -080015592 case RESET_STREAM_AT_FRAME:
15593 frame = QuicFrame(&reset_stream_at_frame);
15594 break;
Bence Békybac04052022-04-07 15:44:29 -040015595 case NUM_FRAME_TYPES:
15596 skipped = true;
15597 break;
15598 }
15599 if (skipped) {
15600 continue;
15601 }
15602 ASSERT_EQ(frame_type, frame.type);
15603 frames.push_back(frame);
15604 EXPECT_FALSE(connection_.HasPendingAcks());
15605 // Process frame.
15606 ProcessFramesPacketAtLevel(packet_number++, frames,
15607 ENCRYPTION_FORWARD_SECURE);
15608 if (QuicUtils::IsAckElicitingFrame(frame_type)) {
15609 ASSERT_TRUE(connection_.HasPendingAcks()) << frame;
15610 // Flush ACK.
15611 clock_.AdvanceTime(DefaultDelayedAckTime());
15612 connection_.GetAckAlarm()->Fire();
15613 }
15614 EXPECT_FALSE(connection_.HasPendingAcks());
15615 ASSERT_TRUE(connection_.connected());
15616 }
15617}
15618
15619TEST_P(QuicConnectionTest, ReceivedChloAndAck) {
15620 if (!version().HasIetfQuicFrames()) {
15621 return;
15622 }
15623 set_perspective(Perspective::IS_SERVER);
15624 QuicFrames frames;
15625 QuicAckFrame ack_frame = InitAckFrame(1);
15626 frames.push_back(MakeCryptoFrame());
15627 frames.push_back(QuicFrame(&ack_frame));
15628
15629 EXPECT_CALL(visitor_, OnCryptoFrame(_))
15630 .WillOnce(IgnoreResult(InvokeWithoutArgs(
15631 &connection_, &TestConnection::SendCryptoStreamData)));
15632 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15633 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15634 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
15635 ENCRYPTION_INITIAL);
15636}
15637
15638// Regression test for b/201643321.
15639TEST_P(QuicConnectionTest, FailedToRetransmitShlo) {
danzh4d58dae2023-06-06 11:13:10 -070015640 if (!version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -070015641 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040015642 return;
15643 }
15644 set_perspective(Perspective::IS_SERVER);
15645 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15646 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015647 // Received INITIAL 1.
15648 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15649 EXPECT_TRUE(connection_.HasPendingAcks());
15650
martinduke9e0811c2022-12-08 20:35:57 -080015651 peer_framer_.SetEncrypter(
15652 ENCRYPTION_ZERO_RTT,
15653 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015654
martinduke9e0811c2022-12-08 20:35:57 -080015655 connection_.SetEncrypter(
15656 ENCRYPTION_HANDSHAKE,
15657 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015658 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015659 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015660 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015661 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15662 connection_.SetEncrypter(
15663 ENCRYPTION_FORWARD_SECURE,
15664 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015665 // Received ENCRYPTION_ZERO_RTT 1.
15666 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15667 {
15668 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15669 // Send INITIAL 1.
15670 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15671 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15672 // Send HANDSHAKE 2.
15673 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15674 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15675 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15676 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15677 // Send half RTT data to exhaust amplification credit.
15678 connection_.SendStreamDataWithString(0, std::string(100 * 1024, 'a'), 0,
15679 NO_FIN);
15680 }
15681 // Received INITIAL 2.
15682 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
15683 ASSERT_TRUE(connection_.HasPendingAcks());
15684 // Verify ACK delay is 1ms.
15685 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
15686 connection_.GetAckAlarm()->deadline());
15687 // ACK is not throttled by amplification limit, and SHLO is bundled. Also
15688 // HANDSHAKE + 1RTT packets get coalesced.
fayange9753892022-05-17 03:57:11 -070015689 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -040015690 // ACK alarm fires.
15691 clock_.AdvanceTime(kAlarmGranularity);
15692 connection_.GetAckAlarm()->Fire();
fayange9753892022-05-17 03:57:11 -070015693 // Verify 1-RTT packet is coalesced.
martinduke9e0811c2022-12-08 20:35:57 -080015694 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015695 // Only the first packet in the coalesced packet has been processed,
15696 // verify SHLO is bundled with INITIAL ACK.
15697 EXPECT_EQ(1u, writer_->ack_frames().size());
15698 EXPECT_EQ(1u, writer_->crypto_frames().size());
15699 // Process the coalesced HANDSHAKE packet.
15700 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15701 auto packet = writer_->coalesced_packet()->Clone();
15702 writer_->framer()->ProcessPacket(*packet);
15703 EXPECT_EQ(0u, writer_->ack_frames().size());
15704 EXPECT_EQ(1u, writer_->crypto_frames().size());
fayange9753892022-05-17 03:57:11 -070015705 // Process the coalesced 1-RTT packet.
15706 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15707 packet = writer_->coalesced_packet()->Clone();
15708 writer_->framer()->ProcessPacket(*packet);
15709 EXPECT_EQ(0u, writer_->crypto_frames().size());
15710 EXPECT_EQ(1u, writer_->stream_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040015711
15712 // Received INITIAL 3.
15713 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
15714 ProcessCryptoPacketAtLevel(3, ENCRYPTION_INITIAL);
15715 EXPECT_TRUE(connection_.HasPendingAcks());
15716}
15717
15718// Regression test for b/216133388.
15719TEST_P(QuicConnectionTest, FailedToConsumeCryptoData) {
15720 if (!version().HasIetfQuicFrames()) {
15721 return;
15722 }
15723 set_perspective(Perspective::IS_SERVER);
15724 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15725 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015726 // Received INITIAL 1.
15727 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15728 EXPECT_TRUE(connection_.HasPendingAcks());
15729
martinduke9e0811c2022-12-08 20:35:57 -080015730 peer_framer_.SetEncrypter(
15731 ENCRYPTION_ZERO_RTT,
15732 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15733 connection_.SetEncrypter(
15734 ENCRYPTION_HANDSHAKE,
15735 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015736 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015737 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015738 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015739 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15740 connection_.SetEncrypter(
15741 ENCRYPTION_FORWARD_SECURE,
15742 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015743 // Received ENCRYPTION_ZERO_RTT 1.
15744 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15745 {
15746 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15747 // Send INITIAL 1.
15748 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15749 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15750 // Send HANDSHAKE 2.
15751 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15752 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15753 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15754 ENCRYPTION_HANDSHAKE);
15755 // Send 1-RTT 3.
15756 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15757 connection_.SendStreamDataWithString(0, std::string(40, 'a'), 0, NO_FIN);
15758 }
15759 // Received HANDSHAKE Ping, hence discard INITIAL keys.
15760 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15761 std::make_unique<TaggingEncrypter>(0x03));
15762 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15763 connection_.NeuterUnencryptedPackets();
15764 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
15765 clock_.AdvanceTime(kAlarmGranularity);
15766 {
15767 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15768 // Sending this 1-RTT data would leave the coalescer only have space to
15769 // accommodate the HANDSHAKE ACK. The crypto data cannot be bundled with the
15770 // ACK.
15771 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15772 connection_.SendStreamDataWithString(0, std::string(1395, 'a'), 40, NO_FIN);
15773 }
15774 // Verify retransmission alarm is armed.
15775 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15776 const QuicTime retransmission_time =
15777 connection_.GetRetransmissionAlarm()->deadline();
15778 clock_.AdvanceTime(retransmission_time - clock_.Now());
15779 connection_.GetRetransmissionAlarm()->Fire();
15780
fayang43294412022-04-21 09:22:12 -070015781 // Verify the retransmission is a coalesced packet with HANDSHAKE 2 and
15782 // 1-RTT 3.
martinduke9e0811c2022-12-08 20:35:57 -080015783 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
fayang43294412022-04-21 09:22:12 -070015784 // Only the first packet in the coalesced packet has been processed.
15785 EXPECT_EQ(1u, writer_->crypto_frames().size());
15786 // Process the coalesced 1-RTT packet.
15787 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15788 auto packet = writer_->coalesced_packet()->Clone();
15789 writer_->framer()->ProcessPacket(*packet);
15790 EXPECT_EQ(1u, writer_->stream_frames().size());
15791 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
Bence Békybac04052022-04-07 15:44:29 -040015792 // Verify retransmission alarm is still armed.
15793 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15794}
15795
15796TEST_P(QuicConnectionTest,
15797 RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing) {
15798 // An endpoint might postpone the processing of ACK when the corresponding
15799 // decryption key is not available. This test makes sure the RTT sample does
15800 // not include the queuing delay.
15801 if (!version().HasIetfQuicFrames()) {
15802 return;
15803 }
15804 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15805 QuicConfig config;
15806 config.set_max_undecryptable_packets(3);
15807 connection_.SetFromConfig(config);
15808
15809 // 30ms RTT.
15810 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
15811 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
15812 rtt_stats->UpdateRtt(kTestRTT, QuicTime::Delta::Zero(), QuicTime::Zero());
Bence Békybac04052022-04-07 15:44:29 -040015813
15814 // Send 0-RTT packet.
15815 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015816 connection_.SetEncrypter(
15817 ENCRYPTION_ZERO_RTT,
15818 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015819 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15820 connection_.SendStreamDataWithString(0, std::string(10, 'a'), 0, FIN);
15821
15822 // Receives 1-RTT ACK for 0-RTT packet after RTT + ack_delay.
wub349df3d2024-04-26 11:37:32 -070015823 clock_.AdvanceTime(kTestRTT + QuicTime::Delta::FromMilliseconds(
15824 GetDefaultDelayedAckTimeMs()));
Bence Békybac04052022-04-07 15:44:29 -040015825 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
martinduke9e0811c2022-12-08 20:35:57 -080015826 peer_framer_.SetEncrypter(
15827 ENCRYPTION_FORWARD_SECURE,
15828 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015829 QuicAckFrame ack_frame = InitAckFrame(1);
15830 // Peer reported ACK delay.
15831 ack_frame.ack_delay_time =
wub349df3d2024-04-26 11:37:32 -070015832 QuicTime::Delta::FromMilliseconds(GetDefaultDelayedAckTimeMs());
Bence Békybac04052022-04-07 15:44:29 -040015833 QuicFrames frames;
15834 frames.push_back(QuicFrame(&ack_frame));
15835 QuicPacketHeader header =
15836 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15837 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15838
15839 char buffer[kMaxOutgoingPacketSize];
15840 size_t encrypted_length = peer_framer_.EncryptPayload(
15841 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15842 kMaxOutgoingPacketSize);
15843 connection_.ProcessUdpPacket(
15844 kSelfAddress, kPeerAddress,
15845 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15846 if (connection_.GetSendAlarm()->IsSet()) {
15847 connection_.GetSendAlarm()->Fire();
15848 }
15849 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15850
15851 // Assume 1-RTT decrypter is available after 10ms.
15852 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15853 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080015854 SetDecrypter(
15855 ENCRYPTION_FORWARD_SECURE,
15856 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015857 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15858
martindukeba002452023-03-21 08:10:46 -070015859 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _));
Bence Békybac04052022-04-07 15:44:29 -040015860 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15861 // Verify RTT sample does not include queueing delay.
15862 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
15863}
15864
15865// Regression test for b/112480134.
15866TEST_P(QuicConnectionTest, NoExtraPaddingInReserializedInitial) {
15867 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
15868 if (!IsDefaultTestConfiguration() ||
15869 !connection_.version().CanSendCoalescedPackets()) {
15870 return;
15871 }
15872
15873 set_perspective(Perspective::IS_SERVER);
15874 MockQuicConnectionDebugVisitor debug_visitor;
15875 connection_.set_debug_visitor(&debug_visitor);
15876
15877 uint64_t debug_visitor_sent_count = 0;
wub92727922023-07-13 08:47:39 -070015878 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040015879 .WillRepeatedly([&]() { debug_visitor_sent_count++; });
15880
15881 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15882 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015883
15884 // Received INITIAL 1.
15885 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15886
martinduke9e0811c2022-12-08 20:35:57 -080015887 peer_framer_.SetEncrypter(
15888 ENCRYPTION_ZERO_RTT,
15889 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15890 connection_.SetEncrypter(
15891 ENCRYPTION_HANDSHAKE,
15892 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015893 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015894 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015895 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015896 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15897 connection_.SetEncrypter(
15898 ENCRYPTION_FORWARD_SECURE,
15899 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015900
15901 // Received ENCRYPTION_ZERO_RTT 2.
15902 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15903
15904 {
15905 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15906 // Send INITIAL 1.
15907 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15908 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15909 // Send HANDSHAKE 2.
15910 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15911 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15912 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15913 ENCRYPTION_HANDSHAKE);
15914 // Send 1-RTT 3.
15915 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15916 connection_.SendStreamDataWithString(0, std::string(400, 'b'), 0, NO_FIN);
15917 }
15918
15919 // Arrange the stream data to be sent in response to ENCRYPTION_INITIAL 3.
15920 const std::string data4(1000, '4'); // Data to send in stream id 4
15921 const std::string data8(3000, '8'); // Data to send in stream id 8
15922 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce([&]() {
15923 connection_.producer()->SaveStreamData(4, data4);
15924 connection_.producer()->SaveStreamData(8, data8);
15925
15926 notifier_.WriteOrBufferData(4, data4.size(), FIN_AND_PADDING);
15927
15928 // This should trigger FlushCoalescedPacket.
15929 notifier_.WriteOrBufferData(8, data8.size(), FIN);
15930 });
15931
15932 QuicByteCount pending_padding_after_serialize_2nd_1rtt_packet = 0;
15933 QuicPacketCount num_1rtt_packets_serialized = 0;
15934 EXPECT_CALL(connection_, OnSerializedPacket(_))
15935 .WillRepeatedly([&](SerializedPacket packet) {
15936 if (packet.encryption_level == ENCRYPTION_FORWARD_SECURE) {
15937 num_1rtt_packets_serialized++;
15938 if (num_1rtt_packets_serialized == 2) {
15939 pending_padding_after_serialize_2nd_1rtt_packet =
15940 connection_.packet_creator().pending_padding_bytes();
15941 }
15942 }
15943 connection_.QuicConnection::OnSerializedPacket(std::move(packet));
15944 });
15945
15946 // Server receives INITIAL 3, this will serialzie FS 7 (stream 4, stream 8),
15947 // which will trigger a flush of a coalesced packet consists of INITIAL 4,
15948 // HS 5 and FS 6 (stream 4).
wub08efde42022-05-09 12:25:02 -070015949
15950 // Expect no QUIC_BUG.
15951 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15952 EXPECT_EQ(
15953 debug_visitor_sent_count,
15954 connection_.sent_packet_manager().GetLargestSentPacket().ToUint64());
Bence Békybac04052022-04-07 15:44:29 -040015955
15956 // The error only happens if after serializing the second 1RTT packet(pkt #7),
15957 // the pending padding bytes is non zero.
15958 EXPECT_GT(pending_padding_after_serialize_2nd_1rtt_packet, 0u);
15959 EXPECT_TRUE(connection_.connected());
15960}
15961
15962TEST_P(QuicConnectionTest, ReportedAckDelayIncludesQueuingDelay) {
15963 if (!version().HasIetfQuicFrames()) {
15964 return;
15965 }
15966 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15967 QuicConfig config;
15968 config.set_max_undecryptable_packets(3);
15969 connection_.SetFromConfig(config);
15970
15971 // Receive 1-RTT ack-eliciting packet while keys are not available.
15972 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015973 peer_framer_.SetEncrypter(
15974 ENCRYPTION_FORWARD_SECURE,
15975 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015976 QuicFrames frames;
15977 frames.push_back(QuicFrame(QuicPingFrame()));
15978 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
15979 QuicPacketHeader header =
15980 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15981 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15982
15983 char buffer[kMaxOutgoingPacketSize];
15984 size_t encrypted_length = peer_framer_.EncryptPayload(
15985 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15986 kMaxOutgoingPacketSize);
15987 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15988 const QuicTime packet_receipt_time = clock_.Now();
15989 connection_.ProcessUdpPacket(
15990 kSelfAddress, kPeerAddress,
15991 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15992 if (connection_.GetSendAlarm()->IsSet()) {
15993 connection_.GetSendAlarm()->Fire();
15994 }
15995 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15996 // 1-RTT keys become available after 10ms.
15997 const QuicTime::Delta kQueuingDelay = QuicTime::Delta::FromMilliseconds(10);
15998 clock_.AdvanceTime(kQueuingDelay);
15999 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
16000 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080016001 SetDecrypter(
16002 ENCRYPTION_FORWARD_SECURE,
16003 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016004 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
16005
16006 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
16007 ASSERT_TRUE(connection_.HasPendingAcks());
fayangfea655c2022-05-17 08:19:12 -070016008 EXPECT_EQ(packet_receipt_time + DefaultDelayedAckTime(),
16009 connection_.GetAckAlarm()->deadline());
16010 clock_.AdvanceTime(packet_receipt_time + DefaultDelayedAckTime() -
16011 clock_.Now());
Bence Békybac04052022-04-07 15:44:29 -040016012 // Fire ACK alarm.
16013 connection_.GetAckAlarm()->Fire();
16014 ASSERT_EQ(1u, writer_->ack_frames().size());
fayangfea655c2022-05-17 08:19:12 -070016015 // Verify ACK delay time does not include queuing delay.
16016 EXPECT_EQ(DefaultDelayedAckTime(), writer_->ack_frames()[0].ack_delay_time);
Bence Békybac04052022-04-07 15:44:29 -040016017}
16018
16019TEST_P(QuicConnectionTest, CoalesceOneRTTPacketWithInitialAndHandshakePackets) {
16020 if (!version().HasIetfQuicFrames()) {
16021 return;
16022 }
16023 set_perspective(Perspective::IS_SERVER);
16024 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
16025 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040016026
16027 // Received INITIAL 1.
16028 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16029
martinduke9e0811c2022-12-08 20:35:57 -080016030 peer_framer_.SetEncrypter(
16031 ENCRYPTION_ZERO_RTT,
16032 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040016033
martinduke9e0811c2022-12-08 20:35:57 -080016034 connection_.SetEncrypter(
16035 ENCRYPTION_HANDSHAKE,
16036 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016037 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080016038 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016039 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080016040 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
16041 connection_.SetEncrypter(
16042 ENCRYPTION_FORWARD_SECURE,
16043 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016044
16045 // Received ENCRYPTION_ZERO_RTT 2.
16046 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
16047
16048 {
16049 QuicConnection::ScopedPacketFlusher flusher(&connection_);
16050 // Send INITIAL 1.
16051 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16052 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
16053 // Send HANDSHAKE 2.
16054 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
16055 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
16056 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
16057 ENCRYPTION_HANDSHAKE);
16058 // Send 1-RTT data.
16059 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16060 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
16061 }
16062 // Verify coalesced packet [INITIAL 1 + HANDSHAKE 2 + part of 1-RTT data] +
16063 // rest of 1-RTT data get sent.
16064 EXPECT_EQ(2u, writer_->packets_write_attempts());
16065
16066 // Received ENCRYPTION_INITIAL 3.
16067 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
16068
16069 // Verify a coalesced packet gets sent.
16070 EXPECT_EQ(3u, writer_->packets_write_attempts());
16071
16072 // Only the first INITIAL packet has been processed yet.
16073 EXPECT_EQ(1u, writer_->ack_frames().size());
16074 EXPECT_EQ(1u, writer_->crypto_frames().size());
16075
16076 // Process HANDSHAKE packet.
16077 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16078 auto packet = writer_->coalesced_packet()->Clone();
16079 writer_->framer()->ProcessPacket(*packet);
16080 EXPECT_EQ(1u, writer_->crypto_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040016081 // Process 1-RTT packet.
16082 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
16083 packet = writer_->coalesced_packet()->Clone();
16084 writer_->framer()->ProcessPacket(*packet);
16085 EXPECT_EQ(1u, writer_->stream_frames().size());
16086}
16087
16088// Regression test for b/180103273
16089TEST_P(QuicConnectionTest, SendMultipleConnectionCloses) {
16090 if (!version().HasIetfQuicFrames() ||
16091 !GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
16092 return;
16093 }
16094 set_perspective(Perspective::IS_SERVER);
16095 // Finish handshake.
16096 QuicConnectionPeer::SetAddressValidated(&connection_);
16097 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16098 notifier_.NeuterUnencryptedData();
16099 connection_.NeuterUnencryptedPackets();
16100 connection_.OnHandshakeComplete();
16101 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
16102 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
16103 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080016104 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040016105
16106 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
16107 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
bnc3000cba2022-04-18 12:19:14 -070016108 // Verify that BeforeConnectionCloseSent() gets called twice,
16109 // while OnConnectionClosed() is called only once.
Bence Békybac04052022-04-07 15:44:29 -040016110 EXPECT_CALL(visitor_, BeforeConnectionCloseSent()).Times(2);
16111 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
16112 // Send connection close w/o closing connection.
16113 QuicConnectionPeer::SendConnectionClosePacket(
16114 &connection_, INTERNAL_ERROR, QUIC_INTERNAL_ERROR, "internal error");
bnc3000cba2022-04-18 12:19:14 -070016115 // Fire blackhole detection alarm. This will invoke
16116 // SendConnectionClosePacket() a second time.
16117 connection_.GetBlackholeDetectorAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -040016118}
16119
16120// Regression test for b/157895910.
16121TEST_P(QuicConnectionTest, EarliestSentTimeNotInitializedWhenPtoFires) {
16122 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
16123 return;
16124 }
16125 set_perspective(Perspective::IS_SERVER);
16126 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
16127 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040016128
16129 // Received INITIAL 1.
16130 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080016131 connection_.SetEncrypter(
16132 ENCRYPTION_HANDSHAKE,
16133 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040016134 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080016135 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
16136 connection_.SetEncrypter(
16137 ENCRYPTION_FORWARD_SECURE,
16138 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040016139 {
16140 QuicConnection::ScopedPacketFlusher flusher(&connection_);
16141 // Send INITIAL 1.
16142 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16143 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
16144 // Send HANDSHAKE 2.
16145 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
16146 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
16147 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
16148 ENCRYPTION_HANDSHAKE);
16149 // Send half RTT data.
16150 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16151 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
16152 }
16153
16154 // Received ACKs for both INITIAL and HANDSHAKE packets.
martindukeba002452023-03-21 08:10:46 -070016155 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _, _, _))
Bence Békybac04052022-04-07 15:44:29 -040016156 .Times(AnyNumber());
16157 QuicFrames frames1;
16158 QuicAckFrame ack_frame1 = InitAckFrame(1);
16159 frames1.push_back(QuicFrame(&ack_frame1));
16160
16161 QuicFrames frames2;
16162 QuicAckFrame ack_frame2 =
16163 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
16164 frames2.push_back(QuicFrame(&ack_frame2));
16165 ProcessCoalescedPacket(
16166 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
16167 // Verify PTO is not armed given the only outstanding data is half RTT data.
16168 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16169}
16170
wub47bb7282022-06-14 09:40:33 -070016171TEST_P(QuicConnectionTest, CalculateNetworkBlackholeDelay) {
16172 if (!IsDefaultTestConfiguration()) {
16173 return;
16174 }
16175
16176 const QuicTime::Delta kOneSec = QuicTime::Delta::FromSeconds(1);
16177 const QuicTime::Delta kTwoSec = QuicTime::Delta::FromSeconds(2);
16178 const QuicTime::Delta kFourSec = QuicTime::Delta::FromSeconds(4);
16179
16180 // Normal case: blackhole_delay longer than path_degrading_delay +
16181 // 2*pto_delay.
16182 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
16183 kOneSec),
16184 kFourSec);
16185
16186 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
16187 kTwoSec),
16188 QuicTime::Delta::FromSeconds(5));
16189}
16190
fayangb225e172022-06-27 17:45:38 -070016191TEST_P(QuicConnectionTest, FixBytesAccountingForBufferedCoalescedPackets) {
16192 if (!connection_.version().CanSendCoalescedPackets()) {
16193 return;
16194 }
fayangb225e172022-06-27 17:45:38 -070016195 // Write is blocked.
16196 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
16197 writer_->SetWriteBlocked();
16198 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16199 QuicConnectionPeer::SendPing(&connection_);
16200 const QuicConnectionStats& stats = connection_.GetStats();
fayang4e283832022-09-01 12:47:07 -070016201 // Verify padding is accounted.
16202 EXPECT_EQ(stats.bytes_sent, connection_.max_packet_length());
fayangb225e172022-06-27 17:45:38 -070016203}
16204
fayang161ce6e2022-07-01 18:02:11 -070016205TEST_P(QuicConnectionTest, StrictAntiAmplificationLimit) {
16206 if (!connection_.version().SupportsAntiAmplificationLimit()) {
16207 return;
16208 }
16209 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
16210 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -070016211 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16212 // Verify no data can be sent at the beginning because bytes received is 0.
16213 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
16214 connection_.SendCryptoDataWithString("foo", 0);
16215 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
16216 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
16217 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16218
16219 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -070016220 GetQuicFlag(quic_anti_amplification_factor);
fayang161ce6e2022-07-01 18:02:11 -070016221 // Receives packet 1.
16222 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
16223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16224 .Times(anti_amplification_factor);
wubc9fd4292023-08-14 13:00:21 -070016225 ForceWillingAndAbleToWriteOnceForDeferSending();
fayang161ce6e2022-07-01 18:02:11 -070016226 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
16227 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16228 std::make_unique<TaggingEncrypter>(0x02));
16229 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16230 std::make_unique<TaggingEncrypter>(0x03));
16231
16232 for (size_t i = 1; i < anti_amplification_factor - 1; ++i) {
16233 connection_.SendCryptoDataWithString("foo", i * 3);
16234 }
16235 // Send an addtion packet with max_packet_size - 1.
16236 connection_.SetMaxPacketLength(connection_.max_packet_length() - 1);
16237 connection_.SendCryptoDataWithString("bar",
16238 (anti_amplification_factor - 1) * 3);
16239 EXPECT_LT(writer_->total_bytes_written(),
16240 anti_amplification_factor *
16241 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
birenroyef686222022-09-12 11:34:34 -070016242 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070016243 // 3 connection closes which will be buffered.
16244 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
16245 // Verify retransmission alarm is not set.
16246 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16247 } else {
16248 // Crypto + 3 connection closes.
16249 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
16250 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
16251 }
16252 // Try to send another packet with max_packet_size.
16253 connection_.SetMaxPacketLength(connection_.max_packet_length() + 1);
16254 connection_.SendCryptoDataWithString("bar", anti_amplification_factor * 3);
16255 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
16256 // Close connection.
16257 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
16258 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
16259 connection_.CloseConnection(
16260 QUIC_INTERNAL_ERROR, "error",
16261 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
16262 EXPECT_EQ(0u, connection_.NumQueuedPackets());
birenroyef686222022-09-12 11:34:34 -070016263 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070016264 EXPECT_LT(writer_->total_bytes_written(),
16265 anti_amplification_factor *
16266 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16267 } else {
16268 EXPECT_LT(writer_->total_bytes_written(),
16269 (anti_amplification_factor + 2) *
16270 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16271 EXPECT_GT(writer_->total_bytes_written(),
16272 (anti_amplification_factor + 1) *
16273 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
16274 }
16275}
16276
martinduke96840a02022-07-14 07:09:06 -070016277TEST_P(QuicConnectionTest, OriginalConnectionId) {
16278 set_perspective(Perspective::IS_SERVER);
16279 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
16280 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
16281 connection_.connection_id());
16282 QuicConnectionId original({0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
16283 connection_.SetOriginalDestinationConnectionId(original);
16284 EXPECT_EQ(original, connection_.GetOriginalDestinationConnectionId());
16285 // Send a 1-RTT packet to start the DiscardZeroRttDecryptionKeys timer.
16286 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16287 ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE);
martindukee6444ef2022-09-23 12:32:23 -070016288 if (connection_.version().UsesTls()) {
martinduke96840a02022-07-14 07:09:06 -070016289 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
16290 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(original));
16291 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
16292 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
16293 connection_.connection_id());
16294 } else {
16295 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), original);
16296 }
16297}
16298
martindukebae24052022-10-06 15:27:46 -070016299ACTION_P2(InstallKeys, conn, level) {
16300 uint8_t crypto_input = (level == ENCRYPTION_FORWARD_SECURE) ? 0x03 : 0x02;
16301 conn->SetEncrypter(level, std::make_unique<TaggingEncrypter>(crypto_input));
16302 conn->InstallDecrypter(
16303 level, std::make_unique<StrictTaggingDecrypter>(crypto_input));
16304 conn->SetDefaultEncryptionLevel(level);
martindukec2a33062022-09-30 16:04:13 -070016305}
16306
martindukebae24052022-10-06 15:27:46 -070016307TEST_P(QuicConnectionTest, ServerConnectionIdChangeWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070016308 if (!connection_.version().HasIetfQuicFrames()) {
16309 return;
16310 }
16311 // Call SetFromConfig so that the undecrypted packet buffer size is
16312 // initialized above zero.
16313 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
16314 QuicConfig config;
16315 connection_.SetFromConfig(config);
martindukebae24052022-10-06 15:27:46 -070016316 connection_.RemoveEncrypter(ENCRYPTION_FORWARD_SECURE);
16317 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martindukec2a33062022-09-30 16:04:13 -070016318
16319 // Send Client Initial.
16320 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16321 connection_.SendCryptoStreamData();
16322
16323 EXPECT_EQ(1u, writer_->packets_write_attempts());
martindukebae24052022-10-06 15:27:46 -070016324 // Server Handshake packet with new connection ID is buffered.
martindukec2a33062022-09-30 16:04:13 -070016325 QuicConnectionId old_id = connection_id_;
16326 connection_id_ = TestConnectionId(2);
16327 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16328 std::make_unique<TaggingEncrypter>(0x02));
16329 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
martindukec2a33062022-09-30 16:04:13 -070016330 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16331 EXPECT_EQ(connection_.connection_id(), old_id);
16332
martindukebae24052022-10-06 15:27:46 -070016333 // Server 1-RTT Packet is buffered.
16334 peer_creator_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16335 std::make_unique<TaggingEncrypter>(0x03));
16336 ProcessDataPacket(0);
16337 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 2u);
16338
martindukec2a33062022-09-30 16:04:13 -070016339 // Pretend the server Initial packet will yield the Handshake keys.
16340 EXPECT_CALL(visitor_, OnCryptoFrame(_))
16341 .Times(2)
martindukebae24052022-10-06 15:27:46 -070016342 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE))
16343 .WillOnce(InstallKeys(&connection_, ENCRYPTION_FORWARD_SECURE));
16344 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martindukec2a33062022-09-30 16:04:13 -070016345 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16346 // Two packets processed, connection ID changed.
16347 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16348 EXPECT_EQ(connection_.connection_id(), connection_id_);
16349}
16350
martindukebae24052022-10-06 15:27:46 -070016351TEST_P(QuicConnectionTest, ServerConnectionIdChangeTwiceWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070016352 if (!connection_.version().HasIetfQuicFrames()) {
16353 return;
16354 }
16355 // Call SetFromConfig so that the undecrypted packet buffer size is
16356 // initialized above zero.
16357 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
16358 QuicConfig config;
16359 connection_.SetFromConfig(config);
16360
16361 // Send Client Initial.
16362 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16363 connection_.SendCryptoStreamData();
16364
16365 EXPECT_EQ(1u, writer_->packets_write_attempts());
16366 // Server Handshake Packet Arrives with new connection ID.
16367 QuicConnectionId old_id = connection_id_;
16368 connection_id_ = TestConnectionId(2);
16369 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16370 std::make_unique<TaggingEncrypter>(0x02));
16371 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
16372 // Packet is buffered.
16373 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16374 EXPECT_EQ(connection_.connection_id(), old_id);
16375
16376 // Pretend the server Initial packet will yield the Handshake keys.
16377 EXPECT_CALL(visitor_, OnCryptoFrame(_))
martindukebae24052022-10-06 15:27:46 -070016378 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE));
martindukec2a33062022-09-30 16:04:13 -070016379 connection_id_ = TestConnectionId(1);
16380 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16381 // Handshake packet discarded because there's a different connection ID.
16382 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16383 EXPECT_EQ(connection_.connection_id(), connection_id_);
16384}
16385
fayangdbd6a302022-12-21 16:24:27 -080016386TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress) {
16387 // Test the scenario where the client validates server preferred address by
16388 // receiving PATH_RESPONSE from server preferred address.
16389 if (!connection_.version().HasIetfQuicFrames()) {
16390 return;
16391 }
fayanga0618a62022-12-28 19:31:24 -080016392 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016393 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016394 const QuicSocketAddress kNewSelfAddress =
16395 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16396 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016397 const StatelessResetToken kNewStatelessResetToken =
16398 QuicUtils::GenerateStatelessResetToken(TestConnectionId(17));
16399 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16400 EXPECT_CALL(visitor_, GetHandshakeState())
16401 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16402 // Kick off path validation of server preferred address on handshake
16403 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016404 EXPECT_CALL(visitor_,
16405 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16406 .WillOnce(Invoke([&]() {
16407 connection_.ValidatePath(
16408 std::make_unique<TestQuicPathValidationContext>(
16409 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16410 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016411 &connection_),
16412 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016413 }));
fayangdbd6a302022-12-21 16:24:27 -080016414 connection_.OnHandshakeComplete();
16415 EXPECT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016416 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16417 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016418 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016419 new_writer.last_packet_header().destination_connection_id);
16420 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016421
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 // While path validation is pending, packet is sent on default path.
16429 EXPECT_EQ(TestConnectionId(),
16430 writer_->last_packet_header().destination_connection_id);
16431 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16432 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16433 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16434
danzh8fdee2e2023-01-05 15:33:02 -080016435 // Receive path response from server preferred address.
fayangdbd6a302022-12-21 16:24:27 -080016436 QuicFrames frames;
16437 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16438 // Verify send_algorithm gets reset after migration (new sent packet is not
16439 // updated to exsting send_algorithm_).
16440 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang37765f62022-12-27 17:49:13 -080016441 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
16442 kServerPreferredAddress,
16443 ENCRYPTION_FORWARD_SECURE);
fayangdbd6a302022-12-21 16:24:27 -080016444 ASSERT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016445 EXPECT_TRUE(QuicConnectionPeer::IsDefaultPath(&connection_, kNewSelfAddress,
16446 kServerPreferredAddress));
16447 ASSERT_FALSE(new_writer.stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016448 // Verify stream data is retransmitted on new path.
16449 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016450 new_writer.last_packet_header().destination_connection_id);
16451 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016452 // Verify stateless reset token gets changed.
16453 EXPECT_FALSE(
16454 connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16455 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16456
16457 auto* retire_peer_issued_cid_alarm =
16458 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16459 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16460 // Verify client retires connection ID with sequence number 0.
16461 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16462 retire_peer_issued_cid_alarm->Fire();
fayang37765f62022-12-27 17:49:13 -080016463 EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16464 EXPECT_FALSE(
16465 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016466}
16467
16468TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress2) {
16469 // Test the scenario where the client validates server preferred address by
16470 // receiving PATH_RESPONSE from original server address.
16471 if (!connection_.version().HasIetfQuicFrames()) {
16472 return;
16473 }
fayanga0618a62022-12-28 19:31:24 -080016474 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016475 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016476 const QuicSocketAddress kNewSelfAddress =
16477 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16478 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016479 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16480 EXPECT_CALL(visitor_, GetHandshakeState())
16481 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16482 // Kick off path validation of server preferred address on handshake
16483 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016484 EXPECT_CALL(visitor_,
16485 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16486 .WillOnce(Invoke([&]() {
16487 connection_.ValidatePath(
16488 std::make_unique<TestQuicPathValidationContext>(
16489 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16490 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016491 &connection_),
16492 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016493 }));
fayangdbd6a302022-12-21 16:24:27 -080016494 connection_.OnHandshakeComplete();
16495 EXPECT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016496 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016497 QuicPathFrameBuffer payload =
fayang37765f62022-12-27 17:49:13 -080016498 new_writer.path_challenge_frames().front().data_buffer;
fayangdbd6a302022-12-21 16:24:27 -080016499 // Send data packet while path validation is pending.
16500 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016501 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016502 EXPECT_EQ(TestConnectionId(),
16503 writer_->last_packet_header().destination_connection_id);
16504 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16505
danzh8fdee2e2023-01-05 15:33:02 -080016506 // Receive path response from original server address.
fayangdbd6a302022-12-21 16:24:27 -080016507 QuicFrames frames;
16508 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
fayang37765f62022-12-27 17:49:13 -080016509 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
fayangdbd6a302022-12-21 16:24:27 -080016510 ENCRYPTION_FORWARD_SECURE);
16511 ASSERT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016512 ASSERT_FALSE(new_writer.stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016513 // Verify stream data is retransmitted on new path.
16514 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016515 new_writer.last_packet_header().destination_connection_id);
16516 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016517
16518 auto* retire_peer_issued_cid_alarm =
16519 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16520 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16521 // Verify client retires connection ID with sequence number 0.
16522 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16523 retire_peer_issued_cid_alarm->Fire();
16524
16525 // Verify another packet from original server address gets processed.
16526 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16527 frames.clear();
16528 frames.push_back(QuicFrame(frame1_));
16529 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
16530 ENCRYPTION_FORWARD_SECURE);
fayang37765f62022-12-27 17:49:13 -080016531 EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16532 EXPECT_FALSE(
16533 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016534}
16535
16536TEST_P(QuicConnectionTest, ClientFailedToValidateServerPreferredAddress) {
16537 // Test the scenario where the client fails to validate server preferred
16538 // address.
16539 if (!connection_.version().HasIetfQuicFrames()) {
16540 return;
16541 }
fayanga0618a62022-12-28 19:31:24 -080016542 QuicConfig config;
fayanga0618a62022-12-28 19:31:24 -080016543 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016544 const QuicSocketAddress kNewSelfAddress =
16545 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16546 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016547 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16548 EXPECT_CALL(visitor_, GetHandshakeState())
16549 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16550 // Kick off path validation of server preferred address on handshake
16551 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016552 EXPECT_CALL(visitor_,
16553 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16554 .WillOnce(Invoke([&]() {
16555 connection_.ValidatePath(
16556 std::make_unique<TestQuicPathValidationContext>(
16557 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16558 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016559 &connection_),
16560 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016561 }));
fayangdbd6a302022-12-21 16:24:27 -080016562 connection_.OnHandshakeComplete();
danzh8fdee2e2023-01-05 15:33:02 -080016563 EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
fayang37765f62022-12-27 17:49:13 -080016564 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16565 &connection_, kNewSelfAddress, kServerPreferredAddress));
16566 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016567
16568 // Receive mismatched path challenge from original server address.
16569 QuicFrames frames;
16570 frames.push_back(
16571 QuicFrame(QuicPathResponseFrame(99, {0, 1, 2, 3, 4, 5, 6, 7})));
fayang37765f62022-12-27 17:49:13 -080016572 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
fayangdbd6a302022-12-21 16:24:27 -080016573 ENCRYPTION_FORWARD_SECURE);
16574 ASSERT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016575 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16576 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016577
16578 // Simluate path validation times out.
16579 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16580 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16581 static_cast<TestAlarmFactory::TestAlarm*>(
16582 QuicPathValidatorPeer::retry_timer(
16583 QuicConnectionPeer::path_validator(&connection_)))
16584 ->Fire();
16585 }
16586 EXPECT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016587 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
16588 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016589 // Verify stream data is sent on the default path.
16590 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016591 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016592 EXPECT_EQ(TestConnectionId(),
16593 writer_->last_packet_header().destination_connection_id);
16594 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16595
16596 auto* retire_peer_issued_cid_alarm =
16597 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16598 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16599 // Verify client retires connection ID with sequence number 1.
16600 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
16601 retire_peer_issued_cid_alarm->Fire();
16602 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
fayang37765f62022-12-27 17:49:13 -080016603 EXPECT_FALSE(connection_.GetStats().server_preferred_address_validated);
16604 EXPECT_TRUE(
16605 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016606}
16607
fayanga0618a62022-12-28 19:31:24 -080016608TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress) {
16609 if (!connection_.version().HasIetfQuicFrames()) {
16610 return;
16611 }
fayanga0618a62022-12-28 19:31:24 -080016612 const QuicSocketAddress kNewSelfAddress =
16613 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16614 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016615 EXPECT_CALL(visitor_,
16616 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16617 .WillOnce(Invoke([&]() {
16618 connection_.ValidatePath(
16619 std::make_unique<TestQuicPathValidationContext>(
16620 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16621 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016622 &connection_),
16623 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016624 }));
fayanga0618a62022-12-28 19:31:24 -080016625 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016626 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080016627 ServerPreferredAddressInit(config);
16628 EXPECT_TRUE(connection_.HasPendingPathValidation());
16629 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16630
16631 // Send data packet while path validation is pending.
16632 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16633 // Verify the packet is sent on both paths.
16634 EXPECT_FALSE(writer_->stream_frames().empty());
16635 EXPECT_FALSE(new_writer.stream_frames().empty());
16636
16637 // Verify packet duplication stops on handshake confirmed.
16638 EXPECT_CALL(visitor_, GetHandshakeState())
16639 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16640 connection_.OnHandshakeComplete();
16641 SendPing();
16642 EXPECT_FALSE(writer_->ping_frames().empty());
16643 EXPECT_TRUE(new_writer.ping_frames().empty());
16644}
16645
16646TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress2) {
16647 if (!connection_.version().HasIetfQuicFrames()) {
16648 return;
16649 }
fayanga0618a62022-12-28 19:31:24 -080016650 const QuicSocketAddress kNewSelfAddress =
16651 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16652 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016653 EXPECT_CALL(visitor_,
16654 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16655 .WillOnce(Invoke([&]() {
16656 connection_.ValidatePath(
16657 std::make_unique<TestQuicPathValidationContext>(
16658 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16659 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016660 &connection_),
16661 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016662 }));
fayanga0618a62022-12-28 19:31:24 -080016663 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016664 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080016665 ServerPreferredAddressInit(config);
16666 EXPECT_TRUE(connection_.HasPendingPathValidation());
16667 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16668
16669 // Send data packet while path validation is pending.
16670 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16671 // Verify the packet is sent on both paths.
16672 EXPECT_FALSE(writer_->stream_frames().empty());
16673 EXPECT_FALSE(new_writer.stream_frames().empty());
16674
16675 // Simluate path validation times out.
16676 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16677 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16678 static_cast<TestAlarmFactory::TestAlarm*>(
16679 QuicPathValidatorPeer::retry_timer(
16680 QuicConnectionPeer::path_validator(&connection_)))
16681 ->Fire();
16682 }
16683 EXPECT_FALSE(connection_.HasPendingPathValidation());
16684 // Verify packet duplication stops if there is no pending validation.
16685 SendPing();
16686 EXPECT_FALSE(writer_->ping_frames().empty());
16687 EXPECT_TRUE(new_writer.ping_frames().empty());
16688}
16689
16690TEST_P(QuicConnectionTest, MaxDuplicatedPacketsSentToServerPreferredAddress) {
16691 if (!connection_.version().HasIetfQuicFrames()) {
16692 return;
16693 }
fayanga0618a62022-12-28 19:31:24 -080016694 const QuicSocketAddress kNewSelfAddress =
16695 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16696 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016697 EXPECT_CALL(visitor_,
16698 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16699 .WillOnce(Invoke([&]() {
16700 connection_.ValidatePath(
16701 std::make_unique<TestQuicPathValidationContext>(
16702 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16703 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016704 &connection_),
16705 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016706 }));
fayanga0618a62022-12-28 19:31:24 -080016707 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016708 config.SetClientConnectionOptions(QuicTagVector{kSPA2});
fayanga0618a62022-12-28 19:31:24 -080016709 ServerPreferredAddressInit(config);
16710 EXPECT_TRUE(connection_.HasPendingPathValidation());
16711 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16712
16713 // Send data packet while path validation is pending.
16714 size_t write_limit = writer_->packets_write_attempts();
16715 size_t new_write_limit = new_writer.packets_write_attempts();
16716 for (size_t i = 0; i < kMaxDuplicatedPacketsSentToServerPreferredAddress;
16717 ++i) {
16718 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
16719 // Verify the packet is sent on both paths.
16720 ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
16721 ASSERT_EQ(new_write_limit + 1, new_writer.packets_write_attempts());
16722 ++write_limit;
16723 ++new_write_limit;
16724 EXPECT_FALSE(writer_->stream_frames().empty());
16725 EXPECT_FALSE(new_writer.stream_frames().empty());
16726 }
16727
16728 // Verify packet duplication stops if duplication limit is hit.
16729 SendPing();
16730 ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
16731 ASSERT_EQ(new_write_limit, new_writer.packets_write_attempts());
16732 EXPECT_FALSE(writer_->ping_frames().empty());
16733 EXPECT_TRUE(new_writer.ping_frames().empty());
16734}
16735
danzh8fdee2e2023-01-05 15:33:02 -080016736TEST_P(QuicConnectionTest, MultiPortCreationAfterServerMigration) {
16737 if (!GetParam().version.HasIetfQuicFrames()) {
16738 return;
16739 }
16740 QuicConfig config;
fayang6aa0d532023-01-10 20:06:35 -080016741 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
danzh8fdee2e2023-01-05 15:33:02 -080016742 ServerPreferredAddressInit(config);
danzh8fdee2e2023-01-05 15:33:02 -080016743 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16744 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16745 const QuicSocketAddress kNewSelfAddress =
16746 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16747 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16748 EXPECT_CALL(visitor_,
16749 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16750 .WillOnce(Invoke([&]() {
16751 connection_.ValidatePath(
16752 std::make_unique<TestQuicPathValidationContext>(
16753 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16754 std::make_unique<ServerPreferredAddressTestResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016755 &connection_),
16756 PathValidationReason::kReasonUnknown);
danzh8fdee2e2023-01-05 15:33:02 -080016757 }));
16758 // The connection should start probing the preferred address after handshake
16759 // confirmed.
16760 QuicPathFrameBuffer payload;
16761 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16762 .Times(testing::AtLeast(1u))
16763 .WillOnce(Invoke([&]() {
16764 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
16765 payload = new_writer.path_challenge_frames().front().data_buffer;
16766 EXPECT_EQ(kServerPreferredAddress,
16767 new_writer.last_write_peer_address());
16768 }));
16769 EXPECT_CALL(visitor_, GetHandshakeState())
16770 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16771 connection_.OnHandshakeComplete();
16772 EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
16773
16774 // Receiving PATH_RESPONSE should cause the connection to migrate to the
16775 // preferred address.
16776 QuicFrames frames;
16777 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16778 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
16779 ENCRYPTION_FORWARD_SECURE);
16780 EXPECT_FALSE(connection_.IsValidatingServerPreferredAddress());
16781 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16782 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16783 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16784
16785 // As the default path changed, the server issued CID 1 should be retired.
16786 auto* retire_peer_issued_cid_alarm =
16787 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16788 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16789 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16790 retire_peer_issued_cid_alarm->Fire();
16791
16792 const QuicSocketAddress kNewSelfAddress2(kNewSelfAddress.host(),
16793 kNewSelfAddress.port() + 1);
16794 EXPECT_NE(kNewSelfAddress2, kNewSelfAddress);
16795 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
16796 QuicNewConnectionIdFrame frame;
16797 frame.connection_id = TestConnectionId(789);
16798 ASSERT_NE(frame.connection_id, connection_.connection_id());
16799 frame.stateless_reset_token =
16800 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
16801 frame.retire_prior_to = 0u;
16802 frame.sequence_number = 2u;
QUICHE team107316f2023-05-03 09:04:11 -070016803 EXPECT_CALL(visitor_, CreateContextForMultiPortPath)
QUICHE team11e17fe2023-05-12 08:21:20 -070016804 .WillOnce(testing::WithArgs<0>([&](auto&& observer) {
16805 observer->OnMultiPortPathContextAvailable(
16806 std::move(std::make_unique<TestQuicPathValidationContext>(
16807 kNewSelfAddress2, connection_.peer_address(), &new_writer2)));
QUICHE team107316f2023-05-03 09:04:11 -070016808 }));
danzh8fdee2e2023-01-05 15:33:02 -080016809 connection_.OnNewConnectionIdFrame(frame);
16810 EXPECT_TRUE(connection_.HasPendingPathValidation());
16811 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
16812 payload = new_writer.path_challenge_frames().front().data_buffer;
16813 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
16814 EXPECT_EQ(kNewSelfAddress2.host(), new_writer.last_write_source_address());
16815 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16816 &connection_, kNewSelfAddress2, connection_.peer_address()));
16817 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
16818 EXPECT_FALSE(alt_path->validated);
16819 QuicFrames frames2;
16820 frames2.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16821 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress2, kPeerAddress,
16822 ENCRYPTION_FORWARD_SECURE);
16823 EXPECT_TRUE(alt_path->validated);
16824}
16825
danzh72225ae2023-01-13 14:57:42 -080016826// Tests that after half-way server migration, the client should be able to
16827// respond to any reverse path validation from the original server address.
16828TEST_P(QuicConnectionTest, ClientReceivePathChallengeAfterServerMigration) {
16829 if (!GetParam().version.HasIetfQuicFrames()) {
16830 return;
16831 }
16832 QuicConfig config;
16833 ServerPreferredAddressInit(config);
16834 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16835 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16836 EXPECT_CALL(visitor_,
16837 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16838 .WillOnce(Invoke([&]() {
16839 connection_.AddKnownServerAddress(kServerPreferredAddress);
16840 }));
16841 EXPECT_CALL(visitor_, GetHandshakeState())
16842 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16843 connection_.OnHandshakeComplete();
16844
16845 const QuicSocketAddress kNewSelfAddress =
16846 QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1);
16847 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16848 auto context = std::make_unique<TestQuicPathValidationContext>(
16849 kNewSelfAddress, kServerPreferredAddress, &new_writer);
16850 // Pretend that the validation already succeeded. And start to use the server
16851 // preferred address.
16852 connection_.OnServerPreferredAddressValidated(*context, false);
16853 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16854 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16855 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16856 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16857 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
16858 send_algorithm_);
16859 // Switch to use a mock send algorithm.
16860 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
16861 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
16862 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
16863 .WillRepeatedly(Return(kDefaultTCPMSS));
16864 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
16865 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
16866 .Times(AnyNumber())
16867 .WillRepeatedly(Return(QuicBandwidth::Zero()));
16868 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
16869 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
16870 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
16871 connection_.SetSendAlgorithm(send_algorithm_);
16872
16873 // As the default path changed, the server issued CID 123 should be retired.
16874 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
16875 auto* retire_peer_issued_cid_alarm =
16876 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16877 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16878 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16879 retire_peer_issued_cid_alarm->Fire();
16880
16881 // Receive PATH_CHALLENGE from the original server
16882 // address. The client connection responds it on the default path.
16883 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
16884 QuicFrames frames1;
16885 frames1.push_back(
16886 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
16887 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16888 .Times(AtLeast(1))
16889 .WillOnce(Invoke([&]() {
16890 ASSERT_FALSE(new_writer.path_response_frames().empty());
16891 EXPECT_EQ(
16892 0, memcmp(&path_challenge_payload,
16893 &(new_writer.path_response_frames().front().data_buffer),
16894 sizeof(path_challenge_payload)));
16895 EXPECT_EQ(kServerPreferredAddress,
16896 new_writer.last_write_peer_address());
16897 EXPECT_EQ(kNewSelfAddress.host(),
16898 new_writer.last_write_source_address());
16899 }));
16900 ProcessFramesPacketWithAddresses(frames1, kNewSelfAddress, kPeerAddress,
16901 ENCRYPTION_FORWARD_SECURE);
16902}
16903
16904// Tests that after half-way server migration, the client should be able to
16905// probe with a different socket and respond to reverse path validation.
16906TEST_P(QuicConnectionTest, ClientProbesAfterServerMigration) {
16907 if (!GetParam().version.HasIetfQuicFrames()) {
16908 return;
16909 }
16910 QuicConfig config;
16911 ServerPreferredAddressInit(config);
16912 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16913 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16914
16915 // The connection should start probing the preferred address after handshake
16916 // confirmed.
16917 EXPECT_CALL(visitor_,
16918 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16919 .WillOnce(Invoke([&]() {
16920 connection_.AddKnownServerAddress(kServerPreferredAddress);
16921 }));
16922 EXPECT_CALL(visitor_, GetHandshakeState())
16923 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16924 connection_.OnHandshakeComplete();
16925
16926 const QuicSocketAddress kNewSelfAddress =
16927 QuicSocketAddress(QuicIpAddress::Loopback6(), kTestPort + 1);
16928 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16929 auto context = std::make_unique<TestQuicPathValidationContext>(
16930 kNewSelfAddress, kServerPreferredAddress, &new_writer);
16931 // Pretend that the validation already succeeded.
16932 connection_.OnServerPreferredAddressValidated(*context, false);
16933 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16934 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16935 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16936 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16937 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
16938 send_algorithm_);
16939 // Switch to use a mock send algorithm.
16940 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
16941 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
16942 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
16943 .WillRepeatedly(Return(kDefaultTCPMSS));
16944 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
16945 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
16946 .Times(AnyNumber())
16947 .WillRepeatedly(Return(QuicBandwidth::Zero()));
16948 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
16949 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
16950 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
16951 connection_.SetSendAlgorithm(send_algorithm_);
16952
16953 // Receiving data from the original server address should not change the peer
16954 // address.
16955 EXPECT_CALL(visitor_, OnCryptoFrame(_));
16956 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kNewSelfAddress,
16957 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
16958 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16959 EXPECT_EQ(kServerPreferredAddress, connection_.peer_address());
16960
16961 // As the default path changed, the server issued CID 123 should be retired.
16962 auto* retire_peer_issued_cid_alarm =
16963 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16964 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16965 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16966 retire_peer_issued_cid_alarm->Fire();
16967
16968 // Receiving a new CID from the server.
16969 QuicNewConnectionIdFrame new_cid_frame1;
16970 new_cid_frame1.connection_id = TestConnectionId(456);
16971 ASSERT_NE(new_cid_frame1.connection_id, connection_.connection_id());
16972 new_cid_frame1.stateless_reset_token =
16973 QuicUtils::GenerateStatelessResetToken(new_cid_frame1.connection_id);
16974 new_cid_frame1.retire_prior_to = 0u;
16975 new_cid_frame1.sequence_number = 2u;
16976 connection_.OnNewConnectionIdFrame(new_cid_frame1);
16977
16978 // Probe from a new socket.
16979 const QuicSocketAddress kNewSelfAddress2 =
16980 QuicSocketAddress(QuicIpAddress::Loopback4(), kTestPort + 2);
16981 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
16982 bool success;
16983 QuicPathFrameBuffer payload;
16984 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16985 .Times(testing::AtLeast(1u))
16986 .WillOnce(Invoke([&]() {
16987 EXPECT_EQ(1u, new_writer2.path_challenge_frames().size());
16988 payload = new_writer2.path_challenge_frames().front().data_buffer;
16989 EXPECT_EQ(kServerPreferredAddress,
16990 new_writer2.last_write_peer_address());
16991 EXPECT_EQ(kNewSelfAddress2.host(),
16992 new_writer2.last_write_source_address());
16993 }));
16994 connection_.ValidatePath(
16995 std::make_unique<TestQuicPathValidationContext>(
16996 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
16997 std::make_unique<TestValidationResultDelegate>(
renjietange499db42023-01-17 15:42:33 -080016998 &connection_, kNewSelfAddress2, connection_.peer_address(), &success),
16999 PathValidationReason::kServerPreferredAddressMigration);
danzh72225ae2023-01-13 14:57:42 -080017000 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
17001 &connection_, kNewSelfAddress2, kServerPreferredAddress));
17002
17003 // Our server implementation will send PATH_CHALLENGE from the original server
17004 // address. The client connection send PATH_RESPONSE to the default peer
17005 // address.
17006 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
17007 QuicFrames frames;
17008 frames.push_back(
17009 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
17010 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
17011 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17012 .Times(AtLeast(1))
17013 .WillOnce(Invoke([&]() {
17014 EXPECT_FALSE(new_writer2.path_response_frames().empty());
17015 EXPECT_EQ(
17016 0, memcmp(&path_challenge_payload,
17017 &(new_writer2.path_response_frames().front().data_buffer),
17018 sizeof(path_challenge_payload)));
17019 EXPECT_EQ(kServerPreferredAddress,
17020 new_writer2.last_write_peer_address());
17021 EXPECT_EQ(kNewSelfAddress2.host(),
17022 new_writer2.last_write_source_address());
17023 }));
17024 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress2, kPeerAddress,
17025 ENCRYPTION_FORWARD_SECURE);
17026 EXPECT_TRUE(success);
17027}
17028
martindukefcfa32a2023-01-12 10:04:44 -080017029TEST_P(QuicConnectionTest, EcnMarksCorrectlyRecorded) {
17030 set_perspective(Perspective::IS_SERVER);
martindukefcfa32a2023-01-12 10:04:44 -080017031 QuicFrames frames;
martindukef33b1da2023-01-12 14:14:29 -080017032 frames.push_back(QuicFrame(QuicPingFrame()));
17033 frames.push_back(QuicFrame(QuicPaddingFrame(7)));
17034 QuicAckFrame ack_frame =
17035 connection_.SupportsMultiplePacketNumberSpaces()
17036 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17037 : connection_.received_packet_manager().ack_frame();
17038 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17039
17040 ProcessFramesPacketAtLevelWithEcn(1, frames, ENCRYPTION_FORWARD_SECURE,
17041 ECN_ECT0);
17042 ack_frame =
17043 connection_.SupportsMultiplePacketNumberSpaces()
17044 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17045 : connection_.received_packet_manager().ack_frame();
martinduke01ee3222023-03-08 17:08:09 -080017046 // Send two PINGs so that the ACK goes too. The second packet should not
17047 // include an ACK, which checks that the packet state is cleared properly.
17048 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17049 if (connection_.version().HasIetfQuicFrames()) {
17050 QuicConnectionPeer::SendPing(&connection_);
17051 QuicConnectionPeer::SendPing(&connection_);
17052 }
17053 QuicConnectionStats stats = connection_.GetStats();
martindukef8b97fc2024-02-06 12:11:57 -080017054 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17055 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17056 EXPECT_EQ(stats.num_ack_frames_sent_with_ecn,
17057 connection_.version().HasIetfQuicFrames() ? 1 : 0);
martinduke01ee3222023-03-08 17:08:09 -080017058 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 1);
17059 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
17060 EXPECT_EQ(stats.num_ecn_marks_received.ce, 0);
martindukefcfa32a2023-01-12 10:04:44 -080017061}
17062
martindukef33b1da2023-01-12 14:14:29 -080017063TEST_P(QuicConnectionTest, EcnMarksCoalescedPacket) {
martindukef8b97fc2024-02-06 12:11:57 -080017064 if (!connection_.version().CanSendCoalescedPackets()) {
martindukef33b1da2023-01-12 14:14:29 -080017065 return;
17066 }
17067 QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"};
17068 QuicFrames frames1;
17069 frames1.push_back(QuicFrame(&crypto_frame1));
17070 QuicFrames frames2;
17071 QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"};
17072 frames2.push_back(QuicFrame(&crypto_frame2));
17073 std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE},
17074 {3, frames2, ENCRYPTION_FORWARD_SECURE}};
17075 QuicAckFrame ack_frame =
17076 connection_.SupportsMultiplePacketNumberSpaces()
17077 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17078 : connection_.received_packet_manager().ack_frame();
17079 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17080 ack_frame =
17081 connection_.SupportsMultiplePacketNumberSpaces()
17082 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17083 : connection_.received_packet_manager().ack_frame();
17084 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17085 // Deliver packets.
17086 connection_.SetEncrypter(
17087 ENCRYPTION_HANDSHAKE,
17088 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
17089 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
17090 ProcessCoalescedPacket(packets, ECN_ECT0);
martinduke01ee3222023-03-08 17:08:09 -080017091 // Send two PINGs so that the ACKs go too.
17092 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17093 if (connection_.version().HasIetfQuicFrames()) {
17094 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
17095 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
17096 QuicConnectionPeer::SendPing(&connection_);
17097 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
17098 QuicConnectionPeer::SendPing(&connection_);
17099 }
17100 QuicConnectionStats stats = connection_.GetStats();
martindukef33b1da2023-01-12 14:14:29 -080017101 ack_frame =
17102 connection_.SupportsMultiplePacketNumberSpaces()
17103 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17104 : connection_.received_packet_manager().ack_frame();
17105 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17106 EXPECT_EQ(ack_frame.ecn_counters->ect0,
17107 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2);
17108 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17109 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17110 ? connection_.received_packet_manager().GetAckFrame(
17111 APPLICATION_DATA)
17112 : connection_.received_packet_manager().ack_frame();
17113 EXPECT_TRUE(ack_frame.ecn_counters.has_value());
17114 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17115 }
martindukef8b97fc2024-02-06 12:11:57 -080017116 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2);
17117 EXPECT_EQ(stats.num_ack_frames_sent_with_ecn,
17118 connection_.version().HasIetfQuicFrames() ? 2 : 0);
martinduke01ee3222023-03-08 17:08:09 -080017119 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
17120 EXPECT_EQ(stats.num_ecn_marks_received.ce, 0);
martindukef33b1da2023-01-12 14:14:29 -080017121}
17122
17123TEST_P(QuicConnectionTest, EcnMarksUndecryptableCoalescedPacket) {
martindukef8b97fc2024-02-06 12:11:57 -080017124 if (!connection_.version().CanSendCoalescedPackets()) {
martindukef33b1da2023-01-12 14:14:29 -080017125 return;
17126 }
17127 // SetFromConfig is always called after construction from InitializeSession.
17128 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
17129 QuicConfig config;
17130 config.set_max_undecryptable_packets(100);
17131 connection_.SetFromConfig(config);
17132 QuicCryptoFrame crypto_frame1{ENCRYPTION_HANDSHAKE, 0, "foo"};
17133 QuicFrames frames1;
17134 frames1.push_back(QuicFrame(&crypto_frame1));
17135 QuicFrames frames2;
17136 QuicCryptoFrame crypto_frame2{ENCRYPTION_FORWARD_SECURE, 0, "bar"};
17137 frames2.push_back(QuicFrame(&crypto_frame2));
17138 std::vector<PacketInfo> packets = {{2, frames1, ENCRYPTION_HANDSHAKE},
17139 {3, frames2, ENCRYPTION_FORWARD_SECURE}};
17140 char coalesced_buffer[kMaxOutgoingPacketSize];
17141 size_t coalesced_size = 0;
17142 for (const auto& packet : packets) {
17143 QuicPacketHeader header =
17144 ConstructPacketHeader(packet.packet_number, packet.level);
17145 // Set the correct encryption level and encrypter on peer_creator and
17146 // peer_framer, respectively.
17147 peer_creator_.set_encryption_level(packet.level);
17148 peer_framer_.SetEncrypter(packet.level,
17149 std::make_unique<TaggingEncrypter>(packet.level));
17150 // Set the corresponding decrypter.
17151 if (packet.level == ENCRYPTION_HANDSHAKE) {
17152 connection_.SetEncrypter(
17153 packet.level, std::make_unique<TaggingEncrypter>(packet.level));
17154 connection_.SetDefaultEncryptionLevel(packet.level);
17155 SetDecrypter(packet.level,
17156 std::make_unique<StrictTaggingDecrypter>(packet.level));
17157 }
17158 // Forward Secure packet is undecryptable.
17159 std::unique_ptr<QuicPacket> constructed_packet(
17160 ConstructPacket(header, packet.frames));
17161
17162 char buffer[kMaxOutgoingPacketSize];
17163 size_t encrypted_length = peer_framer_.EncryptPayload(
17164 packet.level, QuicPacketNumber(packet.packet_number),
17165 *constructed_packet, buffer, kMaxOutgoingPacketSize);
17166 QUICHE_DCHECK_LE(coalesced_size + encrypted_length, kMaxOutgoingPacketSize);
17167 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
17168 coalesced_size += encrypted_length;
17169 }
17170 QuicAckFrame ack_frame =
17171 connection_.SupportsMultiplePacketNumberSpaces()
17172 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17173 : connection_.received_packet_manager().ack_frame();
17174 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17175 ack_frame =
17176 connection_.SupportsMultiplePacketNumberSpaces()
17177 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17178 : connection_.received_packet_manager().ack_frame();
17179 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17180 // Deliver packets, but first remove the Forward Secure decrypter so that
17181 // packet has to be buffered.
17182 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
17183 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
17184 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
17185 connection_.ProcessUdpPacket(
17186 kSelfAddress, kPeerAddress,
17187 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(), false,
17188 0, true, nullptr, 0, true, ECN_ECT0));
17189 if (connection_.GetSendAlarm()->IsSet()) {
17190 connection_.GetSendAlarm()->Fire();
17191 }
17192 ack_frame =
17193 connection_.SupportsMultiplePacketNumberSpaces()
17194 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17195 : connection_.received_packet_manager().ack_frame();
17196 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17197 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17198 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17199 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17200 ? connection_.received_packet_manager().GetAckFrame(
17201 APPLICATION_DATA)
17202 : connection_.received_packet_manager().ack_frame();
17203 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17204 }
17205 // Send PING packet with ECN_CE, which will change the ECN codepoint in
17206 // last_received_packet_info_.
17207 ProcessFramePacketAtLevelWithEcn(4, QuicFrame(QuicPingFrame()),
17208 ENCRYPTION_HANDSHAKE, ECN_CE);
17209 ack_frame =
17210 connection_.SupportsMultiplePacketNumberSpaces()
17211 ? connection_.received_packet_manager().GetAckFrame(HANDSHAKE_DATA)
17212 : connection_.received_packet_manager().ack_frame();
17213 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17214 EXPECT_EQ(ack_frame.ecn_counters->ect0, 1);
17215 EXPECT_EQ(ack_frame.ecn_counters->ce, 1);
17216 if (connection_.SupportsMultiplePacketNumberSpaces()) {
17217 ack_frame = connection_.SupportsMultiplePacketNumberSpaces()
17218 ? connection_.received_packet_manager().GetAckFrame(
17219 APPLICATION_DATA)
17220 : connection_.received_packet_manager().ack_frame();
17221 EXPECT_FALSE(ack_frame.ecn_counters.has_value());
17222 }
17223 // Install decrypter for ENCRYPTION_FORWARD_SECURE. Make sure the original
17224 // ECN codepoint is incremented.
17225 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
17226 SetDecrypter(
17227 ENCRYPTION_FORWARD_SECURE,
17228 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
17229 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
17230 ack_frame =
17231 connection_.SupportsMultiplePacketNumberSpaces()
17232 ? connection_.received_packet_manager().GetAckFrame(APPLICATION_DATA)
17233 : connection_.received_packet_manager().ack_frame();
17234 ASSERT_TRUE(ack_frame.ecn_counters.has_value());
17235 // Should be recorded as ECT(0), not CE.
17236 EXPECT_EQ(ack_frame.ecn_counters->ect0,
17237 connection_.SupportsMultiplePacketNumberSpaces() ? 1 : 2);
martinduke01ee3222023-03-08 17:08:09 -080017238 QuicConnectionStats stats = connection_.GetStats();
martindukef8b97fc2024-02-06 12:11:57 -080017239 EXPECT_EQ(stats.num_ecn_marks_received.ect0, 2);
martinduke01ee3222023-03-08 17:08:09 -080017240 EXPECT_EQ(stats.num_ecn_marks_received.ect1, 0);
martindukef8b97fc2024-02-06 12:11:57 -080017241 EXPECT_EQ(stats.num_ecn_marks_received.ce, 1);
martindukef33b1da2023-01-12 14:14:29 -080017242}
17243
martinduke0bfe7322023-01-18 07:36:34 -080017244TEST_P(QuicConnectionTest, ReceivedPacketInfoDefaults) {
martinduke74528e52023-01-13 12:24:21 -080017245 EXPECT_TRUE(QuicConnectionPeer::TestLastReceivedPacketInfoDefaults());
17246}
17247
danzhb159ab02023-01-30 10:58:46 -080017248TEST_P(QuicConnectionTest, DetectMigrationToPreferredAddress) {
17249 if (!GetParam().version.HasIetfQuicFrames()) {
17250 return;
17251 }
17252 ServerHandlePreferredAddressInit();
17253
17254 // Issue a new server CID associated with the preferred address.
17255 QuicConnectionId server_issued_cid_for_preferred_address =
17256 TestConnectionId(17);
17257 EXPECT_CALL(connection_id_generator_,
17258 GenerateNextConnectionId(connection_id_))
17259 .WillOnce(Return(server_issued_cid_for_preferred_address));
17260 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
vasilvv243b2622023-11-07 17:01:30 -080017261 std::optional<QuicNewConnectionIdFrame> frame =
danzhb159ab02023-01-30 10:58:46 -080017262 connection_.MaybeIssueNewConnectionIdForPreferredAddress();
17263 ASSERT_TRUE(frame.has_value());
17264
17265 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
17266 ASSERT_EQ(packet_creator->GetDestinationConnectionId(),
17267 connection_.client_connection_id());
17268 ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_);
17269
17270 // Process a packet received at the preferred Address.
17271 peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address);
17272 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17273 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17274 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17275 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17276 // The server migrates half-way with the default path unchanged, and
17277 // continuing with the client issued CID 1.
17278 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17279 EXPECT_EQ(kSelfAddress, connection_.self_address());
17280
17281 // The peer retires CID 123.
17282 QuicRetireConnectionIdFrame retire_cid_frame;
17283 retire_cid_frame.sequence_number = 0u;
17284 EXPECT_CALL(connection_id_generator_,
17285 GenerateNextConnectionId(server_issued_cid_for_preferred_address))
17286 .WillOnce(Return(TestConnectionId(456)));
17287 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
17288 EXPECT_CALL(visitor_, SendNewConnectionId(_));
17289 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(retire_cid_frame));
17290
17291 // Process another packet received at Preferred Address.
17292 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17293 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17294 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
17295 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17296 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17297 EXPECT_EQ(kSelfAddress, connection_.self_address());
17298}
17299
17300TEST_P(QuicConnectionTest,
17301 DetectSimutanuousServerAndClientAddressChangeWithProbe) {
17302 if (!GetParam().version.HasIetfQuicFrames()) {
17303 return;
17304 }
17305 ServerHandlePreferredAddressInit();
17306
17307 // Issue a new server CID associated with the preferred address.
17308 QuicConnectionId server_issued_cid_for_preferred_address =
17309 TestConnectionId(17);
17310 EXPECT_CALL(connection_id_generator_,
17311 GenerateNextConnectionId(connection_id_))
17312 .WillOnce(Return(server_issued_cid_for_preferred_address));
17313 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(true));
vasilvv243b2622023-11-07 17:01:30 -080017314 std::optional<QuicNewConnectionIdFrame> frame =
danzhb159ab02023-01-30 10:58:46 -080017315 connection_.MaybeIssueNewConnectionIdForPreferredAddress();
17316 ASSERT_TRUE(frame.has_value());
17317
17318 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
17319 ASSERT_EQ(packet_creator->GetSourceConnectionId(), connection_id_);
17320 ASSERT_EQ(packet_creator->GetDestinationConnectionId(),
17321 connection_.client_connection_id());
17322
17323 // Receiving a probing packet from a new client address to the preferred
17324 // address.
17325 peer_creator_.SetServerConnectionId(server_issued_cid_for_preferred_address);
17326 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
17327 /*port=*/34567);
17328 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
17329 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
17330 QuicEncryptedPacket(probing_packet->encrypted_buffer,
17331 probing_packet->encrypted_length),
17332 clock_.Now()));
17333 uint64_t num_probing_received =
17334 connection_.GetStats().num_connectivity_probing_received;
17335 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
17336 .Times(AtLeast(1u))
17337 .WillOnce(Invoke([&]() {
17338 EXPECT_EQ(1u, writer_->path_response_frames().size());
17339 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
fayang1f578d32023-03-20 11:36:15 -070017340 // The responses should be sent from preferred address given server
17341 // has not received packet on original address from the new client
17342 // address.
17343 EXPECT_EQ(kServerPreferredAddress.host(),
17344 writer_->last_write_source_address());
danzhb159ab02023-01-30 10:58:46 -080017345 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
awillia202240c2024-07-08 09:47:00 -070017346 }))
17347 .WillRepeatedly(DoDefault());
danzhb159ab02023-01-30 10:58:46 -080017348 ProcessReceivedPacket(kServerPreferredAddress, kNewPeerAddress, *received);
17349 EXPECT_EQ(num_probing_received + 1,
17350 connection_.GetStats().num_connectivity_probing_received);
17351 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
17352 kNewPeerAddress));
17353 EXPECT_LT(0u, QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
17354 EXPECT_EQ(received->length(),
17355 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
17356 EXPECT_EQ(kPeerAddress, connection_.peer_address());
17357 EXPECT_EQ(kSelfAddress, connection_.self_address());
17358
17359 // Process a data packet received at the preferred Address from the new client
17360 // address.
17361 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
17362 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17363 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17364 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
17365 // The server migrates half-way with the new peer address but the same default
17366 // self address.
17367 EXPECT_EQ(kSelfAddress.host(), writer_->last_write_source_address());
17368 EXPECT_EQ(kSelfAddress, connection_.self_address());
17369 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
17370 EXPECT_TRUE(connection_.HasPendingPathValidation());
17371 EXPECT_FALSE(QuicConnectionPeer::GetDefaultPath(&connection_)->validated);
17372 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(&connection_, kSelfAddress,
17373 kPeerAddress));
17374 EXPECT_EQ(packet_creator->GetSourceConnectionId(),
17375 server_issued_cid_for_preferred_address);
17376
17377 // Process another packet received at the preferred Address.
17378 EXPECT_CALL(visitor_, OnCryptoFrame(_));
17379 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kServerPreferredAddress,
17380 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
17381 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
fayang1f578d32023-03-20 11:36:15 -070017382 EXPECT_EQ(kServerPreferredAddress.host(),
17383 writer_->last_write_source_address());
danzhb159ab02023-01-30 10:58:46 -080017384 EXPECT_EQ(kSelfAddress, connection_.self_address());
17385}
17386
martinduke007b2ca2023-04-10 10:43:38 -070017387TEST_P(QuicConnectionTest, EcnCodepointsRejected) {
martinduke0643ea92023-12-06 13:16:20 -080017388 SetQuicRestartFlag(quic_support_ect1, true);
martinduke007b2ca2023-04-10 10:43:38 -070017389 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke007b2ca2023-04-10 10:43:38 -070017390 if (ecn == ECN_ECT0) {
martinduke57c456d2023-12-01 12:34:18 -080017391 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(false));
martinduke007b2ca2023-04-10 10:43:38 -070017392 } else if (ecn == ECN_ECT1) {
martinduke57c456d2023-12-01 12:34:18 -080017393 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(false));
martinduke007b2ca2023-04-10 10:43:38 -070017394 }
martinduke039c1552023-05-23 16:10:57 -070017395 if (ecn == ECN_NOT_ECT) {
17396 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17397 } else {
17398 EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17399 }
17400 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduke007b2ca2023-04-10 10:43:38 -070017401 EXPECT_CALL(connection_, OnSerializedPacket(_));
17402 SendPing();
martinduke007b2ca2023-04-10 10:43:38 -070017403 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17404 }
17405}
17406
17407TEST_P(QuicConnectionTest, EcnCodepointsAccepted) {
martinduke0643ea92023-12-06 13:16:20 -080017408 SetQuicRestartFlag(quic_support_ect1, true);
martinduke007b2ca2023-04-10 10:43:38 -070017409 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke007b2ca2023-04-10 10:43:38 -070017410 if (ecn == ECN_ECT0) {
martinduke57c456d2023-12-01 12:34:18 -080017411 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martinduke007b2ca2023-04-10 10:43:38 -070017412 } else if (ecn == ECN_ECT1) {
martinduke57c456d2023-12-01 12:34:18 -080017413 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke007b2ca2023-04-10 10:43:38 -070017414 }
martinduke039c1552023-05-23 16:10:57 -070017415 if (ecn == ECN_CE) {
17416 EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
17417 } else {
17418 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
17419 }
martinduke007b2ca2023-04-10 10:43:38 -070017420 EXPECT_CALL(connection_, OnSerializedPacket(_));
17421 SendPing();
17422 QuicEcnCodepoint expected_codepoint = ecn;
17423 if (ecn == ECN_CE) {
martinduke039c1552023-05-23 16:10:57 -070017424 expected_codepoint = ECN_ECT1;
martinduke007b2ca2023-04-10 10:43:38 -070017425 }
martinduke039c1552023-05-23 16:10:57 -070017426 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
martinduke007b2ca2023-04-10 10:43:38 -070017427 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
17428 }
17429}
17430
martinduked2d9e7b2023-04-20 14:13:01 -070017431TEST_P(QuicConnectionTest, EcnCodepointsRejectedIfFlagIsFalse) {
martinduke0643ea92023-12-06 13:16:20 -080017432 SetQuicRestartFlag(quic_support_ect1, false);
martinduked2d9e7b2023-04-20 14:13:01 -070017433 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke039c1552023-05-23 16:10:57 -070017434 EXPECT_FALSE(connection_.set_ecn_codepoint(ecn));
martinduked2d9e7b2023-04-20 14:13:01 -070017435 EXPECT_CALL(connection_, OnSerializedPacket(_));
17436 SendPing();
martindukeacfdb392023-05-23 15:23:55 -070017437 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduked2d9e7b2023-04-20 14:13:01 -070017438 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
17439 }
17440}
17441
martinduke007b2ca2023-04-10 10:43:38 -070017442TEST_P(QuicConnectionTest, EcnValidationDisabled) {
martinduke0643ea92023-12-06 13:16:20 -080017443 SetQuicRestartFlag(quic_support_ect1, true);
martinduke007b2ca2023-04-10 10:43:38 -070017444 QuicConnectionPeer::DisableEcnCodepointValidation(&connection_);
17445 for (QuicEcnCodepoint ecn : {ECN_NOT_ECT, ECN_ECT0, ECN_ECT1, ECN_CE}) {
martinduke039c1552023-05-23 16:10:57 -070017446 EXPECT_TRUE(connection_.set_ecn_codepoint(ecn));
martinduke007b2ca2023-04-10 10:43:38 -070017447 EXPECT_CALL(connection_, OnSerializedPacket(_));
17448 SendPing();
martindukeacfdb392023-05-23 15:23:55 -070017449 EXPECT_EQ(connection_.ecn_codepoint(), ecn);
martinduke007b2ca2023-04-10 10:43:38 -070017450 EXPECT_EQ(writer_->last_ecn_sent(), ecn);
17451 }
17452}
17453
martinduked2d9e7b2023-04-20 14:13:01 -070017454TEST_P(QuicConnectionTest, RtoDisablesEcnMarking) {
martinduke0643ea92023-12-06 13:16:20 -080017455 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017456 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017457 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martinduked2d9e7b2023-04-20 14:13:01 -070017458 QuicPacketCreatorPeer::SetPacketNumber(
17459 QuicConnectionPeer::GetPacketCreator(&connection_), 1);
17460 SendPing();
vasilvva7d7d442024-05-31 09:42:40 -070017461 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017462 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
martindukeacfdb392023-05-23 15:23:55 -070017463 EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1);
martinduked2d9e7b2023-04-20 14:13:01 -070017464 // On 2nd RTO, QUIC abandons ECN.
vasilvva7d7d442024-05-31 09:42:40 -070017465 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017466 EXPECT_EQ(writer_->last_ecn_sent(), ECN_NOT_ECT);
martindukeacfdb392023-05-23 15:23:55 -070017467 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduked2d9e7b2023-04-20 14:13:01 -070017468}
17469
17470TEST_P(QuicConnectionTest, RtoDoesntDisableEcnMarkingIfEcnAcked) {
martinduke0643ea92023-12-06 13:16:20 -080017471 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017472 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017473 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martinduked2d9e7b2023-04-20 14:13:01 -070017474 QuicPacketCreatorPeer::SetPacketNumber(
17475 QuicConnectionPeer::GetPacketCreator(&connection_), 1);
martinduke0643ea92023-12-06 13:16:20 -080017476 connection_.OnInFlightEcnPacketAcked();
martinduked2d9e7b2023-04-20 14:13:01 -070017477 SendPing();
17478 // Because an ECN packet was acked, PTOs have no effect on ECN settings.
vasilvva7d7d442024-05-31 09:42:40 -070017479 connection_.OnRetransmissionAlarm();
martinduke0643ea92023-12-06 13:16:20 -080017480 QuicEcnCodepoint expected_codepoint = ECN_ECT1;
martinduked2d9e7b2023-04-20 14:13:01 -070017481 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
martindukeacfdb392023-05-23 15:23:55 -070017482 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
vasilvva7d7d442024-05-31 09:42:40 -070017483 connection_.OnRetransmissionAlarm();
martinduked2d9e7b2023-04-20 14:13:01 -070017484 EXPECT_EQ(writer_->last_ecn_sent(), expected_codepoint);
martindukeacfdb392023-05-23 15:23:55 -070017485 EXPECT_EQ(connection_.ecn_codepoint(), expected_codepoint);
martinduked2d9e7b2023-04-20 14:13:01 -070017486}
17487
17488TEST_P(QuicConnectionTest, InvalidFeedbackCancelsEcn) {
martinduke0643ea92023-12-06 13:16:20 -080017489 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017490 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017491 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukeacfdb392023-05-23 15:23:55 -070017492 EXPECT_EQ(connection_.ecn_codepoint(), ECN_ECT1);
martinduke0643ea92023-12-06 13:16:20 -080017493 connection_.OnInvalidEcnFeedback();
martindukeacfdb392023-05-23 15:23:55 -070017494 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
martinduked2d9e7b2023-04-20 14:13:01 -070017495}
17496
martindukec0da7642023-05-04 17:23:22 -070017497TEST_P(QuicConnectionTest, StateMatchesSentEcn) {
martinduke0643ea92023-12-06 13:16:20 -080017498 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017499 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017500 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017501 SendPing();
17502 QuicSentPacketManager* sent_packet_manager =
17503 QuicConnectionPeer::GetSentPacketManager(&connection_);
17504 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1);
17505 EXPECT_EQ(
17506 QuicSentPacketManagerPeer::GetEct1Sent(sent_packet_manager, INITIAL_DATA),
17507 1);
17508}
17509
17510TEST_P(QuicConnectionTest, CoalescedPacketSplitsEcn) {
17511 if (!connection_.version().CanSendCoalescedPackets()) {
17512 return;
17513 }
martinduke0643ea92023-12-06 13:16:20 -080017514 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017515 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017516 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017517 // All these steps are necessary to send an INITIAL ping and save it to be
17518 // coalesced, instead of just calling SendPing() and sending it immediately.
17519 char buffer[1000];
17520 creator_->set_encryption_level(ENCRYPTION_INITIAL);
17521 QuicFrames frames;
17522 QuicPingFrame ping;
17523 frames.emplace_back(QuicFrame(ping));
17524 SerializedPacket packet1 = QuicPacketCreatorPeer::SerializeAllFrames(
17525 creator_, frames, buffer, sizeof(buffer));
17526 connection_.SendOrQueuePacket(std::move(packet1));
17527 creator_->set_encryption_level(ENCRYPTION_FORWARD_SECURE);
martinduke57c456d2023-12-01 12:34:18 -080017528 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martindukec0da7642023-05-04 17:23:22 -070017529 // If not for the line below, these packets would coalesce.
martinduke039c1552023-05-23 16:10:57 -070017530 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0));
martindukec0da7642023-05-04 17:23:22 -070017531 EXPECT_EQ(writer_->packets_write_attempts(), 0);
17532 SendPing();
17533 EXPECT_EQ(writer_->packets_write_attempts(), 2);
17534 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT0);
17535}
17536
17537TEST_P(QuicConnectionTest, BufferedPacketRetainsOldEcn) {
martinduke0643ea92023-12-06 13:16:20 -080017538 SetQuicRestartFlag(quic_support_ect1, true);
martinduke57c456d2023-12-01 12:34:18 -080017539 EXPECT_CALL(*send_algorithm_, EnableECT1()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017540 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT1));
martindukec0da7642023-05-04 17:23:22 -070017541 writer_->SetWriteBlocked();
17542 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(2);
17543 SendPing();
martinduke57c456d2023-12-01 12:34:18 -080017544 EXPECT_CALL(*send_algorithm_, EnableECT0()).WillOnce(Return(true));
martinduke039c1552023-05-23 16:10:57 -070017545 EXPECT_TRUE(connection_.set_ecn_codepoint(ECN_ECT0));
martindukec0da7642023-05-04 17:23:22 -070017546 writer_->SetWritable();
17547 connection_.OnCanWrite();
17548 EXPECT_EQ(writer_->last_ecn_sent(), ECN_ECT1);
17549}
17550
martinduke514a2742023-05-23 16:58:05 -070017551TEST_P(QuicConnectionTest, RejectEcnIfWriterDoesNotSupport) {
martinduke0643ea92023-12-06 13:16:20 -080017552 SetQuicRestartFlag(quic_support_ect1, true);
martinduke514a2742023-05-23 16:58:05 -070017553 MockPacketWriter mock_writer;
17554 QuicConnectionPeer::SetWriter(&connection_, &mock_writer, false);
17555 EXPECT_CALL(mock_writer, SupportsEcn()).WillOnce(Return(false));
17556 EXPECT_FALSE(connection_.set_ecn_codepoint(ECN_ECT1));
17557 EXPECT_EQ(connection_.ecn_codepoint(), ECN_NOT_ECT);
17558}
17559
Bence Békybac04052022-04-07 15:44:29 -040017560} // namespace
17561} // namespace test
17562} // namespace quic