blob: 2a5c9c10de5534ec6b6282caa42853ac07e0e437 [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
9#include <memory>
10#include <ostream>
11#include <string>
martinduke9e0811c2022-12-08 20:35:57 -080012#include <type_traits>
Bence Békybac04052022-04-07 15:44:29 -040013#include <utility>
14
15#include "absl/base/macros.h"
16#include "absl/strings/str_cat.h"
17#include "absl/strings/str_join.h"
18#include "absl/strings/string_view.h"
19#include "quiche/quic/core/congestion_control/loss_detection_interface.h"
20#include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
21#include "quiche/quic/core/crypto/null_decrypter.h"
22#include "quiche/quic/core/crypto/null_encrypter.h"
23#include "quiche/quic/core/crypto/quic_decrypter.h"
24#include "quiche/quic/core/crypto/quic_encrypter.h"
25#include "quiche/quic/core/frames/quic_connection_close_frame.h"
26#include "quiche/quic/core/frames/quic_new_connection_id_frame.h"
27#include "quiche/quic/core/frames/quic_path_response_frame.h"
28#include "quiche/quic/core/frames/quic_rst_stream_frame.h"
29#include "quiche/quic/core/quic_connection_id.h"
30#include "quiche/quic/core/quic_constants.h"
31#include "quiche/quic/core/quic_error_codes.h"
32#include "quiche/quic/core/quic_packet_creator.h"
33#include "quiche/quic/core/quic_packets.h"
34#include "quiche/quic/core/quic_path_validator.h"
35#include "quiche/quic/core/quic_types.h"
36#include "quiche/quic/core/quic_utils.h"
37#include "quiche/quic/core/quic_versions.h"
38#include "quiche/quic/platform/api/quic_expect_bug.h"
39#include "quiche/quic/platform/api/quic_flags.h"
40#include "quiche/quic/platform/api/quic_ip_address.h"
bnc96dc1782022-09-06 08:16:01 -070041#include "quiche/quic/platform/api/quic_ip_address_family.h"
Bence Békybac04052022-04-07 15:44:29 -040042#include "quiche/quic/platform/api/quic_logging.h"
43#include "quiche/quic/platform/api/quic_socket_address.h"
44#include "quiche/quic/platform/api/quic_test.h"
45#include "quiche/quic/test_tools/mock_clock.h"
martinduke605dca22022-09-01 10:40:19 -070046#include "quiche/quic/test_tools/mock_connection_id_generator.h"
Bence Békybac04052022-04-07 15:44:29 -040047#include "quiche/quic/test_tools/mock_random.h"
48#include "quiche/quic/test_tools/quic_coalesced_packet_peer.h"
49#include "quiche/quic/test_tools/quic_config_peer.h"
50#include "quiche/quic/test_tools/quic_connection_peer.h"
51#include "quiche/quic/test_tools/quic_framer_peer.h"
52#include "quiche/quic/test_tools/quic_packet_creator_peer.h"
53#include "quiche/quic/test_tools/quic_path_validator_peer.h"
54#include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h"
55#include "quiche/quic/test_tools/quic_test_utils.h"
56#include "quiche/quic/test_tools/simple_data_producer.h"
57#include "quiche/quic/test_tools/simple_session_notifier.h"
58#include "quiche/common/platform/api/quiche_reference_counted.h"
59#include "quiche/common/simple_buffer_allocator.h"
60
61using testing::_;
62using testing::AnyNumber;
63using testing::AtLeast;
64using testing::DoAll;
65using testing::ElementsAre;
66using testing::Ge;
67using testing::IgnoreResult;
68using testing::InSequence;
69using testing::Invoke;
70using testing::InvokeWithoutArgs;
71using testing::Lt;
72using testing::Ref;
73using testing::Return;
74using testing::SaveArg;
75using testing::SetArgPointee;
76using testing::StrictMock;
77
78namespace quic {
79namespace test {
80namespace {
81
82const char data1[] = "foo data";
83const char data2[] = "bar data";
84
85const bool kHasStopWaiting = true;
86
87const int kDefaultRetransmissionTimeMs = 500;
88
89DiversificationNonce kTestDiversificationNonce = {
90 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
91 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
92 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
93};
94
95const StatelessResetToken kTestStatelessResetToken{
96 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
97 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f};
98
99const QuicSocketAddress kPeerAddress =
100 QuicSocketAddress(QuicIpAddress::Loopback6(),
101 /*port=*/12345);
102const QuicSocketAddress kSelfAddress =
103 QuicSocketAddress(QuicIpAddress::Loopback6(),
104 /*port=*/443);
danzh8fdee2e2023-01-05 15:33:02 -0800105const QuicSocketAddress kServerPreferredAddress = QuicSocketAddress(
106 []() {
107 QuicIpAddress address;
108 address.FromString("2604:31c0::");
109 return address;
110 }(),
111 /*port=*/443);
Bence Békybac04052022-04-07 15:44:29 -0400112
113QuicStreamId GetNthClientInitiatedStreamId(int n,
114 QuicTransportVersion version) {
115 return QuicUtils::GetFirstBidirectionalStreamId(version,
116 Perspective::IS_CLIENT) +
117 n * 2;
118}
119
120QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
121 switch (level) {
122 case ENCRYPTION_INITIAL:
123 return INITIAL;
124 case ENCRYPTION_HANDSHAKE:
125 return HANDSHAKE;
126 case ENCRYPTION_ZERO_RTT:
127 return ZERO_RTT_PROTECTED;
128 case ENCRYPTION_FORWARD_SECURE:
129 QUICHE_DCHECK(false);
130 return INVALID_PACKET_TYPE;
131 default:
132 QUICHE_DCHECK(false);
133 return INVALID_PACKET_TYPE;
134 }
135}
136
martinduke9e0811c2022-12-08 20:35:57 -0800137// A TaggingEncrypterWithConfidentialityLimit is a TaggingEncrypter that allows
Bence Békybac04052022-04-07 15:44:29 -0400138// specifying the confidentiality limit on the maximum number of packets that
139// may be encrypted per key phase in TLS+QUIC.
martinduke9e0811c2022-12-08 20:35:57 -0800140class TaggingEncrypterWithConfidentialityLimit : public TaggingEncrypter {
Bence Békybac04052022-04-07 15:44:29 -0400141 public:
martinduke9e0811c2022-12-08 20:35:57 -0800142 TaggingEncrypterWithConfidentialityLimit(
143 uint8_t tag, QuicPacketCount confidentiality_limit)
144 : TaggingEncrypter(tag), confidentiality_limit_(confidentiality_limit) {}
Bence Békybac04052022-04-07 15:44:29 -0400145
146 QuicPacketCount GetConfidentialityLimit() const override {
147 return confidentiality_limit_;
148 }
149
150 private:
151 QuicPacketCount confidentiality_limit_;
152};
153
154class StrictTaggingDecrypterWithIntegrityLimit : public StrictTaggingDecrypter {
155 public:
156 StrictTaggingDecrypterWithIntegrityLimit(uint8_t tag,
157 QuicPacketCount integrity_limit)
158 : StrictTaggingDecrypter(tag), integrity_limit_(integrity_limit) {}
159
160 QuicPacketCount GetIntegrityLimit() const override {
161 return integrity_limit_;
162 }
163
164 private:
165 QuicPacketCount integrity_limit_;
166};
167
168class TestConnectionHelper : public QuicConnectionHelperInterface {
169 public:
170 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
171 : clock_(clock), random_generator_(random_generator) {
172 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
173 }
174 TestConnectionHelper(const TestConnectionHelper&) = delete;
175 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
176
177 // QuicConnectionHelperInterface
178 const QuicClock* GetClock() const override { return clock_; }
179
180 QuicRandom* GetRandomGenerator() override { return random_generator_; }
181
182 quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override {
183 return &buffer_allocator_;
184 }
185
186 private:
187 MockClock* clock_;
188 MockRandom* random_generator_;
189 quiche::SimpleBufferAllocator buffer_allocator_;
190};
191
192class TestConnection : public QuicConnection {
193 public:
194 TestConnection(QuicConnectionId connection_id,
195 QuicSocketAddress initial_self_address,
196 QuicSocketAddress initial_peer_address,
197 TestConnectionHelper* helper, TestAlarmFactory* alarm_factory,
198 TestPacketWriter* writer, Perspective perspective,
martinduke605dca22022-09-01 10:40:19 -0700199 ParsedQuicVersion version,
200 ConnectionIdGeneratorInterface& generator)
Bence Békybac04052022-04-07 15:44:29 -0400201 : QuicConnection(connection_id, initial_self_address,
202 initial_peer_address, helper, alarm_factory, writer,
203 /* owns_writer= */ false, perspective,
martinduke605dca22022-09-01 10:40:19 -0700204 SupportedVersions(version), generator),
Bence Békybac04052022-04-07 15:44:29 -0400205 notifier_(nullptr) {
206 writer->set_perspective(perspective);
207 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800208 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -0400209 SetDataProducer(&producer_);
210 ON_CALL(*this, OnSerializedPacket(_))
211 .WillByDefault([this](SerializedPacket packet) {
212 QuicConnection::OnSerializedPacket(std::move(packet));
213 });
214 }
215 TestConnection(const TestConnection&) = delete;
216 TestConnection& operator=(const TestConnection&) = delete;
217
218 MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket packet), (override));
219
renjietangff3e9602022-10-25 12:16:49 -0700220 void OnEffectivePeerMigrationValidated(bool is_migration_linkable) override {
221 QuicConnection::OnEffectivePeerMigrationValidated(is_migration_linkable);
222 if (is_migration_linkable) {
223 num_linkable_client_migration_++;
224 } else {
225 num_unlinkable_client_migration_++;
226 }
227 }
228
229 uint32_t num_unlinkable_client_migration() const {
230 return num_unlinkable_client_migration_;
231 }
232
233 uint32_t num_linkable_client_migration() const {
234 return num_linkable_client_migration_;
235 }
236
Bence Békybac04052022-04-07 15:44:29 -0400237 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
238 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
239 }
240
241 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
242 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
243 }
244
245 void SendPacket(EncryptionLevel /*level*/, uint64_t packet_number,
246 std::unique_ptr<QuicPacket> packet,
247 HasRetransmittableData retransmittable, bool has_ack,
248 bool has_pending_frames) {
249 ScopedPacketFlusher flusher(this);
250 char buffer[kMaxOutgoingPacketSize];
251 size_t encrypted_length =
252 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
253 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
254 buffer, kMaxOutgoingPacketSize);
255 SerializedPacket serialized_packet(
256 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
257 encrypted_length, has_ack, has_pending_frames);
258 serialized_packet.peer_address = kPeerAddress;
259 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
260 serialized_packet.retransmittable_frames.push_back(
261 QuicFrame(QuicPingFrame()));
262 }
263 OnSerializedPacket(std::move(serialized_packet));
264 }
265
266 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
267 absl::string_view data,
268 QuicStreamOffset offset,
269 StreamSendingState state) {
QUICHE teamac0a8082022-06-13 09:17:05 -0700270 return SaveAndSendStreamData(id, data, offset, state, NOT_RETRANSMISSION);
271 }
272
273 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
274 absl::string_view data,
275 QuicStreamOffset offset,
276 StreamSendingState state,
277 TransmissionType transmission_type) {
Bence Békybac04052022-04-07 15:44:29 -0400278 ScopedPacketFlusher flusher(this);
279 producer_.SaveStreamData(id, data);
280 if (notifier_ != nullptr) {
QUICHE teamac0a8082022-06-13 09:17:05 -0700281 return notifier_->WriteOrBufferData(id, data.length(), state,
282 transmission_type);
Bence Békybac04052022-04-07 15:44:29 -0400283 }
284 return QuicConnection::SendStreamData(id, data.length(), offset, state);
285 }
286
287 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
288 absl::string_view data,
289 QuicStreamOffset offset,
290 StreamSendingState state) {
291 ScopedPacketFlusher flusher(this);
292 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
293 this->encryption_level() == ENCRYPTION_INITIAL) {
294 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
295 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
296 OnHandshakeComplete();
297 }
298 if (version().SupportsAntiAmplificationLimit()) {
299 QuicConnectionPeer::SetAddressValidated(this);
300 }
301 }
302 return SaveAndSendStreamData(id, data, offset, state);
303 }
304
305 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
306 QuicStreamId id,
307 absl::string_view data,
308 QuicStreamOffset offset,
309 StreamSendingState state) {
310 ScopedPacketFlusher flusher(this);
311 QUICHE_DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -0800312 SetEncrypter(encryption_level,
313 std::make_unique<TaggingEncrypter>(encryption_level));
Bence Békybac04052022-04-07 15:44:29 -0400314 SetDefaultEncryptionLevel(encryption_level);
315 return SaveAndSendStreamData(id, data, offset, state);
316 }
317
318 QuicConsumedData SendStreamData3() {
319 return SendStreamDataWithString(
320 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
321 NO_FIN);
322 }
323
324 QuicConsumedData SendStreamData5() {
325 return SendStreamDataWithString(
326 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
327 NO_FIN);
328 }
329
330 // Ensures the connection can write stream data before writing.
331 QuicConsumedData EnsureWritableAndSendStreamData5() {
332 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
333 return SendStreamData5();
334 }
335
336 // The crypto stream has special semantics so that it is not blocked by a
337 // congestion window limitation, and also so that it gets put into a separate
338 // packet (so that it is easier to reason about a crypto frame not being
339 // split needlessly across packet boundaries). As a result, we have separate
340 // tests for some cases for this stream.
341 QuicConsumedData SendCryptoStreamData() {
342 QuicStreamOffset offset = 0;
343 absl::string_view data("chlo");
344 if (!QuicVersionUsesCryptoFrames(transport_version())) {
345 return SendCryptoDataWithString(data, offset);
346 }
347 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
348 size_t bytes_written;
349 if (notifier_) {
350 bytes_written =
351 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
352 } else {
353 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
354 data.length(), offset);
355 }
356 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
357 }
358
359 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
360 QuicStreamOffset offset) {
361 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
362 }
363
364 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
365 QuicStreamOffset offset,
366 EncryptionLevel encryption_level) {
367 if (!QuicVersionUsesCryptoFrames(transport_version())) {
368 return SendStreamDataWithString(
369 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
370 NO_FIN);
371 }
372 producer_.SaveCryptoData(encryption_level, offset, data);
373 size_t bytes_written;
374 if (notifier_) {
375 bytes_written =
376 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
377 } else {
378 bytes_written = QuicConnection::SendCryptoData(encryption_level,
379 data.length(), offset);
380 }
381 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
382 }
383
384 void set_version(ParsedQuicVersion version) {
385 QuicConnectionPeer::GetFramer(this)->set_version(version);
386 }
387
388 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
389 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
390 writer()->SetSupportedVersions(versions);
391 }
392
393 // This should be called before setting customized encrypters/decrypters for
394 // connection and peer creator.
395 void set_perspective(Perspective perspective) {
396 writer()->set_perspective(perspective);
397 QuicConnectionPeer::ResetPeerIssuedConnectionIdManager(this);
398 QuicConnectionPeer::SetPerspective(this, perspective);
399 QuicSentPacketManagerPeer::SetPerspective(
400 QuicConnectionPeer::GetSentPacketManager(this), perspective);
401 QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators(
402 TestConnectionId());
Bence Békybac04052022-04-07 15:44:29 -0400403 }
404
405 // Enable path MTU discovery. Assumes that the test is performed from the
406 // server perspective and the higher value of MTU target is used.
407 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
408 ASSERT_EQ(Perspective::IS_SERVER, perspective());
409
410 if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) {
411 OnConfigNegotiated();
412 } else {
413 QuicConfig config;
414 QuicTagVector connection_options;
415 connection_options.push_back(kMTUH);
416 config.SetInitialReceivedConnectionOptions(connection_options);
417 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
418 SetFromConfig(config);
419 }
420
421 // Normally, the pacing would be disabled in the test, but calling
422 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
423 // pacing algorithm work.
424 EXPECT_CALL(*send_algorithm, PacingRate(_))
425 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
426 }
427
428 TestAlarmFactory::TestAlarm* GetAckAlarm() {
429 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
430 QuicConnectionPeer::GetAckAlarm(this));
431 }
432
433 TestAlarmFactory::TestAlarm* GetPingAlarm() {
434 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
435 QuicConnectionPeer::GetPingAlarm(this));
436 }
437
438 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
439 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
440 QuicConnectionPeer::GetRetransmissionAlarm(this));
441 }
442
443 TestAlarmFactory::TestAlarm* GetSendAlarm() {
444 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
445 QuicConnectionPeer::GetSendAlarm(this));
446 }
447
448 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
449 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
450 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
451 }
452
453 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
454 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
455 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
456 }
457
458 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
459 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
460 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
461 }
462
463 TestAlarmFactory::TestAlarm* GetDiscardPreviousOneRttKeysAlarm() {
464 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
465 QuicConnectionPeer::GetDiscardPreviousOneRttKeysAlarm(this));
466 }
467
468 TestAlarmFactory::TestAlarm* GetDiscardZeroRttDecryptionKeysAlarm() {
469 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
470 QuicConnectionPeer::GetDiscardZeroRttDecryptionKeysAlarm(this));
471 }
472
473 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
474 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
475 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
476 }
477
478 TestAlarmFactory::TestAlarm* GetRetirePeerIssuedConnectionIdAlarm() {
479 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
480 QuicConnectionPeer::GetRetirePeerIssuedConnectionIdAlarm(this));
481 }
482
483 TestAlarmFactory::TestAlarm* GetRetireSelfIssuedConnectionIdAlarm() {
484 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
485 QuicConnectionPeer::GetRetireSelfIssuedConnectionIdAlarm(this));
486 }
487
renjietangfca5c772022-08-25 13:48:21 -0700488 TestAlarmFactory::TestAlarm* GetMultiPortProbingAlarm() {
489 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
490 QuicConnectionPeer::GetMultiPortProbingAlarm(this));
491 }
492
Bence Békybac04052022-04-07 15:44:29 -0400493 void PathDegradingTimeout() {
494 QUICHE_DCHECK(PathDegradingDetectionInProgress());
495 GetBlackholeDetectorAlarm()->Fire();
496 }
497
498 bool PathDegradingDetectionInProgress() {
499 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
500 }
501
502 bool BlackholeDetectionInProgress() {
503 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
504 .IsInitialized();
505 }
506
507 bool PathMtuReductionDetectionInProgress() {
508 return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this)
509 .IsInitialized();
510 }
511
Bence Békybac04052022-04-07 15:44:29 -0400512 QuicByteCount GetBytesInFlight() {
513 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
514 }
515
516 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
517
518 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
519 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
520 }
521
Bence Békybac04052022-04-07 15:44:29 -0400522 void SendOrQueuePacket(SerializedPacket packet) override {
523 QuicConnection::SendOrQueuePacket(std::move(packet));
524 self_address_on_default_path_while_sending_packet_ = self_address();
525 }
526
527 QuicSocketAddress self_address_on_default_path_while_sending_packet() {
528 return self_address_on_default_path_while_sending_packet_;
529 }
530
531 SimpleDataProducer* producer() { return &producer_; }
532
533 using QuicConnection::active_effective_peer_migration_type;
534 using QuicConnection::IsCurrentPacketConnectivityProbing;
535 using QuicConnection::SelectMutualVersion;
Bence Békybac04052022-04-07 15:44:29 -0400536 using QuicConnection::set_defer_send_in_response_to_packets;
537
538 protected:
539 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
540 if (next_effective_peer_addr_) {
541 return *std::move(next_effective_peer_addr_);
542 }
543 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
544 }
545
546 private:
547 TestPacketWriter* writer() {
548 return static_cast<TestPacketWriter*>(QuicConnection::writer());
549 }
550
551 SimpleDataProducer producer_;
552
553 SimpleSessionNotifier* notifier_;
554
555 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
556
557 QuicSocketAddress self_address_on_default_path_while_sending_packet_;
renjietangff3e9602022-10-25 12:16:49 -0700558
559 uint32_t num_unlinkable_client_migration_ = 0;
560
561 uint32_t num_linkable_client_migration_ = 0;
Bence Békybac04052022-04-07 15:44:29 -0400562};
563
564enum class AckResponse { kDefer, kImmediate };
565
566// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
567struct TestParams {
568 TestParams(ParsedQuicVersion version, AckResponse ack_response,
569 bool no_stop_waiting)
570 : version(version),
571 ack_response(ack_response),
572 no_stop_waiting(no_stop_waiting) {}
573
574 ParsedQuicVersion version;
575 AckResponse ack_response;
576 bool no_stop_waiting;
577};
578
579// Used by ::testing::PrintToStringParamName().
580std::string PrintToString(const TestParams& p) {
581 return absl::StrCat(
582 ParsedQuicVersionToString(p.version), "_",
583 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
584 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
585}
586
587// Constructs various test permutations.
588std::vector<TestParams> GetTestParams() {
589 QuicFlagSaver flags;
590 std::vector<TestParams> params;
591 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
592 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
593 for (AckResponse ack_response :
594 {AckResponse::kDefer, AckResponse::kImmediate}) {
595 params.push_back(
596 TestParams(all_supported_versions[i], ack_response, true));
597 if (!all_supported_versions[i].HasIetfInvariantHeader()) {
598 params.push_back(
599 TestParams(all_supported_versions[i], ack_response, false));
600 }
601 }
602 }
603 return params;
604}
605
606class QuicConnectionTest : public QuicTestWithParam<TestParams> {
607 public:
608 // For tests that do silent connection closes, no such packet is generated. In
609 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
610 // should invoke this method, saving the frame, and then the test can verify
611 // the contents.
612 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
613 ConnectionCloseSource /*source*/) {
614 saved_connection_close_frame_ = frame;
615 connection_close_frame_count_++;
616 }
617
618 protected:
619 QuicConnectionTest()
620 : connection_id_(TestConnectionId()),
621 framer_(SupportedVersions(version()), QuicTime::Zero(),
622 Perspective::IS_CLIENT, connection_id_.length()),
623 send_algorithm_(new StrictMock<MockSendAlgorithm>),
624 loss_algorithm_(new MockLossAlgorithm()),
625 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
626 alarm_factory_(new TestAlarmFactory()),
627 peer_framer_(SupportedVersions(version()), QuicTime::Zero(),
628 Perspective::IS_SERVER, connection_id_.length()),
629 peer_creator_(connection_id_, &peer_framer_,
630 /*delegate=*/nullptr),
631 writer_(
632 new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)),
633 connection_(connection_id_, kSelfAddress, kPeerAddress, helper_.get(),
634 alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT,
martinduke605dca22022-09-01 10:40:19 -0700635 version(), connection_id_generator_),
Bence Békybac04052022-04-07 15:44:29 -0400636 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
637 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
638 frame1_(0, false, 0, absl::string_view(data1)),
639 frame2_(0, false, 3, absl::string_view(data2)),
640 crypto_frame_(ENCRYPTION_INITIAL, 0, absl::string_view(data1)),
641 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
642 connection_id_included_(CONNECTION_ID_PRESENT),
643 notifier_(&connection_),
644 connection_close_frame_count_(0) {
645 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
646 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
647 AckResponse::kDefer);
648 framer_.SetInitialObfuscators(TestConnectionId());
649 connection_.InstallInitialCrypters(TestConnectionId());
650 CrypterPair crypters;
651 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
652 TestConnectionId(), &crypters);
653 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
654 std::move(crypters.encrypter));
655 if (version().KnowsWhichDecrypterToUse()) {
656 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
657 std::move(crypters.decrypter));
658 } else {
659 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
660 std::move(crypters.decrypter));
661 }
662 for (EncryptionLevel level :
663 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
martinduke9e0811c2022-12-08 20:35:57 -0800664 peer_creator_.SetEncrypter(level,
665 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400666 }
667 QuicFramerPeer::SetLastSerializedServerConnectionId(
668 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
669 QuicFramerPeer::SetLastWrittenPacketNumberLength(
670 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
671 if (version().HasIetfInvariantHeader()) {
672 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
673 } else {
674 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
675 GetParam().no_stop_waiting);
676 }
677 QuicStreamId stream_id;
678 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
679 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
680 version().transport_version, Perspective::IS_CLIENT);
681 } else {
682 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
683 }
684 frame1_.stream_id = stream_id;
685 frame2_.stream_id = stream_id;
686 connection_.set_visitor(&visitor_);
687 connection_.SetSessionNotifier(&notifier_);
688 connection_.set_notifier(&notifier_);
689 connection_.SetSendAlgorithm(send_algorithm_);
690 connection_.SetLossAlgorithm(loss_algorithm_.get());
691 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
693 .Times(AnyNumber());
694 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
695 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
696 .WillRepeatedly(Return(kDefaultTCPMSS));
697 EXPECT_CALL(*send_algorithm_, PacingRate(_))
698 .WillRepeatedly(Return(QuicBandwidth::Zero()));
699 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
700 .Times(AnyNumber())
701 .WillRepeatedly(Return(QuicBandwidth::Zero()));
702 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
703 .Times(AnyNumber());
704 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
705 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
706 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
707 .Times(AnyNumber());
708 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
709 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
710 .Times(AnyNumber());
711 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
712 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
713 EXPECT_CALL(visitor_, OnCanWrite())
714 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
715 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
716 .WillRepeatedly(Return(false));
717 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
718 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
719 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
720 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
721 .Times(testing::AtMost(1));
722 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
723 .WillRepeatedly(Return(QuicTime::Zero()));
724 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
725 .Times(AnyNumber());
726 EXPECT_CALL(visitor_, GetHandshakeState())
727 .WillRepeatedly(Return(HANDSHAKE_START));
728 if (connection_.version().KnowsWhichDecrypterToUse()) {
729 connection_.InstallDecrypter(
730 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800731 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
732 } else {
733 connection_.SetAlternativeDecrypter(
734 ENCRYPTION_FORWARD_SECURE,
735 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE),
736 false);
Bence Békybac04052022-04-07 15:44:29 -0400737 }
738 peer_creator_.SetDefaultPeerAddress(kSelfAddress);
739 }
740
741 QuicConnectionTest(const QuicConnectionTest&) = delete;
742 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
743
744 ParsedQuicVersion version() { return GetParam().version; }
745
746 QuicStopWaitingFrame* stop_waiting() {
747 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
748 return &stop_waiting_;
749 }
750
751 QuicPacketNumber least_unacked() {
752 if (writer_->stop_waiting_frames().empty()) {
753 return QuicPacketNumber();
754 }
755 return writer_->stop_waiting_frames()[0].least_unacked;
756 }
757
Bence Békybac04052022-04-07 15:44:29 -0400758 void SetClientConnectionId(const QuicConnectionId& client_connection_id) {
759 connection_.set_client_connection_id(client_connection_id);
760 writer_->framer()->framer()->SetExpectedClientConnectionIdLength(
761 client_connection_id.length());
762 }
763
764 void SetDecrypter(EncryptionLevel level,
765 std::unique_ptr<QuicDecrypter> decrypter) {
766 if (connection_.version().KnowsWhichDecrypterToUse()) {
767 connection_.InstallDecrypter(level, std::move(decrypter));
768 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800769 connection_.SetAlternativeDecrypter(level, std::move(decrypter), false);
Bence Békybac04052022-04-07 15:44:29 -0400770 }
771 }
772
773 void ProcessPacket(uint64_t number) {
774 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
775 ProcessDataPacket(number);
776 if (connection_.GetSendAlarm()->IsSet()) {
777 connection_.GetSendAlarm()->Fire();
778 }
779 }
780
781 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
782 const QuicSocketAddress& peer_address,
783 const QuicReceivedPacket& packet) {
784 connection_.ProcessUdpPacket(self_address, peer_address, packet);
785 if (connection_.GetSendAlarm()->IsSet()) {
786 connection_.GetSendAlarm()->Fire();
787 }
788 }
789
790 QuicFrame MakeCryptoFrame() const {
791 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
792 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
793 }
794 return QuicFrame(QuicStreamFrame(
795 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
796 0u, absl::string_view()));
797 }
798
799 void ProcessFramePacket(QuicFrame frame) {
800 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress,
801 ENCRYPTION_FORWARD_SECURE);
802 }
803
804 void ProcessFramePacketWithAddresses(QuicFrame frame,
805 QuicSocketAddress self_address,
806 QuicSocketAddress peer_address,
807 EncryptionLevel level) {
808 QuicFrames frames;
809 frames.push_back(QuicFrame(frame));
810 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address,
811 level);
812 }
813
814 std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames,
815 EncryptionLevel level,
816 char* buffer,
817 size_t buffer_len) {
818 QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level));
819 peer_creator_.set_encryption_level(level);
820 QuicPacketCreatorPeer::SetSendVersionInPacket(
821 &peer_creator_,
822 level < ENCRYPTION_FORWARD_SECURE &&
823 connection_.perspective() == Perspective::IS_SERVER);
824
825 SerializedPacket serialized_packet =
826 QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
827 buffer, buffer_len);
828 return std::make_unique<QuicReceivedPacket>(
829 serialized_packet.encrypted_buffer, serialized_packet.encrypted_length,
830 clock_.Now());
831 }
832
833 void ProcessFramesPacketWithAddresses(QuicFrames frames,
834 QuicSocketAddress self_address,
835 QuicSocketAddress peer_address,
836 EncryptionLevel level) {
837 char buffer[kMaxOutgoingPacketSize];
838 connection_.ProcessUdpPacket(
839 self_address, peer_address,
840 *ConstructPacket(std::move(frames), level, buffer,
841 kMaxOutgoingPacketSize));
842 if (connection_.GetSendAlarm()->IsSet()) {
843 connection_.GetSendAlarm()->Fire();
844 }
845 }
846
847 // Bypassing the packet creator is unrealistic, but allows us to process
848 // packets the QuicPacketCreator won't allow us to create.
849 void ForceProcessFramePacket(QuicFrame frame) {
850 QuicFrames frames;
851 frames.push_back(QuicFrame(frame));
852 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
853 if (connection_.version().KnowsWhichDecrypterToUse()) {
854 send_version = true;
855 }
856 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
857 QuicPacketHeader header;
858 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
859 char encrypted_buffer[kMaxOutgoingPacketSize];
860 size_t length = peer_framer_.BuildDataPacket(
861 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
862 ENCRYPTION_INITIAL);
863 QUICHE_DCHECK_GT(length, 0u);
864
865 const size_t encrypted_length = peer_framer_.EncryptInPlace(
866 ENCRYPTION_INITIAL, header.packet_number,
867 GetStartOfEncryptedData(peer_framer_.version().transport_version,
868 header),
869 length, kMaxOutgoingPacketSize, encrypted_buffer);
870 QUICHE_DCHECK_GT(encrypted_length, 0u);
871
872 connection_.ProcessUdpPacket(
873 kSelfAddress, kPeerAddress,
874 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
875 }
876
877 size_t ProcessFramePacketAtLevel(uint64_t number, QuicFrame frame,
878 EncryptionLevel level) {
879 QuicFrames frames;
880 frames.push_back(frame);
881 return ProcessFramesPacketAtLevel(number, frames, level);
882 }
883
884 size_t ProcessFramesPacketAtLevel(uint64_t number, const QuicFrames& frames,
885 EncryptionLevel level) {
886 QuicPacketHeader header = ConstructPacketHeader(number, level);
887 // Set the correct encryption level and encrypter on peer_creator and
888 // peer_framer, respectively.
889 peer_creator_.set_encryption_level(level);
martinduke9e0811c2022-12-08 20:35:57 -0800890 if (level > ENCRYPTION_INITIAL) {
891 peer_framer_.SetEncrypter(level,
892 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400893 // Set the corresponding decrypter.
894 if (connection_.version().KnowsWhichDecrypterToUse()) {
895 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800896 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400897 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800898 connection_.SetAlternativeDecrypter(
899 level, std::make_unique<StrictTaggingDecrypter>(level), false);
Bence Békybac04052022-04-07 15:44:29 -0400900 }
901 }
902 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
903
904 char buffer[kMaxOutgoingPacketSize];
905 size_t encrypted_length =
906 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
907 buffer, kMaxOutgoingPacketSize);
908 connection_.ProcessUdpPacket(
909 kSelfAddress, kPeerAddress,
910 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
911 if (connection_.GetSendAlarm()->IsSet()) {
912 connection_.GetSendAlarm()->Fire();
913 }
914 return encrypted_length;
915 }
916
917 struct PacketInfo {
918 PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level)
919 : packet_number(packet_number), frames(frames), level(level) {}
920
921 uint64_t packet_number;
922 QuicFrames frames;
923 EncryptionLevel level;
924 };
925
926 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) {
927 char coalesced_buffer[kMaxOutgoingPacketSize];
928 size_t coalesced_size = 0;
929 bool contains_initial = false;
930 for (const auto& packet : packets) {
931 QuicPacketHeader header =
932 ConstructPacketHeader(packet.packet_number, packet.level);
933 // Set the correct encryption level and encrypter on peer_creator and
934 // peer_framer, respectively.
935 peer_creator_.set_encryption_level(packet.level);
936 if (packet.level == ENCRYPTION_INITIAL) {
937 contains_initial = true;
938 }
martinduke9e0811c2022-12-08 20:35:57 -0800939 EncryptionLevel level =
940 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_);
941 if (level > ENCRYPTION_INITIAL) {
942 peer_framer_.SetEncrypter(level,
943 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400944 // Set the corresponding decrypter.
945 if (connection_.version().KnowsWhichDecrypterToUse()) {
946 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800947 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400948 } else {
949 connection_.SetDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800950 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400951 }
952 }
953 std::unique_ptr<QuicPacket> constructed_packet(
954 ConstructPacket(header, packet.frames));
955
956 char buffer[kMaxOutgoingPacketSize];
957 size_t encrypted_length = peer_framer_.EncryptPayload(
958 packet.level, QuicPacketNumber(packet.packet_number),
959 *constructed_packet, buffer, kMaxOutgoingPacketSize);
960 QUICHE_DCHECK_LE(coalesced_size + encrypted_length,
961 kMaxOutgoingPacketSize);
962 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
963 coalesced_size += encrypted_length;
964 }
965 if (contains_initial) {
966 // Padded coalesced packet to full if it contains initial packet.
967 memset(coalesced_buffer + coalesced_size, '0',
968 kMaxOutgoingPacketSize - coalesced_size);
969 }
970 connection_.ProcessUdpPacket(
971 kSelfAddress, kPeerAddress,
972 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(),
973 false));
974 if (connection_.GetSendAlarm()->IsSet()) {
975 connection_.GetSendAlarm()->Fire();
976 }
977 return coalesced_size;
978 }
979
980 size_t ProcessDataPacket(uint64_t number) {
981 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
982 }
983
984 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
985 return ProcessDataPacketAtLevel(packet_number, false,
986 ENCRYPTION_FORWARD_SECURE);
987 }
988
989 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
990 bool has_stop_waiting,
991 EncryptionLevel level) {
992 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
993 level);
994 }
995
996 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
997 QuicPacketHeader header = ConstructPacketHeader(number, level);
998 QuicFrames frames;
999 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1000 frames.push_back(QuicFrame(&crypto_frame_));
1001 } else {
1002 frames.push_back(QuicFrame(frame1_));
1003 }
1004 if (level == ENCRYPTION_INITIAL) {
1005 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
1006 }
1007 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1008 char buffer[kMaxOutgoingPacketSize];
1009 peer_creator_.set_encryption_level(level);
1010 size_t encrypted_length =
1011 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1012 buffer, kMaxOutgoingPacketSize);
1013 connection_.ProcessUdpPacket(
1014 kSelfAddress, kPeerAddress,
1015 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1016 if (connection_.GetSendAlarm()->IsSet()) {
1017 connection_.GetSendAlarm()->Fire();
1018 }
1019 return encrypted_length;
1020 }
1021
1022 size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting,
1023 EncryptionLevel level) {
1024 std::unique_ptr<QuicPacket> packet(
1025 ConstructDataPacket(number, has_stop_waiting, level));
1026 char buffer[kMaxOutgoingPacketSize];
1027 peer_creator_.set_encryption_level(level);
1028 size_t encrypted_length =
1029 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1030 buffer, kMaxOutgoingPacketSize);
1031 connection_.ProcessUdpPacket(
1032 kSelfAddress, kPeerAddress,
1033 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1034 if (connection_.GetSendAlarm()->IsSet()) {
1035 connection_.GetSendAlarm()->Fire();
1036 }
1037 return encrypted_length;
1038 }
1039
1040 void ProcessClosePacket(uint64_t number) {
1041 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
1042 char buffer[kMaxOutgoingPacketSize];
1043 size_t encrypted_length = peer_framer_.EncryptPayload(
1044 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
1045 kMaxOutgoingPacketSize);
1046 connection_.ProcessUdpPacket(
1047 kSelfAddress, kPeerAddress,
1048 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1049 }
1050
1051 QuicByteCount SendStreamDataToPeer(QuicStreamId id, absl::string_view data,
1052 QuicStreamOffset offset,
1053 StreamSendingState state,
1054 QuicPacketNumber* last_packet) {
QUICHE team24a23852022-10-31 18:03:52 -07001055 QuicByteCount packet_size = 0;
Bence Békybac04052022-04-07 15:44:29 -04001056 // Save the last packet's size.
1057 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1058 .Times(AnyNumber())
1059 .WillRepeatedly(SaveArg<3>(&packet_size));
1060 connection_.SendStreamDataWithString(id, data, offset, state);
1061 if (last_packet != nullptr) {
1062 *last_packet = creator_->packet_number();
1063 }
1064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1065 .Times(AnyNumber());
1066 return packet_size;
1067 }
1068
1069 void SendAckPacketToPeer() {
1070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1071 {
1072 QuicConnection::ScopedPacketFlusher flusher(&connection_);
1073 connection_.SendAck();
1074 }
1075 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1076 .Times(AnyNumber());
1077 }
1078
1079 void SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error,
1080 QuicStreamOffset bytes_written) {
1081 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1082 connection_.OnStreamReset(id, error);
1083 }
1084
1085 void SendPing() { notifier_.WriteOrBufferPing(); }
1086
1087 MessageStatus SendMessage(absl::string_view message) {
1088 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1089 quiche::QuicheMemSlice slice(quiche::QuicheBuffer::Copy(
1090 connection_.helper()->GetStreamSendBufferAllocator(), message));
1091 return connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false);
1092 }
1093
1094 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1095 if (packet_number > 1) {
1096 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1097 } else {
1098 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1099 }
1100 ProcessFramePacket(QuicFrame(frame));
1101 }
1102
1103 void ProcessAckPacket(QuicAckFrame* frame) {
1104 ProcessFramePacket(QuicFrame(frame));
1105 }
1106
1107 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1108 ProcessFramePacket(QuicFrame(frame));
1109 }
1110
1111 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1112 QuicStopWaitingFrame frame,
1113 EncryptionLevel /*level*/) {
1114 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1115 ENCRYPTION_ZERO_RTT);
1116 }
1117
1118 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1119 ProcessFramePacket(QuicFrame(frame));
1120 }
1121
1122 bool IsMissing(uint64_t number) {
1123 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
1124 QuicPacketNumber());
1125 }
1126
1127 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1128 const QuicFrames& frames) {
1129 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1130 EXPECT_NE(nullptr, packet.get());
1131 return packet;
1132 }
1133
1134 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1135 EncryptionLevel level) {
1136 QuicPacketHeader header;
1137 if (peer_framer_.version().HasIetfInvariantHeader() &&
1138 level < ENCRYPTION_FORWARD_SECURE) {
1139 // Set long header type accordingly.
1140 header.version_flag = true;
1141 header.form = IETF_QUIC_LONG_HEADER_PACKET;
1142 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1143 if (QuicVersionHasLongHeaderLengths(
1144 peer_framer_.version().transport_version)) {
dschinazi35c0ff72022-08-16 12:10:06 -07001145 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04001146 if (header.long_packet_type == INITIAL) {
dschinazi35c0ff72022-08-16 12:10:06 -07001147 header.retry_token_length_length =
1148 quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
Bence Békybac04052022-04-07 15:44:29 -04001149 }
1150 }
1151 }
1152 // Set connection_id to peer's in memory representation as this data packet
1153 // is created by peer_framer.
1154 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1155 header.source_connection_id = connection_id_;
1156 header.source_connection_id_included = connection_id_included_;
1157 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1158 } else {
1159 header.destination_connection_id = connection_id_;
1160 header.destination_connection_id_included = connection_id_included_;
1161 }
1162 if (peer_framer_.version().HasIetfInvariantHeader() &&
1163 peer_framer_.perspective() == Perspective::IS_SERVER) {
1164 if (!connection_.client_connection_id().IsEmpty()) {
1165 header.destination_connection_id = connection_.client_connection_id();
1166 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
1167 } else {
1168 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1169 }
1170 if (header.version_flag) {
1171 header.source_connection_id = connection_id_;
1172 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1173 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1174 header.long_packet_type == ZERO_RTT_PROTECTED) {
1175 header.nonce = &kTestDiversificationNonce;
1176 }
1177 }
1178 }
martinduke9e0811c2022-12-08 20:35:57 -08001179 if (!peer_framer_.version().HasIetfInvariantHeader() &&
1180 peer_framer_.perspective() == Perspective::IS_SERVER &&
1181 GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1182 level == ENCRYPTION_ZERO_RTT) {
1183 header.nonce = &kTestDiversificationNonce;
1184 }
Bence Békybac04052022-04-07 15:44:29 -04001185 header.packet_number_length = packet_number_length_;
1186 header.packet_number = QuicPacketNumber(number);
1187 return header;
1188 }
1189
1190 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1191 bool has_stop_waiting,
1192 EncryptionLevel level) {
1193 QuicPacketHeader header = ConstructPacketHeader(number, level);
1194 QuicFrames frames;
1195 if (VersionHasIetfQuicFrames(version().transport_version) &&
1196 (level == ENCRYPTION_INITIAL || level == ENCRYPTION_HANDSHAKE)) {
1197 frames.push_back(QuicFrame(QuicPingFrame()));
1198 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
1199 } else {
1200 frames.push_back(QuicFrame(frame1_));
1201 if (has_stop_waiting) {
1202 frames.push_back(QuicFrame(stop_waiting_));
1203 }
1204 }
1205 return ConstructPacket(header, frames);
1206 }
1207
1208 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
1209 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1210 if (VersionHasIetfQuicFrames(version().transport_version)) {
1211 QuicPathFrameBuffer payload = {
1212 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1213 return QuicPacketCreatorPeer::
1214 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1215 payload);
1216 }
1217 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1218 &peer_creator_);
1219 }
1220
1221 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1222 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1223 QuicPacketHeader header;
1224 // Set connection_id to peer's in memory representation as this connection
1225 // close packet is created by peer_framer.
1226 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1227 header.source_connection_id = connection_id_;
1228 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1229 if (!peer_framer_.version().HasIetfInvariantHeader()) {
1230 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1231 }
1232 } else {
1233 header.destination_connection_id = connection_id_;
1234 if (peer_framer_.version().HasIetfInvariantHeader()) {
1235 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1236 }
1237 }
1238
1239 header.packet_number = QuicPacketNumber(number);
1240
1241 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
1242 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1243 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
1244 /*transport_close_frame_type=*/0);
1245 QuicFrames frames;
1246 frames.push_back(QuicFrame(&qccf));
1247 return ConstructPacket(header, frames);
1248 }
1249
1250 QuicTime::Delta DefaultRetransmissionTime() {
1251 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1252 }
1253
1254 QuicTime::Delta DefaultDelayedAckTime() {
1255 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1256 }
1257
1258 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1259 QuicStopWaitingFrame frame;
1260 frame.least_unacked = QuicPacketNumber(least_unacked);
1261 return frame;
1262 }
1263
1264 // Construct a ack_frame that acks all packet numbers between 1 and
1265 // |largest_acked|, except |missing|.
1266 // REQUIRES: 1 <= |missing| < |largest_acked|
1267 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1268 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1269 QuicPacketNumber(missing));
1270 }
1271
1272 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1273 QuicPacketNumber missing) {
1274 if (missing == QuicPacketNumber(1)) {
1275 return InitAckFrame({{missing + 1, largest_acked + 1}});
1276 }
1277 return InitAckFrame(
1278 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1279 }
1280
1281 // Undo nacking a packet within the frame.
1282 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1283 EXPECT_FALSE(frame->packets.Contains(arrived));
1284 frame->packets.Add(arrived);
1285 }
1286
1287 void TriggerConnectionClose() {
1288 // Send an erroneous packet to close the connection.
1289 EXPECT_CALL(visitor_,
1290 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1291 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1292
1293 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1294 // Triggers a connection by receiving ACK of unsent packet.
1295 QuicAckFrame frame = InitAckFrame(10000);
1296 ProcessAckPacket(1, &frame);
1297 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1298 nullptr);
1299 EXPECT_EQ(1, connection_close_frame_count_);
1300 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1301 IsError(QUIC_INVALID_ACK_DATA));
1302 }
1303
1304 void BlockOnNextWrite() {
1305 writer_->BlockOnNextWrite();
1306 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1307 }
1308
1309 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1310
fayangf6607db2022-04-21 18:10:41 -07001311 void ExpectNextPacketUnprocessable() {
1312 writer_->ExpectNextPacketUnprocessable();
1313 }
1314
Bence Békybac04052022-04-07 15:44:29 -04001315 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1316
1317 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1318 writer_->SetWritePauseTimeDelta(delta);
1319 }
1320
1321 void CongestionBlockWrites() {
1322 EXPECT_CALL(*send_algorithm_, CanSend(_))
1323 .WillRepeatedly(testing::Return(false));
1324 }
1325
1326 void CongestionUnblockWrites() {
1327 EXPECT_CALL(*send_algorithm_, CanSend(_))
1328 .WillRepeatedly(testing::Return(true));
1329 }
1330
1331 void set_perspective(Perspective perspective) {
1332 connection_.set_perspective(perspective);
1333 if (perspective == Perspective::IS_SERVER) {
1334 QuicConfig config;
1335 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -07001336 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -04001337 QuicTagVector connection_options;
1338 connection_options.push_back(kRVCM);
1339 config.SetInitialReceivedConnectionOptions(connection_options);
1340 }
1341 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1342 connection_.SetFromConfig(config);
1343
1344 connection_.set_can_truncate_connection_ids(true);
1345 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
1346 connection_.OnSuccessfulVersionNegotiation();
1347 }
1348 QuicFramerPeer::SetPerspective(&peer_framer_,
1349 QuicUtils::InvertPerspective(perspective));
1350 peer_framer_.SetInitialObfuscators(TestConnectionId());
1351 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
1352 ENCRYPTION_FORWARD_SECURE}) {
1353 if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) {
martinduke9e0811c2022-12-08 20:35:57 -08001354 peer_creator_.SetEncrypter(level,
1355 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -04001356 }
1357 }
1358 }
1359
1360 void set_packets_between_probes_base(
1361 const QuicPacketCount packets_between_probes_base) {
1362 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1363 &connection_, packets_between_probes_base,
1364 QuicPacketNumber(packets_between_probes_base));
1365 }
1366
1367 bool IsDefaultTestConfiguration() {
1368 TestParams p = GetParam();
1369 return p.ack_response == AckResponse::kImmediate &&
1370 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1371 }
1372
1373 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1374 // Not strictly needed for this test, but is commonly done.
1375 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1376 nullptr);
1377 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1378 writer_->connection_close_frames();
1379 ASSERT_EQ(1u, connection_close_frames.size());
1380
1381 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1382 IsError(expected_code));
1383
1384 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1385 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1386 IsError(expected_code));
1387 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1388 connection_close_frames[0].close_type);
1389 return;
1390 }
1391
1392 QuicErrorCodeToIetfMapping mapping =
1393 QuicErrorCodeToTransportErrorCode(expected_code);
1394
1395 if (mapping.is_transport_close) {
1396 // This Google QUIC Error Code maps to a transport close,
1397 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1398 connection_close_frames[0].close_type);
1399 } else {
1400 // This maps to an application close.
1401 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1402 connection_close_frames[0].close_type);
1403 }
1404 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
1405 }
1406
1407 void MtuDiscoveryTestInit() {
1408 set_perspective(Perspective::IS_SERVER);
1409 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1410 if (version().SupportsAntiAmplificationLimit()) {
1411 QuicConnectionPeer::SetAddressValidated(&connection_);
1412 }
1413 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1414 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04001415 // Prevent packets from being coalesced.
1416 EXPECT_CALL(visitor_, GetHandshakeState())
1417 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1418 EXPECT_TRUE(connection_.connected());
1419 }
1420
1421 void PathProbeTestInit(Perspective perspective,
1422 bool receive_new_server_connection_id = true) {
1423 set_perspective(perspective);
1424 connection_.CreateConnectionIdManager();
1425 EXPECT_EQ(connection_.perspective(), perspective);
1426 if (perspective == Perspective::IS_SERVER) {
1427 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1428 }
1429 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1430 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1431 // Discard INITIAL key.
1432 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1433 connection_.NeuterUnencryptedPackets();
1434 // Prevent packets from being coalesced.
1435 EXPECT_CALL(visitor_, GetHandshakeState())
1436 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1437 if (version().SupportsAntiAmplificationLimit() &&
1438 perspective == Perspective::IS_SERVER) {
1439 QuicConnectionPeer::SetAddressValidated(&connection_);
1440 }
1441 // Clear direct_peer_address.
1442 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1443 // Clear effective_peer_address, it is the same as direct_peer_address for
1444 // this test.
1445 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1446 QuicSocketAddress());
1447 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1448
1449 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1450 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1451 } else {
1452 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1453 }
1454 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1455 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1456 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1457 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1458 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1459 if (perspective == Perspective::IS_CLIENT &&
1460 receive_new_server_connection_id && version().HasIetfQuicFrames()) {
1461 QuicNewConnectionIdFrame frame;
1462 frame.connection_id = TestConnectionId(1234);
1463 ASSERT_NE(frame.connection_id, connection_.connection_id());
1464 frame.stateless_reset_token =
1465 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
1466 frame.retire_prior_to = 0u;
1467 frame.sequence_number = 1u;
1468 connection_.OnNewConnectionIdFrame(frame);
1469 }
1470 }
1471
fayangdbd6a302022-12-21 16:24:27 -08001472 // Receive server preferred address.
fayanga0618a62022-12-28 19:31:24 -08001473 void ServerPreferredAddressInit(QuicConfig& config) {
fayangdbd6a302022-12-21 16:24:27 -08001474 ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1475 ASSERT_TRUE(version().HasIetfQuicFrames());
1476 ASSERT_TRUE(connection_.self_address().host().IsIPv6());
1477 SetQuicReloadableFlag(quic_connection_migration_use_new_cid_v2, true);
fayangdbd6a302022-12-21 16:24:27 -08001478 const QuicConnectionId connection_id = TestConnectionId(17);
1479 const StatelessResetToken reset_token =
1480 QuicUtils::GenerateStatelessResetToken(connection_id);
1481
1482 connection_.CreateConnectionIdManager();
1483
1484 connection_.SendCryptoStreamData();
1485 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
1486 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
1487 QuicAckFrame frame = InitAckFrame(1);
1488 // Received ACK for packet 1.
1489 ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
fayang37765f62022-12-27 17:49:13 -08001490 // Discard INITIAL key.
1491 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
fayanga0618a62022-12-28 19:31:24 -08001492 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
fayangdbd6a302022-12-21 16:24:27 -08001493
fayangdbd6a302022-12-21 16:24:27 -08001494 config.SetConnectionOptionsToSend(QuicTagVector{kRVCM});
fayangdbd6a302022-12-21 16:24:27 -08001495 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
1496 kTestStatelessResetToken);
1497 QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
danzh8fdee2e2023-01-05 15:33:02 -08001498 kServerPreferredAddress);
fayangdbd6a302022-12-21 16:24:27 -08001499 QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
1500 &config, connection_id, reset_token);
1501 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1502 connection_.SetFromConfig(config);
1503
1504 ASSERT_TRUE(QuicConnectionPeer::GetServerPreferredAddress(&connection_)
1505 .IsInitialized());
danzh8fdee2e2023-01-05 15:33:02 -08001506 EXPECT_EQ(kServerPreferredAddress,
fayangdbd6a302022-12-21 16:24:27 -08001507 QuicConnectionPeer::GetServerPreferredAddress(&connection_));
1508 }
1509
Bence Békybac04052022-04-07 15:44:29 -04001510 void TestClientRetryHandling(bool invalid_retry_tag,
1511 bool missing_original_id_in_config,
1512 bool wrong_original_id_in_config,
1513 bool missing_retry_id_in_config,
1514 bool wrong_retry_id_in_config);
1515
1516 void TestReplaceConnectionIdFromInitial();
1517
1518 QuicConnectionId connection_id_;
1519 QuicFramer framer_;
1520
1521 MockSendAlgorithm* send_algorithm_;
1522 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1523 MockClock clock_;
1524 MockRandom random_generator_;
1525 quiche::SimpleBufferAllocator buffer_allocator_;
1526 std::unique_ptr<TestConnectionHelper> helper_;
1527 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1528 QuicFramer peer_framer_;
1529 QuicPacketCreator peer_creator_;
1530 std::unique_ptr<TestPacketWriter> writer_;
1531 TestConnection connection_;
1532 QuicPacketCreator* creator_;
1533 QuicSentPacketManager* manager_;
1534 StrictMock<MockQuicConnectionVisitor> visitor_;
1535
1536 QuicStreamFrame frame1_;
1537 QuicStreamFrame frame2_;
1538 QuicCryptoFrame crypto_frame_;
1539 QuicAckFrame ack_;
1540 QuicStopWaitingFrame stop_waiting_;
1541 QuicPacketNumberLength packet_number_length_;
1542 QuicConnectionIdIncluded connection_id_included_;
1543
1544 SimpleSessionNotifier notifier_;
1545
1546 QuicConnectionCloseFrame saved_connection_close_frame_;
1547 int connection_close_frame_count_;
martinduke605dca22022-09-01 10:40:19 -07001548 MockConnectionIdGenerator connection_id_generator_;
Bence Békybac04052022-04-07 15:44:29 -04001549};
1550
1551// Run all end to end tests with all supported versions.
1552INSTANTIATE_TEST_SUITE_P(QuicConnectionTests, QuicConnectionTest,
1553 ::testing::ValuesIn(GetTestParams()),
1554 ::testing::PrintToStringParamName());
1555
1556// These two tests ensure that the QuicErrorCode mapping works correctly.
1557// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1558// If running IETF QUIC, the first will generate a transport connection
1559// close, the second an application connection close.
1560// The connection close codes for the two tests are manually chosen;
1561// they are expected to always map to transport- and application-
1562// closes, respectively. If that changes, new codes should be chosen.
1563TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1564 EXPECT_TRUE(connection_.connected());
1565 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1566 connection_.CloseConnection(
1567 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1568 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1569 EXPECT_FALSE(connection_.connected());
1570 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1571}
1572
1573// Test that the IETF QUIC Error code mapping function works
1574// properly for application connection close codes.
1575TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1576 EXPECT_TRUE(connection_.connected());
1577 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1578 connection_.CloseConnection(
1579 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1580 "Should be application close",
1581 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1582 EXPECT_FALSE(connection_.connected());
1583 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1584}
1585
1586TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1587 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1588
1589 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1590 EXPECT_TRUE(connection_.connected());
1591
1592 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1593 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1594 } else {
1595 EXPECT_CALL(visitor_, OnStreamFrame(_));
1596 }
1597 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1598 ENCRYPTION_INITIAL);
1599 // Cause change in self_address.
1600 QuicIpAddress host;
1601 host.FromString("1.1.1.1");
1602 QuicSocketAddress self_address(host, 123);
1603 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1604 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1605 } else {
1606 EXPECT_CALL(visitor_, OnStreamFrame(_));
1607 }
1608 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1609 ENCRYPTION_INITIAL);
1610 EXPECT_TRUE(connection_.connected());
1611}
1612
1613TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1614 set_perspective(Perspective::IS_SERVER);
1615 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1616
1617 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1618 EXPECT_TRUE(connection_.connected());
1619
1620 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1621 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1622 } else {
1623 EXPECT_CALL(visitor_, OnStreamFrame(_));
1624 }
1625 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1626 ENCRYPTION_INITIAL);
1627 // Cause change in self_address.
1628 QuicIpAddress host;
1629 host.FromString("1.1.1.1");
1630 QuicSocketAddress self_address(host, 123);
1631 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
1632 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fayang19027942022-05-16 10:29:29 -07001633 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1634 ENCRYPTION_INITIAL);
1635 EXPECT_TRUE(connection_.connected());
Bence Békybac04052022-04-07 15:44:29 -04001636 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
1637}
1638
1639TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1640 set_perspective(Perspective::IS_SERVER);
1641 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1642
1643 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1644 EXPECT_TRUE(connection_.connected());
1645
1646 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1647 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1648 } else {
1649 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1650 }
1651 QuicIpAddress host;
1652 host.FromString("1.1.1.1");
1653 QuicSocketAddress self_address1(host, 443);
1654 connection_.SetSelfAddress(self_address1);
1655 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1656 kPeerAddress, ENCRYPTION_INITIAL);
1657 // Cause self_address change to mapped Ipv4 address.
1658 QuicIpAddress host2;
1659 host2.FromString(
1660 absl::StrCat("::ffff:", connection_.self_address().host().ToString()));
1661 QuicSocketAddress self_address2(host2, connection_.self_address().port());
1662 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1663 kPeerAddress, ENCRYPTION_INITIAL);
1664 EXPECT_TRUE(connection_.connected());
1665 // self_address change back to Ipv4 address.
1666 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1667 kPeerAddress, ENCRYPTION_INITIAL);
1668 EXPECT_TRUE(connection_.connected());
1669}
1670
1671TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1672 set_perspective(Perspective::IS_SERVER);
1673 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1674 EXPECT_CALL(visitor_, GetHandshakeState())
1675 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1676
1677 // Clear direct_peer_address.
1678 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1679 // Clear effective_peer_address, it is the same as direct_peer_address for
1680 // this test.
1681 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1682 QuicSocketAddress());
1683
1684 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1685 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1686 } else {
1687 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1688 }
1689 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1690 const QuicSocketAddress kNewPeerAddress =
1691 QuicSocketAddress(QuicIpAddress::Loopback6(),
1692 /*port=*/23456);
1693 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1694 kNewPeerAddress, ENCRYPTION_INITIAL);
1695 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1696 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1697
1698 // Decrease packet number to simulate out-of-order packets.
1699 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1700 // This is an old packet, do not migrate.
1701 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1702 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1703 ENCRYPTION_INITIAL);
1704 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1705 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1706}
1707
1708TEST_P(QuicConnectionTest, PeerPortChangeAtServer) {
1709 set_perspective(Perspective::IS_SERVER);
1710 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1711 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1712 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1713 // Prevent packets from being coalesced.
1714 EXPECT_CALL(visitor_, GetHandshakeState())
1715 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1716 if (version().SupportsAntiAmplificationLimit()) {
1717 QuicConnectionPeer::SetAddressValidated(&connection_);
1718 }
1719
1720 // Clear direct_peer_address.
1721 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1722 // Clear effective_peer_address, it is the same as direct_peer_address for
1723 // this test.
1724 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1725 QuicSocketAddress());
1726 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1727
1728 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
1729 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
1730 rtt_stats->set_initial_rtt(default_init_rtt * 2);
1731 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
1732
fayang339f0c82022-04-30 14:20:02 -07001733 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
1734 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001735
1736 const QuicSocketAddress kNewPeerAddress =
1737 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1738 EXPECT_CALL(visitor_, OnStreamFrame(_))
1739 .WillOnce(Invoke(
1740 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1741 .WillOnce(Invoke(
1742 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1743 QuicFrames frames;
1744 frames.push_back(QuicFrame(frame1_));
1745 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1746 ENCRYPTION_FORWARD_SECURE);
1747 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1748 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1749
1750 // Process another packet with a different peer address on server side will
1751 // start connection migration.
1752 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1753 QuicFrames frames2;
1754 frames2.push_back(QuicFrame(frame2_));
1755 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1756 ENCRYPTION_FORWARD_SECURE);
1757 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1758 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1759 // PORT_CHANGE shouldn't state change in sent packet manager.
1760 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07001761 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001762 EXPECT_EQ(manager_->GetSendAlgorithm(), send_algorithm_);
1763 if (connection_.validate_client_address()) {
1764 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1765 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001766 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001767 }
1768}
1769
1770TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServer) {
1771 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07001772 if (!connection_.validate_client_address() ||
birenroyef686222022-09-12 11:34:34 -07001773 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04001774 return;
1775 }
1776 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1777 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1778 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1779 // Discard INITIAL key.
1780 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1781 connection_.NeuterUnencryptedPackets();
1782 // Prevent packets from being coalesced.
1783 EXPECT_CALL(visitor_, GetHandshakeState())
1784 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1785 QuicConnectionPeer::SetAddressValidated(&connection_);
1786 connection_.OnHandshakeComplete();
1787
1788 // Enable 5 RTO
1789 QuicConfig config;
1790 QuicTagVector connection_options;
1791 connection_options.push_back(k5RTO);
1792 config.SetInitialReceivedConnectionOptions(connection_options);
1793 QuicConfigPeer::SetNegotiated(&config, true);
1794 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
1795 connection_.connection_id());
1796 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
1797 QuicConnectionId());
1798 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1799 connection_.SetFromConfig(config);
1800
1801 // Clear direct_peer_address.
1802 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1803 // Clear effective_peer_address, it is the same as direct_peer_address for
1804 // this test.
1805 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1806 QuicSocketAddress());
1807 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1808
1809 const QuicSocketAddress kNewPeerAddress =
1810 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1811 EXPECT_CALL(visitor_, OnStreamFrame(_))
1812 .WillOnce(Invoke(
1813 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1814 .WillOnce(Invoke(
1815 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1816 QuicFrames frames;
1817 frames.push_back(QuicFrame(frame1_));
1818 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1819 ENCRYPTION_FORWARD_SECURE);
1820 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1821 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1822
1823 // Send some data to make connection has packets in flight.
1824 connection_.SendStreamData3();
1825 EXPECT_EQ(1u, writer_->packets_write_attempts());
1826 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
1827 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1828
1829 // Process another packet with a different peer address on server side will
1830 // start connection migration.
1831 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1832 // IETF QUIC send algorithm should be changed to a different object, so no
1833 // OnPacketSent() called on the old send algorithm.
1834 EXPECT_CALL(*send_algorithm_,
1835 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
1836 .Times(0);
1837 // Do not propagate OnCanWrite() to session notifier.
1838 EXPECT_CALL(visitor_, OnCanWrite()).Times(AtLeast(1u));
1839
1840 QuicFrames frames2;
1841 frames2.push_back(QuicFrame(frame2_));
1842 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1843 ENCRYPTION_FORWARD_SECURE);
1844 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1845 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1846 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1847 connection_.active_effective_peer_migration_type());
1848 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
1849 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1850
1851 EXPECT_EQ(2u, writer_->packets_write_attempts());
1852 EXPECT_FALSE(writer_->path_challenge_frames().empty());
1853 QuicPathFrameBuffer payload =
1854 writer_->path_challenge_frames().front().data_buffer;
1855 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
1856 send_algorithm_);
1857 // Switch to use the mock send algorithm.
1858 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
1859 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1860 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1861 .WillRepeatedly(Return(kDefaultTCPMSS));
1862 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1863 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1864 .Times(AnyNumber())
1865 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1866 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1867 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1868 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
1869 connection_.SetSendAlgorithm(send_algorithm_);
1870
1871 // PATH_CHALLENGE is expanded upto the max packet size which may exceeds the
1872 // anti-amplification limit.
1873 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
1874 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1875 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1876 EXPECT_EQ(1u,
1877 connection_.GetStats().num_reverse_path_validtion_upon_migration);
1878
1879 // Verify server is throttled by anti-amplification limit.
1880 connection_.SendCryptoDataWithString("foo", 0);
1881 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1882
1883 // Receiving an ACK to the packet sent after changing peer address doesn't
1884 // finish migration validation.
1885 QuicAckFrame ack_frame = InitAckFrame(2);
1886 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1887 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1888 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
1889 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1890 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1891 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1892 connection_.active_effective_peer_migration_type());
1893
1894 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
1895 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -07001896 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04001897 EXPECT_CALL(visitor_, MaybeSendAddressToken());
1898 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1899 .Times(testing::AtLeast(1u));
1900 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
1901 ENCRYPTION_FORWARD_SECURE);
1902 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1903
1904 // Verify the anti-amplification limit is lifted by sending a packet larger
1905 // than the anti-amplification limit.
1906 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
1907 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001908 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001909}
1910
1911TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServerWithMissingConnectionId) {
1912 set_perspective(Perspective::IS_SERVER);
1913 if (!connection_.connection_migration_use_new_cid()) {
1914 return;
1915 }
1916 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1917 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1918
1919 QuicConnectionId client_cid0 = TestConnectionId(1);
1920 QuicConnectionId client_cid1 = TestConnectionId(3);
1921 QuicConnectionId server_cid1;
1922 SetClientConnectionId(client_cid0);
1923 connection_.CreateConnectionIdManager();
1924 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1925 // Prevent packets from being coalesced.
1926 EXPECT_CALL(visitor_, GetHandshakeState())
1927 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1928 QuicConnectionPeer::SetAddressValidated(&connection_);
1929
1930 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07001931 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07001932 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
1933 .WillOnce(Return(TestConnectionId(456)));
1934 }
haoyuewangada6b822022-06-23 13:41:18 -07001935 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
1936 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
1937 server_cid1 = cid;
1938 return true;
1939 }));
Bence Békybac04052022-04-07 15:44:29 -04001940 EXPECT_CALL(visitor_, SendNewConnectionId(_));
1941 connection_.OnHandshakeComplete();
1942
1943 // Clear direct_peer_address.
1944 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1945 // Clear effective_peer_address, it is the same as direct_peer_address for
1946 // this test.
1947 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1948 QuicSocketAddress());
1949 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1950
1951 const QuicSocketAddress kNewPeerAddress =
1952 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1953 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
1954 QuicFrames frames;
1955 frames.push_back(QuicFrame(frame1_));
1956 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1957 ENCRYPTION_FORWARD_SECURE);
1958 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1959 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1960
1961 // Send some data to make connection has packets in flight.
1962 connection_.SendStreamData3();
1963 EXPECT_EQ(1u, writer_->packets_write_attempts());
1964
1965 // Process another packet with a different peer address on server side will
1966 // start connection migration.
1967 peer_creator_.SetServerConnectionId(server_cid1);
1968 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1969 // Do not propagate OnCanWrite() to session notifier.
1970 EXPECT_CALL(visitor_, OnCanWrite()).Times(AtLeast(1u));
1971
1972 QuicFrames frames2;
1973 frames2.push_back(QuicFrame(frame2_));
birenroyef686222022-09-12 11:34:34 -07001974 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07001975 frames2.push_back(QuicFrame(QuicPaddingFrame(-1)));
1976 }
Bence Békybac04052022-04-07 15:44:29 -04001977 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1978 ENCRYPTION_FORWARD_SECURE);
1979 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1980 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1981
1982 // Writing path response & reverse path challenge is blocked due to missing
1983 // client connection ID, i.e., packets_write_attempts is unchanged.
1984 EXPECT_EQ(1u, writer_->packets_write_attempts());
1985
1986 // Receives new client CID from client would unblock write.
1987 QuicNewConnectionIdFrame new_cid_frame;
1988 new_cid_frame.connection_id = client_cid1;
1989 new_cid_frame.sequence_number = 1u;
1990 new_cid_frame.retire_prior_to = 0u;
1991 connection_.OnNewConnectionIdFrame(new_cid_frame);
1992 connection_.SendStreamData3();
1993
1994 EXPECT_EQ(2u, writer_->packets_write_attempts());
1995}
1996
1997TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
birenroyef686222022-09-12 11:34:34 -07001998 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07001999 return;
2000 }
Bence Békybac04052022-04-07 15:44:29 -04002001 set_perspective(Perspective::IS_SERVER);
2002 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2003 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2004 if (version().SupportsAntiAmplificationLimit()) {
2005 QuicConnectionPeer::SetAddressValidated(&connection_);
2006 }
2007 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2008 // Discard INITIAL key.
2009 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2010 connection_.NeuterUnencryptedPackets();
2011 EXPECT_CALL(visitor_, GetHandshakeState())
2012 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2013
2014 // Clear direct_peer_address.
2015 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2016 // Clear effective_peer_address, it is different from direct_peer_address for
2017 // this test.
2018 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2019 QuicSocketAddress());
2020 const QuicSocketAddress kEffectivePeerAddress =
2021 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
2022 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
2023
2024 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2025 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2026 } else {
2027 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2028 }
2029 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2030 ENCRYPTION_FORWARD_SECURE);
2031 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2032 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2033
2034 // Process another packet with the same direct peer address and different
2035 // effective peer address on server side will start connection migration.
2036 const QuicSocketAddress kNewEffectivePeerAddress =
2037 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2038 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2039 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2040 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2041 ENCRYPTION_FORWARD_SECURE);
2042 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2043 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2044 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
2045 if (connection_.validate_client_address()) {
2046 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2047 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07002048 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04002049 }
2050
2051 // Process another packet with a different direct peer address and the same
2052 // effective peer address on server side will not start connection migration.
2053 const QuicSocketAddress kNewPeerAddress =
2054 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2055 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2056 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2057
2058 if (!connection_.validate_client_address()) {
2059 // ack_frame is used to complete the migration started by the last packet,
2060 // we need to make sure a new migration does not start after the previous
2061 // one is completed.
2062 QuicAckFrame ack_frame = InitAckFrame(1);
2063 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2064 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2065 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2066 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2067 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2068 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2069 }
2070
2071 // Process another packet with different direct peer address and different
2072 // effective peer address on server side will start connection migration.
2073 const QuicSocketAddress kNewerEffectivePeerAddress =
2074 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2075 const QuicSocketAddress kFinalPeerAddress =
2076 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2077 connection_.ReturnEffectivePeerAddressForNextPacket(
2078 kNewerEffectivePeerAddress);
2079 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2080 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2081 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2082 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2083 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2084 if (connection_.validate_client_address()) {
2085 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2086 EXPECT_EQ(send_algorithm_,
2087 connection_.sent_packet_manager().GetSendAlgorithm());
2088 EXPECT_EQ(2u, connection_.GetStats().num_validated_peer_migration);
2089 }
2090
2091 // While the previous migration is ongoing, process another packet with the
2092 // same direct peer address and different effective peer address on server
2093 // side will start a new connection migration.
2094 const QuicSocketAddress kNewestEffectivePeerAddress =
2095 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2096 connection_.ReturnEffectivePeerAddressForNextPacket(
2097 kNewestEffectivePeerAddress);
2098 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2099 if (!connection_.validate_client_address()) {
2100 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
2101 }
2102 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2103 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2104 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2105 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2106 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2107 connection_.active_effective_peer_migration_type());
2108 if (connection_.validate_client_address()) {
2109 EXPECT_NE(send_algorithm_,
2110 connection_.sent_packet_manager().GetSendAlgorithm());
2111 EXPECT_EQ(kFinalPeerAddress, writer_->last_write_peer_address());
2112 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2113 EXPECT_EQ(0u, connection_.GetStats()
2114 .num_peer_migration_while_validating_default_path);
2115 EXPECT_TRUE(connection_.HasPendingPathValidation());
2116 }
2117}
2118
2119// Regression test for b/200020764.
2120TEST_P(QuicConnectionTest, ConnectionMigrationWithPendingPaddingBytes) {
2121 // TODO(haoyuewang) Move these test setup code to a common member function.
2122 set_perspective(Perspective::IS_SERVER);
2123 if (!connection_.connection_migration_use_new_cid()) {
2124 return;
2125 }
2126 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2127 connection_.CreateConnectionIdManager();
2128 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2129 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2130 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2131 QuicConnectionPeer::SetAddressValidated(&connection_);
2132
2133 // Sends new server CID to client.
2134 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002135 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002136 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2137 .WillOnce(Return(TestConnectionId(456)));
2138 }
haoyuewangada6b822022-06-23 13:41:18 -07002139 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2140 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2141 new_cid = cid;
2142 return true;
2143 }));
Bence Békybac04052022-04-07 15:44:29 -04002144 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2145 // Discard INITIAL key.
2146 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2147 connection_.NeuterUnencryptedPackets();
2148 connection_.OnHandshakeComplete();
2149 EXPECT_CALL(visitor_, GetHandshakeState())
2150 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2151
2152 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2153 packet_creator->FlushCurrentPacket();
2154 packet_creator->AddPendingPadding(50u);
2155 const QuicSocketAddress kPeerAddress3 =
2156 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2157 auto ack_frame = InitAckFrame(1);
2158 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2159 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2160 ProcessFramesPacketWithAddresses({QuicFrame(&ack_frame)}, kSelfAddress,
2161 kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
2162 if (GetQuicReloadableFlag(
2163 quic_flush_pending_frames_and_padding_bytes_on_migration)) {
2164 // Any pending frames/padding should be flushed before default_path_ is
2165 // temporarily reset.
2166 ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2167 .host()
2168 .address_family(),
2169 IpAddressFamily::IP_V6);
2170 } else {
2171 ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2172 .host()
2173 .address_family(),
2174 IpAddressFamily::IP_UNSPEC);
2175 }
2176}
2177
2178// Regression test for b/196208556.
2179TEST_P(QuicConnectionTest,
2180 ReversePathValidationResponseReceivedFromUnexpectedPeerAddress) {
2181 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07002182 if (!connection_.connection_migration_use_new_cid() ||
birenroyef686222022-09-12 11:34:34 -07002183 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04002184 return;
2185 }
2186 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2187 connection_.CreateConnectionIdManager();
2188 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2189 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2190 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2191 QuicConnectionPeer::SetAddressValidated(&connection_);
2192 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2193 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2194
2195 // Sends new server CID to client.
2196 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002197 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002198 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2199 .WillOnce(Return(TestConnectionId(456)));
2200 }
haoyuewangada6b822022-06-23 13:41:18 -07002201 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2202 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2203 new_cid = cid;
2204 return true;
2205 }));
Bence Békybac04052022-04-07 15:44:29 -04002206 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2207 // Discard INITIAL key.
2208 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2209 connection_.NeuterUnencryptedPackets();
2210 connection_.OnHandshakeComplete();
2211 EXPECT_CALL(visitor_, GetHandshakeState())
2212 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2213
2214 // Process a non-probing packet to migrate to path 2 and kick off reverse path
2215 // validation.
2216 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2217 const QuicSocketAddress kPeerAddress2 =
2218 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2219 peer_creator_.SetServerConnectionId(new_cid);
2220 ProcessFramesPacketWithAddresses({QuicFrame(QuicPingFrame())}, kSelfAddress,
2221 kPeerAddress2, ENCRYPTION_FORWARD_SECURE);
2222 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2223 QuicPathFrameBuffer reverse_path_challenge_payload =
2224 writer_->path_challenge_frames().front().data_buffer;
2225
2226 // Receiveds a packet from path 3 with PATH_RESPONSE frame intended to
2227 // validate path 2 and a non-probing frame.
2228 {
2229 QuicConnection::ScopedPacketFlusher flusher(&connection_);
2230 const QuicSocketAddress kPeerAddress3 =
2231 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2232 auto ack_frame = InitAckFrame(1);
2233 EXPECT_CALL(visitor_, OnConnectionMigration(IPV4_TO_IPV6_CHANGE)).Times(1);
2234 EXPECT_CALL(visitor_, MaybeSendAddressToken()).WillOnce(Invoke([this]() {
2235 connection_.SendControlFrame(
2236 QuicFrame(new QuicNewTokenFrame(1, "new_token")));
2237 return true;
2238 }));
wubd0152ca2022-04-08 08:26:44 -07002239 ProcessFramesPacketWithAddresses(
2240 {QuicFrame(QuicPathResponseFrame(0, reverse_path_challenge_payload)),
2241 QuicFrame(&ack_frame)},
2242 kSelfAddress, kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04002243 }
2244}
2245
2246TEST_P(QuicConnectionTest, ReversePathValidationFailureAtServer) {
2247 set_perspective(Perspective::IS_SERVER);
2248 if (!connection_.connection_migration_use_new_cid()) {
2249 return;
2250 }
2251 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2252 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2253 SetClientConnectionId(TestConnectionId(1));
2254 connection_.CreateConnectionIdManager();
2255 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2256 // Discard INITIAL key.
2257 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2258 connection_.NeuterUnencryptedPackets();
2259 // Prevent packets from being coalesced.
2260 EXPECT_CALL(visitor_, GetHandshakeState())
2261 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2262 QuicConnectionPeer::SetAddressValidated(&connection_);
2263
2264 QuicConnectionId client_cid0 = connection_.client_connection_id();
2265 QuicConnectionId client_cid1 = TestConnectionId(2);
2266 QuicConnectionId server_cid0 = connection_.connection_id();
2267 QuicConnectionId server_cid1;
2268 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07002269 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002270 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2271 .WillOnce(Return(TestConnectionId(456)));
2272 }
haoyuewangada6b822022-06-23 13:41:18 -07002273 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2274 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2275 server_cid1 = cid;
2276 return true;
2277 }));
Bence Békybac04052022-04-07 15:44:29 -04002278 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2279 connection_.OnHandshakeComplete();
2280 // Receives new client CID from client.
2281 QuicNewConnectionIdFrame new_cid_frame;
2282 new_cid_frame.connection_id = client_cid1;
2283 new_cid_frame.sequence_number = 1u;
2284 new_cid_frame.retire_prior_to = 0u;
2285 connection_.OnNewConnectionIdFrame(new_cid_frame);
2286 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2287 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2288 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2289
2290 // Clear direct_peer_address.
2291 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2292 // Clear effective_peer_address, it is the same as direct_peer_address for
2293 // this test.
2294 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2295 QuicSocketAddress());
2296 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2297
2298 const QuicSocketAddress kNewPeerAddress =
2299 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2300 EXPECT_CALL(visitor_, OnStreamFrame(_))
2301 .WillOnce(Invoke(
2302 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
2303 .WillOnce(Invoke(
2304 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
2305 QuicFrames frames;
2306 frames.push_back(QuicFrame(frame1_));
2307 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
2308 ENCRYPTION_FORWARD_SECURE);
2309 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2310 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2311
2312 // Process another packet with a different peer address on server side will
2313 // start connection migration.
2314 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2315 // IETF QUIC send algorithm should be changed to a different object, so no
2316 // OnPacketSent() called on the old send algorithm.
2317 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0);
2318
2319 QuicFrames frames2;
2320 frames2.push_back(QuicFrame(frame2_));
2321 QuicPaddingFrame padding;
2322 frames2.push_back(QuicFrame(padding));
2323 peer_creator_.SetServerConnectionId(server_cid1);
2324 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2325 ENCRYPTION_FORWARD_SECURE);
2326 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2327 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2328 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2329 connection_.active_effective_peer_migration_type());
2330 EXPECT_LT(0u, writer_->packets_write_attempts());
2331 EXPECT_TRUE(connection_.HasPendingPathValidation());
2332 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
2333 send_algorithm_);
2334 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2335 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2336 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2337 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
2338 const auto* alternative_path =
2339 QuicConnectionPeer::GetAlternativePath(&connection_);
2340 EXPECT_EQ(default_path->client_connection_id, client_cid1);
2341 EXPECT_EQ(default_path->server_connection_id, server_cid1);
2342 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
2343 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
2344 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
2345 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
2346
2347 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes; ++i) {
2348 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2349 static_cast<TestAlarmFactory::TestAlarm*>(
2350 QuicPathValidatorPeer::retry_timer(
2351 QuicConnectionPeer::path_validator(&connection_)))
2352 ->Fire();
2353 }
2354 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2355 connection_.active_effective_peer_migration_type());
2356
2357 // Make sure anti-amplification limit is not reached.
2358 ProcessFramesPacketWithAddresses(
2359 {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
2360 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2361 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2362 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2363
2364 // Advance the time so that the reverse path validation times out.
2365 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2366 static_cast<TestAlarmFactory::TestAlarm*>(
2367 QuicPathValidatorPeer::retry_timer(
2368 QuicConnectionPeer::path_validator(&connection_)))
2369 ->Fire();
2370 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2371 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2372 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2373 EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
2374 send_algorithm_);
2375 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2376
2377 // Verify that default_path_ is reverted and alternative_path_ is cleared.
2378 EXPECT_EQ(default_path->client_connection_id, client_cid0);
2379 EXPECT_EQ(default_path->server_connection_id, server_cid0);
2380 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
2381 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
2382 auto* retire_peer_issued_cid_alarm =
2383 connection_.GetRetirePeerIssuedConnectionIdAlarm();
2384 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
2385 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
2386 retire_peer_issued_cid_alarm->Fire();
2387 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2388 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2389}
2390
2391TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
2392 PathProbeTestInit(Perspective::IS_SERVER);
2393
2394 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2395 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
2396
2397 // Process a padded PING packet with no peer address change on server side
2398 // will be ignored. But a PATH CHALLENGE packet with no peer address change
2399 // will be considered as path probing.
2400 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2401
2402 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2403 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2404 probing_packet->encrypted_length),
2405 clock_.Now()));
2406
2407 uint64_t num_probing_received =
2408 connection_.GetStats().num_connectivity_probing_received;
2409 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2410
2411 EXPECT_EQ(
2412 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2413 connection_.GetStats().num_connectivity_probing_received);
2414 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2415 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2416}
2417
2418// Regression test for b/150161358.
2419TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
2420 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2421 writer_->SetWriteBlocked();
2422
2423 // Send a MTU packet while blocked. It should be buffered.
2424 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2425 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2426 EXPECT_TRUE(writer_->IsWriteBlocked());
2427
2428 writer_->AlwaysGetPacketTooLarge();
2429 writer_->SetWritable();
2430 connection_.OnCanWrite();
2431}
2432
2433TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2434 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2435 if (!IsDefaultTestConfiguration()) {
2436 return;
2437 }
2438
2439 set_perspective(Perspective::IS_CLIENT);
2440
2441 BlockOnNextWrite();
2442
2443 QuicStreamId stream_id = 2;
2444 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2445
2446 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2447
2448 writer_->SetWritable();
2449 connection_.SendConnectivityProbingPacket(writer_.get(),
2450 connection_.peer_address());
2451 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2452 connection_.OnCanWrite();
2453}
2454
2455TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2456 // Regression test for b/74073386.
2457 {
2458 InSequence seq;
2459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2460 .Times(AtLeast(1));
2461 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
2462 }
2463
2464 set_perspective(Perspective::IS_CLIENT);
2465
2466 writer_->SimulateNextPacketTooLarge();
2467
2468 // This packet write should fail, which should cause the connection to close
2469 // after sending a connection close packet, then the failed packet should be
2470 // queued.
2471 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2472
2473 EXPECT_FALSE(connection_.connected());
2474 // No need to buffer packets.
2475 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2476
2477 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2478 connection_.OnCanWrite();
2479 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2480}
2481
2482class TestQuicPathValidationContext : public QuicPathValidationContext {
2483 public:
2484 TestQuicPathValidationContext(const QuicSocketAddress& self_address,
2485 const QuicSocketAddress& peer_address,
2486
2487 QuicPacketWriter* writer)
2488 : QuicPathValidationContext(self_address, peer_address),
2489 writer_(writer) {}
2490
2491 QuicPacketWriter* WriterToUse() override { return writer_; }
2492
2493 private:
2494 QuicPacketWriter* writer_;
2495};
2496
2497class TestValidationResultDelegate : public QuicPathValidator::ResultDelegate {
2498 public:
2499 TestValidationResultDelegate(QuicConnection* connection,
2500 const QuicSocketAddress& expected_self_address,
2501 const QuicSocketAddress& expected_peer_address,
2502 bool* success)
2503 : QuicPathValidator::ResultDelegate(),
2504 connection_(connection),
2505 expected_self_address_(expected_self_address),
2506 expected_peer_address_(expected_peer_address),
2507 success_(success) {}
2508 void OnPathValidationSuccess(
wub130bde92022-08-01 14:33:14 -07002509 std::unique_ptr<QuicPathValidationContext> context,
2510 QuicTime /*start_time*/) override {
Bence Békybac04052022-04-07 15:44:29 -04002511 EXPECT_EQ(expected_self_address_, context->self_address());
2512 EXPECT_EQ(expected_peer_address_, context->peer_address());
2513 *success_ = true;
2514 }
2515
2516 void OnPathValidationFailure(
2517 std::unique_ptr<QuicPathValidationContext> context) override {
2518 EXPECT_EQ(expected_self_address_, context->self_address());
2519 EXPECT_EQ(expected_peer_address_, context->peer_address());
2520 if (connection_->perspective() == Perspective::IS_CLIENT) {
danzh8fdee2e2023-01-05 15:33:02 -08002521 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2522 *context);
Bence Békybac04052022-04-07 15:44:29 -04002523 }
2524 *success_ = false;
2525 }
2526
2527 private:
2528 QuicConnection* connection_;
2529 QuicSocketAddress expected_self_address_;
2530 QuicSocketAddress expected_peer_address_;
2531 bool* success_;
2532};
2533
danzh8fdee2e2023-01-05 15:33:02 -08002534// A test implementation which migrates to server preferred address
2535// on path validation suceeds. Otherwise, client cleans up alternative path.
fayang5c6e7012023-01-08 20:06:01 -08002536class ServerPreferredAddressTestResultDelegate
danzh8fdee2e2023-01-05 15:33:02 -08002537 : public QuicPathValidator::ResultDelegate {
2538 public:
2539 explicit ServerPreferredAddressTestResultDelegate(QuicConnection* connection)
2540 : connection_(connection) {}
2541 void OnPathValidationSuccess(
2542 std::unique_ptr<QuicPathValidationContext> context,
2543 QuicTime /*start_time*/) override {
2544 connection_->OnServerPreferredAddressValidated(*context, false);
2545 }
2546
2547 void OnPathValidationFailure(
2548 std::unique_ptr<QuicPathValidationContext> context) override {
2549 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false,
2550 *context);
2551 }
2552
2553 protected:
2554 QuicConnection* connection() { return connection_; }
2555
2556 private:
2557 QuicConnection* connection_;
2558};
2559
Bence Békybac04052022-04-07 15:44:29 -04002560// Receive a path probe request at the server side, i.e.,
2561// in non-IETF version: receive a padded PING packet with a peer addess change;
2562// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2563// change.
2564TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
2565 PathProbeTestInit(Perspective::IS_SERVER);
2566
2567 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2568 QuicPathFrameBuffer payload;
2569 if (!GetParam().version.HasIetfQuicFrames()) {
2570 EXPECT_CALL(visitor_,
2571 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2572 .Times(1);
2573 } else {
2574 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2575 if (connection_.validate_client_address()) {
2576 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2577 .Times(AtLeast(1u))
2578 .WillOnce(Invoke([&]() {
2579 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2580 EXPECT_EQ(1u, writer_->path_response_frames().size());
2581 payload = writer_->path_challenge_frames().front().data_buffer;
2582 }));
2583 }
2584 }
2585 // Process a probing packet from a new peer address on server side
2586 // is effectively receiving a connectivity probing.
2587 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2588 /*port=*/23456);
2589
2590 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2591 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2592 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2593 probing_packet->encrypted_length),
2594 clock_.Now()));
2595 uint64_t num_probing_received =
2596 connection_.GetStats().num_connectivity_probing_received;
2597 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2598
2599 EXPECT_EQ(num_probing_received + 1,
2600 connection_.GetStats().num_connectivity_probing_received);
2601 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2602 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhaf2e52a2022-04-20 07:37:03 -07002603 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002604 QuicByteCount bytes_sent =
2605 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_);
2606 EXPECT_LT(0u, bytes_sent);
2607 EXPECT_EQ(received->length(),
2608 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2609
2610 // Receiving one more probing packet should update the bytes count.
2611 probing_packet = ConstructProbingPacket();
2612 received.reset(ConstructReceivedPacket(
2613 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2614 probing_packet->encrypted_length),
2615 clock_.Now()));
2616 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2617
2618 EXPECT_EQ(num_probing_received + 2,
2619 connection_.GetStats().num_connectivity_probing_received);
2620 EXPECT_EQ(2 * bytes_sent,
2621 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2622 EXPECT_EQ(2 * received->length(),
2623 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2624
2625 bool success = false;
2626 if (!connection_.validate_client_address()) {
2627 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2628 .Times(AtLeast(1u))
2629 .WillOnce(Invoke([&]() {
2630 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2631 payload = writer_->path_challenge_frames().front().data_buffer;
2632 }));
2633
2634 connection_.ValidatePath(
2635 std::make_unique<TestQuicPathValidationContext>(
2636 connection_.self_address(), kNewPeerAddress, writer_.get()),
2637 std::make_unique<TestValidationResultDelegate>(
2638 &connection_, connection_.self_address(), kNewPeerAddress,
2639 &success));
2640 }
2641 EXPECT_EQ((connection_.validate_client_address() ? 2 : 3) * bytes_sent,
2642 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2643 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -07002644 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04002645 ProcessFramesPacketWithAddresses(frames, connection_.self_address(),
2646 kNewPeerAddress,
2647 ENCRYPTION_FORWARD_SECURE);
2648 EXPECT_LT(2 * received->length(),
2649 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2650 if (connection_.validate_client_address()) {
2651 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
2652 }
2653 // Receiving another probing packet from a newer address with a different
2654 // port shouldn't trigger another reverse path validation.
2655 QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
2656 /*port=*/34567);
2657 probing_packet = ConstructProbingPacket();
2658 received.reset(ConstructReceivedPacket(
2659 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2660 probing_packet->encrypted_length),
2661 clock_.Now()));
2662 ProcessReceivedPacket(kSelfAddress, kNewerPeerAddress, *received);
2663 EXPECT_FALSE(connection_.HasPendingPathValidation());
2664 EXPECT_EQ(connection_.validate_client_address(),
2665 QuicConnectionPeer::IsAlternativePathValidated(&connection_));
2666 }
2667
2668 // Process another packet with the old peer address on server side will not
2669 // start peer migration.
2670 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2671 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2672 ENCRYPTION_INITIAL);
2673 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2674 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2675}
2676
2677// Receive a padded PING packet with a port change on server side.
2678TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2679 set_perspective(Perspective::IS_SERVER);
2680 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2681 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2682 if (version().SupportsAntiAmplificationLimit()) {
2683 QuicConnectionPeer::SetAddressValidated(&connection_);
2684 }
2685
2686 // Clear direct_peer_address.
2687 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2688 // Clear effective_peer_address, it is the same as direct_peer_address for
2689 // this test.
2690 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2691 QuicSocketAddress());
2692 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2693
2694 if (GetParam().version.UsesCryptoFrames()) {
2695 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2696 } else {
2697 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2698 }
2699 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2700 ENCRYPTION_INITIAL);
2701 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2702 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2703
2704 if (GetParam().version.HasIetfQuicFrames()) {
2705 // In IETF version, a padded PING packet with port change is not taken as
2706 // connectivity probe.
2707 EXPECT_CALL(visitor_, GetHandshakeState())
2708 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2709 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2710 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2711 } else {
2712 // In non-IETF version, process a padded PING packet from a new peer
2713 // address on server side is effectively receiving a connectivity probing.
2714 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2715 EXPECT_CALL(visitor_,
2716 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2717 .Times(1);
2718 }
2719 const QuicSocketAddress kNewPeerAddress =
2720 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2721
2722 QuicFrames frames;
2723 // Write a PING frame, which has no data payload.
2724 QuicPingFrame ping_frame;
2725 frames.push_back(QuicFrame(ping_frame));
2726
2727 // Add padding to the rest of the packet.
2728 QuicPaddingFrame padding_frame;
2729 frames.push_back(QuicFrame(padding_frame));
2730
2731 uint64_t num_probing_received =
2732 connection_.GetStats().num_connectivity_probing_received;
2733
2734 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
2735 ENCRYPTION_INITIAL);
2736
2737 if (GetParam().version.HasIetfQuicFrames()) {
2738 // Padded PING with port changen is not considered as connectivity probe but
2739 // a PORT CHANGE.
2740 EXPECT_EQ(num_probing_received,
2741 connection_.GetStats().num_connectivity_probing_received);
2742 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2743 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2744 } else {
2745 EXPECT_EQ(num_probing_received + 1,
2746 connection_.GetStats().num_connectivity_probing_received);
2747 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2748 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2749 }
2750
2751 if (GetParam().version.HasIetfQuicFrames()) {
2752 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2753 }
2754 // Process another packet with the old peer address on server side. gQUIC
2755 // shouldn't regard this as a peer migration.
2756 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2757 ENCRYPTION_INITIAL);
2758 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2759 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2760}
2761
2762TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
2763 PathProbeTestInit(Perspective::IS_SERVER);
2764
2765 // Decrease packet number to simulate out-of-order packets.
2766 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2767
2768 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2769 if (!GetParam().version.HasIetfQuicFrames()) {
2770 EXPECT_CALL(visitor_,
2771 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2772 .Times(1);
2773 } else {
2774 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2775 }
2776
2777 // Process a padded PING packet from a new peer address on server side
2778 // is effectively receiving a connectivity probing, even if a newer packet has
2779 // been received before this one.
2780 const QuicSocketAddress kNewPeerAddress =
2781 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2782
2783 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2784 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2785 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2786 probing_packet->encrypted_length),
2787 clock_.Now()));
2788
2789 uint64_t num_probing_received =
2790 connection_.GetStats().num_connectivity_probing_received;
2791 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2792
2793 EXPECT_EQ(num_probing_received + 1,
2794 connection_.GetStats().num_connectivity_probing_received);
2795 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2796 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2797}
2798
2799TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2800 PathProbeTestInit(Perspective::IS_SERVER);
2801
2802 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2803 if (!GetParam().version.HasIetfQuicFrames()) {
2804 EXPECT_CALL(visitor_,
2805 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2806 .Times(1);
2807 } else {
2808 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2809 }
2810
2811 // Process a padded PING packet from a new peer address on server side
2812 // is effectively receiving a connectivity probing.
2813 const QuicSocketAddress kNewPeerAddress =
2814 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2815
2816 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2817 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2818 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2819 probing_packet->encrypted_length),
2820 clock_.Now()));
2821 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2822 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2823 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2824
2825 // Process another non-probing packet with the new peer address on server
2826 // side will start peer migration.
2827 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2828
2829 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2830 kNewPeerAddress, ENCRYPTION_INITIAL);
2831 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2832 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2833}
2834
2835TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) {
2836 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2837 PathProbeTestInit(Perspective::IS_CLIENT);
2838
2839 // Client takes all padded PING packet as speculative connectivity
2840 // probing packet, and reports to visitor.
2841 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2842
2843 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2844 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2845 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2846 probing_packet->encrypted_length),
2847 clock_.Now()));
2848 uint64_t num_probing_received =
2849 connection_.GetStats().num_connectivity_probing_received;
2850 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2851
2852 EXPECT_EQ(
2853 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2854 connection_.GetStats().num_connectivity_probing_received);
2855 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2856 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2857}
2858
2859TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2860 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2861 // PATH RESPONSE with peer address change as correct validation on the new
2862 // path.
2863 if (GetParam().version.HasIetfQuicFrames()) {
2864 return;
2865 }
2866 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2867 PathProbeTestInit(Perspective::IS_CLIENT);
2868
2869 // Process a padded PING packet with a different self address on client side
2870 // is effectively receiving a connectivity probing.
2871 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2872 if (!GetParam().version.HasIetfQuicFrames()) {
2873 EXPECT_CALL(visitor_,
2874 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2875 .Times(1);
2876 } else {
2877 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2878 }
2879
2880 const QuicSocketAddress kNewSelfAddress =
2881 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2882
2883 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2884 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2885 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2886 probing_packet->encrypted_length),
2887 clock_.Now()));
2888 uint64_t num_probing_received =
2889 connection_.GetStats().num_connectivity_probing_received;
2890 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2891
2892 EXPECT_EQ(num_probing_received + 1,
2893 connection_.GetStats().num_connectivity_probing_received);
2894 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2895 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2896}
2897
2898TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2899 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2900 set_perspective(Perspective::IS_CLIENT);
2901 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2902
2903 // Clear direct_peer_address.
2904 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2905 // Clear effective_peer_address, it is the same as direct_peer_address for
2906 // this test.
2907 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2908 QuicSocketAddress());
2909 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2910
fayangd1f2c992022-12-21 10:34:55 -08002911 if (connection_.version().HasIetfQuicFrames()) {
2912 // Verify the 2nd packet from unknown server address gets dropped.
2913 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2914 } else if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2915 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -04002916 } else {
fayangd1f2c992022-12-21 10:34:55 -08002917 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
Bence Békybac04052022-04-07 15:44:29 -04002918 }
2919 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2920 ENCRYPTION_INITIAL);
2921 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2922 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
Bence Békybac04052022-04-07 15:44:29 -04002923 const QuicSocketAddress kNewPeerAddress =
2924 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2925 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2926 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2927 kNewPeerAddress, ENCRYPTION_INITIAL);
2928 if (connection_.version().HasIetfQuicFrames()) {
2929 // IETF QUIC disallows server initiated address change.
2930 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2931 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2932 } else {
2933 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2934 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2935 }
2936}
2937
fayangd1f2c992022-12-21 10:34:55 -08002938TEST_P(QuicConnectionTest, ServerAddressChangesToKnownAddress) {
2939 if (!connection_.version().HasIetfQuicFrames()) {
2940 return;
2941 }
2942 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2943 set_perspective(Perspective::IS_CLIENT);
2944 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2945
2946 // Clear direct_peer_address.
2947 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2948 // Clear effective_peer_address, it is the same as direct_peer_address for
2949 // this test.
2950 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2951 QuicSocketAddress());
2952 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2953
2954 // Verify all 3 packets get processed.
2955 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
2956 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2957 ENCRYPTION_INITIAL);
2958 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2959 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2960
2961 // Process another packet with a different but known server address.
2962 const QuicSocketAddress kNewPeerAddress =
2963 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2964 connection_.AddKnownServerAddress(kNewPeerAddress);
2965 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(0);
2966 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2967 kNewPeerAddress, ENCRYPTION_INITIAL);
2968 // Verify peer address does not change.
2969 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2970 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2971
2972 // Process 3rd packet from previous server address.
2973 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2974 ENCRYPTION_INITIAL);
2975 // Verify peer address does not change.
2976 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2977 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2978}
2979
danzh8fdee2e2023-01-05 15:33:02 -08002980TEST_P(QuicConnectionTest,
2981 PeerAddressChangesToPreferredAddressBeforeClientInitiates) {
2982 if (!version().HasIetfQuicFrames()) {
2983 return;
2984 }
2985 ASSERT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2986 ASSERT_TRUE(connection_.self_address().host().IsIPv6());
2987 SetQuicReloadableFlag(quic_connection_migration_use_new_cid_v2, true);
2988 const QuicConnectionId connection_id = TestConnectionId(17);
2989 const StatelessResetToken reset_token =
2990 QuicUtils::GenerateStatelessResetToken(connection_id);
2991
2992 connection_.CreateConnectionIdManager();
2993
2994 connection_.SendCryptoStreamData();
2995 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
2996 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
2997 QuicAckFrame frame = InitAckFrame(1);
2998 // Received ACK for packet 1.
2999 ProcessFramePacketAtLevel(1, QuicFrame(&frame), ENCRYPTION_INITIAL);
3000 // Discard INITIAL key.
3001 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
3002 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3003
3004 QuicConfig config;
3005 config.SetClientConnectionOptions(QuicTagVector{kSPAD});
3006 config.SetConnectionOptionsToSend(QuicTagVector{kRVCM});
3007 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
3008 kTestStatelessResetToken);
3009 QuicConfigPeer::SetReceivedAlternateServerAddress(&config,
3010 kServerPreferredAddress);
3011 QuicConfigPeer::SetPreferredAddressConnectionIdAndToken(
3012 &config, connection_id, reset_token);
3013 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3014 connection_.SetFromConfig(config);
3015 EXPECT_EQ(kPeerAddress, connection_.peer_address());
3016 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
3017 ASSERT_TRUE(QuicConnectionPeer::GetServerPreferredAddress(&connection_)
3018 .IsInitialized());
3019 EXPECT_EQ(kServerPreferredAddress,
3020 QuicConnectionPeer::GetServerPreferredAddress(&connection_));
3021
3022 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(0);
3023 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
3024 kServerPreferredAddress, ENCRYPTION_INITIAL);
3025}
3026
Bence Békybac04052022-04-07 15:44:29 -04003027TEST_P(QuicConnectionTest, MaxPacketSize) {
3028 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3029 EXPECT_EQ(1250u, connection_.max_packet_length());
3030}
3031
3032TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
3033 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3034
3035 // SetFromConfig is always called after construction from InitializeSession.
3036 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3037 constexpr uint32_t kTestMaxPacketSize = 1233u;
3038 QuicConfig config;
3039 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3040 connection_.SetFromConfig(config);
3041
3042 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
3043}
3044
3045TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
3046 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
3047
3048 // SetFromConfig is always called after construction from InitializeSession.
3049 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3050 constexpr uint32_t kTestMaxPacketSize = 1450u;
3051 QuicConfig config;
3052 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
3053 connection_.SetFromConfig(config);
3054
3055 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
3056}
3057
3058TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
3059 TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress,
3060 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003061 Perspective::IS_SERVER, version(),
3062 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003063 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
3064 EXPECT_EQ(1000u, connection.max_packet_length());
3065}
3066
3067TEST_P(QuicConnectionTest, LowerServerResponseMtuTest) {
3068 set_perspective(Perspective::IS_SERVER);
3069 connection_.SetMaxPacketLength(1000);
3070 EXPECT_EQ(1000u, connection_.max_packet_length());
3071
birenroyef686222022-09-12 11:34:34 -07003072 SetQuicFlag(quic_use_lower_server_response_mtu_for_test, true);
Bence Békybac04052022-04-07 15:44:29 -04003073 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(::testing::AtMost(1));
3074 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(::testing::AtMost(1));
3075 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3076 EXPECT_EQ(1250u, connection_.max_packet_length());
3077}
3078
3079TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
3080 set_perspective(Perspective::IS_SERVER);
3081 connection_.SetMaxPacketLength(1000);
3082
3083 QuicPacketHeader header;
3084 header.destination_connection_id = connection_id_;
3085 header.version_flag = true;
3086 header.packet_number = QuicPacketNumber(12);
3087
3088 if (QuicVersionHasLongHeaderLengths(
3089 peer_framer_.version().transport_version)) {
3090 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07003091 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3092 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04003093 }
3094
3095 QuicFrames frames;
3096 QuicPaddingFrame padding;
3097 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3098 frames.push_back(QuicFrame(&crypto_frame_));
3099 } else {
3100 frames.push_back(QuicFrame(frame1_));
3101 }
3102 frames.push_back(QuicFrame(padding));
3103 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3104 char buffer[kMaxOutgoingPacketSize];
3105 size_t encrypted_length =
3106 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3107 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08003108 EXPECT_EQ(kMaxOutgoingPacketSize,
3109 encrypted_length +
3110 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003111
3112 framer_.set_version(version());
3113 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3114 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3115 } else {
3116 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3117 }
3118 connection_.ProcessUdpPacket(
3119 kSelfAddress, kPeerAddress,
3120 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3121 false));
3122
martinduke9e0811c2022-12-08 20:35:57 -08003123 EXPECT_EQ(kMaxOutgoingPacketSize,
3124 connection_.max_packet_length() +
3125 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003126}
3127
3128TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
3129 const QuicByteCount lower_max_packet_size = 1240;
3130 writer_->set_max_packet_size(lower_max_packet_size);
3131 set_perspective(Perspective::IS_SERVER);
3132 connection_.SetMaxPacketLength(1000);
3133 EXPECT_EQ(1000u, connection_.max_packet_length());
3134
3135 QuicPacketHeader header;
3136 header.destination_connection_id = connection_id_;
3137 header.version_flag = true;
3138 header.packet_number = QuicPacketNumber(12);
3139
3140 if (QuicVersionHasLongHeaderLengths(
3141 peer_framer_.version().transport_version)) {
3142 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07003143 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
3144 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04003145 }
3146
3147 QuicFrames frames;
3148 QuicPaddingFrame padding;
3149 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3150 frames.push_back(QuicFrame(&crypto_frame_));
3151 } else {
3152 frames.push_back(QuicFrame(frame1_));
3153 }
3154 frames.push_back(QuicFrame(padding));
3155 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3156 char buffer[kMaxOutgoingPacketSize];
3157 size_t encrypted_length =
3158 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3159 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08003160 EXPECT_EQ(kMaxOutgoingPacketSize,
3161 encrypted_length +
3162 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003163
3164 framer_.set_version(version());
3165 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3166 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3167 } else {
3168 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3169 }
3170 connection_.ProcessUdpPacket(
3171 kSelfAddress, kPeerAddress,
3172 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3173 false));
3174
3175 // Here, the limit imposed by the writer is lower than the size of the packet
3176 // received, so the writer max packet size is used.
3177 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3178}
3179
3180TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
3181 const QuicByteCount lower_max_packet_size = 1240;
3182 writer_->set_max_packet_size(lower_max_packet_size);
3183
3184 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
3185 "Default maximum packet size is too low");
3186 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
3187
3188 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3189}
3190
3191TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
3192 const QuicConnectionId connection_id = TestConnectionId(17);
3193 const QuicByteCount lower_max_packet_size = 1240;
3194 writer_->set_max_packet_size(lower_max_packet_size);
3195 TestConnection connection(connection_id, kSelfAddress, kPeerAddress,
3196 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003197 Perspective::IS_CLIENT, version(),
3198 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003199 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
3200 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
3201}
3202
3203TEST_P(QuicConnectionTest, PacketsInOrder) {
3204 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3205
3206 ProcessPacket(1);
3207 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
3208 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3209
3210 ProcessPacket(2);
3211 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
3212 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3213
3214 ProcessPacket(3);
3215 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3216 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3217}
3218
3219TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
3220 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3221
3222 ProcessPacket(3);
3223 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3224 EXPECT_TRUE(IsMissing(2));
3225 EXPECT_TRUE(IsMissing(1));
3226
3227 ProcessPacket(2);
3228 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3229 EXPECT_FALSE(IsMissing(2));
3230 EXPECT_TRUE(IsMissing(1));
3231
3232 ProcessPacket(1);
3233 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3234 EXPECT_FALSE(IsMissing(2));
3235 EXPECT_FALSE(IsMissing(1));
3236}
3237
3238TEST_P(QuicConnectionTest, DuplicatePacket) {
3239 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3240
3241 ProcessPacket(3);
3242 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3243 EXPECT_TRUE(IsMissing(2));
3244 EXPECT_TRUE(IsMissing(1));
3245
3246 // Send packet 3 again, but do not set the expectation that
3247 // the visitor OnStreamFrame() will be called.
3248 ProcessDataPacket(3);
3249 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3250 EXPECT_TRUE(IsMissing(2));
3251 EXPECT_TRUE(IsMissing(1));
3252}
3253
3254TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
3255 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3256 return;
3257 }
3258 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3259
3260 ProcessPacket(3);
3261 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3262 EXPECT_TRUE(IsMissing(2));
3263 EXPECT_TRUE(IsMissing(1));
3264
3265 ProcessPacket(2);
3266 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3267 EXPECT_TRUE(IsMissing(1));
3268
3269 ProcessPacket(5);
3270 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
3271 EXPECT_TRUE(IsMissing(1));
3272 EXPECT_TRUE(IsMissing(4));
3273
3274 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
3275 // packet the peer will not retransmit. It indicates this by sending 'least
3276 // awaiting' is 4. The connection should then realize 1 will not be
3277 // retransmitted, and will remove it from the missing list.
3278 QuicAckFrame frame = InitAckFrame(1);
3279 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3280 ProcessAckPacket(6, &frame);
3281
3282 // Force an ack to be sent.
3283 SendAckPacketToPeer();
3284 EXPECT_TRUE(IsMissing(4));
3285}
3286
3287TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
3288 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
3289 if (!IsDefaultTestConfiguration() ||
3290 VersionHasIetfQuicFrames(version().transport_version)) {
3291 return;
3292 }
3293
3294 // Process an unencrypted packet from the non-crypto stream.
3295 frame1_.stream_id = 3;
3296 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3297 EXPECT_CALL(visitor_,
3298 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3299 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
3300 "");
3301 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
3302}
3303
3304TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
3305 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3306
3307 ProcessPacket(3);
3308 // Should not cause an ack.
3309 EXPECT_EQ(0u, writer_->packets_write_attempts());
3310
3311 ProcessPacket(2);
3312 // Should ack immediately, since this fills the last hole.
3313 EXPECT_EQ(1u, writer_->packets_write_attempts());
3314
3315 ProcessPacket(1);
3316 // Should ack immediately, since this fills the last hole.
3317 EXPECT_EQ(2u, writer_->packets_write_attempts());
3318
3319 ProcessPacket(4);
3320 // Should not cause an ack.
3321 EXPECT_EQ(2u, writer_->packets_write_attempts());
3322}
3323
3324TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
3325 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3326
3327 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3328 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3329 EXPECT_EQ(2u, writer_->packets_write_attempts());
3330
3331 QuicAckFrame ack1 = InitAckFrame(1);
3332 QuicAckFrame ack2 = InitAckFrame(2);
3333 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3334 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3335 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
3336 }
3337 ProcessAckPacket(2, &ack2);
3338 // Should ack immediately since we have missing packets.
3339 EXPECT_EQ(2u, writer_->packets_write_attempts());
3340
3341 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3342 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
3343 }
3344 ProcessAckPacket(1, &ack1);
3345 // Should not ack an ack filling a missing packet.
3346 EXPECT_EQ(2u, writer_->packets_write_attempts());
3347}
3348
3349TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
3350 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3351 QuicPacketNumber original, second;
3352
3353 QuicByteCount packet_size =
3354 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3355 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3356
3357 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3358 // First nack triggers early retransmit.
3359 LostPacketVector lost_packets;
3360 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
3361 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3362 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3363 Return(LossDetectionInterface::DetectionStats())));
3364 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3365 QuicPacketNumber retransmission;
3366 // Packet 1 is short header for IETF QUIC because the encryption level
3367 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
3368 EXPECT_CALL(*send_algorithm_,
3369 OnPacketSent(_, _, _,
3370 GetParam().version.HasIetfInvariantHeader()
3371 ? packet_size
3372 : packet_size - kQuicVersionSize,
3373 _))
3374 .WillOnce(SaveArg<2>(&retransmission));
3375
3376 ProcessAckPacket(&frame);
3377
3378 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
3379 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3380 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3381 ProcessAckPacket(&frame2);
3382
3383 // Now if the peer sends an ack which still reports the retransmitted packet
3384 // as missing, that will bundle an ack with data after two acks in a row
3385 // indicate the high water mark needs to be raised.
3386 EXPECT_CALL(*send_algorithm_,
3387 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3388 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
3389 // No ack sent.
3390 size_t padding_frame_count = writer_->padding_frames().size();
3391 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3392 EXPECT_EQ(1u, writer_->stream_frames().size());
3393
3394 // No more packet loss for the rest of the test.
3395 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3396 .Times(AnyNumber());
3397 ProcessAckPacket(&frame2);
3398 EXPECT_CALL(*send_algorithm_,
3399 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3400 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
3401 // Ack bundled.
3402 if (GetParam().no_stop_waiting) {
3403 // Do not ACK acks.
3404 EXPECT_EQ(1u, writer_->frame_count());
3405 } else {
3406 EXPECT_EQ(3u, writer_->frame_count());
3407 }
3408 EXPECT_EQ(1u, writer_->stream_frames().size());
3409 if (GetParam().no_stop_waiting) {
3410 EXPECT_TRUE(writer_->ack_frames().empty());
3411 } else {
3412 EXPECT_FALSE(writer_->ack_frames().empty());
3413 }
3414
3415 // But an ack with no missing packets will not send an ack.
3416 AckPacket(original, &frame2);
3417 ProcessAckPacket(&frame2);
3418 ProcessAckPacket(&frame2);
3419}
3420
3421TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) {
3422 if (!GetParam().version.HasIetfQuicFrames()) {
3423 return;
3424 }
3425 connection_.set_can_receive_ack_frequency_frame();
3426
3427 // Expect 13 acks, every 3rd packet including the first packet with
3428 // AckFrequencyFrame.
3429 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
3430 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3431
3432 QuicAckFrequencyFrame ack_frequency_frame;
3433 ack_frequency_frame.packet_tolerance = 3;
3434 ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
3435 ENCRYPTION_FORWARD_SECURE);
3436
3437 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38);
3438 // Receives packets 2 - 39.
3439 for (size_t i = 2; i <= 39; ++i) {
3440 ProcessDataPacket(i);
3441 }
3442}
3443
3444TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
3445 const size_t kMinRttMs = 40;
3446 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
3447 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
3448 QuicTime::Delta::Zero(), QuicTime::Zero());
3449 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
3450
3451 // Start ack decimation from 10th packet.
3452 connection_.set_min_received_before_ack_decimation(10);
3453
3454 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3455 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
3456
3457 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
3458 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
3459 // Receives packets 1 - 29.
3460 for (size_t i = 1; i <= 29; ++i) {
3461 ProcessDataPacket(i);
3462 }
3463
3464 // We now receive the 30th packet, and so we send an ack.
3465 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3466 ProcessDataPacket(30);
3467}
3468
3469TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
3470 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3471 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3472 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3473
3474 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3475 // Receives packets 1 - 39.
3476 for (size_t i = 1; i <= 39; ++i) {
3477 ProcessDataPacket(i);
3478 }
3479 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3480 // WINDOW_UPDATE.
3481 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3482 .WillOnce(Invoke([this]() {
3483 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3484 }));
3485 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3486 EXPECT_EQ(0u, writer_->window_update_frames().size());
3487 ProcessDataPacket(40);
3488 EXPECT_EQ(1u, writer_->window_update_frames().size());
3489
3490 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3491 // Receives packets 41 - 59.
3492 for (size_t i = 41; i <= 59; ++i) {
3493 ProcessDataPacket(i);
3494 }
3495 // Send a packet containing stream frame.
3496 SendStreamDataToPeer(
3497 QuicUtils::GetFirstBidirectionalStreamId(
3498 connection_.version().transport_version, Perspective::IS_CLIENT),
3499 "bar", 0, NO_FIN, nullptr);
3500
3501 // Session will not be informed until receiving another 20 packets.
3502 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3503 for (size_t i = 60; i <= 98; ++i) {
3504 ProcessDataPacket(i);
3505 EXPECT_EQ(0u, writer_->window_update_frames().size());
3506 }
3507 // Session does not add a retransmittable frame.
3508 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3509 .WillOnce(Invoke([this]() {
3510 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3511 }));
3512 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3513 EXPECT_EQ(0u, writer_->ping_frames().size());
3514 ProcessDataPacket(99);
3515 EXPECT_EQ(0u, writer_->window_update_frames().size());
3516 // A ping frame will be added.
3517 EXPECT_EQ(1u, writer_->ping_frames().size());
3518}
3519
3520TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
Bence Békybac04052022-04-07 15:44:29 -04003521 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3522 QuicConfig config;
3523 QuicTagVector connection_options;
3524 connection_options.push_back(kEACK);
3525 config.SetConnectionOptionsToSend(connection_options);
3526 connection_.SetFromConfig(config);
3527
3528 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3529 connection_.OnHandshakeComplete();
3530
3531 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3532 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3533
3534 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3535 // Receive packets 1 - 9.
3536 for (size_t i = 1; i <= 9; ++i) {
3537 ProcessDataPacket(i);
3538 }
3539
3540 // Send a ping and fire the retransmission alarm.
3541 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3542 SendPing();
3543 QuicTime retransmission_time =
3544 connection_.GetRetransmissionAlarm()->deadline();
3545 clock_.AdvanceTime(retransmission_time - clock_.Now());
3546 connection_.GetRetransmissionAlarm()->Fire();
fayang339f0c82022-04-30 14:20:02 -07003547 ASSERT_LT(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04003548
3549 // Process a packet, which requests a retransmittable frame be bundled
3550 // with the ACK.
3551 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3552 .WillOnce(Invoke([this]() {
3553 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3554 }));
3555 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3556 ProcessDataPacket(11);
3557 EXPECT_EQ(1u, writer_->window_update_frames().size());
3558}
3559
3560TEST_P(QuicConnectionTest, LeastUnackedLower) {
3561 if (GetParam().version.HasIetfInvariantHeader()) {
3562 return;
3563 }
3564 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3565
3566 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3567 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3568 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3569
3570 // Start out saying the least unacked is 2.
3571 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3572 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3573
3574 // Change it to 1, but lower the packet number to fake out-of-order packets.
3575 // This should be fine.
3576 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3577 // The scheduler will not process out of order acks, but all packet processing
3578 // causes the connection to try to write.
3579 if (!GetParam().no_stop_waiting) {
3580 EXPECT_CALL(visitor_, OnCanWrite());
3581 }
3582 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3583
3584 // Now claim it's one, but set the ordering so it was sent "after" the first
3585 // one. This should cause a connection error.
3586 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3587 if (!GetParam().no_stop_waiting) {
3588 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3589 .Times(AtLeast(1));
3590 EXPECT_CALL(visitor_,
3591 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3592 .Times(AtLeast(1));
3593 }
3594 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3595 if (!GetParam().no_stop_waiting) {
3596 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3597 }
3598}
3599
3600TEST_P(QuicConnectionTest, TooManySentPackets) {
3601 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3602
3603 QuicPacketCount max_tracked_packets = 50;
3604 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3605
3606 const int num_packets = max_tracked_packets + 5;
3607
3608 for (int i = 0; i < num_packets; ++i) {
3609 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3610 }
3611
3612 EXPECT_CALL(visitor_,
3613 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3614
3615 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3616
3617 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
3618}
3619
3620TEST_P(QuicConnectionTest, LargestObservedLower) {
3621 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3622
3623 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3624 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3625 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3626 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3627
3628 // Start out saying the largest observed is 2.
3629 QuicAckFrame frame1 = InitAckFrame(1);
3630 QuicAckFrame frame2 = InitAckFrame(2);
3631 ProcessAckPacket(&frame2);
3632
3633 EXPECT_CALL(visitor_, OnCanWrite());
3634 ProcessAckPacket(&frame1);
3635}
3636
3637TEST_P(QuicConnectionTest, AckUnsentData) {
3638 // Ack a packet which has not been sent.
3639 EXPECT_CALL(visitor_,
3640 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3641 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3642 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3643 QuicAckFrame frame = InitAckFrame(1);
3644 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3645 ProcessAckPacket(&frame);
3646 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
3647}
3648
3649TEST_P(QuicConnectionTest, BasicSending) {
3650 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3651 return;
3652 }
3653 const QuicConnectionStats& stats = connection_.GetStats();
3654 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
3655 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3656 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3657 ProcessDataPacket(1);
3658 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3659 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3660 QuicPacketNumber last_packet;
3661 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3662 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3663 SendAckPacketToPeer(); // Packet 2
3664
3665 if (GetParam().no_stop_waiting) {
3666 // Expect no stop waiting frame is sent.
3667 EXPECT_FALSE(least_unacked().IsInitialized());
3668 } else {
3669 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3670 }
3671
3672 SendAckPacketToPeer(); // Packet 3
3673 if (GetParam().no_stop_waiting) {
3674 // Expect no stop waiting frame is sent.
3675 EXPECT_FALSE(least_unacked().IsInitialized());
3676 } else {
3677 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3678 }
3679
3680 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3681 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3682 SendAckPacketToPeer(); // Packet 5
3683 if (GetParam().no_stop_waiting) {
3684 // Expect no stop waiting frame is sent.
3685 EXPECT_FALSE(least_unacked().IsInitialized());
3686 } else {
3687 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3688 }
3689
3690 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3691
3692 // Peer acks up to packet 3.
3693 QuicAckFrame frame = InitAckFrame(3);
3694 ProcessAckPacket(&frame);
3695 SendAckPacketToPeer(); // Packet 6
3696
3697 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3698 // ack for 4.
3699 if (GetParam().no_stop_waiting) {
3700 // Expect no stop waiting frame is sent.
3701 EXPECT_FALSE(least_unacked().IsInitialized());
3702 } else {
3703 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3704 }
3705
3706 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3707
3708 // Peer acks up to packet 4, the last packet.
3709 QuicAckFrame frame2 = InitAckFrame(6);
3710 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3711
3712 // Verify that we did not send an ack.
3713 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3714
3715 // So the last ack has not changed.
3716 if (GetParam().no_stop_waiting) {
3717 // Expect no stop waiting frame is sent.
3718 EXPECT_FALSE(least_unacked().IsInitialized());
3719 } else {
3720 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3721 }
3722
3723 // If we force an ack, we shouldn't change our retransmit state.
3724 SendAckPacketToPeer(); // Packet 7
3725 if (GetParam().no_stop_waiting) {
3726 // Expect no stop waiting frame is sent.
3727 EXPECT_FALSE(least_unacked().IsInitialized());
3728 } else {
3729 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3730 }
3731
3732 // But if we send more data it should.
3733 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3734 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3735 SendAckPacketToPeer(); // Packet 9
3736 if (GetParam().no_stop_waiting) {
3737 // Expect no stop waiting frame is sent.
3738 EXPECT_FALSE(least_unacked().IsInitialized());
3739 } else {
3740 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3741 }
3742 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3743}
3744
3745// QuicConnection should record the packet sent-time prior to sending the
3746// packet.
3747TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3748 // We're using a MockClock for the tests, so we have complete control over the
3749 // time.
3750 // Our recorded timestamp for the last packet sent time will be passed in to
3751 // the send_algorithm. Make sure that it is set to the correct value.
3752 QuicTime actual_recorded_send_time = QuicTime::Zero();
3753 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3754 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3755
3756 // First send without any pause and check the result.
3757 QuicTime expected_recorded_send_time = clock_.Now();
3758 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3759 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3760 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3761 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3762
3763 // Now pause during the write, and check the results.
3764 actual_recorded_send_time = QuicTime::Zero();
3765 const QuicTime::Delta write_pause_time_delta =
3766 QuicTime::Delta::FromMilliseconds(5000);
3767 SetWritePauseTimeDelta(write_pause_time_delta);
3768 expected_recorded_send_time = clock_.Now();
3769
3770 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3771 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3772 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3773 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3774 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3775 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3776}
3777
QUICHE teamac0a8082022-06-13 09:17:05 -07003778TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithRetransmissions) {
3779 // Send two stream frames in 1 packet by queueing them.
3780 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3781
3782 {
3783 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3784 connection_.SaveAndSendStreamData(
3785 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3786 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3787 connection_.SaveAndSendStreamData(
3788 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3789 "helloworld", 0, NO_FIN, LOSS_RETRANSMISSION);
3790 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3791 }
3792
3793 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3794 EXPECT_FALSE(connection_.HasQueuedData());
3795
3796 EXPECT_EQ(2u, writer_->frame_count());
3797 for (auto& frame : writer_->stream_frames()) {
3798 EXPECT_EQ(frame->data_length, 10u);
3799 }
3800
3801 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3802 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 20u);
3803}
3804
3805TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithMixedFrames) {
3806 // Send two stream frames in 1 packet by queueing them.
3807 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3808
3809 {
3810 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3811 // First frame is retransmission. Second is NOT_RETRANSMISSION but the
3812 // packet retains the PTO_RETRANSMISSION type.
3813 connection_.SaveAndSendStreamData(
3814 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3815 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3816 connection_.SaveAndSendStreamData(
3817 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3818 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3819 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3820 }
3821
3822 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3823 EXPECT_FALSE(connection_.HasQueuedData());
3824
3825 EXPECT_EQ(2u, writer_->frame_count());
3826 for (auto& frame : writer_->stream_frames()) {
3827 EXPECT_EQ(frame->data_length, 10u);
3828 }
3829
3830 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3831 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 10u);
3832}
3833
3834TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_NoRetransmission) {
3835 // Send two stream frames in 1 packet by queueing them.
3836 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3837
3838 {
3839 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3840 // Both frames are NOT_RETRANSMISSION
3841 connection_.SaveAndSendStreamData(
3842 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3843 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3844 connection_.SaveAndSendStreamData(
3845 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3846 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3847 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3848 }
3849
3850 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3851 EXPECT_FALSE(connection_.HasQueuedData());
3852
3853 EXPECT_EQ(2u, writer_->frame_count());
3854 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 0u);
3855 ASSERT_EQ(connection_.GetStats().bytes_retransmitted, 0u);
3856}
3857
Bence Békybac04052022-04-07 15:44:29 -04003858TEST_P(QuicConnectionTest, FramePacking) {
3859 // Send two stream frames in 1 packet by queueing them.
3860 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3861 {
3862 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3863 connection_.SendStreamData3();
3864 connection_.SendStreamData5();
3865 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3866 }
3867 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3868 EXPECT_FALSE(connection_.HasQueuedData());
3869
3870 // Parse the last packet and ensure it's an ack and two stream frames from
3871 // two different streams.
3872 if (GetParam().no_stop_waiting) {
3873 EXPECT_EQ(2u, writer_->frame_count());
3874 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3875 } else {
3876 EXPECT_EQ(2u, writer_->frame_count());
3877 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3878 }
3879
3880 EXPECT_TRUE(writer_->ack_frames().empty());
3881
3882 ASSERT_EQ(2u, writer_->stream_frames().size());
3883 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3884 writer_->stream_frames()[0]->stream_id);
3885 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3886 writer_->stream_frames()[1]->stream_id);
3887}
3888
3889TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3890 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3891 // queueing them.
3892 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3893 {
3894 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3895 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3896 connection_.SendStreamData3();
3897 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08003898 // Set the crypters for INITIAL packets in the TestPacketWriter.
3899 if (!connection_.version().KnowsWhichDecrypterToUse()) {
3900 writer_->framer()->framer()->SetAlternativeDecrypter(
3901 ENCRYPTION_INITIAL,
3902 std::make_unique<NullDecrypter>(Perspective::IS_SERVER), false);
3903 }
Bence Békybac04052022-04-07 15:44:29 -04003904 connection_.SendCryptoStreamData();
3905 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3906 }
3907 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3908 EXPECT_FALSE(connection_.HasQueuedData());
3909
3910 // Parse the last packet and ensure it contains a crypto stream frame.
3911 EXPECT_LE(2u, writer_->frame_count());
3912 ASSERT_LE(1u, writer_->padding_frames().size());
3913 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3914 ASSERT_EQ(1u, writer_->stream_frames().size());
3915 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3916 writer_->stream_frames()[0]->stream_id);
3917 } else {
3918 EXPECT_LE(1u, writer_->crypto_frames().size());
3919 }
3920}
3921
3922TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3923 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3924 // queueing them.
3925 {
3926 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3927 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3928 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3929 connection_.SendCryptoStreamData();
3930 connection_.SendStreamData3();
3931 }
3932 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3933 EXPECT_FALSE(connection_.HasQueuedData());
3934
3935 // Parse the last packet and ensure it's the stream frame from stream 3.
3936 size_t padding_frame_count = writer_->padding_frames().size();
3937 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3938 ASSERT_EQ(1u, writer_->stream_frames().size());
3939 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3940 writer_->stream_frames()[0]->stream_id);
3941}
3942
3943TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3944 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3945 // Process a data packet to queue up a pending ack.
3946 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3947 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3948 } else {
3949 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3950 }
3951 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3952
3953 QuicPacketNumber last_packet;
3954 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3955 connection_.SendCryptoDataWithString("foo", 0);
3956 } else {
3957 SendStreamDataToPeer(
3958 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3959 NO_FIN, &last_packet);
3960 }
3961 // Verify ack is bundled with outging packet.
3962 EXPECT_FALSE(writer_->ack_frames().empty());
3963
3964 EXPECT_CALL(visitor_, OnCanWrite())
3965 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3966 &connection_, &TestConnection::SendStreamData3)),
3967 IgnoreResult(InvokeWithoutArgs(
3968 &connection_, &TestConnection::SendStreamData5))));
3969
3970 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3971
3972 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3973 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martinduke9e0811c2022-12-08 20:35:57 -08003974 peer_framer_.SetEncrypter(
3975 ENCRYPTION_FORWARD_SECURE,
3976 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
3977 SetDecrypter(
3978 ENCRYPTION_FORWARD_SECURE,
3979 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04003980 ProcessDataPacket(2);
3981
3982 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3983 EXPECT_FALSE(connection_.HasQueuedData());
3984
3985 // Parse the last packet and ensure it's an ack and two stream frames from
3986 // two different streams.
3987 if (GetParam().no_stop_waiting) {
3988 EXPECT_EQ(3u, writer_->frame_count());
3989 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3990 } else {
3991 EXPECT_EQ(4u, writer_->frame_count());
3992 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3993 }
3994 EXPECT_FALSE(writer_->ack_frames().empty());
3995 ASSERT_EQ(2u, writer_->stream_frames().size());
3996 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3997 writer_->stream_frames()[0]->stream_id);
3998 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3999 writer_->stream_frames()[1]->stream_id);
4000}
4001
4002TEST_P(QuicConnectionTest, FramePackingSendv) {
4003 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4004 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4005
4006 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4007 connection_.transport_version(), Perspective::IS_CLIENT);
4008 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4009
4010 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4011 EXPECT_FALSE(connection_.HasQueuedData());
4012
4013 // Parse the last packet and ensure multiple iovector blocks have
4014 // been packed into a single stream frame from one stream.
4015 EXPECT_EQ(1u, writer_->frame_count());
4016 EXPECT_EQ(1u, writer_->stream_frames().size());
4017 EXPECT_EQ(0u, writer_->padding_frames().size());
4018 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4019 EXPECT_EQ(stream_id, frame->stream_id);
4020 EXPECT_EQ("ABCDEF",
4021 absl::string_view(frame->data_buffer, frame->data_length));
4022}
4023
4024TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
4025 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4026 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4027
4028 BlockOnNextWrite();
4029 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4030 connection_.transport_version(), Perspective::IS_CLIENT);
4031 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
4032
4033 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4034 EXPECT_TRUE(connection_.HasQueuedData());
4035
4036 // Unblock the writes and actually send.
4037 writer_->SetWritable();
4038 connection_.OnCanWrite();
4039 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4040
4041 // Parse the last packet and ensure it's one stream frame from one stream.
4042 EXPECT_EQ(1u, writer_->frame_count());
4043 EXPECT_EQ(1u, writer_->stream_frames().size());
4044 EXPECT_EQ(0u, writer_->padding_frames().size());
4045 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
4046 EXPECT_EQ(stream_id, frame->stream_id);
4047 EXPECT_EQ("ABCDEF",
4048 absl::string_view(frame->data_buffer, frame->data_length));
4049}
4050
4051TEST_P(QuicConnectionTest, SendingZeroBytes) {
4052 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4053 // Send a zero byte write with a fin using writev.
4054 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
4055 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
4056 connection_.transport_version(), Perspective::IS_CLIENT);
4057 connection_.SaveAndSendStreamData(stream_id, {}, 0, FIN);
4058
4059 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4060 EXPECT_FALSE(connection_.HasQueuedData());
4061
4062 // Padding frames are added by v99 to ensure a minimum packet size.
4063 size_t extra_padding_frames = 0;
4064 if (GetParam().version.HasHeaderProtection()) {
4065 extra_padding_frames = 1;
4066 }
4067
4068 // Parse the last packet and ensure it's one stream frame from one stream.
4069 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
4070 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
4071 ASSERT_EQ(1u, writer_->stream_frames().size());
4072 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
4073 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4074}
4075
4076TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
4077 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4078 EXPECT_CALL(visitor_, GetHandshakeState())
4079 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
4080 // Set the ack alarm by processing a ping frame.
4081 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4082
4083 // Processs a PING frame.
4084 ProcessFramePacket(QuicFrame(QuicPingFrame()));
4085 // Ensure that this has caused the ACK alarm to be set.
4086 EXPECT_TRUE(connection_.HasPendingAcks());
4087
4088 // Send data and ensure the ack is bundled.
4089 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
4090 const std::string data(10000, '?');
4091 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
4092 GetNthClientInitiatedStreamId(0, connection_.transport_version()), data,
4093 0, FIN);
4094 EXPECT_EQ(data.length(), consumed.bytes_consumed);
4095 EXPECT_TRUE(consumed.fin_consumed);
4096 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4097 EXPECT_FALSE(connection_.HasQueuedData());
4098
4099 // Parse the last packet and ensure it's one stream frame with a fin.
4100 EXPECT_EQ(1u, writer_->frame_count());
4101 ASSERT_EQ(1u, writer_->stream_frames().size());
4102 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4103 writer_->stream_frames()[0]->stream_id);
4104 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
4105 // Ensure the ack alarm was cancelled when the ack was sent.
4106 EXPECT_FALSE(connection_.HasPendingAcks());
4107}
4108
4109TEST_P(QuicConnectionTest, OnCanWrite) {
4110 // Visitor's OnCanWrite will send data, but will have more pending writes.
4111 EXPECT_CALL(visitor_, OnCanWrite())
4112 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
4113 &connection_, &TestConnection::SendStreamData3)),
4114 IgnoreResult(InvokeWithoutArgs(
4115 &connection_, &TestConnection::SendStreamData5))));
4116 {
4117 InSequence seq;
4118 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
4119 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
4120 .WillRepeatedly(Return(false));
4121 }
4122
4123 EXPECT_CALL(*send_algorithm_, CanSend(_))
4124 .WillRepeatedly(testing::Return(true));
4125
4126 connection_.OnCanWrite();
4127
4128 // Parse the last packet and ensure it's the two stream frames from
4129 // two different streams.
4130 EXPECT_EQ(2u, writer_->frame_count());
4131 EXPECT_EQ(2u, writer_->stream_frames().size());
4132 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
4133 writer_->stream_frames()[0]->stream_id);
4134 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
4135 writer_->stream_frames()[1]->stream_id);
4136}
4137
4138TEST_P(QuicConnectionTest, RetransmitOnNack) {
4139 QuicPacketNumber last_packet;
4140 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
4141 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet);
4142 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet);
4143
4144 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4145
4146 // Don't lose a packet on an ack, and nothing is retransmitted.
4147 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4148 QuicAckFrame ack_one = InitAckFrame(1);
4149 ProcessAckPacket(&ack_one);
4150
4151 // Lose a packet and ensure it triggers retransmission.
4152 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4153 LostPacketVector lost_packets;
4154 lost_packets.push_back(
4155 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4156 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4157 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4158 Return(LossDetectionInterface::DetectionStats())));
4159 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4160 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4161 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4162 ProcessAckPacket(&nack_two);
4163}
4164
4165TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
4166 // Block the connection to queue the packet.
4167 BlockOnNextWrite();
4168
4169 QuicStreamId stream_id = 2;
4170 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4171
4172 // Now that there is a queued packet, reset the stream.
4173 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4174
4175 // Unblock the connection and verify that only the RST_STREAM is sent.
4176 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4177 writer_->SetWritable();
4178 connection_.OnCanWrite();
4179 size_t padding_frame_count = writer_->padding_frames().size();
4180 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4181 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4182}
4183
4184TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
4185 // Block the connection to queue the packet.
4186 BlockOnNextWrite();
4187
4188 QuicStreamId stream_id = 2;
4189 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4190 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4191
4192 // Now that there is a queued packet, reset the stream.
4193 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4194
4195 // Unblock the connection and verify that the RST_STREAM is sent and the data
4196 // packet is sent.
4197 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4198 writer_->SetWritable();
4199 connection_.OnCanWrite();
4200 size_t padding_frame_count = writer_->padding_frames().size();
4201 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4202 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4203}
4204
4205TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
4206 QuicStreamId stream_id = 2;
4207 QuicPacketNumber last_packet;
4208 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4209 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4210 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4211
4212 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4213 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4214
4215 // Lose a packet and ensure it does not trigger retransmission.
4216 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4217 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4218 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4219 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4220 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4221 ProcessAckPacket(&nack_two);
4222}
4223
4224TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
4225 QuicStreamId stream_id = 2;
4226 QuicPacketNumber last_packet;
4227 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4228 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4229 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4230
4231 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4232 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4233
4234 // Lose a packet, ensure it triggers retransmission.
4235 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4236 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4237 LostPacketVector lost_packets;
4238 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4239 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4240 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4241 Return(LossDetectionInterface::DetectionStats())));
4242 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4243 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4244 ProcessAckPacket(&nack_two);
4245}
4246
4247TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
4248 QuicStreamId stream_id = 2;
4249 QuicPacketNumber last_packet;
4250 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4251
4252 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4253 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4254
4255 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
4256 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4257 clock_.AdvanceTime(DefaultRetransmissionTime());
4258 connection_.GetRetransmissionAlarm()->Fire();
4259 size_t padding_frame_count = writer_->padding_frames().size();
4260 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4261 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4262 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4263}
4264
4265// Ensure that if the only data in flight is non-retransmittable, the
4266// retransmission alarm is not set.
4267TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
4268 QuicStreamId stream_id = 2;
4269 QuicPacketNumber last_data_packet;
4270 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
4271
4272 // Cancel the stream.
4273 const QuicPacketNumber rst_packet = last_data_packet + 1;
4274 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
4275 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4276
4277 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
4278 // packet, which is no longer retransmittable since the stream was cancelled.
4279 QuicAckFrame nack_stream_data =
4280 ConstructAckFrame(rst_packet, last_data_packet);
4281 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4282 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4283 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4284 ProcessAckPacket(&nack_stream_data);
4285
4286 // Ensure that the data is still in flight, but the retransmission alarm is no
4287 // longer set.
4288 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
4289 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4290}
4291
fayang339f0c82022-04-30 14:20:02 -07004292TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnPTO) {
Bence Békybac04052022-04-07 15:44:29 -04004293 QuicStreamId stream_id = 2;
4294 QuicPacketNumber last_packet;
4295 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4296
4297 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4298 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4299
4300 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
4301 // is sent.
fayang339f0c82022-04-30 14:20:02 -07004302 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
Bence Békybac04052022-04-07 15:44:29 -04004303 clock_.AdvanceTime(DefaultRetransmissionTime());
4304 connection_.GetRetransmissionAlarm()->Fire();
4305 size_t padding_frame_count = writer_->padding_frames().size();
4306 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04004307}
4308
4309TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
4310 QuicStreamId stream_id = 2;
4311 QuicPacketNumber last_packet;
4312 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4313 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4314 BlockOnNextWrite();
4315 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4316
4317 // Lose a packet which will trigger a pending retransmission.
4318 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4319 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4320 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4321 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4322 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4323 ProcessAckPacket(&ack);
4324
4325 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4326
4327 // Unblock the connection and verify that the RST_STREAM is sent but not the
4328 // second data packet nor a retransmit.
4329 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4330 writer_->SetWritable();
4331 connection_.OnCanWrite();
4332 size_t padding_frame_count = writer_->padding_frames().size();
4333 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4334 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
4335 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4336}
4337
4338TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
4339 QuicStreamId stream_id = 2;
4340 QuicPacketNumber last_packet;
4341 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4342 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4343 BlockOnNextWrite();
4344 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4345
4346 // Lose a packet which will trigger a pending retransmission.
4347 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4348 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4349 LostPacketVector lost_packets;
4350 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4351 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4352 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4353 Return(LossDetectionInterface::DetectionStats())));
4354 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4355 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4356 ProcessAckPacket(&ack);
4357
4358 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4359
4360 // Unblock the connection and verify that the RST_STREAM is sent and the
4361 // second data packet or a retransmit is sent.
4362 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
4363 writer_->SetWritable();
4364 connection_.OnCanWrite();
4365 // The RST_STREAM_FRAME is sent after queued packets and pending
4366 // retransmission.
4367 connection_.SendControlFrame(QuicFrame(
4368 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
4369 size_t padding_frame_count = writer_->padding_frames().size();
4370 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4371 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4372}
4373
4374TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
4375 QuicPacketNumber last_packet;
4376 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4377 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
4378 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
4379
4380 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4381
4382 // Instigate a loss with an ack.
4383 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4384 // The first nack should trigger a fast retransmission, but we'll be
4385 // write blocked, so the packet will be queued.
4386 BlockOnNextWrite();
4387
4388 LostPacketVector lost_packets;
4389 lost_packets.push_back(
4390 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4391 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4392 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4393 Return(LossDetectionInterface::DetectionStats())));
4394 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4395 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4396 .Times(1);
4397 ProcessAckPacket(&nack_two);
4398 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4399
4400 // Now, ack the previous transmission.
4401 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4402 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
4403 QuicAckFrame ack_all = InitAckFrame(3);
4404 ProcessAckPacket(&ack_all);
4405
4406 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4407 .Times(0);
4408
4409 writer_->SetWritable();
4410 connection_.OnCanWrite();
4411
4412 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4413 // We do not store retransmittable frames of this retransmission.
4414 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
4415}
4416
4417TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
4418 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4419 QuicPacketNumber original, second;
4420
4421 QuicByteCount packet_size =
4422 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
4423 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
4424
4425 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
4426 // The first nack should retransmit the largest observed packet.
4427 LostPacketVector lost_packets;
4428 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
4429 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4430 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4431 Return(LossDetectionInterface::DetectionStats())));
4432 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4433 // Packet 1 is short header for IETF QUIC because the encryption level
4434 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
4435 EXPECT_CALL(*send_algorithm_,
4436 OnPacketSent(_, _, _,
4437 GetParam().version.HasIetfInvariantHeader()
4438 ? packet_size
4439 : packet_size - kQuicVersionSize,
4440 _));
4441 ProcessAckPacket(&frame);
4442}
4443
Bence Békybac04052022-04-07 15:44:29 -04004444TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
4445 BlockOnNextWrite();
4446 writer_->set_is_write_blocked_data_buffered(true);
4447 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4448 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4449 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4450
4451 writer_->SetWritable();
4452 connection_.OnCanWrite();
4453 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4454}
4455
4456TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
4457 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4458 BlockOnNextWrite();
4459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4460 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4461 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4462 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4463
4464 // The second packet should also be queued, in order to ensure packets are
4465 // never sent out of order.
4466 writer_->SetWritable();
4467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4468 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4469 EXPECT_EQ(2u, connection_.NumQueuedPackets());
4470
4471 // Now both are sent in order when we unblock.
4472 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4473 connection_.OnCanWrite();
4474 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4475 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4476}
4477
4478TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
4479 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4480 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4481 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4482
4483 BlockOnNextWrite();
4484 writer_->set_is_write_blocked_data_buffered(true);
4485 // Simulate the retransmission alarm firing.
4486 clock_.AdvanceTime(DefaultRetransmissionTime());
4487 connection_.GetRetransmissionAlarm()->Fire();
4488
4489 // Ack the sent packet before the callback returns, which happens in
4490 // rare circumstances with write blocked sockets.
4491 QuicAckFrame ack = InitAckFrame(1);
4492 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4493 ProcessAckPacket(&ack);
4494
4495 writer_->SetWritable();
4496 connection_.OnCanWrite();
4497 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang339f0c82022-04-30 14:20:02 -07004498 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 3));
Bence Békybac04052022-04-07 15:44:29 -04004499}
4500
4501TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4502 // Block the connection.
4503 BlockOnNextWrite();
4504 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4505 EXPECT_EQ(1u, writer_->packets_write_attempts());
4506 EXPECT_TRUE(writer_->IsWriteBlocked());
4507
4508 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4509 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4510 connection_.GetSendAlarm()->Fire();
4511 EXPECT_TRUE(writer_->IsWriteBlocked());
4512 EXPECT_EQ(1u, writer_->packets_write_attempts());
4513}
4514
4515TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4516 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4517
4518 // Block the connection.
4519 BlockOnNextWrite();
4520 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4521 EXPECT_TRUE(writer_->IsWriteBlocked());
4522 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4523 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4524
4525 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4526 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4527 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4528 // is returned.
4529 const uint64_t received_packet_num = 1;
4530 const bool has_stop_waiting = false;
4531 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4532 std::unique_ptr<QuicPacket> packet(
4533 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4534 char buffer[kMaxOutgoingPacketSize];
4535 size_t encrypted_length =
4536 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4537 *packet, buffer, kMaxOutgoingPacketSize);
4538 connection_.ProcessUdpPacket(
4539 kSelfAddress, kPeerAddress,
4540 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4541
4542 EXPECT_TRUE(writer_->IsWriteBlocked());
4543 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4544}
4545
4546TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4547 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4548 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4549
4550 // Simulate the case where a shared writer gets blocked by another connection.
4551 writer_->SetWriteBlocked();
4552
4553 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4554 QuicAckFrame ack1 = InitAckFrame(1);
4555 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4556 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4557 ProcessAckPacket(1, &ack1);
4558}
4559
4560TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4561 writer_->SetBatchMode(true);
4562 EXPECT_TRUE(connection_.connected());
4563 // Have to explicitly grab the OnConnectionClosed frame and check
4564 // its parameters because this is a silent connection close and the
4565 // frame is not also transmitted to the peer.
4566 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4567 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4568
4569 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4570
4571 {
4572 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4573 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4574 ConnectionCloseBehavior::SILENT_CLOSE);
4575
4576 EXPECT_FALSE(connection_.connected());
4577 writer_->SetWriteBlocked();
4578 }
4579 EXPECT_EQ(1, connection_close_frame_count_);
4580 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4581 IsError(QUIC_PEER_GOING_AWAY));
4582}
4583
4584TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4585 writer_->SetBatchMode(true);
4586 writer_->BlockOnNextFlush();
4587
4588 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4589 {
4590 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4591 // flusher's destructor will call connection_.FlushPackets, which should add
4592 // the connection to the write blocked list.
4593 }
4594}
4595
4596TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4597 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4598 int offset = 0;
4599 // Send packets 1 to 15.
4600 for (int i = 0; i < 15; ++i) {
4601 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4602 offset += 3;
4603 }
4604
4605 // Ack 15, nack 1-14.
4606
4607 QuicAckFrame nack =
4608 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4609
4610 // 14 packets have been NACK'd and lost.
4611 LostPacketVector lost_packets;
4612 for (int i = 1; i < 15; ++i) {
4613 lost_packets.push_back(
4614 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
4615 }
4616 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4617 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4618 Return(LossDetectionInterface::DetectionStats())));
4619 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4621 ProcessAckPacket(&nack);
4622}
4623
4624// Test sending multiple acks from the connection to the session.
4625TEST_P(QuicConnectionTest, MultipleAcks) {
4626 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4627 return;
4628 }
4629 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4630 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4631 ProcessDataPacket(1);
4632 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4633 QuicPacketNumber last_packet;
4634 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4635 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4636 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4637 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4638 SendAckPacketToPeer(); // Packet 3
4639 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4640 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4641 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4642 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4643 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4644 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4645
4646 // Client will ack packets 1, 2, [!3], 4, 5.
4647 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4648 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4649 ProcessAckPacket(&frame1);
4650
4651 // Now the client implicitly acks 3, and explicitly acks 6.
4652 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4653 QuicAckFrame frame2 = InitAckFrame(6);
4654 ProcessAckPacket(&frame2);
4655}
4656
4657TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
4658 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4659 return;
4660 }
4661 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4662 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4663 ProcessDataPacket(1);
4664 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4665 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4666 // From now on, we send acks, so the send algorithm won't mark them pending.
4667 SendAckPacketToPeer(); // Packet 2
4668
4669 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4670 QuicAckFrame frame = InitAckFrame(1);
4671 ProcessAckPacket(&frame);
4672
4673 // Verify that our internal state has least-unacked as 2, because we're still
4674 // waiting for a potential ack for 2.
4675
4676 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4677
4678 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4679 frame = InitAckFrame(2);
4680 ProcessAckPacket(&frame);
4681 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4682
4683 // When we send an ack, we make sure our least-unacked makes sense. In this
4684 // case since we're not waiting on an ack for 2 and all packets are acked, we
4685 // set it to 3.
4686 SendAckPacketToPeer(); // Packet 3
4687 // Least_unacked remains at 3 until another ack is received.
4688 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4689 if (GetParam().no_stop_waiting) {
4690 // Expect no stop waiting frame is sent.
4691 EXPECT_FALSE(least_unacked().IsInitialized());
4692 } else {
4693 // Check that the outgoing ack had its packet number as least_unacked.
4694 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4695 }
4696
4697 // Ack the ack, which updates the rtt and raises the least unacked.
4698 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4699 frame = InitAckFrame(3);
4700 ProcessAckPacket(&frame);
4701
4702 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4703 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4704 SendAckPacketToPeer(); // Packet 5
4705 if (GetParam().no_stop_waiting) {
4706 // Expect no stop waiting frame is sent.
4707 EXPECT_FALSE(least_unacked().IsInitialized());
4708 } else {
4709 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4710 }
4711
4712 // Send two data packets at the end, and ensure if the last one is acked,
4713 // the least unacked is raised above the ack packets.
4714 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4715 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4716
4717 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4718 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4719 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4720 ProcessAckPacket(&frame);
4721
4722 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4723}
4724
Bence Békybac04052022-04-07 15:44:29 -04004725TEST_P(QuicConnectionTest, SendHandshakeMessages) {
Bence Békybac04052022-04-07 15:44:29 -04004726 // Attempt to send a handshake message and have the socket block.
4727 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4728 BlockOnNextWrite();
4729 connection_.SendCryptoDataWithString("foo", 0);
4730 // The packet should be serialized, but not queued.
4731 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4732
4733 // Switch to the new encrypter.
martinduke9e0811c2022-12-08 20:35:57 -08004734 connection_.SetEncrypter(
4735 ENCRYPTION_ZERO_RTT,
4736 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004737 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4738
4739 // Now become writeable and flush the packets.
4740 writer_->SetWritable();
4741 EXPECT_CALL(visitor_, OnCanWrite());
4742 connection_.OnCanWrite();
4743 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4744
martinduke9e0811c2022-12-08 20:35:57 -08004745 // Verify that the handshake packet went out with Initial encryption.
4746 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -04004747}
4748
martinduke9e0811c2022-12-08 20:35:57 -08004749TEST_P(QuicConnectionTest, DropRetransmitsForInitialPacketAfterForwardSecure) {
Bence Békybac04052022-04-07 15:44:29 -04004750 connection_.SendCryptoStreamData();
Bence Békybac04052022-04-07 15:44:29 -04004751 // Simulate the retransmission alarm firing and the socket blocking.
4752 BlockOnNextWrite();
4753 clock_.AdvanceTime(DefaultRetransmissionTime());
4754 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4755 connection_.GetRetransmissionAlarm()->Fire();
4756 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4757
4758 // Go forward secure.
4759 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4760 std::make_unique<TaggingEncrypter>(0x02));
4761 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4762 notifier_.NeuterUnencryptedData();
4763 connection_.NeuterUnencryptedPackets();
4764 connection_.OnHandshakeComplete();
4765
4766 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4767 // Unblock the socket and ensure that no packets are sent.
4768 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4769 writer_->SetWritable();
4770 connection_.OnCanWrite();
4771}
4772
4773TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
Bence Békybac04052022-04-07 15:44:29 -04004774 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
4775
4776 connection_.SendCryptoDataWithString("foo", 0);
4777
martinduke9e0811c2022-12-08 20:35:57 -08004778 connection_.SetEncrypter(
4779 ENCRYPTION_ZERO_RTT,
4780 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004781 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -08004782 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4783 writer_->framer()->framer()->SetAlternativeDecrypter(
4784 ENCRYPTION_ZERO_RTT,
4785 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT), false);
4786 }
Bence Békybac04052022-04-07 15:44:29 -04004787
4788 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4789 EXPECT_FALSE(notifier_.HasLostStreamData());
4790 connection_.MarkZeroRttPacketsForRetransmission(0);
4791 EXPECT_TRUE(notifier_.HasLostStreamData());
4792}
4793
4794TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
4795 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4796 return;
4797 }
4798 // SetFromConfig is always called after construction from InitializeSession.
4799 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4800 QuicConfig config;
4801 connection_.SetFromConfig(config);
4802 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004803
martinduke9e0811c2022-12-08 20:35:57 -08004804 peer_framer_.SetEncrypter(
4805 ENCRYPTION_ZERO_RTT,
4806 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4807 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4808 writer_->framer()->framer()->SetDecrypter(
4809 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4810 }
Bence Békybac04052022-04-07 15:44:29 -04004811
4812 // Process an encrypted packet which can not yet be decrypted which should
4813 // result in the packet being buffered.
4814 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4815
4816 // Transition to the new encryption state and process another encrypted packet
4817 // which should result in the original packet being processed.
4818 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004819 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
4820 connection_.SetEncrypter(
4821 ENCRYPTION_ZERO_RTT,
4822 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004823 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4824 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4825 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4826
4827 // Finally, process a third packet and note that we do not reprocess the
4828 // buffered packet.
4829 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4830 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4831}
4832
Bence Békybac04052022-04-07 15:44:29 -04004833TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
4834 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4835 return;
4836 }
4837 // SetFromConfig is always called after construction from InitializeSession.
4838 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4839 QuicConfig config;
4840 config.set_max_undecryptable_packets(100);
4841 connection_.SetFromConfig(config);
4842 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004843
martinduke9e0811c2022-12-08 20:35:57 -08004844 peer_framer_.SetEncrypter(
4845 ENCRYPTION_ZERO_RTT,
4846 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004847
4848 // Process an encrypted packet which can not yet be decrypted which should
4849 // result in the packet being buffered.
4850 for (uint64_t i = 1; i <= 100; ++i) {
4851 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4852 }
4853
4854 // Transition to the new encryption state and process another encrypted packet
4855 // which should result in the original packets being processed.
4856 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4857 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004858 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004859 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -08004860 connection_.SetEncrypter(
4861 ENCRYPTION_ZERO_RTT,
4862 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004863 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4864
4865 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
martinduke9e0811c2022-12-08 20:35:57 -08004866 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4867 writer_->framer()->framer()->SetDecrypter(
4868 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4869 }
Bence Békybac04052022-04-07 15:44:29 -04004870 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4871
4872 // Finally, process a third packet and note that we do not reprocess the
4873 // buffered packet.
4874 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4875 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4876}
4877
4878TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4879 BlockOnNextWrite();
4880 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4881 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4882 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4883
4884 // Test that RTO is started once we write to the socket.
4885 writer_->SetWritable();
4886 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4887 connection_.OnCanWrite();
4888 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4889}
4890
Bence Békybac04052022-04-07 15:44:29 -04004891TEST_P(QuicConnectionTest, TestQueued) {
Bence Békybac04052022-04-07 15:44:29 -04004892 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4893 BlockOnNextWrite();
4894 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4895 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4896
4897 // Unblock the writes and actually send.
4898 writer_->SetWritable();
4899 connection_.OnCanWrite();
4900 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4901}
4902
4903TEST_P(QuicConnectionTest, InitialTimeout) {
4904 EXPECT_TRUE(connection_.connected());
4905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4906 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4907
4908 // SetFromConfig sets the initial timeouts before negotiation.
4909 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4910 QuicConfig config;
4911 connection_.SetFromConfig(config);
4912 // Subtract a second from the idle timeout on the client side.
4913 QuicTime default_timeout =
4914 clock_.ApproximateNow() +
4915 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4916 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4917
4918 EXPECT_CALL(visitor_,
4919 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4920 // Simulate the timeout alarm firing.
4921 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4922 connection_.GetTimeoutAlarm()->Fire();
4923
4924 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4925 EXPECT_FALSE(connection_.connected());
4926
4927 EXPECT_FALSE(connection_.HasPendingAcks());
4928 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4929 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4930 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4931 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4932 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4933 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4934}
4935
4936TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4937 EXPECT_TRUE(connection_.connected());
4938 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4939 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4940
4941 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4942 QuicConfig config;
4943 connection_.SetFromConfig(config);
4944 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4945 QuicTime initial_ddl =
4946 clock_.ApproximateNow() +
4947 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4948 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4949 EXPECT_TRUE(connection_.connected());
4950
4951 // Advance the time and send the first packet to the peer.
4952 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4953 QuicPacketNumber last_packet;
4954 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4955 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4956 // This will be the updated deadline for the connection to idle time out.
4957 QuicTime new_ddl = clock_.ApproximateNow() +
4958 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4959
4960 // Simulate the timeout alarm firing, the connection should not be closed as
4961 // a new packet has been sent.
4962 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
4963 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4964 clock_.AdvanceTime(delay);
4965 // Verify the timeout alarm deadline is updated.
4966 EXPECT_TRUE(connection_.connected());
4967 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4968 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4969
4970 // Simulate the timeout alarm firing again, the connection now should be
4971 // closed.
4972 EXPECT_CALL(visitor_,
4973 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4974 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4975 connection_.GetTimeoutAlarm()->Fire();
4976 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4977 EXPECT_FALSE(connection_.connected());
4978
4979 EXPECT_FALSE(connection_.HasPendingAcks());
4980 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4981 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4982 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4983 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4984 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4985}
4986
4987TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4988 EXPECT_TRUE(connection_.connected());
4989 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4990 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4991
4992 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4993 QuicConfig config;
4994 connection_.SetFromConfig(config);
4995 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4996 QuicTime initial_ddl =
4997 clock_.ApproximateNow() +
4998 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4999 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
5000 EXPECT_TRUE(connection_.connected());
5001
5002 // Immediately send the first packet, this is a rare case but test code will
5003 // hit this issue often as MockClock used for tests doesn't move with code
5004 // execution until manually adjusted.
5005 QuicPacketNumber last_packet;
5006 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5007 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
5008
5009 // Advance the time and send the second packet to the peer.
5010 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
5011 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
5012 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
5013
5014 // Simulate the timeout alarm firing, the connection will be closed.
5015 EXPECT_CALL(visitor_,
5016 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5017 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
5018 connection_.GetTimeoutAlarm()->Fire();
5019
5020 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5021 EXPECT_FALSE(connection_.connected());
5022
5023 EXPECT_FALSE(connection_.HasPendingAcks());
5024 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5025 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5026 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5027 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5028 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5029}
5030
5031TEST_P(QuicConnectionTest, HandshakeTimeout) {
5032 // Use a shorter handshake timeout than idle timeout for this test.
5033 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
5034 connection_.SetNetworkTimeouts(timeout, timeout);
5035 EXPECT_TRUE(connection_.connected());
5036 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5037
5038 QuicTime handshake_timeout =
5039 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
5040 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
5041 EXPECT_TRUE(connection_.connected());
5042
5043 // Send and ack new data 3 seconds later to lengthen the idle timeout.
5044 SendStreamDataToPeer(
5045 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5046 "GET /", 0, FIN, nullptr);
5047 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
5048 QuicAckFrame frame = InitAckFrame(1);
5049 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5050 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5051 ProcessAckPacket(&frame);
5052
5053 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5054 EXPECT_TRUE(connection_.connected());
5055
5056 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
5057
5058 EXPECT_CALL(visitor_,
5059 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5060 // Simulate the timeout alarm firing.
5061 connection_.GetTimeoutAlarm()->Fire();
5062
5063 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5064 EXPECT_FALSE(connection_.connected());
5065
5066 EXPECT_FALSE(connection_.HasPendingAcks());
5067 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5068 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5069 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
5070 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
5071}
5072
5073TEST_P(QuicConnectionTest, PingAfterSend) {
5074 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5075 return;
5076 }
5077 EXPECT_TRUE(connection_.connected());
5078 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5079 .WillRepeatedly(Return(true));
5080 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5081
5082 // Advance to 5ms, and send a packet to the peer, which will set
5083 // the ping alarm.
5084 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5085 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5086 SendStreamDataToPeer(
5087 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5088 "GET /", 0, FIN, nullptr);
5089 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5090 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
5091 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5092
5093 // Now recevie an ACK of the previous packet, which will move the
5094 // ping alarm forward.
5095 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5096 QuicAckFrame frame = InitAckFrame(1);
5097 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5098 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5099 ProcessAckPacket(&frame);
5100 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5101 // The ping timer is set slightly less than 15 seconds in the future, because
5102 // of the 1s ping timer alarm granularity.
5103 EXPECT_EQ(
5104 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
5105 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5106
5107 writer_->Reset();
5108 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
5109 connection_.GetPingAlarm()->Fire();
5110 size_t padding_frame_count = writer_->padding_frames().size();
5111 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5112 ASSERT_EQ(1u, writer_->ping_frames().size());
5113 writer_->Reset();
5114
5115 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5116 .WillRepeatedly(Return(false));
5117 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5118 SendAckPacketToPeer();
5119
5120 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5121}
5122
5123TEST_P(QuicConnectionTest, ReducedPingTimeout) {
5124 if (connection_.SupportsMultiplePacketNumberSpaces()) {
5125 return;
5126 }
5127 EXPECT_TRUE(connection_.connected());
5128 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5129 .WillRepeatedly(Return(true));
5130 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5131
5132 // Use a reduced ping timeout for this connection.
fayang5d393332022-04-18 13:34:54 -07005133 connection_.set_keep_alive_ping_timeout(QuicTime::Delta::FromSeconds(10));
Bence Békybac04052022-04-07 15:44:29 -04005134
5135 // Advance to 5ms, and send a packet to the peer, which will set
5136 // the ping alarm.
5137 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5138 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
5139 SendStreamDataToPeer(
5140 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
5141 "GET /", 0, FIN, nullptr);
5142 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5143 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
5144 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5145
5146 // Now recevie an ACK of the previous packet, which will move the
5147 // ping alarm forward.
5148 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5149 QuicAckFrame frame = InitAckFrame(1);
5150 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5151 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5152 ProcessAckPacket(&frame);
5153 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
5154 // The ping timer is set slightly less than 10 seconds in the future, because
5155 // of the 1s ping timer alarm granularity.
5156 EXPECT_EQ(
5157 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
5158 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5159
5160 writer_->Reset();
5161 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5162 connection_.GetPingAlarm()->Fire();
5163 size_t padding_frame_count = writer_->padding_frames().size();
5164 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5165 ASSERT_EQ(1u, writer_->ping_frames().size());
5166 writer_->Reset();
5167
5168 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5169 .WillRepeatedly(Return(false));
5170 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5171 SendAckPacketToPeer();
5172
5173 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5174}
5175
5176// Tests whether sending an MTU discovery packet to peer successfully causes the
5177// maximum packet size to increase.
5178TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
5179 MtuDiscoveryTestInit();
5180
5181 // Send an MTU probe.
5182 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5183 QuicByteCount mtu_probe_size;
5184 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5185 .WillOnce(SaveArg<3>(&mtu_probe_size));
5186 connection_.SendMtuDiscoveryPacket(new_mtu);
5187 EXPECT_EQ(new_mtu, mtu_probe_size);
5188 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5189
5190 // Send more than MTU worth of data. No acknowledgement was received so far,
5191 // so the MTU should be at its old value.
5192 const std::string data(kDefaultMaxPacketSize + 1, '.');
5193 QuicByteCount size_before_mtu_change;
5194 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5195 .Times(2)
5196 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5197 .WillOnce(Return());
5198 connection_.SendStreamDataWithString(3, data, 0, FIN);
5199 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5200 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5201
5202 // Acknowledge all packets so far.
5203 QuicAckFrame probe_ack = InitAckFrame(3);
5204 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5205 ProcessAckPacket(&probe_ack);
5206 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5207
5208 // Send the same data again. Check that it fits into a single packet now.
5209 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5210 connection_.SendStreamDataWithString(3, data, 0, FIN);
5211 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5212}
5213
5214// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5215// the writer is flushed immediately.
5216TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5217 writer_->SetBatchMode(true);
5218 MtuDiscoveryTestInit();
5219
5220 // Send an MTU probe.
5221 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5222 QuicByteCount mtu_probe_size;
5223 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5224 .WillOnce(SaveArg<3>(&mtu_probe_size));
5225 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5226 connection_.SendMtuDiscoveryPacket(target_mtu);
5227 EXPECT_EQ(target_mtu, mtu_probe_size);
5228 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
5229}
5230
5231// Tests whether MTU discovery does not happen when it is not explicitly enabled
5232// by the connection options.
5233TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
5234 MtuDiscoveryTestInit();
5235
5236 const QuicPacketCount packets_between_probes_base = 10;
5237 set_packets_between_probes_base(packets_between_probes_base);
5238
5239 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5240 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5241 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5242 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5243 EXPECT_EQ(0u, connection_.mtu_probe_count());
5244 }
5245}
5246
5247// Tests whether MTU discovery works when all probes are acknowledged on the
5248// first try.
5249TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
5250 MtuDiscoveryTestInit();
5251
5252 const QuicPacketCount packets_between_probes_base = 5;
5253 set_packets_between_probes_base(packets_between_probes_base);
5254
5255 connection_.EnablePathMtuDiscovery(send_algorithm_);
5256
5257 // Send enough packets so that the next one triggers path MTU discovery.
5258 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5259 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5260 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5261 }
5262
5263 // Trigger the probe.
5264 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5265 nullptr);
5266 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5267 QuicByteCount probe_size;
5268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5269 .WillOnce(SaveArg<3>(&probe_size));
5270 connection_.GetMtuDiscoveryAlarm()->Fire();
5271
5272 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5273 kMtuDiscoveryTargetPacketSizeHigh));
5274
5275 const QuicPacketNumber probe_packet_number =
5276 FirstSendingPacketNumber() + packets_between_probes_base;
5277 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5278
5279 // Acknowledge all packets sent so far.
5280 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5281 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5282 .Times(AnyNumber());
5283 ProcessAckPacket(&probe_ack);
5284 EXPECT_EQ(probe_size, connection_.max_packet_length());
5285 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5286
5287 EXPECT_EQ(1u, connection_.mtu_probe_count());
5288
5289 QuicStreamOffset stream_offset = packets_between_probes_base;
5290 QuicByteCount last_probe_size = 0;
5291 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5292 ++num_probes) {
5293 // Send just enough packets without triggering the next probe.
5294 for (QuicPacketCount i = 0;
5295 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5296 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5297 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5298 }
5299
5300 // Trigger the next probe.
5301 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5302 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5303 QuicByteCount new_probe_size;
5304 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5305 .WillOnce(SaveArg<3>(&new_probe_size));
5306 connection_.GetMtuDiscoveryAlarm()->Fire();
5307 EXPECT_THAT(new_probe_size,
5308 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5309 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5310
5311 // Acknowledge all packets sent so far.
5312 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5313 ProcessAckPacket(&probe_ack);
5314 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5315 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5316
5317 last_probe_size = probe_size;
5318 probe_size = new_probe_size;
5319 }
5320
5321 // The last probe size should be equal to the target.
5322 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
5323
5324 writer_->SetShouldWriteFail();
5325
5326 // Ignore PACKET_WRITE_ERROR once.
5327 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5328 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5329 EXPECT_TRUE(connection_.connected());
5330
5331 // Close connection on another PACKET_WRITE_ERROR.
5332 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5333 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5334 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5335 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5336 EXPECT_FALSE(connection_.connected());
5337 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5338 IsError(QUIC_PACKET_WRITE_ERROR));
5339}
5340
5341// After a successful MTU probe, one and only one write error should be ignored
5342// if it happened in QuicConnection::FlushPacket.
5343TEST_P(QuicConnectionTest,
5344 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5345 MtuDiscoveryTestInit();
5346 writer_->SetBatchMode(true);
5347
5348 const QuicPacketCount packets_between_probes_base = 5;
5349 set_packets_between_probes_base(packets_between_probes_base);
5350
5351 connection_.EnablePathMtuDiscovery(send_algorithm_);
5352
5353 const QuicByteCount original_max_packet_length =
5354 connection_.max_packet_length();
5355 // Send enough packets so that the next one triggers path MTU discovery.
5356 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5357 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5358 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5359 }
5360
5361 // Trigger the probe.
5362 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5363 nullptr);
5364 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5365 QuicByteCount probe_size;
5366 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5367 .WillOnce(SaveArg<3>(&probe_size));
5368 connection_.GetMtuDiscoveryAlarm()->Fire();
5369
5370 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5371 kMtuDiscoveryTargetPacketSizeHigh));
5372
5373 const QuicPacketNumber probe_packet_number =
5374 FirstSendingPacketNumber() + packets_between_probes_base;
5375 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5376
5377 // Acknowledge all packets sent so far.
5378 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5379 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5380 .Times(AnyNumber());
5381 ProcessAckPacket(&probe_ack);
5382 EXPECT_EQ(probe_size, connection_.max_packet_length());
5383 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5384
5385 EXPECT_EQ(1u, connection_.mtu_probe_count());
5386
5387 writer_->SetShouldWriteFail();
5388
5389 // Ignore PACKET_WRITE_ERROR once.
5390 {
5391 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5392 // flusher's destructor will call connection_.FlushPackets, which should
5393 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5394 }
5395 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5396 EXPECT_TRUE(connection_.connected());
5397
5398 // Close connection on another PACKET_WRITE_ERROR.
5399 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5400 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5401 {
5402 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5403 // flusher's destructor will call connection_.FlushPackets, which should
5404 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5405 }
5406 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5407 EXPECT_FALSE(connection_.connected());
5408 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5409 IsError(QUIC_PACKET_WRITE_ERROR));
5410}
5411
5412// Simulate the case where the first attempt to send a probe is write blocked,
5413// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5414TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
5415 MtuDiscoveryTestInit();
5416
5417 const QuicPacketCount packets_between_probes_base = 5;
5418 set_packets_between_probes_base(packets_between_probes_base);
5419
5420 connection_.EnablePathMtuDiscovery(send_algorithm_);
5421
5422 // Send enough packets so that the next one triggers path MTU discovery.
5423 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5424 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5425 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5426 }
5427
5428 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5429
5430 // Trigger the probe.
5431 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5432 nullptr);
5433 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5434 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5435 BlockOnNextWrite();
5436 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5437 connection_.GetMtuDiscoveryAlarm()->Fire();
5438 EXPECT_EQ(1u, connection_.mtu_probe_count());
5439 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5440 ASSERT_TRUE(connection_.connected());
5441
5442 writer_->SetWritable();
5443 SimulateNextPacketTooLarge();
5444 connection_.OnCanWrite();
5445 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5446 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5447 EXPECT_TRUE(connection_.connected());
5448}
5449
5450// Tests whether MTU discovery works correctly when the probes never get
5451// acknowledged.
5452TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5453 MtuDiscoveryTestInit();
5454
5455 // Lower the number of probes between packets in order to make the test go
5456 // much faster.
5457 const QuicPacketCount packets_between_probes_base = 5;
5458 set_packets_between_probes_base(packets_between_probes_base);
5459
5460 connection_.EnablePathMtuDiscovery(send_algorithm_);
5461
5462 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5463
5464 EXPECT_EQ(packets_between_probes_base,
5465 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5466
5467 // This tests sends more packets than strictly necessary to make sure that if
5468 // the connection was to send more discovery packets than needed, those would
5469 // get caught as well.
5470 const QuicPacketCount number_of_packets =
5471 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5472 std::vector<QuicPacketNumber> mtu_discovery_packets;
5473 // Called on many acks.
5474 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5475 .Times(AnyNumber());
5476 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5477 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5478 clock_.AdvanceTime(rtt);
5479
5480 // Receive an ACK, which marks all data packets as received, and all MTU
5481 // discovery packets as missing.
5482
5483 QuicAckFrame ack;
5484
5485 if (!mtu_discovery_packets.empty()) {
5486 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5487 mtu_discovery_packets.end());
5488 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5489 mtu_discovery_packets.end());
5490 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5491 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5492 creator_->packet_number() + 1);
5493 ack.largest_acked = creator_->packet_number();
5494
5495 } else {
5496 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5497 ack.largest_acked = creator_->packet_number();
5498 }
5499
5500 ProcessAckPacket(&ack);
5501
5502 // Trigger MTU probe if it would be scheduled now.
5503 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5504 continue;
5505 }
5506
5507 // Fire the alarm. The alarm should cause a packet to be sent.
5508 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5509 connection_.GetMtuDiscoveryAlarm()->Fire();
5510 // Record the packet number of the MTU discovery packet in order to
5511 // mark it as NACK'd.
5512 mtu_discovery_packets.push_back(creator_->packet_number());
5513 }
5514
5515 // Ensure the number of packets between probes grows exponentially by checking
5516 // it against the closed-form expression for the packet number.
5517 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5518 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5519 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5520 const QuicPacketCount packets_between_probes =
5521 packets_between_probes_base * ((1 << (i + 1)) - 1);
5522 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5523 mtu_discovery_packets[i]);
5524 }
5525
5526 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5527 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5528 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5529}
5530
5531// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5532TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
5533 MtuDiscoveryTestInit();
5534
5535 const QuicPacketCount packets_between_probes_base = 5;
5536 set_packets_between_probes_base(packets_between_probes_base);
5537
5538 connection_.EnablePathMtuDiscovery(send_algorithm_);
5539
5540 // Send enough packets so that the next one triggers path MTU discovery.
5541 QuicStreamOffset stream_offset = 0;
5542 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5543 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5544 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5545 }
5546
5547 // Trigger the probe.
5548 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5549 nullptr);
5550 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5551 QuicByteCount probe_size;
5552 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5553 .WillOnce(SaveArg<3>(&probe_size));
5554 connection_.GetMtuDiscoveryAlarm()->Fire();
5555 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5556 kMtuDiscoveryTargetPacketSizeHigh));
5557
5558 const QuicPacketNumber probe_packet_number =
5559 FirstSendingPacketNumber() + packets_between_probes_base;
5560 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5561
5562 // Acknowledge all packets sent so far.
5563 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
5564 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5565 .Times(AnyNumber());
5566 ProcessAckPacket(&first_ack);
5567 EXPECT_EQ(probe_size, connection_.max_packet_length());
5568 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5569
5570 EXPECT_EQ(1u, connection_.mtu_probe_count());
5571
5572 // Send just enough packets without triggering the second probe.
5573 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5574 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5575 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5576 }
5577
5578 // Trigger the second probe.
5579 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5580 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5581 QuicByteCount second_probe_size;
5582 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5583 .WillOnce(SaveArg<3>(&second_probe_size));
5584 connection_.GetMtuDiscoveryAlarm()->Fire();
5585 EXPECT_THAT(second_probe_size,
5586 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5587 EXPECT_EQ(2u, connection_.mtu_probe_count());
5588
5589 // Acknowledge all packets sent so far, except the second probe.
5590 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5591 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5592 ProcessAckPacket(&first_ack);
5593 EXPECT_EQ(probe_size, connection_.max_packet_length());
5594
5595 // Send just enough packets without triggering the third probe.
5596 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5597 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5598 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5599 }
5600
5601 // Trigger the third probe.
5602 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5603 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5604 QuicByteCount third_probe_size;
5605 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5606 .WillOnce(SaveArg<3>(&third_probe_size));
5607 connection_.GetMtuDiscoveryAlarm()->Fire();
5608 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5609 EXPECT_EQ(3u, connection_.mtu_probe_count());
5610
5611 // Acknowledge all packets sent so far, except the second probe.
5612 QuicAckFrame third_ack =
5613 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5614 ProcessAckPacket(&third_ack);
5615 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5616
5617 SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr);
5618 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5619
5620 if (connection_.PathDegradingDetectionInProgress() &&
5621 QuicConnectionPeer::GetPathDegradingDeadline(&connection_) <
5622 QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(
5623 &connection_)) {
5624 // Fire path degrading alarm first.
5625 connection_.PathDegradingTimeout();
5626 }
5627
5628 // Verify the max packet size has not reduced.
5629 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5630
5631 // Fire alarm to get path mtu reduction callback called.
5632 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5633 connection_.GetBlackholeDetectorAlarm()->Fire();
5634
5635 // Verify the max packet size has reduced to the previous value.
5636 EXPECT_EQ(probe_size, connection_.max_packet_length());
5637}
5638
5639// Tests whether MTU discovery works when the writer has a limit on how large a
5640// packet can be.
5641TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5642 MtuDiscoveryTestInit();
5643
5644 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5645 writer_->set_max_packet_size(mtu_limit);
5646
5647 const QuicPacketCount packets_between_probes_base = 5;
5648 set_packets_between_probes_base(packets_between_probes_base);
5649
5650 connection_.EnablePathMtuDiscovery(send_algorithm_);
5651
5652 // Send enough packets so that the next one triggers path MTU discovery.
5653 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5654 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5655 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5656 }
5657
5658 // Trigger the probe.
5659 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5660 nullptr);
5661 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5662 QuicByteCount probe_size;
5663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5664 .WillOnce(SaveArg<3>(&probe_size));
5665 connection_.GetMtuDiscoveryAlarm()->Fire();
5666
5667 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
5668
5669 const QuicPacketNumber probe_sequence_number =
5670 FirstSendingPacketNumber() + packets_between_probes_base;
5671 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5672
5673 // Acknowledge all packets sent so far.
5674 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5675 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5676 .Times(AnyNumber());
5677 ProcessAckPacket(&probe_ack);
5678 EXPECT_EQ(probe_size, connection_.max_packet_length());
5679 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5680
5681 EXPECT_EQ(1u, connection_.mtu_probe_count());
5682
5683 QuicStreamOffset stream_offset = packets_between_probes_base;
5684 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5685 ++num_probes) {
5686 // Send just enough packets without triggering the next probe.
5687 for (QuicPacketCount i = 0;
5688 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5689 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5690 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5691 }
5692
5693 // Trigger the next probe.
5694 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5695 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5696 QuicByteCount new_probe_size;
5697 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5698 .WillOnce(SaveArg<3>(&new_probe_size));
5699 connection_.GetMtuDiscoveryAlarm()->Fire();
5700 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5701 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5702
5703 // Acknowledge all packets sent so far.
5704 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5705 ProcessAckPacket(&probe_ack);
5706 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5707 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5708
5709 probe_size = new_probe_size;
5710 }
5711
5712 // The last probe size should be equal to the target.
5713 EXPECT_EQ(probe_size, mtu_limit);
5714}
5715
5716// Tests whether MTU discovery works when the writer returns an error despite
5717// advertising higher packet length.
5718TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5719 MtuDiscoveryTestInit();
5720
5721 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5722 const QuicByteCount initial_mtu = connection_.max_packet_length();
5723 EXPECT_LT(initial_mtu, mtu_limit);
5724 writer_->set_max_packet_size(mtu_limit);
5725
5726 const QuicPacketCount packets_between_probes_base = 5;
5727 set_packets_between_probes_base(packets_between_probes_base);
5728
5729 connection_.EnablePathMtuDiscovery(send_algorithm_);
5730
5731 // Send enough packets so that the next one triggers path MTU discovery.
5732 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5733 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5734 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5735 }
5736
5737 // Trigger the probe.
5738 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5739 nullptr);
5740 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5741 writer_->SimulateNextPacketTooLarge();
5742 connection_.GetMtuDiscoveryAlarm()->Fire();
5743 ASSERT_TRUE(connection_.connected());
5744
5745 // Send more data.
5746 QuicPacketNumber probe_number = creator_->packet_number();
5747 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5748 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5749 connection_.EnsureWritableAndSendStreamData5();
5750 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5751 }
5752
5753 // Acknowledge all packets sent so far, except for the lost probe.
5754 QuicAckFrame probe_ack =
5755 ConstructAckFrame(creator_->packet_number(), probe_number);
5756 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5757 ProcessAckPacket(&probe_ack);
5758 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5759
5760 // Send more packets, and ensure that none of them sets the alarm.
5761 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5762 connection_.EnsureWritableAndSendStreamData5();
5763 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5764 }
5765
5766 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5767 EXPECT_EQ(1u, connection_.mtu_probe_count());
5768}
5769
5770TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5771 MtuDiscoveryTestInit();
5772
5773 const QuicPacketCount packets_between_probes_base = 10;
5774 set_packets_between_probes_base(packets_between_probes_base);
5775
5776 connection_.EnablePathMtuDiscovery(send_algorithm_);
5777
5778 // Send enough packets so that the next one triggers path MTU discovery.
5779 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5780 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5781 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5782 }
5783
5784 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5785 nullptr);
5786 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5787
5788 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
5789 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5790 ConnectionCloseBehavior::SILENT_CLOSE);
5791 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5792}
5793
5794TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
5795 EXPECT_TRUE(connection_.connected());
5796 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5797 QuicConfig config;
5798 connection_.SetFromConfig(config);
5799
5800 const QuicTime::Delta initial_idle_timeout =
5801 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5802 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5803 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5804
5805 // When we send a packet, the timeout will change to 5ms +
5806 // kInitialIdleTimeoutSecs.
5807 clock_.AdvanceTime(five_ms);
5808 SendStreamDataToPeer(
5809 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5810 0, FIN, nullptr);
5811 EXPECT_EQ(default_timeout + five_ms,
5812 connection_.GetTimeoutAlarm()->deadline());
5813
5814 // Now send more data. This will not move the timeout because
5815 // no data has been received since the previous write.
5816 clock_.AdvanceTime(five_ms);
5817 SendStreamDataToPeer(
5818 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5819 3, FIN, nullptr);
5820 EXPECT_EQ(default_timeout + five_ms,
5821 connection_.GetTimeoutAlarm()->deadline());
5822
5823 // The original alarm will fire. We should not time out because we had a
5824 // network event at t=5ms. The alarm will reregister.
5825 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5826 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5827 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5828 EXPECT_TRUE(connection_.connected());
5829 EXPECT_EQ(default_timeout + five_ms,
5830 connection_.GetTimeoutAlarm()->deadline());
5831
5832 // This time, we should time out.
5833 EXPECT_CALL(visitor_,
5834 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5835 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5836 clock_.AdvanceTime(five_ms);
5837 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5838 connection_.GetTimeoutAlarm()->Fire();
5839 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5840 EXPECT_FALSE(connection_.connected());
5841 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5842}
5843
Bence Békybac04052022-04-07 15:44:29 -04005844TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5845 // When the idle timeout fires, verify that by default we do not send any
5846 // connection close packets.
5847 EXPECT_TRUE(connection_.connected());
5848 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5849 QuicConfig config;
5850
5851 // Create a handshake message that also enables silent close.
5852 CryptoHandshakeMessage msg;
5853 std::string error_details;
5854 QuicConfig client_config;
5855 client_config.SetInitialStreamFlowControlWindowToSend(
5856 kInitialStreamFlowControlWindowForTest);
5857 client_config.SetInitialSessionFlowControlWindowToSend(
5858 kInitialSessionFlowControlWindowForTest);
5859 client_config.SetIdleNetworkTimeout(
5860 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5861 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5862 const QuicErrorCode error =
5863 config.ProcessPeerHello(msg, CLIENT, &error_details);
5864 EXPECT_THAT(error, IsQuicNoError());
5865
5866 if (connection_.version().UsesTls()) {
5867 QuicConfigPeer::SetReceivedOriginalConnectionId(
5868 &config, connection_.connection_id());
5869 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5870 &config, connection_.connection_id());
5871 }
5872 connection_.SetFromConfig(config);
haoyuewang7b43efb2022-04-20 16:26:03 -07005873 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04005874
5875 const QuicTime::Delta default_idle_timeout =
5876 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5877 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5878 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5879
5880 // When we send a packet, the timeout will change to 5ms +
5881 // kInitialIdleTimeoutSecs.
5882 clock_.AdvanceTime(five_ms);
5883 SendStreamDataToPeer(
5884 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5885 0, FIN, nullptr);
5886 EXPECT_EQ(default_timeout + five_ms,
5887 connection_.GetTimeoutAlarm()->deadline());
5888
5889 // Now send more data. This will not move the timeout because
5890 // no data has been received since the previous write.
5891 clock_.AdvanceTime(five_ms);
5892 SendStreamDataToPeer(
5893 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5894 3, FIN, nullptr);
5895 EXPECT_EQ(default_timeout + five_ms,
5896 connection_.GetTimeoutAlarm()->deadline());
5897
5898 // The original alarm will fire. We should not time out because we had a
5899 // network event at t=5ms. The alarm will reregister.
5900 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5901 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5902 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5903 EXPECT_TRUE(connection_.connected());
5904 EXPECT_EQ(default_timeout + five_ms,
5905 connection_.GetTimeoutAlarm()->deadline());
5906
5907 // This time, we should time out.
5908 // This results in a SILENT_CLOSE, so the writer will not be invoked
5909 // and will not save the frame. Grab the frame from OnConnectionClosed
5910 // directly.
5911 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5912 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5913
5914 clock_.AdvanceTime(five_ms);
5915 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5916 connection_.GetTimeoutAlarm()->Fire();
5917 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5918 EXPECT_FALSE(connection_.connected());
5919 EXPECT_EQ(1, connection_close_frame_count_);
5920 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5921 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
5922}
5923
Bence Békybac04052022-04-07 15:44:29 -04005924TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5925 // Same test as above, but having open streams causes a connection close
5926 // to be sent.
5927 EXPECT_TRUE(connection_.connected());
5928 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5929 QuicConfig config;
5930
5931 // Create a handshake message that also enables silent close.
5932 CryptoHandshakeMessage msg;
5933 std::string error_details;
5934 QuicConfig client_config;
5935 client_config.SetInitialStreamFlowControlWindowToSend(
5936 kInitialStreamFlowControlWindowForTest);
5937 client_config.SetInitialSessionFlowControlWindowToSend(
5938 kInitialSessionFlowControlWindowForTest);
5939 client_config.SetIdleNetworkTimeout(
5940 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5941 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5942 const QuicErrorCode error =
5943 config.ProcessPeerHello(msg, CLIENT, &error_details);
5944 EXPECT_THAT(error, IsQuicNoError());
5945
5946 if (connection_.version().UsesTls()) {
5947 QuicConfigPeer::SetReceivedOriginalConnectionId(
5948 &config, connection_.connection_id());
5949 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5950 &config, connection_.connection_id());
5951 }
5952 connection_.SetFromConfig(config);
haoyuewang7b43efb2022-04-20 16:26:03 -07005953 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04005954
5955 const QuicTime::Delta default_idle_timeout =
5956 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5957 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5958 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5959
5960 // When we send a packet, the timeout will change to 5ms +
5961 // kInitialIdleTimeoutSecs.
5962 clock_.AdvanceTime(five_ms);
5963 SendStreamDataToPeer(
5964 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5965 0, FIN, nullptr);
5966 EXPECT_EQ(default_timeout + five_ms,
5967 connection_.GetTimeoutAlarm()->deadline());
5968
5969 // Indicate streams are still open.
5970 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5971 .WillRepeatedly(Return(true));
5972 if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) {
5973 EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return(""));
5974 }
5975
5976 // This time, we should time out and send a connection close due to the TLP.
5977 EXPECT_CALL(visitor_,
5978 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5979 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5980 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5981 clock_.ApproximateNow() + five_ms);
5982 connection_.GetTimeoutAlarm()->Fire();
5983 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5984 EXPECT_FALSE(connection_.connected());
5985 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5986}
5987
5988TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5989 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5990 EXPECT_TRUE(connection_.connected());
5991 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5992 QuicConfig config;
5993 connection_.SetFromConfig(config);
5994
5995 const QuicTime::Delta initial_idle_timeout =
5996 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5997 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5998 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5999
6000 connection_.SendStreamDataWithString(
6001 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6002 0, NO_FIN);
6003 connection_.SendStreamDataWithString(
6004 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6005 3, NO_FIN);
6006
6007 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6008 clock_.AdvanceTime(five_ms);
6009
6010 // When we receive a packet, the timeout will change to 5ms +
6011 // kInitialIdleTimeoutSecs.
6012 QuicAckFrame ack = InitAckFrame(2);
6013 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6014 ProcessAckPacket(&ack);
6015
6016 // The original alarm will fire. We should not time out because we had a
6017 // network event at t=5ms. The alarm will reregister.
6018 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6019 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6020 EXPECT_TRUE(connection_.connected());
6021 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6022 EXPECT_EQ(default_timeout + five_ms,
6023 connection_.GetTimeoutAlarm()->deadline());
6024
6025 // This time, we should time out.
6026 EXPECT_CALL(visitor_,
6027 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6028 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
6029 clock_.AdvanceTime(five_ms);
6030 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
6031 connection_.GetTimeoutAlarm()->Fire();
6032 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6033 EXPECT_FALSE(connection_.connected());
6034 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6035}
6036
6037TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
6038 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6039 EXPECT_TRUE(connection_.connected());
6040 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6041 QuicConfig config;
6042 connection_.SetFromConfig(config);
6043
6044 const QuicTime::Delta initial_idle_timeout =
6045 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
6046 connection_.SetNetworkTimeouts(
6047 QuicTime::Delta::Infinite(),
6048 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
haoyuewang7b43efb2022-04-20 16:26:03 -07006049 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04006050 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
6051 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
6052
6053 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6054 connection_.SendStreamDataWithString(
6055 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6056 0, NO_FIN);
6057 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6058 connection_.SendStreamDataWithString(
6059 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6060 3, NO_FIN);
6061
6062 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
6063
6064 clock_.AdvanceTime(five_ms);
6065
6066 // When we receive a packet, the timeout will change to 5ms +
6067 // kInitialIdleTimeoutSecs.
6068 QuicAckFrame ack = InitAckFrame(2);
6069 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6070 ProcessAckPacket(&ack);
6071
6072 // The original alarm will fire. We should not time out because we had a
6073 // network event at t=5ms. The alarm will reregister.
6074 clock_.AdvanceTime(initial_idle_timeout - five_ms);
6075 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
6076 EXPECT_TRUE(connection_.connected());
6077 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
6078 EXPECT_EQ(default_timeout + five_ms,
6079 connection_.GetTimeoutAlarm()->deadline());
6080
6081 // Now, send packets while advancing the time and verify that the connection
6082 // eventually times out.
6083 EXPECT_CALL(visitor_,
6084 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
6085 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
6086 for (int i = 0; i < 100 && connection_.connected(); ++i) {
6087 QUIC_LOG(INFO) << "sending data packet";
6088 connection_.SendStreamDataWithString(
6089 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
6090 "foo", 0, NO_FIN);
6091 connection_.GetTimeoutAlarm()->Fire();
6092 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
6093 }
6094 EXPECT_FALSE(connection_.connected());
6095 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
6096 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
6097}
6098
Bence Békybac04052022-04-07 15:44:29 -04006099TEST_P(QuicConnectionTest, SendScheduler) {
6100 // Test that if we send a packet without delay, it is not queued.
6101 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6102 std::unique_ptr<QuicPacket> packet =
6103 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6104 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6105 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
6106 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6107 HAS_RETRANSMITTABLE_DATA, false, false);
6108 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6109}
6110
6111TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
6112 // Test that the connection does not crash when it fails to send the first
6113 // packet at which point self_address_ might be uninitialized.
6114 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6115 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
6116 std::unique_ptr<QuicPacket> packet =
6117 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6118 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6119 writer_->SetShouldWriteFail();
6120 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6121 HAS_RETRANSMITTABLE_DATA, false, false);
6122}
6123
6124TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
6125 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
6126 std::unique_ptr<QuicPacket> packet =
6127 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
6128 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
6129 BlockOnNextWrite();
6130 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
6131 .Times(0);
6132 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
6133 HAS_RETRANSMITTABLE_DATA, false, false);
6134 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6135}
6136
6137TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
6138 // Queue the first packet.
6139 size_t payload_length = connection_.max_packet_length();
6140 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
6141 const std::string payload(payload_length, 'a');
6142 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6143 connection_.version().transport_version, Perspective::IS_CLIENT));
6144 EXPECT_EQ(0u, connection_
6145 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
6146 NO_FIN)
6147 .bytes_consumed);
6148 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6149}
6150
6151TEST_P(QuicConnectionTest, SendingThreePackets) {
6152 // Make the payload twice the size of the packet, so 3 packets are written.
6153 size_t total_payload_length = 2 * connection_.max_packet_length();
6154 const std::string payload(total_payload_length, 'a');
6155 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
6156 connection_.version().transport_version, Perspective::IS_CLIENT));
6157 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
6158 EXPECT_EQ(payload.size(), connection_
6159 .SendStreamDataWithString(first_bidi_stream_id,
6160 payload, 0, NO_FIN)
6161 .bytes_consumed);
6162}
6163
6164TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6165 set_perspective(Perspective::IS_SERVER);
6166 if (!GetParam().version.HasIetfInvariantHeader()) {
6167 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6168 // SendStreamDataWithString.
6169 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6170 }
6171 // Set up a larger payload than will fit in one packet.
6172 const std::string payload(connection_.max_packet_length(), 'a');
6173 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6174
6175 // Now send some packets with no truncation.
6176 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6177 EXPECT_EQ(payload.size(),
6178 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6179 .bytes_consumed);
6180 // Track the size of the second packet here. The overhead will be the largest
6181 // we see in this test, due to the non-truncated connection id.
6182 size_t non_truncated_packet_size = writer_->last_packet_size();
6183
6184 // Change to a 0 byte connection id.
6185 QuicConfig config;
6186 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6187 connection_.SetFromConfig(config);
6188 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6189 EXPECT_EQ(payload.size(),
6190 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6191 .bytes_consumed);
6192 if (connection_.version().HasIetfInvariantHeader()) {
6193 // Short header packets sent from server omit connection ID already, and
6194 // stream offset size increases from 0 to 2.
6195 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6196 } else {
6197 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6198 // because stream offset size is 2 instead of 0.
6199 EXPECT_EQ(non_truncated_packet_size,
6200 writer_->last_packet_size() + 8 * 2 - 2);
6201 }
6202}
6203
6204TEST_P(QuicConnectionTest, SendDelayedAck) {
6205 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6206 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6207 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006208 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006209 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6210 peer_framer_.SetEncrypter(
6211 ENCRYPTION_ZERO_RTT,
6212 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006213 // Process a packet from the non-crypto stream.
6214 frame1_.stream_id = 3;
6215
6216 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6217 // instead of ENCRYPTION_INITIAL.
6218 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6219 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6220
6221 // Check if delayed ack timer is running for the expected interval.
6222 EXPECT_TRUE(connection_.HasPendingAcks());
6223 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6224 // Simulate delayed ack alarm firing.
6225 clock_.AdvanceTime(DefaultDelayedAckTime());
6226 connection_.GetAckAlarm()->Fire();
6227 // Check that ack is sent and that delayed ack alarm is reset.
6228 size_t padding_frame_count = writer_->padding_frames().size();
6229 if (GetParam().no_stop_waiting) {
6230 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6231 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6232 } else {
6233 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6234 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6235 }
6236 EXPECT_FALSE(writer_->ack_frames().empty());
6237 EXPECT_FALSE(connection_.HasPendingAcks());
6238}
6239
6240TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6241 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6242
6243 const size_t kMinRttMs = 40;
6244 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6245 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6246 QuicTime::Delta::Zero(), QuicTime::Zero());
6247 // The ack time should be based on min_rtt/4, since it's less than the
6248 // default delayed ack time.
6249 QuicTime ack_time = clock_.ApproximateNow() +
6250 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6251 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6252 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006253 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006254 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6255 peer_framer_.SetEncrypter(
6256 ENCRYPTION_ZERO_RTT,
6257 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006258 // Process a packet from the non-crypto stream.
6259 frame1_.stream_id = 3;
6260
6261 // Process all the initial packets in order so there aren't missing packets.
6262 uint64_t kFirstDecimatedPacket = 101;
6263 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6264 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6265 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6266 }
6267 EXPECT_FALSE(connection_.HasPendingAcks());
6268 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6269 // instead of ENCRYPTION_INITIAL.
6270 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6271 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6272 ENCRYPTION_ZERO_RTT);
6273
6274 // Check if delayed ack timer is running for the expected interval.
6275 EXPECT_TRUE(connection_.HasPendingAcks());
6276 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6277
6278 // The 10th received packet causes an ack to be sent.
6279 for (int i = 0; i < 9; ++i) {
6280 EXPECT_TRUE(connection_.HasPendingAcks());
6281 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6282 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6283 ENCRYPTION_ZERO_RTT);
6284 }
6285 // Check that ack is sent and that delayed ack alarm is reset.
6286 size_t padding_frame_count = writer_->padding_frames().size();
6287 if (GetParam().no_stop_waiting) {
6288 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6289 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6290 } else {
6291 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6292 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6293 }
6294 EXPECT_FALSE(writer_->ack_frames().empty());
6295 EXPECT_FALSE(connection_.HasPendingAcks());
6296}
6297
6298TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6299 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6300 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6301 QuicConfig config;
6302 QuicTagVector connection_options;
6303 // No limit on the number of packets received before sending an ack.
6304 connection_options.push_back(kAKDU);
6305 config.SetConnectionOptionsToSend(connection_options);
6306 connection_.SetFromConfig(config);
6307
6308 const size_t kMinRttMs = 40;
6309 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6310 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6311 QuicTime::Delta::Zero(), QuicTime::Zero());
6312 // The ack time should be based on min_rtt/4, since it's less than the
6313 // default delayed ack time.
6314 QuicTime ack_time = clock_.ApproximateNow() +
6315 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6316 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6317 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006318 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006319 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6320 peer_framer_.SetEncrypter(
6321 ENCRYPTION_ZERO_RTT,
6322 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006323 // Process a packet from the non-crypto stream.
6324 frame1_.stream_id = 3;
6325
6326 // Process all the initial packets in order so there aren't missing packets.
6327 uint64_t kFirstDecimatedPacket = 101;
6328 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6329 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6330 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6331 }
6332 EXPECT_FALSE(connection_.HasPendingAcks());
6333 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6334 // instead of ENCRYPTION_INITIAL.
6335 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6336 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6337 ENCRYPTION_ZERO_RTT);
6338
6339 // Check if delayed ack timer is running for the expected interval.
6340 EXPECT_TRUE(connection_.HasPendingAcks());
6341 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6342
6343 // 18 packets will not cause an ack to be sent. 19 will because when
6344 // stop waiting frames are in use, we ack every 20 packets no matter what.
6345 for (int i = 0; i < 18; ++i) {
6346 EXPECT_TRUE(connection_.HasPendingAcks());
6347 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6348 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6349 ENCRYPTION_ZERO_RTT);
6350 }
6351 // The delayed ack timer should still be set to the expected deadline.
6352 EXPECT_TRUE(connection_.HasPendingAcks());
6353 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6354}
6355
6356TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6357 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6358 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6359
6360 const size_t kMinRttMs = 40;
6361 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6362 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6363 QuicTime::Delta::Zero(), QuicTime::Zero());
6364 // The ack time should be based on min_rtt/8, since it's less than the
6365 // default delayed ack time.
6366 QuicTime ack_time = clock_.ApproximateNow() +
6367 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6368 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6369 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006370 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006371 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6372 peer_framer_.SetEncrypter(
6373 ENCRYPTION_ZERO_RTT,
6374 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006375 // Process a packet from the non-crypto stream.
6376 frame1_.stream_id = 3;
6377
6378 // Process all the initial packets in order so there aren't missing packets.
6379 uint64_t kFirstDecimatedPacket = 101;
6380 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6381 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6382 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6383 }
6384 EXPECT_FALSE(connection_.HasPendingAcks());
6385 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6386 // instead of ENCRYPTION_INITIAL.
6387 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6388 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6389 ENCRYPTION_ZERO_RTT);
6390
6391 // Check if delayed ack timer is running for the expected interval.
6392 EXPECT_TRUE(connection_.HasPendingAcks());
6393 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6394
6395 // The 10th received packet causes an ack to be sent.
6396 for (int i = 0; i < 9; ++i) {
6397 EXPECT_TRUE(connection_.HasPendingAcks());
6398 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6399 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6400 ENCRYPTION_ZERO_RTT);
6401 }
6402 // Check that ack is sent and that delayed ack alarm is reset.
6403 size_t padding_frame_count = writer_->padding_frames().size();
6404 if (GetParam().no_stop_waiting) {
6405 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6406 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6407 } else {
6408 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6409 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6410 }
6411 EXPECT_FALSE(writer_->ack_frames().empty());
6412 EXPECT_FALSE(connection_.HasPendingAcks());
6413}
6414
6415TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6416 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6417 ProcessPacket(1);
6418 // Check that ack is sent and that delayed ack alarm is set.
6419 EXPECT_TRUE(connection_.HasPendingAcks());
6420 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6421 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6422
6423 // Completing the handshake as the server does nothing.
6424 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6425 connection_.OnHandshakeComplete();
6426 EXPECT_TRUE(connection_.HasPendingAcks());
6427 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6428
6429 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6430 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6431 connection_.OnHandshakeComplete();
6432 EXPECT_TRUE(connection_.HasPendingAcks());
6433 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6434 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6435 connection_.GetAckAlarm()->deadline());
6436 } else {
6437 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6438 }
6439}
6440
6441TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6442 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6443 ProcessPacket(1);
6444 ProcessPacket(2);
6445 // Check that ack is sent and that delayed ack alarm is reset.
6446 size_t padding_frame_count = writer_->padding_frames().size();
6447 if (GetParam().no_stop_waiting) {
6448 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6449 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6450 } else {
6451 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6452 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6453 }
6454 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);
6462 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
6463
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.
6505 if (GetParam().no_stop_waiting) {
6506 EXPECT_EQ(2u, writer_->frame_count());
6507 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6508 } else {
6509 EXPECT_EQ(3u, writer_->frame_count());
6510 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6511 }
6512 EXPECT_FALSE(writer_->ack_frames().empty());
6513 EXPECT_FALSE(connection_.HasPendingAcks());
6514}
6515
6516TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6517 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6518 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6519 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6520 } else {
6521 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6522 }
6523 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6524 connection_.SendCryptoDataWithString("foo", 0);
6525 // Check that ack is bundled with outgoing crypto data.
6526 if (GetParam().no_stop_waiting) {
6527 EXPECT_EQ(3u, writer_->frame_count());
6528 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6529 } else {
6530 EXPECT_EQ(4u, writer_->frame_count());
6531 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6532 }
6533 EXPECT_FALSE(connection_.HasPendingAcks());
6534}
6535
6536TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6537 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6538 ProcessPacket(1);
6539 BlockOnNextWrite();
6540 writer_->set_is_write_blocked_data_buffered(true);
6541 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6542 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6543 } else {
6544 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6545 }
6546 connection_.SendCryptoDataWithString("foo", 0);
6547 EXPECT_TRUE(writer_->IsWriteBlocked());
6548 EXPECT_FALSE(connection_.HasQueuedData());
6549 connection_.SendCryptoDataWithString("bar", 3);
6550 EXPECT_TRUE(writer_->IsWriteBlocked());
6551 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6552 // CRYPTO frames are not flushed when writer is blocked.
6553 EXPECT_FALSE(connection_.HasQueuedData());
6554 } else {
6555 EXPECT_TRUE(connection_.HasQueuedData());
6556 }
6557}
6558
6559TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6560 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6561 EXPECT_FALSE(connection_.HasPendingAcks());
6562 EXPECT_CALL(visitor_, OnCanWrite())
6563 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6564 &connection_, &TestConnection::SendCryptoStreamData)));
6565 // Process a packet from the crypto stream, which is frame1_'s default.
6566 // Receiving the CHLO as packet 2 first will cause the connection to
6567 // immediately send an ack, due to the packet gap.
6568 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6569 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6570 } else {
6571 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6572 }
6573 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6574 // Check that ack is sent and that delayed ack alarm is reset.
6575 if (GetParam().no_stop_waiting) {
6576 EXPECT_EQ(3u, writer_->frame_count());
6577 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6578 } else {
6579 EXPECT_EQ(4u, writer_->frame_count());
6580 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6581 }
6582 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6583 EXPECT_EQ(1u, writer_->stream_frames().size());
6584 } else {
6585 EXPECT_EQ(1u, writer_->crypto_frames().size());
6586 }
6587 EXPECT_EQ(1u, writer_->padding_frames().size());
6588 ASSERT_FALSE(writer_->ack_frames().empty());
6589 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6590 EXPECT_FALSE(connection_.HasPendingAcks());
6591}
6592
6593TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6594 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6595 EXPECT_FALSE(connection_.HasPendingAcks());
6596
6597 // Process two packets from the crypto stream, which is frame1_'s default,
6598 // simulating a 2 packet reject.
6599 {
6600 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6601 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6602 } else {
6603 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6604 }
6605 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6606 // Send the new CHLO when the REJ is processed.
6607 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6608 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6609 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6610 &connection_, &TestConnection::SendCryptoStreamData)));
6611 } else {
6612 EXPECT_CALL(visitor_, OnStreamFrame(_))
6613 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6614 &connection_, &TestConnection::SendCryptoStreamData)));
6615 }
6616 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6617 }
6618 // Check that ack is sent and that delayed ack alarm is reset.
6619 if (GetParam().no_stop_waiting) {
6620 EXPECT_EQ(3u, writer_->frame_count());
6621 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6622 } else {
6623 EXPECT_EQ(4u, writer_->frame_count());
6624 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6625 }
6626 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6627 EXPECT_EQ(1u, writer_->stream_frames().size());
6628 } else {
6629 EXPECT_EQ(1u, writer_->crypto_frames().size());
6630 }
6631 EXPECT_EQ(1u, writer_->padding_frames().size());
6632 ASSERT_FALSE(writer_->ack_frames().empty());
6633 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6634 EXPECT_FALSE(connection_.HasPendingAcks());
6635}
6636
6637TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6638 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6639 connection_.SendStreamDataWithString(
6640 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6641 0, NO_FIN);
6642 connection_.SendStreamDataWithString(
6643 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6644 3, NO_FIN);
6645 // Ack the second packet, which will retransmit the first packet.
6646 QuicAckFrame ack = ConstructAckFrame(2, 1);
6647 LostPacketVector lost_packets;
6648 lost_packets.push_back(
6649 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6650 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6651 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
6652 Return(LossDetectionInterface::DetectionStats())));
6653 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6654 ProcessAckPacket(&ack);
6655 size_t padding_frame_count = writer_->padding_frames().size();
6656 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6657 EXPECT_EQ(1u, writer_->stream_frames().size());
6658 writer_->Reset();
6659
6660 // Now ack the retransmission, which will both raise the high water mark
6661 // and see if there is more data to send.
6662 ack = ConstructAckFrame(3, 1);
6663 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6664 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6665 ProcessAckPacket(&ack);
6666
6667 // Check that no packet is sent and the ack alarm isn't set.
6668 EXPECT_EQ(0u, writer_->frame_count());
6669 EXPECT_FALSE(connection_.HasPendingAcks());
6670 writer_->Reset();
6671
6672 // Send the same ack, but send both data and an ack together.
6673 ack = ConstructAckFrame(3, 1);
6674 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6675 EXPECT_CALL(visitor_, OnCanWrite())
6676 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6677 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6678 ProcessAckPacket(&ack);
6679
6680 // Check that ack is bundled with outgoing data and the delayed ack
6681 // alarm is reset.
6682 if (GetParam().no_stop_waiting) {
6683 // Do not ACK acks.
6684 EXPECT_EQ(1u, writer_->frame_count());
6685 } else {
6686 EXPECT_EQ(3u, writer_->frame_count());
6687 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6688 }
6689 if (GetParam().no_stop_waiting) {
6690 EXPECT_TRUE(writer_->ack_frames().empty());
6691 } else {
6692 EXPECT_FALSE(writer_->ack_frames().empty());
6693 EXPECT_EQ(QuicPacketNumber(3u),
6694 LargestAcked(writer_->ack_frames().front()));
6695 }
6696 EXPECT_EQ(1u, writer_->stream_frames().size());
6697 EXPECT_FALSE(connection_.HasPendingAcks());
6698}
6699
6700TEST_P(QuicConnectionTest, NoAckSentForClose) {
6701 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6702 ProcessPacket(1);
6703 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6704 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6705 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6706 ProcessClosePacket(2);
6707 EXPECT_EQ(1, connection_close_frame_count_);
6708 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6709 IsError(QUIC_PEER_GOING_AWAY));
6710}
6711
6712TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6713 EXPECT_TRUE(connection_.connected());
6714 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6715 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6716 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6717 ConnectionCloseBehavior::SILENT_CLOSE);
6718 EXPECT_FALSE(connection_.connected());
6719 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6720 EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
6721 /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
6722}
6723
6724TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6725 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
6726 if (!IsDefaultTestConfiguration()) {
6727 return;
6728 }
6729
6730 EXPECT_TRUE(connection_.connected());
6731 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6732 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6733 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6734 ConnectionCloseBehavior::SILENT_CLOSE);
6735 EXPECT_FALSE(connection_.connected());
6736 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6737
6738 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6739 .Times(0);
6740
6741 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6742 writer_.get(), connection_.peer_address()),
6743 "Not sending connectivity probing packet as connection is "
6744 "disconnected.");
6745 EXPECT_EQ(1, connection_close_frame_count_);
6746 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6747 IsError(QUIC_PEER_GOING_AWAY));
6748}
6749
6750TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6751 PathProbeTestInit(Perspective::IS_CLIENT);
6752 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6753 // Block next write so that sending connectivity probe will encounter a
6754 // blocked write when send a connectivity probe to the peer.
6755 probing_writer.BlockOnNextWrite();
6756 // Connection will not be marked as write blocked as connectivity probe only
6757 // affects the probing_writer which is not the default.
6758 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6759
6760 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6761 .Times(1);
6762 connection_.SendConnectivityProbingPacket(&probing_writer,
6763 connection_.peer_address());
6764}
6765
6766TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6767 PathProbeTestInit(Perspective::IS_SERVER);
6768 if (version().SupportsAntiAmplificationLimit()) {
6769 QuicConnectionPeer::SetAddressValidated(&connection_);
6770 }
6771
6772 // Block next write so that sending connectivity probe will encounter a
6773 // blocked write when send a connectivity probe to the peer.
6774 writer_->BlockOnNextWrite();
6775 // Connection will be marked as write blocked as server uses the default
6776 // writer to send connectivity probes.
6777 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6778
6779 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6780 .Times(1);
6781 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6782 QuicPathFrameBuffer payload{
6783 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
6784 QuicConnection::ScopedPacketFlusher flusher(&connection_);
6785 connection_.SendPathChallenge(
6786 payload, connection_.self_address(), connection_.peer_address(),
6787 connection_.effective_peer_address(), writer_.get());
6788 } else {
6789 connection_.SendConnectivityProbingPacket(writer_.get(),
6790 connection_.peer_address());
6791 }
6792}
6793
6794TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6795 PathProbeTestInit(Perspective::IS_CLIENT);
6796 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6797 probing_writer.SetShouldWriteFail();
6798
6799 // Connection should not be closed if a connectivity probe is failed to be
6800 // sent.
6801 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6802
6803 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6804 .Times(0);
6805 connection_.SendConnectivityProbingPacket(&probing_writer,
6806 connection_.peer_address());
6807}
6808
6809TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6810 PathProbeTestInit(Perspective::IS_SERVER);
6811
6812 writer_->SetShouldWriteFail();
6813 // Connection should not be closed if a connectivity probe is failed to be
6814 // sent.
6815 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6816
6817 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6818 .Times(0);
6819 connection_.SendConnectivityProbingPacket(writer_.get(),
6820 connection_.peer_address());
6821}
6822
6823TEST_P(QuicConnectionTest, PublicReset) {
6824 if (GetParam().version.HasIetfInvariantHeader()) {
6825 return;
6826 }
6827 QuicPublicResetPacket header;
6828 // Public reset packet in only built by server.
6829 header.connection_id = connection_id_;
6830 std::unique_ptr<QuicEncryptedPacket> packet(
6831 framer_.BuildPublicResetPacket(header));
6832 std::unique_ptr<QuicReceivedPacket> received(
6833 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6834 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6835 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6836 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6837 EXPECT_EQ(1, connection_close_frame_count_);
6838 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6839 IsError(QUIC_PUBLIC_RESET));
6840}
6841
6842TEST_P(QuicConnectionTest, IetfStatelessReset) {
6843 if (!GetParam().version.HasIetfInvariantHeader()) {
6844 return;
6845 }
6846 QuicConfig config;
6847 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6848 kTestStatelessResetToken);
6849 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6850 connection_.SetFromConfig(config);
6851 std::unique_ptr<QuicEncryptedPacket> packet(
6852 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6853 /*received_packet_length=*/100,
6854 kTestStatelessResetToken));
6855 std::unique_ptr<QuicReceivedPacket> received(
6856 ConstructReceivedPacket(*packet, QuicTime::Zero()));
Bence Békybac04052022-04-07 15:44:29 -04006857 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6858 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6859 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6860 EXPECT_EQ(1, connection_close_frame_count_);
6861 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6862 IsError(QUIC_PUBLIC_RESET));
6863}
6864
6865TEST_P(QuicConnectionTest, GoAway) {
6866 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6867 // GoAway is not available in version 99.
6868 return;
6869 }
6870
6871 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6872
6873 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
6874 goaway->last_good_stream_id = 1;
6875 goaway->error_code = QUIC_PEER_GOING_AWAY;
6876 goaway->reason_phrase = "Going away.";
6877 EXPECT_CALL(visitor_, OnGoAway(_));
6878 ProcessGoAwayPacket(goaway);
6879}
6880
6881TEST_P(QuicConnectionTest, WindowUpdate) {
6882 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6883
6884 QuicWindowUpdateFrame window_update;
6885 window_update.stream_id = 3;
6886 window_update.max_data = 1234;
6887 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6888 ProcessFramePacket(QuicFrame(window_update));
6889}
6890
6891TEST_P(QuicConnectionTest, Blocked) {
6892 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6893
6894 QuicBlockedFrame blocked;
6895 blocked.stream_id = 3;
6896 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6897 ProcessFramePacket(QuicFrame(blocked));
6898 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6899 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6900}
6901
6902TEST_P(QuicConnectionTest, ZeroBytePacket) {
6903 // Don't close the connection for zero byte packets.
6904 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6905 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6906 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6907}
6908
6909TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
6910 if (GetParam().version.HasIetfInvariantHeader()) {
6911 return;
6912 }
6913 // Set the packet number of the ack packet to be least unacked (4).
6914 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
6915 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6916 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
6917 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
6918}
6919
6920TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
6921 // All supported versions except the one the connection supports.
6922 ParsedQuicVersionVector versions;
6923 for (auto version : AllSupportedVersions()) {
6924 if (version != connection_.version()) {
6925 versions.push_back(version);
6926 }
6927 }
6928
6929 // Send a version negotiation packet.
6930 std::unique_ptr<QuicEncryptedPacket> encrypted(
6931 QuicFramer::BuildVersionNegotiationPacket(
6932 connection_id_, EmptyQuicConnectionId(),
6933 connection_.version().HasIetfInvariantHeader(),
6934 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6935 std::unique_ptr<QuicReceivedPacket> received(
6936 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6937 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6938 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6939 // Verify no connection close packet gets sent.
6940 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6941 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6942 EXPECT_FALSE(connection_.connected());
6943 EXPECT_EQ(1, connection_close_frame_count_);
6944 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6945 IsError(QUIC_INVALID_VERSION));
6946}
6947
6948TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiationWithConnectionClose) {
6949 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6950 QuicConfig config;
6951 QuicTagVector connection_options;
6952 connection_options.push_back(kINVC);
6953 config.SetClientConnectionOptions(connection_options);
6954 connection_.SetFromConfig(config);
6955
6956 // All supported versions except the one the connection supports.
6957 ParsedQuicVersionVector versions;
6958 for (auto version : AllSupportedVersions()) {
6959 if (version != connection_.version()) {
6960 versions.push_back(version);
6961 }
6962 }
6963
6964 // Send a version negotiation packet.
6965 std::unique_ptr<QuicEncryptedPacket> encrypted(
6966 QuicFramer::BuildVersionNegotiationPacket(
6967 connection_id_, EmptyQuicConnectionId(),
6968 connection_.version().HasIetfInvariantHeader(),
6969 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6970 std::unique_ptr<QuicReceivedPacket> received(
6971 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6972 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6973 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6974 // Verify connection close packet gets sent.
6975 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1u));
6976 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6977 EXPECT_FALSE(connection_.connected());
6978 EXPECT_EQ(1, connection_close_frame_count_);
6979 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6980 IsError(QUIC_INVALID_VERSION));
6981}
6982
6983TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6984 // Send a version negotiation packet with the version the client started with.
6985 // It should be rejected.
6986 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6987 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6988 std::unique_ptr<QuicEncryptedPacket> encrypted(
6989 QuicFramer::BuildVersionNegotiationPacket(
6990 connection_id_, EmptyQuicConnectionId(),
6991 connection_.version().HasIetfInvariantHeader(),
6992 connection_.version().HasLengthPrefixedConnectionIds(),
6993 AllSupportedVersions()));
6994 std::unique_ptr<QuicReceivedPacket> received(
6995 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6996 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6997 EXPECT_EQ(1, connection_close_frame_count_);
6998 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6999 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
7000}
7001
Bence Békybac04052022-04-07 15:44:29 -04007002TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
7003 // Construct a packet with stream frame and connection close frame.
7004 QuicPacketHeader header;
7005 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
7006 header.source_connection_id = connection_id_;
7007 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7008 if (!peer_framer_.version().HasIetfInvariantHeader()) {
7009 header.source_connection_id_included = CONNECTION_ID_PRESENT;
7010 }
7011 } else {
7012 header.destination_connection_id = connection_id_;
7013 if (peer_framer_.version().HasIetfInvariantHeader()) {
7014 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
7015 }
7016 }
7017 header.packet_number = QuicPacketNumber(1);
7018 header.version_flag = false;
7019
7020 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
7021 // This QuicConnectionCloseFrame will default to being for a Google QUIC
7022 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
7023 // depending on the mapping.
7024 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
7025 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
7026 /*transport_close_frame_type=*/0);
7027 QuicFrames frames;
7028 frames.push_back(QuicFrame(frame1_));
7029 frames.push_back(QuicFrame(&qccf));
7030 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
7031 EXPECT_TRUE(nullptr != packet);
7032 char buffer[kMaxOutgoingPacketSize];
7033 size_t encrypted_length = peer_framer_.EncryptPayload(
7034 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
7035 kMaxOutgoingPacketSize);
7036
7037 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
7038 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7039 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7040 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7041
7042 connection_.ProcessUdpPacket(
7043 kSelfAddress, kPeerAddress,
7044 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
7045 EXPECT_EQ(1, connection_close_frame_count_);
7046 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7047 IsError(QUIC_PEER_GOING_AWAY));
7048}
7049
7050TEST_P(QuicConnectionTest, SelectMutualVersion) {
7051 connection_.SetSupportedVersions(AllSupportedVersions());
7052 // Set the connection to speak the lowest quic version.
7053 connection_.set_version(QuicVersionMin());
7054 EXPECT_EQ(QuicVersionMin(), connection_.version());
7055
7056 // Pass in available versions which includes a higher mutually supported
7057 // version. The higher mutually supported version should be selected.
7058 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
7059 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
7060 EXPECT_EQ(QuicVersionMax(), connection_.version());
7061
7062 // Expect that the lowest version is selected.
7063 // Ensure the lowest supported version is less than the max, unless they're
7064 // the same.
7065 ParsedQuicVersionVector lowest_version_vector;
7066 lowest_version_vector.push_back(QuicVersionMin());
7067 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
7068 EXPECT_EQ(QuicVersionMin(), connection_.version());
7069
7070 // Shouldn't be able to find a mutually supported version.
7071 ParsedQuicVersionVector unsupported_version;
7072 unsupported_version.push_back(UnsupportedQuicVersion());
7073 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
7074}
7075
7076TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
7077 EXPECT_FALSE(writer_->IsWriteBlocked());
7078
7079 // Send a packet.
7080 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7081 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7082 EXPECT_EQ(1u, writer_->packets_write_attempts());
7083
7084 TriggerConnectionClose();
7085 EXPECT_LE(2u, writer_->packets_write_attempts());
7086}
7087
7088TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
7089 BlockOnNextWrite();
7090 TriggerConnectionClose();
7091 EXPECT_EQ(1u, writer_->packets_write_attempts());
7092 EXPECT_TRUE(writer_->IsWriteBlocked());
7093}
7094
7095TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
7096 BlockOnNextWrite();
7097 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7098 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7099 EXPECT_EQ(1u, writer_->packets_write_attempts());
7100 EXPECT_TRUE(writer_->IsWriteBlocked());
7101 TriggerConnectionClose();
7102 EXPECT_EQ(1u, writer_->packets_write_attempts());
7103}
7104
7105TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
7106 PathProbeTestInit(Perspective::IS_CLIENT);
7107 MockQuicConnectionDebugVisitor debug_visitor;
7108 connection_.set_debug_visitor(&debug_visitor);
7109
7110 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
7111 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
7112
7113 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
7114 connection_.SendConnectivityProbingPacket(writer_.get(),
7115 connection_.peer_address());
7116}
7117
7118TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
7119 QuicPacketHeader header;
7120 header.packet_number = QuicPacketNumber(1);
7121 if (GetParam().version.HasIetfInvariantHeader()) {
7122 header.form = IETF_QUIC_LONG_HEADER_PACKET;
7123 }
7124
7125 MockQuicConnectionDebugVisitor debug_visitor;
7126 connection_.set_debug_visitor(&debug_visitor);
7127 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header), _, _)).Times(1);
7128 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
7129 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
7130 connection_.OnPacketHeader(header);
7131}
7132
7133TEST_P(QuicConnectionTest, Pacing) {
7134 TestConnection server(connection_id_, kPeerAddress, kSelfAddress,
7135 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07007136 Perspective::IS_SERVER, version(),
7137 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04007138 TestConnection client(connection_id_, kSelfAddress, kPeerAddress,
7139 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07007140 Perspective::IS_CLIENT, version(),
7141 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04007142 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7143 static_cast<const QuicSentPacketManager*>(
7144 &client.sent_packet_manager())));
7145 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
7146 static_cast<const QuicSentPacketManager*>(
7147 &server.sent_packet_manager())));
7148}
7149
7150TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
7151 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7152
7153 // Send a WINDOW_UPDATE frame.
7154 QuicWindowUpdateFrame window_update;
7155 window_update.stream_id = 3;
7156 window_update.max_data = 1234;
7157 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
7158 ProcessFramePacket(QuicFrame(window_update));
7159
7160 // Ensure that this has caused the ACK alarm to be set.
7161 EXPECT_TRUE(connection_.HasPendingAcks());
7162}
7163
7164TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7165 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7166
7167 // Send a BLOCKED frame.
7168 QuicBlockedFrame blocked;
7169 blocked.stream_id = 3;
7170 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7171 ProcessFramePacket(QuicFrame(blocked));
7172
7173 // Ensure that this has caused the ACK alarm to be set.
7174 EXPECT_TRUE(connection_.HasPendingAcks());
7175}
7176
7177TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7178 // Enable pacing.
7179 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7180 QuicConfig config;
7181 connection_.SetFromConfig(config);
7182
7183 // Send two packets. One packet is not sufficient because if it gets acked,
7184 // there will be no packets in flight after that and the pacer will always
7185 // allow the next packet in that situation.
7186 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7187 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7188 connection_.SendStreamDataWithString(
7189 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7190 0, NO_FIN);
7191 connection_.SendStreamDataWithString(
7192 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7193 3, NO_FIN);
7194 connection_.OnCanWrite();
7195
7196 // Schedule the next packet for a few milliseconds in future.
7197 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7198 QuicTime scheduled_pacing_time =
7199 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7200 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7201 scheduled_pacing_time);
7202
7203 // Send a packet and have it be blocked by congestion control.
7204 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7205 connection_.SendStreamDataWithString(
7206 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7207 6, NO_FIN);
7208 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7209
7210 // Process an ack and the send alarm will be set to the new 5ms delay.
7211 QuicAckFrame ack = InitAckFrame(1);
7212 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7213 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7214 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7215 ProcessAckPacket(&ack);
7216 size_t padding_frame_count = writer_->padding_frames().size();
7217 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
7218 EXPECT_EQ(1u, writer_->stream_frames().size());
7219 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7220 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7221 writer_->Reset();
7222}
7223
7224TEST_P(QuicConnectionTest, SendAcksImmediately) {
7225 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7226 return;
7227 }
7228 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7229 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7230 ProcessDataPacket(1);
7231 CongestionBlockWrites();
7232 SendAckPacketToPeer();
7233}
7234
7235TEST_P(QuicConnectionTest, SendPingImmediately) {
7236 MockQuicConnectionDebugVisitor debug_visitor;
7237 connection_.set_debug_visitor(&debug_visitor);
7238
7239 CongestionBlockWrites();
7240 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7241 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7242 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
7243 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7244 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7245 EXPECT_FALSE(connection_.HasQueuedData());
7246}
7247
7248TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7249 MockQuicConnectionDebugVisitor debug_visitor;
7250 connection_.set_debug_visitor(&debug_visitor);
7251
7252 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7253 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7254 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
7255 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
QUICHE team1a271082022-05-18 10:22:22 -07007256 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04007257 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7258 EXPECT_FALSE(connection_.HasQueuedData());
7259}
7260
7261TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7262 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7263 return;
7264 }
7265 MockQuicConnectionDebugVisitor debug_visitor;
7266 connection_.set_debug_visitor(&debug_visitor);
QUICHE team1a271082022-05-18 10:22:22 -07007267 QuicBlockedFrame blocked(1, 3, 0);
Bence Békybac04052022-04-07 15:44:29 -04007268
7269 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7270 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(0);
7271 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7272 connection_.SendControlFrame(QuicFrame(blocked));
7273 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7274 EXPECT_FALSE(connection_.HasQueuedData());
7275}
7276
7277TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7278 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7279 if (!IsDefaultTestConfiguration()) {
7280 return;
7281 }
7282
vasilvvac2e30d2022-06-02 14:26:59 -07007283 EXPECT_QUIC_BUG(
7284 {
7285 EXPECT_CALL(visitor_,
7286 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7287 .WillOnce(
7288 Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7289 connection_.SaveAndSendStreamData(3, {}, 0, FIN);
7290 EXPECT_FALSE(connection_.connected());
7291 EXPECT_EQ(1, connection_close_frame_count_);
7292 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7293 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
7294 },
7295 "Cannot send stream data with level: ENCRYPTION_INITIAL");
Bence Békybac04052022-04-07 15:44:29 -04007296}
7297
7298TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7299 EXPECT_TRUE(connection_.connected());
7300 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7301
7302 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7303 connection_.SendCryptoStreamData();
7304
7305 // Verify retransmission timer is correctly set after crypto packet has been
7306 // sent.
7307 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7308 QuicTime retransmission_time =
7309 QuicConnectionPeer::GetSentPacketManager(&connection_)
7310 ->GetRetransmissionTime();
7311 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7312 EXPECT_EQ(retransmission_time,
7313 connection_.GetRetransmissionAlarm()->deadline());
7314
7315 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7316 connection_.GetRetransmissionAlarm()->Fire();
7317}
7318
7319// Includes regression test for b/69979024.
7320TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
7321 EXPECT_TRUE(connection_.connected());
7322 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7323 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007324 EXPECT_CALL(visitor_, GetHandshakeState())
7325 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7326 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007327
7328 const char data[] = "data";
7329 size_t data_size = strlen(data);
7330 QuicStreamOffset offset = 0;
7331
7332 for (int i = 0; i < 2; ++i) {
7333 // Send a packet. Now there's a retransmittable packet on the wire, so the
7334 // path degrading detection should be set.
7335 connection_.SendStreamDataWithString(
7336 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7337 offset, NO_FIN);
7338 offset += data_size;
7339 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7340 // Check the deadline of the path degrading detection.
7341 QuicTime::Delta delay =
7342 QuicConnectionPeer::GetSentPacketManager(&connection_)
7343 ->GetPathDegradingDelay();
7344 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7345 clock_.ApproximateNow());
7346
7347 // Send a second packet. The path degrading detection's deadline should
7348 // remain the same.
7349 // Regression test for b/69979024.
7350 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7351 QuicTime prev_deadline =
7352 connection_.GetBlackholeDetectorAlarm()->deadline();
7353 connection_.SendStreamDataWithString(
7354 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7355 offset, NO_FIN);
7356 offset += data_size;
7357 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7358 EXPECT_EQ(prev_deadline,
7359 connection_.GetBlackholeDetectorAlarm()->deadline());
7360
7361 // Now receive an ACK of the first packet. This should advance the path
7362 // degrading detection's deadline since forward progress has been made.
7363 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7364 if (i == 0) {
7365 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7366 }
7367 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7368 QuicAckFrame frame = InitAckFrame(
7369 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7370 ProcessAckPacket(&frame);
7371 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7372 // Check the deadline of the path degrading detection.
7373 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7374 ->GetPathDegradingDelay();
7375 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7376 clock_.ApproximateNow());
7377
7378 if (i == 0) {
7379 // Now receive an ACK of the second packet. Since there are no more
7380 // retransmittable packets on the wire, this should cancel the path
7381 // degrading detection.
7382 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7383 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7384 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7385 ProcessAckPacket(&frame);
7386 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7387 } else {
7388 // Advance time to the path degrading alarm's deadline and simulate
7389 // firing the alarm.
7390 clock_.AdvanceTime(delay);
7391 EXPECT_CALL(visitor_, OnPathDegrading());
7392 connection_.PathDegradingTimeout();
7393 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7394 }
7395 }
7396 EXPECT_TRUE(connection_.IsPathDegrading());
7397}
7398
7399TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7400 const QuicTime::Delta retransmittable_on_wire_timeout =
7401 QuicTime::Delta::FromMilliseconds(50);
7402 connection_.set_initial_retransmittable_on_wire_timeout(
7403 retransmittable_on_wire_timeout);
7404
7405 EXPECT_TRUE(connection_.connected());
7406 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7407 .WillRepeatedly(Return(true));
7408
7409 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7410 EXPECT_FALSE(connection_.IsPathDegrading());
7411 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
fayang59e518a2022-11-29 11:16:45 -08007412 EXPECT_CALL(visitor_, GetHandshakeState())
7413 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7414 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007415
7416 const char data[] = "data";
7417 size_t data_size = strlen(data);
7418 QuicStreamOffset offset = 0;
7419
7420 // Send a packet.
7421 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7422 offset += data_size;
7423 // Now there's a retransmittable packet on the wire, so the path degrading
7424 // alarm should be set.
7425 // The retransmittable-on-wire alarm should not be set.
7426 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7427 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7428 ->GetPathDegradingDelay();
7429 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7430 clock_.ApproximateNow());
7431 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7432 // The ping alarm is set for the ping timeout, not the shorter
7433 // retransmittable_on_wire_timeout.
7434 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7435 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7436 EXPECT_EQ(ping_delay,
7437 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7438
7439 // Now receive an ACK of the packet.
7440 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7441 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7442 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7443 QuicAckFrame frame =
7444 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7445 ProcessAckPacket(&frame);
7446 // No more retransmittable packets on the wire, so the path degrading alarm
7447 // should be cancelled, and the ping alarm should be set to the
7448 // retransmittable_on_wire_timeout.
7449 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7450 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7451 EXPECT_EQ(retransmittable_on_wire_timeout,
7452 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7453
7454 // Simulate firing the ping alarm and sending a PING.
7455 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7456 connection_.GetPingAlarm()->Fire();
7457
7458 // Now there's a retransmittable packet (PING) on the wire, so the path
7459 // degrading alarm should be set.
fayang59e518a2022-11-29 11:16:45 -08007460 ASSERT_TRUE(connection_.PathDegradingDetectionInProgress());
Bence Békybac04052022-04-07 15:44:29 -04007461 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7462 ->GetPathDegradingDelay();
7463 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7464 clock_.ApproximateNow());
7465}
7466
7467TEST_P(QuicConnectionTest, ServerRetransmittableOnWire) {
7468 set_perspective(Perspective::IS_SERVER);
7469 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7470 SetQuicReloadableFlag(quic_enable_server_on_wire_ping, true);
7471
7472 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7473 QuicConfig config;
7474 QuicTagVector connection_options;
7475 connection_options.push_back(kSRWP);
7476 config.SetInitialReceivedConnectionOptions(connection_options);
7477 connection_.SetFromConfig(config);
7478
7479 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7480 .WillRepeatedly(Return(true));
7481
7482 ProcessPacket(1);
7483
7484 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7485 QuicTime::Delta ping_delay = QuicTime::Delta::FromMilliseconds(200);
7486 EXPECT_EQ(ping_delay,
7487 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7488
7489 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
7490 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
7491 // Verify PING alarm gets cancelled.
7492 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7493
7494 // Now receive an ACK of the packet.
7495 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
7496 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7497 QuicAckFrame frame =
7498 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7499 ProcessAckPacket(2, &frame);
7500 // Verify PING alarm gets scheduled.
7501 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7502 EXPECT_EQ(ping_delay,
7503 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7504}
7505
fayangf6607db2022-04-21 18:10:41 -07007506TEST_P(QuicConnectionTest, RetransmittableOnWireSendFirstPacket) {
fayang9b455102022-11-29 18:19:20 -08007507 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007508 return;
7509 }
7510 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7511 .WillRepeatedly(Return(true));
7512 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7513
7514 const QuicTime::Delta kRetransmittableOnWireTimeout =
7515 QuicTime::Delta::FromMilliseconds(200);
7516 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7517
7518 connection_.set_initial_retransmittable_on_wire_timeout(
7519 kRetransmittableOnWireTimeout);
7520
7521 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7522 QuicConfig config;
7523 QuicTagVector connection_options;
7524 connection_options.push_back(kROWF);
7525 config.SetClientConnectionOptions(connection_options);
7526 connection_.SetFromConfig(config);
7527
7528 // Send a request.
7529 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7530 // Receive an ACK after 1-RTT.
7531 clock_.AdvanceTime(kTestRtt);
7532 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7533 QuicAckFrame frame =
7534 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7535 ProcessAckPacket(&frame);
7536 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7537 EXPECT_EQ(kRetransmittableOnWireTimeout,
7538 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7539 EXPECT_EQ(1u, writer_->packets_write_attempts());
7540
7541 // Fire retransmittable-on-wire alarm.
7542 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7543 connection_.GetPingAlarm()->Fire();
7544 EXPECT_EQ(2u, writer_->packets_write_attempts());
7545 // Verify alarm is set in keep-alive mode.
7546 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7547 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7548 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7549}
7550
7551TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytes) {
fayang9b455102022-11-29 18:19:20 -08007552 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007553 return;
7554 }
7555 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7556 .WillRepeatedly(Return(true));
7557 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7558
7559 const QuicTime::Delta kRetransmittableOnWireTimeout =
7560 QuicTime::Delta::FromMilliseconds(200);
7561 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7562
7563 connection_.set_initial_retransmittable_on_wire_timeout(
7564 kRetransmittableOnWireTimeout);
7565
7566 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7567 QuicConfig config;
7568 QuicTagVector connection_options;
7569 connection_options.push_back(kROWR);
7570 config.SetClientConnectionOptions(connection_options);
7571 connection_.SetFromConfig(config);
7572
7573 // Send a request.
7574 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7575 // Receive an ACK after 1-RTT.
7576 clock_.AdvanceTime(kTestRtt);
7577 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7578 QuicAckFrame frame =
7579 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7580 ProcessAckPacket(&frame);
7581 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7582 EXPECT_EQ(kRetransmittableOnWireTimeout,
7583 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7584 EXPECT_EQ(1u, writer_->packets_write_attempts());
7585
7586 // Fire retransmittable-on-wire alarm.
7587 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7588 // Next packet is not processable by the framer in the test writer.
7589 ExpectNextPacketUnprocessable();
7590 connection_.GetPingAlarm()->Fire();
7591 EXPECT_EQ(2u, writer_->packets_write_attempts());
7592 // Verify alarm is set in keep-alive mode.
7593 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7594 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7595 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7596}
7597
7598TEST_P(QuicConnectionTest,
7599 RetransmittableOnWireSendRandomBytesWithWriterBlocked) {
fayang9b455102022-11-29 18:19:20 -08007600 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007601 return;
7602 }
7603 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7604 .WillRepeatedly(Return(true));
7605 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7606 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7607
7608 const QuicTime::Delta kRetransmittableOnWireTimeout =
7609 QuicTime::Delta::FromMilliseconds(200);
7610 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7611
7612 connection_.set_initial_retransmittable_on_wire_timeout(
7613 kRetransmittableOnWireTimeout);
7614
7615 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7616 QuicConfig config;
7617 QuicTagVector connection_options;
7618 connection_options.push_back(kROWR);
7619 config.SetClientConnectionOptions(connection_options);
7620 connection_.SetFromConfig(config);
7621
7622 // Send a request.
7623 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7624 // Receive an ACK after 1-RTT.
7625 clock_.AdvanceTime(kTestRtt);
7626 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7627 QuicAckFrame frame =
7628 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7629 ProcessAckPacket(&frame);
7630 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7631 EXPECT_EQ(kRetransmittableOnWireTimeout,
7632 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7633 EXPECT_EQ(1u, writer_->packets_write_attempts());
7634 // Receive an out of order data packet and block the ACK packet.
7635 BlockOnNextWrite();
7636 ProcessDataPacket(3);
7637 EXPECT_EQ(2u, writer_->packets_write_attempts());
7638 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7639
7640 // Fire retransmittable-on-wire alarm.
7641 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7642 connection_.GetPingAlarm()->Fire();
7643 // Verify the random bytes packet gets queued.
7644 EXPECT_EQ(2u, connection_.NumQueuedPackets());
7645}
7646
Bence Békybac04052022-04-07 15:44:29 -04007647// This test verifies that the connection marks path as degrading and does not
7648// spin timer to detect path degrading when a new packet is sent on the
7649// degraded path.
7650TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
7651 EXPECT_TRUE(connection_.connected());
7652 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7653 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007654 EXPECT_CALL(visitor_, GetHandshakeState())
7655 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7656 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007657
7658 const char data[] = "data";
7659 size_t data_size = strlen(data);
7660 QuicStreamOffset offset = 0;
7661
7662 // Send the first packet. Now there's a retransmittable packet on the wire, so
7663 // the path degrading alarm should be set.
7664 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7665 offset += data_size;
7666 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7667 // Check the deadline of the path degrading detection.
7668 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7669 ->GetPathDegradingDelay();
7670 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7671 clock_.ApproximateNow());
7672
7673 // Send a second packet. The path degrading detection's deadline should remain
7674 // the same.
7675 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7676 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7677 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7678 offset += data_size;
7679 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7680 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7681
7682 // Now receive an ACK of the first packet. This should advance the path
7683 // degrading detection's deadline since forward progress has been made.
7684 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7685 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7686 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7687 QuicAckFrame frame =
7688 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7689 ProcessAckPacket(&frame);
7690 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7691 // Check the deadline of the path degrading alarm.
7692 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7693 ->GetPathDegradingDelay();
7694 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7695 clock_.ApproximateNow());
7696
7697 // Advance time to the path degrading detection's deadline and simulate
7698 // firing the path degrading detection. This path will be considered as
7699 // degrading.
7700 clock_.AdvanceTime(delay);
7701 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7702 connection_.PathDegradingTimeout();
7703 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7704 EXPECT_TRUE(connection_.IsPathDegrading());
7705
7706 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7707 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7708 // Send a third packet. The path degrading detection is no longer set but path
7709 // should still be marked as degrading.
7710 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7711 offset += data_size;
7712 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7713 EXPECT_TRUE(connection_.IsPathDegrading());
7714}
7715
fayang59e518a2022-11-29 11:16:45 -08007716TEST_P(QuicConnectionTest, NoPathDegradingDetectionBeforeHandshakeConfirmed) {
7717 EXPECT_TRUE(connection_.connected());
7718 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7719 EXPECT_FALSE(connection_.IsPathDegrading());
7720 EXPECT_CALL(visitor_, GetHandshakeState())
7721 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
7722
7723 connection_.SendStreamDataWithString(1, "data", 0, NO_FIN);
7724 if (GetQuicReloadableFlag(
7725 quic_no_path_degrading_before_handshake_confirmed) &&
7726 connection_.SupportsMultiplePacketNumberSpaces()) {
7727 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7728 } else {
7729 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7730 }
7731}
7732
Bence Békybac04052022-04-07 15:44:29 -04007733// This test verifies that the connection unmarks path as degrarding and spins
7734// the timer to detect future path degrading when forward progress is made
7735// after path has been marked degrading.
7736TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7737 EXPECT_TRUE(connection_.connected());
7738 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7739 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007740 EXPECT_CALL(visitor_, GetHandshakeState())
7741 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7742 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007743
7744 const char data[] = "data";
7745 size_t data_size = strlen(data);
7746 QuicStreamOffset offset = 0;
7747
7748 // Send the first packet. Now there's a retransmittable packet on the wire, so
7749 // the path degrading alarm should be set.
7750 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7751 offset += data_size;
7752 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7753 // Check the deadline of the path degrading alarm.
7754 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7755 ->GetPathDegradingDelay();
7756 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7757 clock_.ApproximateNow());
7758
7759 // Send a second packet. The path degrading alarm's deadline should remain
7760 // the same.
7761 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7762 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7763 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7764 offset += data_size;
7765 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7766 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7767
7768 // Now receive an ACK of the first packet. This should advance the path
7769 // degrading alarm's deadline since forward progress has been made.
7770 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7771 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7772 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7773 QuicAckFrame frame =
7774 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7775 ProcessAckPacket(&frame);
7776 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7777 // Check the deadline of the path degrading alarm.
7778 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7779 ->GetPathDegradingDelay();
7780 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7781 clock_.ApproximateNow());
7782
7783 // Advance time to the path degrading alarm's deadline and simulate
7784 // firing the alarm.
7785 clock_.AdvanceTime(delay);
7786 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7787 connection_.PathDegradingTimeout();
7788 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7789 EXPECT_TRUE(connection_.IsPathDegrading());
7790
7791 // Send a third packet. The path degrading alarm is no longer set but path
7792 // should still be marked as degrading.
7793 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7794 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7795 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7796 offset += data_size;
7797 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7798 EXPECT_TRUE(connection_.IsPathDegrading());
7799
7800 // Now receive an ACK of the second packet. This should unmark the path as
7801 // degrading. And will set a timer to detect new path degrading.
7802 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7803 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7804 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
7805 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7806 ProcessAckPacket(&frame);
7807 EXPECT_FALSE(connection_.IsPathDegrading());
7808 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7809}
7810
7811TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
7812 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7813 return;
7814 }
7815 set_perspective(Perspective::IS_SERVER);
7816 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7817
7818 EXPECT_FALSE(connection_.IsPathDegrading());
7819 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7820
7821 // Send data.
7822 const char data[] = "data";
7823 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7824 EXPECT_FALSE(connection_.IsPathDegrading());
7825 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7826
7827 // Ack data.
7828 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7829 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7830 QuicAckFrame frame =
7831 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7832 ProcessAckPacket(&frame);
7833 EXPECT_FALSE(connection_.IsPathDegrading());
7834 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7835}
7836
7837TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
7838 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7839 return;
7840 }
7841 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7842 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7843 ProcessDataPacket(1);
7844 SendAckPacketToPeer();
7845 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7846 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7847 EXPECT_FALSE(connection_.IsPathDegrading());
7848 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7849}
7850
7851TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7852 // Verifies that multiple calls to CloseConnection do not
7853 // result in multiple attempts to close the connection - it will be marked as
7854 // disconnected after the first call.
7855 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
7856 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7857 ConnectionCloseBehavior::SILENT_CLOSE);
7858 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7859 ConnectionCloseBehavior::SILENT_CLOSE);
7860}
7861
7862TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7863 set_perspective(Perspective::IS_SERVER);
7864 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang161ce6e2022-07-01 18:02:11 -07007865 QuicConnectionPeer::SetAddressValidated(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04007866
7867 CryptoHandshakeMessage message;
7868 CryptoFramer framer;
7869 message.set_tag(kCHLO);
7870 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7871 frame1_.stream_id = 10;
7872 frame1_.data_buffer = data->data();
7873 frame1_.data_length = data->length();
7874
7875 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7876 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7877 }
7878 EXPECT_CALL(visitor_,
7879 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7880 ForceProcessFramePacket(QuicFrame(frame1_));
7881 if (VersionHasIetfQuicFrames(version().transport_version)) {
7882 // INITIAL packet should not contain STREAM frame.
7883 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7884 } else {
7885 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7886 }
7887}
7888
7889TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7890 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7891
7892 CryptoHandshakeMessage message;
7893 CryptoFramer framer;
7894 message.set_tag(kREJ);
7895 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7896 frame1_.stream_id = 10;
7897 frame1_.data_buffer = data->data();
7898 frame1_.data_length = data->length();
7899
7900 EXPECT_CALL(visitor_,
7901 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7902 ForceProcessFramePacket(QuicFrame(frame1_));
7903 if (VersionHasIetfQuicFrames(version().transport_version)) {
7904 // INITIAL packet should not contain STREAM frame.
7905 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7906 } else {
7907 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7908 }
7909}
7910
7911TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7912 SimulateNextPacketTooLarge();
7913 // A connection close packet is sent
7914 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7915 .Times(1);
7916 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7917 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7918}
7919
7920TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7921 // Test even we always get packet too large, we do not infinitely try to send
7922 // close packet.
7923 AlwaysGetPacketTooLarge();
7924 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7925 .Times(1);
7926 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7927 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7928}
7929
7930TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
7931 // Regression test for crbug.com/979507.
7932 //
7933 // If we get a write error when writing queued packets, we should attempt to
7934 // send a connection close packet, but if sending that fails, it shouldn't get
7935 // queued.
7936
7937 // Queue a packet to write.
7938 BlockOnNextWrite();
7939 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7940 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7941
7942 // Configure writer to always fail.
7943 AlwaysGetPacketTooLarge();
7944
7945 // Expect that we attempt to close the connection exactly once.
7946 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7947 .Times(1);
7948
7949 // Unblock the writes and actually send.
7950 writer_->SetWritable();
7951 connection_.OnCanWrite();
7952 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7953
7954 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7955}
7956
7957// Verify that if connection has no outstanding data, it notifies the send
7958// algorithm after the write.
7959TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7960 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7961 {
7962 InSequence seq;
7963 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7964 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7965 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7966 .WillRepeatedly(Return(false));
7967 }
7968
7969 connection_.SendStreamData3();
7970}
7971
7972// Verify that the connection does not become app-limited if there is
7973// outstanding data to send after the write.
7974TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7975 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7976 {
7977 InSequence seq;
7978 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7979 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7980 }
7981
7982 connection_.SendStreamData3();
7983}
7984
7985// Verify that the connection does not become app-limited after blocked write
7986// even if there is outstanding data to send after the write.
7987TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7988 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7989 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7990 BlockOnNextWrite();
7991
7992 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7993 connection_.SendStreamData3();
7994
7995 // Now unblock the writer, become congestion control blocked,
7996 // and ensure we become app-limited after writing.
7997 writer_->SetWritable();
7998 CongestionBlockWrites();
7999 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
8000 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8001 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
8002 connection_.OnCanWrite();
8003}
8004
Bence Békybac04052022-04-07 15:44:29 -04008005TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
8006 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8007 // Send an ack by simulating delayed ack alarm firing.
8008 ProcessPacket(1);
8009 EXPECT_TRUE(connection_.HasPendingAcks());
8010 connection_.GetAckAlarm()->Fire();
8011 // Simulate data packet causes write error.
8012 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8013 SimulateNextPacketTooLarge();
8014 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8015 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8016 // Ack frame is not bundled in connection close packet.
8017 EXPECT_TRUE(writer_->ack_frames().empty());
8018 if (writer_->padding_frames().empty()) {
8019 EXPECT_EQ(1u, writer_->frame_count());
8020 } else {
8021 EXPECT_EQ(2u, writer_->frame_count());
8022 }
8023
8024 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8025}
8026
8027TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
8028 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8029 return;
8030 }
8031
8032 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8033 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8034 connection_.CloseConnection(
8035 kQuicErrorCode, "Some random error message",
8036 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8037
8038 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8039
8040 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8041 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8042
8043 if (!connection_.version().CanSendCoalescedPackets()) {
8044 // Each connection close packet should be sent in distinct UDP packets.
8045 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8046 writer_->connection_close_packets());
8047 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
8048 writer_->packets_write_attempts());
8049 return;
8050 }
8051
8052 // A single UDP packet should be sent with multiple connection close packets
8053 // coalesced together.
8054 EXPECT_EQ(1u, writer_->packets_write_attempts());
8055
8056 // Only the first packet has been processed yet.
8057 EXPECT_EQ(1u, writer_->connection_close_packets());
8058
8059 // ProcessPacket resets the visitor and frees the coalesced packet.
8060 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
8061 auto packet = writer_->coalesced_packet()->Clone();
8062 writer_->framer()->ProcessPacket(*packet);
8063 EXPECT_EQ(1u, writer_->connection_close_packets());
8064 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8065}
8066
8067TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
8068 if (connection_.SupportsMultiplePacketNumberSpaces()) {
8069 return;
8070 }
8071
8072 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8073 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8074 connection_.CloseConnection(
8075 kQuicErrorCode, "Some random error message",
8076 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8077
8078 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8079
8080 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8081 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8082 EXPECT_EQ(1u, writer_->connection_close_packets());
8083 EXPECT_EQ(1u, writer_->packets_write_attempts());
8084 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
8085}
8086
8087TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
8088 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8089 return;
8090 }
8091 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07008092 // Receives packet 1000 in initial data.
8093 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8094 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -04008095
8096 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
8097 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
8098 }
8099 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
8100 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
8101 connection_.CloseConnection(
8102 kQuicErrorCode, "Some random error message",
8103 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
8104
8105 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
8106
8107 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
8108 EXPECT_EQ(1u, writer_->connection_close_frames().size());
8109 EXPECT_TRUE(writer_->padding_frames().empty());
8110 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
8111}
8112
8113// Regression test for b/63620844.
8114TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
8115 SimulateNextPacketTooLarge();
8116 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
8117 .Times(1);
8118
8119 connection_.SendCryptoStreamData();
8120 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
8121}
8122
8123TEST_P(QuicConnectionTest, MaxPacingRate) {
8124 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
8125 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
8126 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
8127}
8128
8129TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
8130 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
8131 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8132 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
8133 EXPECT_EQ(CONNECTION_ID_PRESENT,
8134 writer_->last_packet_header().destination_connection_id_included);
8135
8136 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8137 QuicConfig config;
8138 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
8139 connection_.SetFromConfig(config);
8140
8141 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8142 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
8143 // Verify connection id is still sent in the packet.
8144 EXPECT_EQ(CONNECTION_ID_PRESENT,
8145 writer_->last_packet_header().destination_connection_id_included);
8146}
8147
Bence Békybac04052022-04-07 15:44:29 -04008148TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
8149 const QuicTime::Delta retransmittable_on_wire_timeout =
8150 QuicTime::Delta::FromMilliseconds(50);
8151 connection_.set_initial_retransmittable_on_wire_timeout(
8152 retransmittable_on_wire_timeout);
8153
8154 EXPECT_TRUE(connection_.connected());
8155 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8156 .WillRepeatedly(Return(true));
8157
8158 const char data[] = "data";
8159 size_t data_size = strlen(data);
8160 QuicStreamOffset offset = 0;
8161
8162 // Advance 5ms, send a retransmittable packet to the peer.
8163 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8164 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8165 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8166 offset += data_size;
8167 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8168 // The ping alarm is set for the ping timeout, not the shorter
8169 // retransmittable_on_wire_timeout.
8170 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8171 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8172 EXPECT_EQ(ping_delay,
8173 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8174
8175 // Advance 5ms, send a second retransmittable packet to the peer.
8176 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8177 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8178 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8179 offset += data_size;
8180 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8181
8182 // Now receive an ACK of the first packet. This should not set the
8183 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8184 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8185 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8186 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8187 QuicAckFrame frame =
8188 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8189 ProcessAckPacket(&frame);
8190 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8191 // The ping alarm is set for the ping timeout, not the shorter
8192 // retransmittable_on_wire_timeout.
8193 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8194 // The ping alarm has a 1 second granularity, and the clock has been advanced
8195 // 10ms since it was originally set.
8196 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8197 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8198
8199 // Now receive an ACK of the second packet. This should set the
8200 // retransmittable-on-wire alarm now that no retransmittable packets are on
8201 // the wire.
8202 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8203 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8204 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8205 ProcessAckPacket(&frame);
8206 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8207 EXPECT_EQ(retransmittable_on_wire_timeout,
8208 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8209
8210 // Now receive a duplicate ACK of the second packet. This should not update
8211 // the ping alarm.
8212 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8213 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8214 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8215 ProcessAckPacket(&frame);
8216 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8217 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8218
8219 // Now receive a non-ACK packet. This should not update the ping alarm.
8220 prev_deadline = connection_.GetPingAlarm()->deadline();
8221 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8222 ProcessPacket(4);
8223 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8224 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8225
8226 // Simulate the alarm firing and check that a PING is sent.
8227 connection_.GetPingAlarm()->Fire();
8228 size_t padding_frame_count = writer_->padding_frames().size();
8229 if (GetParam().no_stop_waiting) {
8230 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
8231 } else {
8232 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
8233 }
8234 ASSERT_EQ(1u, writer_->ping_frames().size());
8235}
8236
8237TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8238 const QuicTime::Delta retransmittable_on_wire_timeout =
8239 QuicTime::Delta::FromMilliseconds(50);
8240 connection_.set_initial_retransmittable_on_wire_timeout(
8241 retransmittable_on_wire_timeout);
8242
8243 EXPECT_TRUE(connection_.connected());
8244 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8245 .WillRepeatedly(Return(true));
8246
8247 const char data[] = "data";
8248 size_t data_size = strlen(data);
8249 QuicStreamOffset offset = 0;
8250
8251 // Advance 5ms, send a retransmittable packet to the peer.
8252 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8253 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8254 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8255 offset += data_size;
8256 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8257 // The ping alarm is set for the ping timeout, not the shorter
8258 // retransmittable_on_wire_timeout.
8259 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8260 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8261 EXPECT_EQ(ping_delay,
8262 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8263
8264 // Now receive an ACK of the first packet. This should set the
8265 // retransmittable-on-wire alarm now that no retransmittable packets are on
8266 // the wire.
8267 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8268 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8269 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8270 QuicAckFrame frame =
8271 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8272 ProcessAckPacket(&frame);
8273 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8274 EXPECT_EQ(retransmittable_on_wire_timeout,
8275 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8276
8277 // Before the alarm fires, send another retransmittable packet. This should
8278 // cancel the retransmittable-on-wire alarm since now there's a
8279 // retransmittable packet on the wire.
8280 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8281 offset += data_size;
8282 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8283
8284 // Now receive an ACK of the second packet. This should set the
8285 // retransmittable-on-wire alarm now that no retransmittable packets are on
8286 // the wire.
8287 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8288 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8289 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8290 ProcessAckPacket(&frame);
8291 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8292 EXPECT_EQ(retransmittable_on_wire_timeout,
8293 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8294
8295 // Simulate the alarm firing and check that a PING is sent.
8296 writer_->Reset();
8297 connection_.GetPingAlarm()->Fire();
8298 size_t padding_frame_count = writer_->padding_frames().size();
8299 if (GetParam().no_stop_waiting) {
8300 // Do not ACK acks.
8301 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
8302 } else {
8303 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
8304 }
8305 ASSERT_EQ(1u, writer_->ping_frames().size());
8306}
8307
8308// When there is no stream data received but are open streams, send the
8309// first few consecutive pings with aggressive retransmittable-on-wire
8310// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8311// afterwards until it exceeds the default ping timeout.
8312TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8313 int max_aggressive_retransmittable_on_wire_ping_count = 5;
birenroyef686222022-09-12 11:34:34 -07008314 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008315 max_aggressive_retransmittable_on_wire_ping_count);
8316 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8317 QuicTime::Delta::FromMilliseconds(200);
8318 connection_.set_initial_retransmittable_on_wire_timeout(
8319 initial_retransmittable_on_wire_timeout);
8320
8321 EXPECT_TRUE(connection_.connected());
8322 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8323 .WillRepeatedly(Return(true));
8324
8325 const char data[] = "data";
8326 // Advance 5ms, send a retransmittable data packet to the peer.
8327 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8328 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8329 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8330 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8331 // The ping alarm is set for the ping timeout, not the shorter
8332 // retransmittable_on_wire_timeout.
8333 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008334 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008335 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8336
8337 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8338 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8339 .Times(AnyNumber());
8340
8341 // Verify that the first few consecutive retransmittable on wire pings are
8342 // sent with aggressive timeout.
8343 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8344 // Receive an ACK of the previous packet. This should set the ping alarm
8345 // with the initial retransmittable-on-wire timeout.
8346 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8347 QuicPacketNumber ack_num = creator_->packet_number();
8348 QuicAckFrame frame = InitAckFrame(
8349 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8350 ProcessAckPacket(&frame);
8351 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8352 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8353 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8354 // Simulate the alarm firing and check that a PING is sent.
8355 writer_->Reset();
8356 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8357 connection_.GetPingAlarm()->Fire();
8358 }
8359
8360 QuicTime::Delta retransmittable_on_wire_timeout =
8361 initial_retransmittable_on_wire_timeout;
8362
8363 // Verify subsequent pings are sent with timeout that is exponentially backed
8364 // off.
fayang5d393332022-04-18 13:34:54 -07008365 while (retransmittable_on_wire_timeout * 2 <
8366 QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) {
Bence Békybac04052022-04-07 15:44:29 -04008367 // Receive an ACK for the previous PING. This should set the
8368 // ping alarm with backed off retransmittable-on-wire timeout.
8369 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8370 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8371 QuicPacketNumber ack_num = creator_->packet_number();
8372 QuicAckFrame frame = InitAckFrame(
8373 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8374 ProcessAckPacket(&frame);
8375 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8376 EXPECT_EQ(retransmittable_on_wire_timeout,
8377 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8378
8379 // Simulate the alarm firing and check that a PING is sent.
8380 writer_->Reset();
8381 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8382 connection_.GetPingAlarm()->Fire();
8383 }
8384
8385 // The ping alarm is set with default ping timeout.
8386 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008387 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008388 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8389
8390 // Receive an ACK for the previous PING. The ping alarm is set with an
8391 // earlier deadline.
8392 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8393 QuicPacketNumber ack_num = creator_->packet_number();
8394 QuicAckFrame frame = InitAckFrame(
8395 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8396 ProcessAckPacket(&frame);
8397 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008398 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) -
8399 QuicTime::Delta::FromMilliseconds(5),
Bence Békybac04052022-04-07 15:44:29 -04008400 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8401}
8402
8403// This test verify that the count of consecutive aggressive pings is reset
8404// when new data is received. And it also verifies the connection resets
8405// the exponential back-off of the retransmittable-on-wire ping timeout
8406// after receiving new stream data.
8407TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8408 int max_aggressive_retransmittable_on_wire_ping_count = 3;
birenroyef686222022-09-12 11:34:34 -07008409 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
Bence Békybac04052022-04-07 15:44:29 -04008410 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8411 QuicTime::Delta::FromMilliseconds(200);
8412 connection_.set_initial_retransmittable_on_wire_timeout(
8413 initial_retransmittable_on_wire_timeout);
8414
8415 EXPECT_TRUE(connection_.connected());
8416 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8417 .WillRepeatedly(Return(true));
8418 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8419 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8420 .Times(AnyNumber());
8421
8422 const char data[] = "data";
8423 // Advance 5ms, send a retransmittable data packet to the peer.
8424 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8425 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8426 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8427 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8428 // The ping alarm is set for the ping timeout, not the shorter
8429 // retransmittable_on_wire_timeout.
8430 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008431 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008432 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8433
8434 // Receive an ACK of the first packet. This should set the ping alarm with
8435 // initial retransmittable-on-wire timeout since there is no retransmittable
8436 // packet on the wire.
8437 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8438 QuicAckFrame frame =
8439 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8440 ProcessAckPacket(&frame);
8441 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8442 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8443 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8444
8445 // Simulate the alarm firing and check that a PING is sent.
8446 writer_->Reset();
8447 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8448 connection_.GetPingAlarm()->Fire();
8449
8450 // Receive an ACK for the previous PING. Ping alarm will be set with
8451 // aggressive timeout.
8452 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8453 QuicPacketNumber ack_num = creator_->packet_number();
8454 frame = InitAckFrame(
8455 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8456 ProcessAckPacket(&frame);
8457 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8458 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8459 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8460
8461 // Process a data packet.
8462 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8463 ProcessDataPacket(peer_creator_.packet_number() + 1);
8464 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8465 peer_creator_.packet_number() + 1);
8466 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8467 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
fayang327663d2022-05-10 18:25:36 -07008468 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8469 connection_.GetPingAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -04008470
8471 // Verify the count of consecutive aggressive pings is reset.
8472 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8473 // Receive an ACK of the previous packet. This should set the ping alarm
8474 // with the initial retransmittable-on-wire timeout.
8475 QuicPacketNumber ack_num = creator_->packet_number();
8476 QuicAckFrame frame = InitAckFrame(
8477 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8478 ProcessAckPacket(&frame);
8479 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8480 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8481 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8482 // Simulate the alarm firing and check that a PING is sent.
8483 writer_->Reset();
8484 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8485 connection_.GetPingAlarm()->Fire();
8486 // Advance 5ms to receive next packet.
8487 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8488 }
8489
8490 // Receive another ACK for the previous PING. This should set the
8491 // ping alarm with backed off retransmittable-on-wire timeout.
8492 ack_num = creator_->packet_number();
8493 frame = InitAckFrame(
8494 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8495 ProcessAckPacket(&frame);
8496 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8497 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8498 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8499
8500 writer_->Reset();
8501 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8502 connection_.GetPingAlarm()->Fire();
8503
8504 // Process another data packet and a new ACK packet. The ping alarm is set
8505 // with aggressive ping timeout again.
8506 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8507 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8508 ProcessDataPacket(peer_creator_.packet_number() + 1);
8509 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8510 peer_creator_.packet_number() + 1);
8511 ack_num = creator_->packet_number();
8512 frame = InitAckFrame(
8513 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8514 ProcessAckPacket(&frame);
8515 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8516 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8517 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8518}
8519
8520// Make sure that we never send more retransmissible on the wire pings than
8521// the limit in FLAGS_quic_max_retransmittable_on_wire_ping_count.
8522TEST_P(QuicConnectionTest, RetransmittableOnWirePingLimit) {
8523 static constexpr int kMaxRetransmittableOnWirePingCount = 3;
birenroyef686222022-09-12 11:34:34 -07008524 SetQuicFlag(quic_max_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008525 kMaxRetransmittableOnWirePingCount);
8526 static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout =
8527 QuicTime::Delta::FromMilliseconds(200);
8528 static constexpr QuicTime::Delta short_delay =
8529 QuicTime::Delta::FromMilliseconds(5);
8530 ASSERT_LT(short_delay * 10, initial_retransmittable_on_wire_timeout);
8531 connection_.set_initial_retransmittable_on_wire_timeout(
8532 initial_retransmittable_on_wire_timeout);
8533
8534 EXPECT_TRUE(connection_.connected());
8535 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8536 .WillRepeatedly(Return(true));
8537
8538 const char data[] = "data";
8539 // Advance 5ms, send a retransmittable data packet to the peer.
8540 clock_.AdvanceTime(short_delay);
8541 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8542 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8543 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8544 // The ping alarm is set for the ping timeout, not the shorter
8545 // retransmittable_on_wire_timeout.
8546 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008547 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008548 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8549
8550 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8551 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8552 .Times(AnyNumber());
8553
8554 // Verify that the first few consecutive retransmittable on wire pings are
8555 // sent with aggressive timeout.
8556 for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) {
8557 // Receive an ACK of the previous packet. This should set the ping alarm
8558 // with the initial retransmittable-on-wire timeout.
8559 clock_.AdvanceTime(short_delay);
8560 QuicPacketNumber ack_num = creator_->packet_number();
8561 QuicAckFrame frame = InitAckFrame(
8562 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8563 ProcessAckPacket(&frame);
8564 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8565 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8566 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8567 // Simulate the alarm firing and check that a PING is sent.
8568 writer_->Reset();
8569 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8570 connection_.GetPingAlarm()->Fire();
8571 }
8572
8573 // Receive an ACK of the previous packet. This should set the ping alarm
8574 // but this time with the default ping timeout.
8575 QuicPacketNumber ack_num = creator_->packet_number();
8576 QuicAckFrame frame = InitAckFrame(
8577 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8578 ProcessAckPacket(&frame);
8579 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008580 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008581 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8582}
8583
8584TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8585 const StatelessResetToken kTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8586 0, 1, 0, 1, 0, 1, 0, 1};
8587 const StatelessResetToken kWrongTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8588 0, 1, 0, 1, 0, 1, 0, 2};
8589 QuicConfig config;
8590 // No token has been received.
8591 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8592
8593 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8594 // Token is different from received token.
8595 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8596 connection_.SetFromConfig(config);
8597 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8598
8599 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8600 connection_.SetFromConfig(config);
8601 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8602}
8603
8604TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8605 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8606 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8607 BlockOnNextWrite();
8608 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8609 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8610 // This causes connection to be closed because packet 1 has not been sent yet.
8611 QuicAckFrame frame = InitAckFrame(1);
8612 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
8613 ProcessAckPacket(1, &frame);
8614 EXPECT_EQ(0, connection_close_frame_count_);
8615}
8616
8617TEST_P(QuicConnectionTest, SendMessage) {
8618 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
8619 return;
8620 }
8621 if (connection_.version().UsesTls()) {
8622 QuicConfig config;
8623 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8624 &config, kMaxAcceptedDatagramFrameSize);
8625 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8626 connection_.SetFromConfig(config);
8627 }
8628 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
8629 quiche::QuicheMemSlice slice;
8630 {
8631 QuicConnection::ScopedPacketFlusher flusher(&connection_);
8632 connection_.SendStreamData3();
8633 // Send a message which cannot fit into current open packet, and 2 packets
8634 // get sent, one contains stream frame, and the other only contains the
8635 // message frame.
8636 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8637 slice = MemSliceFromString(absl::string_view(
8638 message.data(), connection_.GetCurrentLargestMessagePayload()));
8639 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8640 connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false));
8641 }
8642 // Fail to send a message if connection is congestion control blocked.
8643 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8644 slice = MemSliceFromString("message");
8645 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8646 connection_.SendMessage(2, absl::MakeSpan(&slice, 1), false));
8647
8648 // Always fail to send a message which cannot fit into one packet.
8649 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8650 slice = MemSliceFromString(absl::string_view(
8651 message.data(), connection_.GetCurrentLargestMessagePayload() + 1));
8652 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8653 connection_.SendMessage(3, absl::MakeSpan(&slice, 1), false));
8654}
8655
8656TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
8657 if (!connection_.version().SupportsMessageFrames()) {
8658 return;
8659 }
martinduke225e91a2022-11-28 17:18:13 -08008660 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008661 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
8662 expected_largest_payload += 3;
8663 }
8664 if (connection_.version().HasLongHeaderLengths()) {
8665 expected_largest_payload -= 2;
8666 }
8667 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8668 expected_largest_payload -= 1;
8669 }
8670 if (connection_.version().UsesTls()) {
8671 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8672 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8673 QuicConfig config;
8674 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8675 &config, kMaxAcceptedDatagramFrameSize);
8676 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8677 connection_.SetFromConfig(config);
8678 // Verify the value post-handshake.
8679 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8680 expected_largest_payload);
8681 } else {
8682 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8683 expected_largest_payload);
8684 }
8685}
8686
8687TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
8688 if (!connection_.version().SupportsMessageFrames()) {
8689 return;
8690 }
martinduke225e91a2022-11-28 17:18:13 -08008691 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008692 if (connection_.version().HasLongHeaderLengths()) {
8693 expected_largest_payload -= 2;
8694 }
8695 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8696 expected_largest_payload -= 1;
8697 }
8698 if (connection_.version().UsesTls()) {
8699 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8700 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8701 QuicConfig config;
8702 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8703 &config, kMaxAcceptedDatagramFrameSize);
8704 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8705 connection_.SetFromConfig(config);
8706 // Verify the value post-handshake.
8707 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8708 expected_largest_payload);
8709 } else {
8710 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8711 expected_largest_payload);
8712 }
8713}
8714
8715TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
8716 if (!connection_.version().SupportsMessageFrames() ||
8717 !connection_.version().UsesTls()) {
8718 return;
8719 }
8720 constexpr QuicPacketLength kFrameSizeLimit = 1000;
8721 constexpr QuicPacketLength kPayloadSizeLimit =
8722 kFrameSizeLimit - kQuicFrameTypeSize;
8723 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8724 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8725 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8726 QuicConfig config;
8727 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
8728 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8729 connection_.SetFromConfig(config);
8730 // Verify the value post-handshake.
8731 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
8732 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8733 kPayloadSizeLimit);
8734}
8735
8736// Test to check that the path challenge/path response logic works
8737// correctly. This test is only for version-99
8738TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) {
8739 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8740 return;
8741 }
8742 PathProbeTestInit(Perspective::IS_SERVER);
8743 QuicConnectionPeer::SetAddressValidated(&connection_);
8744 // First check if the server can send probing packet.
8745 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8746
8747 // Create and send the probe request (PATH_CHALLENGE frame).
8748 // SendConnectivityProbingPacket ends up calling
8749 // TestPacketWriter::WritePacket() which in turns receives and parses the
8750 // packet by calling framer_.ProcessPacket() -- which in turn calls
8751 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8752 // the packet in writer_->path_challenge_frames()
8753 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8754 connection_.SendConnectivityProbingPacket(writer_.get(),
8755 connection_.peer_address());
8756 // Save the random contents of the challenge for later comparison to the
8757 // response.
8758 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8759 QuicPathFrameBuffer challenge_data =
8760 writer_->path_challenge_frames().front().data_buffer;
8761
8762 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8763 // called and it will perform actions to ensure that the rest of the protocol
8764 // is performed.
8765 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8766 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8767 writer_->path_challenge_frames().front()));
8768 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8769 creator_->FlushCurrentPacket();
8770
8771 // The final check is to ensure that the random data in the response matches
8772 // the random data from the challenge.
8773 EXPECT_EQ(1u, writer_->path_response_frames().size());
8774 EXPECT_EQ(0, memcmp(&challenge_data,
8775 &(writer_->path_response_frames().front().data_buffer),
8776 sizeof(challenge_data)));
8777}
8778
8779TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnDefaulSocket) {
8780 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8781 return;
8782 }
8783 PathProbeTestInit(Perspective::IS_CLIENT);
8784 // First check if the client can send probing packet.
8785 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8786
8787 // Create and send the probe request (PATH_CHALLENGE frame).
8788 // SendConnectivityProbingPacket ends up calling
8789 // TestPacketWriter::WritePacket() which in turns receives and parses the
8790 // packet by calling framer_.ProcessPacket() -- which in turn calls
8791 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8792 // the packet in writer_->path_challenge_frames()
8793 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8794 connection_.SendConnectivityProbingPacket(writer_.get(),
8795 connection_.peer_address());
8796 // Save the random contents of the challenge for later validation against the
8797 // response.
8798 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8799 QuicPathFrameBuffer challenge_data =
8800 writer_->path_challenge_frames().front().data_buffer;
8801
8802 // Normally, QuicConnection::OnPathChallengeFrame would be
8803 // called and it will perform actions to ensure that the rest of the protocol
8804 // is performed.
8805 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8806 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8807 writer_->path_challenge_frames().front()));
8808 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8809 creator_->FlushCurrentPacket();
8810
8811 // The final check is to ensure that the random data in the response matches
8812 // the random data from the challenge.
8813 EXPECT_EQ(1u, writer_->path_response_frames().size());
8814 EXPECT_EQ(0, memcmp(&challenge_data,
8815 &(writer_->path_response_frames().front().data_buffer),
8816 sizeof(challenge_data)));
8817}
8818
8819TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnAlternativeSocket) {
danzh87605712022-04-11 14:36:39 -07008820 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -04008821 return;
8822 }
8823 PathProbeTestInit(Perspective::IS_CLIENT);
8824 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8825
8826 QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8827 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8828 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8829 .Times(AtLeast(1u))
8830 .WillOnce(Invoke([&]() {
8831 EXPECT_EQ(1u, new_writer.packets_write_attempts());
8832 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
8833 EXPECT_EQ(1u, new_writer.padding_frames().size());
8834 EXPECT_EQ(kNewSelfAddress.host(),
8835 new_writer.last_write_source_address());
8836 }));
8837 bool success = false;
8838 connection_.ValidatePath(
8839 std::make_unique<TestQuicPathValidationContext>(
8840 kNewSelfAddress, connection_.peer_address(), &new_writer),
8841 std::make_unique<TestValidationResultDelegate>(
8842 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
8843
8844 // Receiving a PATH_CHALLENGE on the alternative path. Response to this
8845 // PATH_CHALLENGE should be sent via the alternative writer.
8846 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8847 .Times(AtLeast(1u))
8848 .WillOnce(Invoke([&]() {
8849 EXPECT_EQ(2u, new_writer.packets_write_attempts());
8850 EXPECT_EQ(1u, new_writer.path_response_frames().size());
8851 EXPECT_EQ(1u, new_writer.padding_frames().size());
8852 EXPECT_EQ(kNewSelfAddress.host(),
8853 new_writer.last_write_source_address());
8854 }));
8855 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8856 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8857 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8858 probing_packet->encrypted_length),
8859 clock_.Now()));
8860 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8861
8862 QuicSocketAddress kNewerSelfAddress(QuicIpAddress::Loopback6(),
8863 /*port=*/34567);
8864 // Receiving a PATH_CHALLENGE on an unknown socket should be ignored.
8865 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
8866 ProcessReceivedPacket(kNewerSelfAddress, kPeerAddress, *received);
8867}
8868
8869TEST_P(QuicConnectionTest,
8870 RestartPathDegradingDetectionAfterMigrationWithProbe) {
8871 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8872 PathProbeTestInit(Perspective::IS_CLIENT);
8873
8874 // Send data and verify the path degrading detection is set.
8875 const char data[] = "data";
8876 size_t data_size = strlen(data);
8877 QuicStreamOffset offset = 0;
8878 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8879 offset += data_size;
8880
8881 // Verify the path degrading detection is in progress.
8882 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8883 EXPECT_FALSE(connection_.IsPathDegrading());
8884 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
8885
8886 // Simulate the firing of path degrading.
8887 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
8888 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
8889 connection_.PathDegradingTimeout();
8890 EXPECT_TRUE(connection_.IsPathDegrading());
8891 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8892
8893 if (!GetParam().version.HasIetfQuicFrames()) {
8894 // Simulate path degrading handling by sending a probe on an alternet path.
8895 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8896 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
8897 connection_.SendConnectivityProbingPacket(&probing_writer,
8898 connection_.peer_address());
8899 // Verify that path degrading detection is not reset.
8900 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8901
8902 // Simulate successful path degrading handling by receiving probe response.
8903 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
8904
8905 EXPECT_CALL(visitor_,
8906 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
8907 .Times(1);
8908 const QuicSocketAddress kNewSelfAddress =
8909 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8910
8911 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8912 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8913 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8914 probing_packet->encrypted_length),
8915 clock_.Now()));
8916 uint64_t num_probing_received =
8917 connection_.GetStats().num_connectivity_probing_received;
8918 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8919
8920 EXPECT_EQ(num_probing_received + 1,
8921 connection_.GetStats().num_connectivity_probing_received);
8922 EXPECT_EQ(kPeerAddress, connection_.peer_address());
8923 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8924 EXPECT_TRUE(connection_.IsPathDegrading());
8925 }
8926
8927 // Verify new path degrading detection is activated.
8928 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
8929 connection_.OnSuccessfulMigration(/*is_port_change*/ true);
8930 EXPECT_FALSE(connection_.IsPathDegrading());
8931 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8932}
8933
8934TEST_P(QuicConnectionTest, ClientsResetCwndAfterConnectionMigration) {
8935 if (!GetParam().version.HasIetfQuicFrames()) {
8936 return;
8937 }
8938 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8939 PathProbeTestInit(Perspective::IS_CLIENT);
8940 EXPECT_EQ(kSelfAddress, connection_.self_address());
8941
8942 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
8943 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
8944 rtt_stats->set_initial_rtt(default_init_rtt * 2);
8945 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
8946
fayang339f0c82022-04-30 14:20:02 -07008947 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
8948 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008949 const SendAlgorithmInterface* send_algorithm = manager_->GetSendAlgorithm();
8950
8951 // Migrate to a new address with different IP.
8952 const QuicSocketAddress kNewSelfAddress =
8953 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
8954 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8955 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
8956 &new_writer, false);
8957 EXPECT_EQ(default_init_rtt, manager_->GetRttStats()->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07008958 EXPECT_EQ(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008959 EXPECT_NE(send_algorithm, manager_->GetSendAlgorithm());
8960}
8961
8962// Regression test for b/110259444
8963TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8964 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8965 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8966 writer_->SetWriteBlocked();
8967
8968 ProcessPacket(1);
8969 // Verify ack alarm is set.
8970 EXPECT_TRUE(connection_.HasPendingAcks());
8971 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8972 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8973 connection_.GetAckAlarm()->Fire();
8974
8975 writer_->SetWritable();
8976 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8977 ProcessPacket(2);
8978 // Verify ack alarm is not set.
8979 EXPECT_FALSE(connection_.HasPendingAcks());
8980}
8981
8982TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8983 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8984 writer_->set_supports_release_time(true);
8985 QuicConfig config;
8986 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8987 connection_.SetFromConfig(config);
8988 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8989
8990 QuicTagVector connection_options;
8991 connection_options.push_back(kNPCO);
8992 config.SetConnectionOptionsToSend(connection_options);
8993 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8994 connection_.SetFromConfig(config);
8995 // Verify pacing offload is disabled.
8996 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8997}
8998
8999// Regression test for b/110259444
9000// Get a path response without having issued a path challenge...
9001TEST_P(QuicConnectionTest, OrphanPathResponse) {
9002 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
9003
9004 QuicPathResponseFrame frame(99, data);
9005 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
9006 // If PATH_RESPONSE was accepted (payload matches the payload saved
9007 // in QuicConnection::transmitted_connectivity_probe_payload_) then
9008 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
9009 // Since this PATH_RESPONSE does not match, current_packet_content_
9010 // must not be FIRST_FRAME_IS_PING.
9011 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
9012 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
9013}
9014
9015// Regression test for b/120791670
9016TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
9017 // This test mimics a problematic scenario where a QUIC connection using a
9018 // modern version received a Q043 packet and processed it incorrectly.
9019 // We can remove this test once Q043 is deprecated.
9020 if (!version().HasIetfInvariantHeader()) {
9021 return;
9022 }
9023 set_perspective(Perspective::IS_SERVER);
9024 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9025 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
9026 } else {
9027 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
9028 }
9029 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
9030 ENCRYPTION_INITIAL);
9031
9032 // Let connection process a Google QUIC packet.
9033 peer_framer_.set_version_for_tests(ParsedQuicVersion::Q043());
9034 std::unique_ptr<QuicPacket> packet(
9035 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
9036 char buffer[kMaxOutgoingPacketSize];
9037 size_t encrypted_length =
9038 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9039 *packet, buffer, kMaxOutgoingPacketSize);
9040 // Make sure no stream frame is processed.
9041 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
9042 connection_.ProcessUdpPacket(
9043 kSelfAddress, kPeerAddress,
9044 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
9045
9046 EXPECT_EQ(2u, connection_.GetStats().packets_received);
9047 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
9048}
9049
9050TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
9051 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9052 return;
9053 }
9054 // Set first_sending_packet_number to be 0 to allow successfully processing
9055 // acks which ack packet number 0.
9056 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
9057 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9058
9059 ProcessPacket(0);
9060 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
9061 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
9062
9063 ProcessPacket(1);
9064 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
9065 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
9066
9067 ProcessPacket(2);
9068 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
9069 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
9070}
9071
9072TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
9073 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9074 return;
9075 }
Bence Békybac04052022-04-07 15:44:29 -04009076 connection_.SendCryptoStreamData();
9077 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9078 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9079 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9080 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9081 QuicAckFrame frame1 = InitAckFrame(1);
9082 // Received ACK for packet 1.
9083 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9084
9085 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
9086 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9087 NO_FIN);
9088 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9089 NO_FIN);
9090 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9091 8, NO_FIN);
9092 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9093 12, FIN);
9094 // Received ACK for packets 2, 4, 5.
9095 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9096 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9097 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9098 QuicAckFrame frame2 =
9099 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
9100 {QuicPacketNumber(4), QuicPacketNumber(6)}});
9101 // Make sure although the same packet number is used, but they are in
9102 // different packet number spaces.
9103 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
9104}
9105
9106TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
9107 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9108 return;
9109 }
Bence Békybac04052022-04-07 15:44:29 -04009110 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9111 std::make_unique<TaggingEncrypter>(0x01));
9112
9113 connection_.SendCryptoStreamData();
9114 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9115 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9116 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9117 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9118 QuicAckFrame frame1 = InitAckFrame(1);
9119 // Received ACK for packet 1.
9120 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9121
9122 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9123 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
9124 NO_FIN);
9125 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
9126 NO_FIN);
9127
9128 // Received ACK for packets 2 and 3 in wrong packet number space.
9129 QuicAckFrame invalid_ack =
9130 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
9131 EXPECT_CALL(visitor_,
9132 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9133 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9134 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
9135 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
9136}
9137
9138TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
9139 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9140 return;
9141 }
9142 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9143 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9144 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9145 }
9146 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009147 // Receives packet 1000 in initial data.
9148 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9149 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009150 peer_framer_.SetEncrypter(
9151 ENCRYPTION_FORWARD_SECURE,
9152 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
9153 SetDecrypter(
9154 ENCRYPTION_FORWARD_SECURE,
9155 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009156 // Receives packet 1000 in application data.
9157 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
9158 EXPECT_TRUE(connection_.HasPendingAcks());
9159 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
9160 0, NO_FIN);
9161 // Verify application data ACK gets bundled with outgoing data.
9162 EXPECT_EQ(2u, writer_->frame_count());
9163 // Make sure ACK alarm is still set because initial data is not ACKed.
9164 EXPECT_TRUE(connection_.HasPendingAcks());
9165 // Receive packet 1001 in application data.
9166 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_FORWARD_SECURE);
9167 clock_.AdvanceTime(DefaultRetransmissionTime());
9168 // Simulates ACK alarm fires and verify two ACKs are flushed.
9169 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
martinduke9e0811c2022-12-08 20:35:57 -08009170 connection_.SetEncrypter(
9171 ENCRYPTION_FORWARD_SECURE,
9172 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009173 connection_.GetAckAlarm()->Fire();
9174 EXPECT_FALSE(connection_.HasPendingAcks());
9175 // Receives more packets in application data.
9176 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_FORWARD_SECURE);
9177 EXPECT_TRUE(connection_.HasPendingAcks());
9178
9179 // Verify zero rtt and forward secure packets get acked in the same packet.
9180 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9181 ProcessDataPacket(1003);
9182 EXPECT_FALSE(connection_.HasPendingAcks());
9183}
9184
9185TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9186 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9187 return;
9188 }
9189 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9190 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9191 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9192 }
9193 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009194 // Receives packet 1000 in initial data.
9195 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9196 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009197 peer_framer_.SetEncrypter(
9198 ENCRYPTION_ZERO_RTT,
9199 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009200 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08009201 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009202 // Receives packet 1000 in application data.
9203 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9204 EXPECT_TRUE(connection_.HasPendingAcks());
9205
9206 writer_->SetWriteBlocked();
9207 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9208 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9209 // blocked.
9210 clock_.AdvanceTime(DefaultDelayedAckTime());
9211 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9212 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9213 std::make_unique<TaggingEncrypter>(0x02));
9214 connection_.GetAckAlarm()->Fire();
9215 // Verify ACK alarm is not set.
9216 EXPECT_FALSE(connection_.HasPendingAcks());
9217
9218 writer_->SetWritable();
9219 // Verify 2 ACKs are sent when connection gets unblocked.
9220 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9221 connection_.OnCanWrite();
9222 EXPECT_FALSE(connection_.HasPendingAcks());
9223}
9224
9225// Make sure a packet received with the right client connection ID is processed.
9226TEST_P(QuicConnectionTest, ValidClientConnectionId) {
9227 if (!framer_.version().SupportsClientConnectionIds()) {
9228 return;
9229 }
9230 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9231 SetClientConnectionId(TestConnectionId(0x33));
9232 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9233 header.destination_connection_id = TestConnectionId(0x33);
9234 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9235 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9236 QuicFrames frames;
9237 QuicPingFrame ping_frame;
9238 QuicPaddingFrame padding_frame;
9239 frames.push_back(QuicFrame(ping_frame));
9240 frames.push_back(QuicFrame(padding_frame));
9241 std::unique_ptr<QuicPacket> packet =
9242 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9243 char buffer[kMaxOutgoingPacketSize];
9244 size_t encrypted_length = peer_framer_.EncryptPayload(
9245 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9246 kMaxOutgoingPacketSize);
9247 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9248 false);
9249 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9250 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9251 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9252}
9253
9254// Make sure a packet received with a different client connection ID is dropped.
9255TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
9256 if (!framer_.version().SupportsClientConnectionIds()) {
9257 return;
9258 }
9259 SetClientConnectionId(TestConnectionId(0x33));
9260 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9261 header.destination_connection_id = TestConnectionId(0xbad);
9262 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9263 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9264 QuicFrames frames;
9265 QuicPingFrame ping_frame;
9266 QuicPaddingFrame padding_frame;
9267 frames.push_back(QuicFrame(ping_frame));
9268 frames.push_back(QuicFrame(padding_frame));
9269 std::unique_ptr<QuicPacket> packet =
9270 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9271 char buffer[kMaxOutgoingPacketSize];
9272 size_t encrypted_length = peer_framer_.EncryptPayload(
9273 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9274 kMaxOutgoingPacketSize);
9275 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9276 false);
9277 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9278 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9279 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9280}
9281
9282// Make sure the first packet received with a different client connection ID on
9283// the server is processed and it changes the client connection ID.
9284TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
9285 if (!framer_.version().SupportsClientConnectionIds()) {
9286 return;
9287 }
9288 set_perspective(Perspective::IS_SERVER);
9289 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9290 header.source_connection_id = TestConnectionId(0x33);
9291 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9292 QuicFrames frames;
9293 QuicPingFrame ping_frame;
9294 QuicPaddingFrame padding_frame;
9295 frames.push_back(QuicFrame(ping_frame));
9296 frames.push_back(QuicFrame(padding_frame));
9297 std::unique_ptr<QuicPacket> packet =
9298 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9299 char buffer[kMaxOutgoingPacketSize];
9300 size_t encrypted_length =
9301 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9302 *packet, buffer, kMaxOutgoingPacketSize);
9303 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9304 false);
9305 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9306 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9307 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9308 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9309}
9310void QuicConnectionTest::TestReplaceConnectionIdFromInitial() {
9311 if (!framer_.version().AllowsVariableLengthConnectionIds()) {
9312 return;
9313 }
9314 // We start with a known connection ID.
9315 EXPECT_TRUE(connection_.connected());
9316 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9317 EXPECT_NE(TestConnectionId(0x33), connection_.connection_id());
9318 // Receiving an initial can replace the connection ID once.
9319 {
9320 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9321 header.source_connection_id = TestConnectionId(0x33);
9322 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9323 QuicFrames frames;
9324 QuicPingFrame ping_frame;
9325 QuicPaddingFrame padding_frame;
9326 frames.push_back(QuicFrame(ping_frame));
9327 frames.push_back(QuicFrame(padding_frame));
9328 std::unique_ptr<QuicPacket> packet =
9329 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9330 char buffer[kMaxOutgoingPacketSize];
9331 size_t encrypted_length =
9332 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9333 *packet, buffer, kMaxOutgoingPacketSize);
9334 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9335 false);
9336 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9337 }
9338 EXPECT_TRUE(connection_.connected());
9339 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9340 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9341 // Trying to replace the connection ID a second time drops the packet.
9342 {
9343 QuicPacketHeader header = ConstructPacketHeader(2, ENCRYPTION_INITIAL);
9344 header.source_connection_id = TestConnectionId(0x66);
9345 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9346 QuicFrames frames;
9347 QuicPingFrame ping_frame;
9348 QuicPaddingFrame padding_frame;
9349 frames.push_back(QuicFrame(ping_frame));
9350 frames.push_back(QuicFrame(padding_frame));
9351 std::unique_ptr<QuicPacket> packet =
9352 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9353 char buffer[kMaxOutgoingPacketSize];
9354 size_t encrypted_length =
9355 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9356 *packet, buffer, kMaxOutgoingPacketSize);
9357 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9358 false);
9359 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9360 }
9361 EXPECT_TRUE(connection_.connected());
9362 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9363 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9364}
9365
9366TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromInitial) {
9367 TestReplaceConnectionIdFromInitial();
9368}
9369
9370TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromRetryAndInitial) {
9371 // First make the connection process a RETRY and replace the server connection
9372 // ID a first time.
9373 TestClientRetryHandling(/*invalid_retry_tag=*/false,
9374 /*missing_original_id_in_config=*/false,
9375 /*wrong_original_id_in_config=*/false,
9376 /*missing_retry_id_in_config=*/false,
9377 /*wrong_retry_id_in_config=*/false);
9378 // Reset the test framer to use the right connection ID.
9379 peer_framer_.SetInitialObfuscators(connection_.connection_id());
9380 // Now process an INITIAL and replace the server connection ID a second time.
9381 TestReplaceConnectionIdFromInitial();
9382}
9383
9384// Regression test for b/134416344.
9385TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9386 // This test mimics a scenario where a connection processes 2 packets and the
9387 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9388 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9389 // because connection is disconnected.
9390 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9391 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9392 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
9393 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
9394 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
9395 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9396 NO_IETF_QUIC_ERROR, "",
9397 /*transport_close_frame_type=*/0));
9398
9399 // Received 2 packets.
9400 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9401 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9402 } else {
9403 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9404 }
9405 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
9406 ENCRYPTION_INITIAL);
9407 EXPECT_TRUE(connection_.HasPendingAcks());
9408 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
9409 kSelfAddress, kPeerAddress,
9410 ENCRYPTION_INITIAL);
9411 // Verify ack alarm is not set.
9412 EXPECT_FALSE(connection_.HasPendingAcks());
9413}
9414
9415// Verify that a packet containing three coalesced packets is parsed correctly.
9416TEST_P(QuicConnectionTest, CoalescedPacket) {
9417 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9418 // Coalesced packets can only be encoded using long header lengths.
9419 return;
9420 }
9421 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9422 EXPECT_TRUE(connection_.connected());
9423 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9424 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9425 } else {
9426 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9427 }
9428
9429 uint64_t packet_numbers[3] = {1, 2, 3};
9430 EncryptionLevel encryption_levels[3] = {
9431 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9432 char buffer[kMaxOutgoingPacketSize] = {};
9433 size_t total_encrypted_length = 0;
9434 for (int i = 0; i < 3; i++) {
9435 QuicPacketHeader header =
9436 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9437 QuicFrames frames;
9438 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9439 frames.push_back(QuicFrame(&crypto_frame_));
9440 } else {
9441 frames.push_back(QuicFrame(frame1_));
9442 }
9443 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9444 peer_creator_.set_encryption_level(encryption_levels[i]);
9445 size_t encrypted_length = peer_framer_.EncryptPayload(
9446 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9447 buffer + total_encrypted_length,
9448 sizeof(buffer) - total_encrypted_length);
9449 EXPECT_GT(encrypted_length, 0u);
9450 total_encrypted_length += encrypted_length;
9451 }
9452 connection_.ProcessUdpPacket(
9453 kSelfAddress, kPeerAddress,
9454 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9455 if (connection_.GetSendAlarm()->IsSet()) {
9456 connection_.GetSendAlarm()->Fire();
9457 }
9458
9459 EXPECT_TRUE(connection_.connected());
9460}
9461
9462// Regression test for crbug.com/992831.
9463TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9464 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9465 // Coalesced packets can only be encoded using long header lengths.
9466 return;
9467 }
9468 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9469 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9470 return;
9471 }
9472 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9473 EXPECT_TRUE(connection_.connected());
9474 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9475 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9476 .Times(3)
9477 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9478 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009479 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009480 });
9481 } else {
9482 EXPECT_CALL(visitor_, OnStreamFrame(_))
9483 .Times(3)
9484 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9485 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009486 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009487 });
9488 }
9489
9490 uint64_t packet_numbers[3] = {1, 2, 3};
9491 EncryptionLevel encryption_levels[3] = {
9492 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9493 char buffer[kMaxOutgoingPacketSize] = {};
9494 size_t total_encrypted_length = 0;
9495 for (int i = 0; i < 3; i++) {
9496 QuicPacketHeader header =
9497 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9498 QuicFrames frames;
9499 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9500 frames.push_back(QuicFrame(&crypto_frame_));
9501 } else {
9502 frames.push_back(QuicFrame(frame1_));
9503 }
9504 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9505 peer_creator_.set_encryption_level(encryption_levels[i]);
9506 size_t encrypted_length = peer_framer_.EncryptPayload(
9507 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9508 buffer + total_encrypted_length,
9509 sizeof(buffer) - total_encrypted_length);
9510 EXPECT_GT(encrypted_length, 0u);
9511 total_encrypted_length += encrypted_length;
9512 }
9513 connection_.ProcessUdpPacket(
9514 kSelfAddress, kPeerAddress,
9515 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9516 if (connection_.GetSendAlarm()->IsSet()) {
9517 connection_.GetSendAlarm()->Fire();
9518 }
9519
9520 EXPECT_TRUE(connection_.connected());
9521
9522 SendAckPacketToPeer();
9523}
9524
9525// Regresstion test for b/138962304.
9526TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
9527 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9528
9529 QuicStreamId stream_id = 2;
9530 QuicPacketNumber last_data_packet;
9531 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9532 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9533
9534 // Writer gets blocked.
9535 writer_->SetWriteBlocked();
9536
9537 // Cancel the stream.
9538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9539 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9540 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9541 .WillRepeatedly(
9542 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
9543 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9544
9545 // Retransmission timer fires in RTO mode.
9546 connection_.GetRetransmissionAlarm()->Fire();
9547 // Verify no packets get flushed when writer is blocked.
9548 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9549}
9550
9551// Regresstion test for b/138962304.
fayang339f0c82022-04-30 14:20:02 -07009552TEST_P(QuicConnectionTest, PtoAndWriteBlocked) {
Bence Békybac04052022-04-07 15:44:29 -04009553 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
Bence Békybac04052022-04-07 15:44:29 -04009554
9555 QuicStreamId stream_id = 2;
9556 QuicPacketNumber last_data_packet;
9557 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9558 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9559 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9560
9561 // Writer gets blocked.
9562 writer_->SetWriteBlocked();
9563
9564 // Cancel stream 2.
9565 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9566 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9567 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9568
9569 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9570 // Retransmission timer fires in TLP mode.
9571 connection_.GetRetransmissionAlarm()->Fire();
9572 // Verify one packets is forced flushed when writer is blocked.
9573 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9574}
9575
Bence Békybac04052022-04-07 15:44:29 -04009576TEST_P(QuicConnectionTest, ProbeTimeout) {
9577 QuicConfig config;
9578 QuicTagVector connection_options;
9579 connection_options.push_back(k2PTO);
9580 config.SetConnectionOptionsToSend(connection_options);
9581 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9582 connection_.SetFromConfig(config);
9583 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9584
9585 QuicStreamId stream_id = 2;
9586 QuicPacketNumber last_packet;
9587 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9588 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9589 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9590
9591 // Reset stream.
9592 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9593 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9594
9595 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9596 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9597 connection_.GetRetransmissionAlarm()->Fire();
9598 EXPECT_EQ(0u, writer_->stream_frames().size());
9599 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9600 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9601}
9602
9603TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
9604 QuicConfig config;
9605 QuicTagVector connection_options;
9606 connection_options.push_back(k1PTO);
9607 connection_options.push_back(k6PTO);
9608 config.SetConnectionOptionsToSend(connection_options);
9609 QuicConfigPeer::SetNegotiated(&config, true);
9610 if (connection_.version().UsesTls()) {
9611 QuicConfigPeer::SetReceivedOriginalConnectionId(
9612 &config, connection_.connection_id());
9613 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9614 &config, connection_.connection_id());
9615 }
9616 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9617 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009618 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9619 GetQuicReloadableFlag(
9620 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009621 EXPECT_CALL(visitor_, GetHandshakeState())
9622 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9623 }
9624 connection_.OnHandshakeComplete();
9625 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9626
9627 // Send stream data.
9628 SendStreamDataToPeer(
9629 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9630 0, FIN, nullptr);
9631
9632 // Fire the retransmission alarm 5 times.
9633 for (int i = 0; i < 5; ++i) {
9634 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9635 connection_.GetRetransmissionAlarm()->Fire();
9636 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9637 EXPECT_TRUE(connection_.connected());
9638 }
9639 EXPECT_CALL(visitor_, OnPathDegrading());
9640 connection_.PathDegradingTimeout();
9641
Bence Békybac04052022-04-07 15:44:29 -04009642 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9643 // Closes connection on 6th PTO.
9644 // May send multiple connecction close packets with multiple PN spaces.
9645 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9646 EXPECT_CALL(visitor_,
9647 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9648 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9649 connection_.GetBlackholeDetectorAlarm()->Fire();
9650 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9651 EXPECT_FALSE(connection_.connected());
9652 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9653}
9654
9655TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
9656 QuicConfig config;
9657 QuicTagVector connection_options;
9658 connection_options.push_back(k2PTO);
9659 connection_options.push_back(k7PTO);
9660 config.SetConnectionOptionsToSend(connection_options);
9661 QuicConfigPeer::SetNegotiated(&config, true);
9662 if (connection_.version().UsesTls()) {
9663 QuicConfigPeer::SetReceivedOriginalConnectionId(
9664 &config, connection_.connection_id());
9665 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9666 &config, connection_.connection_id());
9667 }
9668 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9669 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009670 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9671 GetQuicReloadableFlag(
9672 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009673 EXPECT_CALL(visitor_, GetHandshakeState())
9674 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9675 }
9676 connection_.OnHandshakeComplete();
9677 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9678
9679 // Send stream data.
9680 SendStreamDataToPeer(
9681 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9682 0, FIN, nullptr);
9683
9684 // Fire the retransmission alarm 6 times.
9685 for (int i = 0; i < 6; ++i) {
9686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9687 connection_.GetRetransmissionAlarm()->Fire();
9688 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9689 EXPECT_TRUE(connection_.connected());
9690 }
9691 EXPECT_CALL(visitor_, OnPathDegrading());
9692 connection_.PathDegradingTimeout();
9693
Bence Békybac04052022-04-07 15:44:29 -04009694 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9695 // Closes connection on 7th PTO.
9696 EXPECT_CALL(visitor_,
9697 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9698 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9699 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9700 connection_.GetBlackholeDetectorAlarm()->Fire();
9701 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9702 EXPECT_FALSE(connection_.connected());
9703 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9704}
9705
9706TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
9707 QuicConfig config;
9708 QuicTagVector connection_options;
9709 connection_options.push_back(k2PTO);
9710 connection_options.push_back(k8PTO);
9711 QuicConfigPeer::SetNegotiated(&config, true);
9712 if (connection_.version().UsesTls()) {
9713 QuicConfigPeer::SetReceivedOriginalConnectionId(
9714 &config, connection_.connection_id());
9715 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9716 &config, connection_.connection_id());
9717 }
9718 config.SetConnectionOptionsToSend(connection_options);
9719 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9720 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009721 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9722 GetQuicReloadableFlag(
9723 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009724 EXPECT_CALL(visitor_, GetHandshakeState())
9725 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9726 }
9727 connection_.OnHandshakeComplete();
9728 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9729
9730 // Send stream data.
9731 SendStreamDataToPeer(
9732 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9733 0, FIN, nullptr);
9734
9735 // Fire the retransmission alarm 7 times.
9736 for (int i = 0; i < 7; ++i) {
9737 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9738 connection_.GetRetransmissionAlarm()->Fire();
9739 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9740 EXPECT_TRUE(connection_.connected());
9741 }
9742 EXPECT_CALL(visitor_, OnPathDegrading());
9743 connection_.PathDegradingTimeout();
9744
Bence Békybac04052022-04-07 15:44:29 -04009745 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9746 // Closes connection on 8th PTO.
9747 EXPECT_CALL(visitor_,
9748 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9749 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9750 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9751 connection_.GetBlackholeDetectorAlarm()->Fire();
9752 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9753 EXPECT_FALSE(connection_.connected());
9754 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9755}
9756
9757TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9758 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9759 return;
9760 }
9761 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9762 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9763
9764 // Send CHLO.
9765 connection_.SendCryptoStreamData();
9766 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9767
9768 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9769 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9770 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9771 QuicAckFrame frame1 = InitAckFrame(1);
9772 // Received ACK for packet 1.
9773 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9774
9775 // Verify retransmission alarm is still set because handshake is not
9776 // confirmed although there is nothing in flight.
9777 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9778 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9779 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9780
9781 // PTO fires, verify a PING packet gets sent because there is no data to send.
9782 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9783 connection_.GetRetransmissionAlarm()->Fire();
9784 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9785 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
9786 EXPECT_EQ(1u, writer_->ping_frames().size());
9787}
9788
9789TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009790 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009791 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009792 return;
9793 }
9794 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9795
9796 set_perspective(Perspective::IS_SERVER);
9797 // Verify no data can be sent at the beginning because bytes received is 0.
9798 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9799 connection_.SendCryptoDataWithString("foo", 0);
9800 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9801 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9802 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9803
9804 // Receives packet 1.
9805 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9806 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9807
9808 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -07009809 GetQuicFlag(quic_anti_amplification_factor);
Bence Békybac04052022-04-07 15:44:29 -04009810 // Verify now packets can be sent.
9811 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9812 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9813 connection_.SendCryptoDataWithString("foo", i * 3);
9814 // Verify retransmission alarm is not set if throttled by anti-amplification
9815 // limit.
9816 EXPECT_EQ(i != anti_amplification_factor - 1,
9817 connection_.GetRetransmissionAlarm()->IsSet());
9818 }
9819 // Verify server is throttled by anti-amplification limit.
9820 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9821 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9822
9823 // Receives packet 2.
9824 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9825 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9826 // Verify more packets can be sent.
9827 for (size_t i = anti_amplification_factor + 1;
9828 i < anti_amplification_factor * 2; ++i) {
9829 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9830 connection_.SendCryptoDataWithString("foo", i * 3);
9831 }
9832 // Verify server is throttled by anti-amplification limit.
9833 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9834 connection_.SendCryptoDataWithString("foo",
9835 2 * anti_amplification_factor * 3);
9836
9837 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9838 ProcessPacket(3);
9839 // Verify anti-amplification limit is gone after address validation.
9840 for (size_t i = 0; i < 100; ++i) {
9841 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9842 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9843 }
9844}
9845
9846TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009847 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009848 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009849 return;
9850 }
9851 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9852
9853 set_perspective(Perspective::IS_SERVER);
9854 QuicConfig config;
9855 QuicTagVector connection_options;
9856 connection_options.push_back(k3AFF);
9857 config.SetInitialReceivedConnectionOptions(connection_options);
9858 if (connection_.version().UsesTls()) {
9859 QuicConfigPeer::SetReceivedOriginalConnectionId(
9860 &config, connection_.connection_id());
9861 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9862 QuicConnectionId());
9863 }
9864 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9865 connection_.SetFromConfig(config);
9866
9867 // Verify no data can be sent at the beginning because bytes received is 0.
9868 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9869 connection_.SendCryptoDataWithString("foo", 0);
9870 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9871 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9872 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9873
9874 // Receives packet 1.
9875 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9876 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9877
9878 const size_t anti_amplification_factor = 3;
9879 // Verify now packets can be sent.
9880 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9881 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9882 connection_.SendCryptoDataWithString("foo", i * 3);
9883 // Verify retransmission alarm is not set if throttled by anti-amplification
9884 // limit.
9885 EXPECT_EQ(i != anti_amplification_factor - 1,
9886 connection_.GetRetransmissionAlarm()->IsSet());
9887 }
9888 // Verify server is throttled by anti-amplification limit.
9889 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9890 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9891
9892 // Receives packet 2.
9893 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9894 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9895 // Verify more packets can be sent.
9896 for (size_t i = anti_amplification_factor + 1;
9897 i < anti_amplification_factor * 2; ++i) {
9898 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9899 connection_.SendCryptoDataWithString("foo", i * 3);
9900 }
9901 // Verify server is throttled by anti-amplification limit.
9902 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9903 connection_.SendCryptoDataWithString("foo",
9904 2 * anti_amplification_factor * 3);
9905
9906 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9907 ProcessPacket(3);
9908 // Verify anti-amplification limit is gone after address validation.
9909 for (size_t i = 0; i < 100; ++i) {
9910 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9911 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9912 }
9913}
9914
9915TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009916 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009917 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009918 return;
9919 }
9920 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9921
9922 set_perspective(Perspective::IS_SERVER);
9923 QuicConfig config;
9924 QuicTagVector connection_options;
9925 connection_options.push_back(k10AF);
9926 config.SetInitialReceivedConnectionOptions(connection_options);
9927 if (connection_.version().UsesTls()) {
9928 QuicConfigPeer::SetReceivedOriginalConnectionId(
9929 &config, connection_.connection_id());
9930 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9931 QuicConnectionId());
9932 }
9933 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9934 connection_.SetFromConfig(config);
9935
9936 // Verify no data can be sent at the beginning because bytes received is 0.
9937 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9938 connection_.SendCryptoDataWithString("foo", 0);
9939 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9940 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9941 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9942
9943 // Receives packet 1.
9944 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9945 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9946
9947 const size_t anti_amplification_factor = 10;
9948 // Verify now packets can be sent.
9949 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9950 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9951 connection_.SendCryptoDataWithString("foo", i * 3);
9952 // Verify retransmission alarm is not set if throttled by anti-amplification
9953 // limit.
9954 EXPECT_EQ(i != anti_amplification_factor - 1,
9955 connection_.GetRetransmissionAlarm()->IsSet());
9956 }
9957 // Verify server is throttled by anti-amplification limit.
9958 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9959 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9960
9961 // Receives packet 2.
9962 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9963 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9964 // Verify more packets can be sent.
9965 for (size_t i = anti_amplification_factor + 1;
9966 i < anti_amplification_factor * 2; ++i) {
9967 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9968 connection_.SendCryptoDataWithString("foo", i * 3);
9969 }
9970 // Verify server is throttled by anti-amplification limit.
9971 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9972 connection_.SendCryptoDataWithString("foo",
9973 2 * anti_amplification_factor * 3);
9974
9975 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9976 ProcessPacket(3);
9977 // Verify anti-amplification limit is gone after address validation.
9978 for (size_t i = 0; i < 100; ++i) {
9979 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9980 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9981 }
9982}
9983
9984TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
9985 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9986 return;
9987 }
9988 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9989 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
9990 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -04009991 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9992 // Receives packet 1.
9993 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08009994 connection_.SetEncrypter(
9995 ENCRYPTION_HANDSHAKE,
9996 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -04009997 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9998 EXPECT_TRUE(connection_.HasPendingAcks());
9999 // Send response in different encryption level and cause amplification factor
10000 // throttled.
10001 size_t i = 0;
10002 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
10003 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
10004 ENCRYPTION_HANDSHAKE);
10005 ++i;
10006 }
10007 // Verify ACK is still pending.
10008 EXPECT_TRUE(connection_.HasPendingAcks());
10009
10010 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
10011 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
10012 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
10013 connection_.GetAckAlarm()->Fire();
10014 // Verify ACK alarm is cancelled.
10015 EXPECT_FALSE(connection_.HasPendingAcks());
10016
10017 // Receives packet 2 and verify ACK gets flushed.
10018 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10019 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
10020 EXPECT_FALSE(writer_->ack_frames().empty());
10021}
10022
10023TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
10024 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10025 // Test relevent only for IETF QUIC.
10026 return;
10027 }
10028 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
10029 // Use the (unknown) frame type of 9999 to avoid triggering any logic
10030 // which might be associated with the processing of a known frame type.
10031 const uint64_t kTransportCloseFrameType = 9999u;
10032 QuicFramerPeer::set_current_received_frame_type(
10033 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
10034 // Do a transport connection close
10035 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10036 connection_.CloseConnection(
10037 kQuicErrorCode, "Some random error message",
10038 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10039 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
10040 writer_->connection_close_frames();
10041 ASSERT_EQ(1u, connection_close_frames.size());
10042 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
10043 connection_close_frames[0].close_type);
10044 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
10045 EXPECT_EQ(kTransportCloseFrameType,
10046 connection_close_frames[0].transport_close_frame_type);
10047}
10048
Bence Békybac04052022-04-07 15:44:29 -040010049TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
10050 QuicConfig config;
10051 QuicTagVector connection_options;
10052 connection_options.push_back(k1PTO);
10053 connection_options.push_back(kPTOS);
10054 config.SetConnectionOptionsToSend(connection_options);
10055 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10056 connection_.SetFromConfig(config);
10057 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10058
10059 QuicStreamId stream_id = 2;
10060 QuicPacketNumber last_packet;
10061 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
10062 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
10063 EXPECT_EQ(QuicPacketNumber(2), last_packet);
10064 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10065
10066 // Fire PTO and verify the PTO retransmission skips one packet number.
10067 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10068 connection_.GetRetransmissionAlarm()->Fire();
10069 EXPECT_EQ(1u, writer_->stream_frames().size());
10070 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
10071 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10072}
10073
10074TEST_P(QuicConnectionTest, SendCoalescedPackets) {
10075 if (!connection_.version().CanSendCoalescedPackets()) {
10076 return;
10077 }
10078 MockQuicConnectionDebugVisitor debug_visitor;
10079 connection_.set_debug_visitor(&debug_visitor);
10080 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(3);
10081 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
10082 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10083 {
10084 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040010085 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10086 connection_.SendCryptoDataWithString("foo", 0);
10087 // Verify this packet is on hold.
10088 EXPECT_EQ(0u, writer_->packets_write_attempts());
10089
10090 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10091 std::make_unique<TaggingEncrypter>(0x02));
10092 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10093 connection_.SendCryptoDataWithString("bar", 3);
10094 EXPECT_EQ(0u, writer_->packets_write_attempts());
10095
10096 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10097 std::make_unique<TaggingEncrypter>(0x03));
10098 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10099 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
10100 }
10101 // Verify all 3 packets are coalesced in the same UDP datagram.
10102 EXPECT_EQ(1u, writer_->packets_write_attempts());
10103 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
10104 // Verify the packet is padded to full.
10105 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
10106
10107 // Verify packet process.
10108 EXPECT_EQ(1u, writer_->crypto_frames().size());
10109 EXPECT_EQ(0u, writer_->stream_frames().size());
10110 // Verify there is coalesced packet.
10111 EXPECT_NE(nullptr, writer_->coalesced_packet());
10112}
10113
10114TEST_P(QuicConnectionTest, FailToCoalescePacket) {
10115 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
10116 if (!IsDefaultTestConfiguration() ||
fayang161ce6e2022-07-01 18:02:11 -070010117 !connection_.version().CanSendCoalescedPackets() ||
birenroyef686222022-09-12 11:34:34 -070010118 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040010119 return;
10120 }
10121
10122 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040010123
Bence Békybac04052022-04-07 15:44:29 -040010124 auto test_body = [&] {
vasilvvac2e30d2022-06-02 14:26:59 -070010125 EXPECT_CALL(visitor_,
10126 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10127 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
Bence Békybac04052022-04-07 15:44:29 -040010128
vasilvvac2e30d2022-06-02 14:26:59 -070010129 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -040010130
vasilvvac2e30d2022-06-02 14:26:59 -070010131 {
10132 QuicConnection::ScopedPacketFlusher flusher(&connection_);
vasilvvac2e30d2022-06-02 14:26:59 -070010133 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10134 connection_.SendCryptoDataWithString("foo", 0);
10135 // Verify this packet is on hold.
10136 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -040010137
vasilvvac2e30d2022-06-02 14:26:59 -070010138 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10139 std::make_unique<TaggingEncrypter>(0x02));
10140 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10141 connection_.SendCryptoDataWithString("bar", 3);
10142 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -040010143
vasilvvac2e30d2022-06-02 14:26:59 -070010144 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10145 std::make_unique<TaggingEncrypter>(0x03));
10146 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10147 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
Bence Békybac04052022-04-07 15:44:29 -040010148
vasilvvac2e30d2022-06-02 14:26:59 -070010149 creator_->Flush();
10150
10151 auto& coalesced_packet =
10152 QuicConnectionPeer::GetCoalescedPacket(&connection_);
10153 QuicPacketLength coalesced_packet_max_length =
10154 coalesced_packet.max_packet_length();
10155 QuicCoalescedPacketPeer::SetMaxPacketLength(coalesced_packet,
10156 coalesced_packet.length());
10157
10158 // Make the coalescer's FORWARD_SECURE packet longer.
10159 *QuicCoalescedPacketPeer::GetMutableEncryptedBuffer(
10160 coalesced_packet, ENCRYPTION_FORWARD_SECURE) += "!!! TEST !!!";
10161
10162 QUIC_LOG(INFO) << "Reduced coalesced_packet_max_length from "
10163 << coalesced_packet_max_length << " to "
10164 << coalesced_packet.max_packet_length()
10165 << ", coalesced_packet.length:"
10166 << coalesced_packet.length()
10167 << ", coalesced_packet.packet_lengths:"
10168 << absl::StrJoin(coalesced_packet.packet_lengths(), ":");
10169 }
10170
10171 EXPECT_FALSE(connection_.connected());
10172 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10173 IsError(QUIC_FAILED_TO_SERIALIZE_PACKET));
10174 EXPECT_EQ(saved_connection_close_frame_.error_details,
10175 "Failed to serialize coalesced packet.");
Bence Békybac04052022-04-07 15:44:29 -040010176 };
10177
10178 EXPECT_QUIC_BUG(test_body(), "SerializeCoalescedPacket failed.");
Bence Békybac04052022-04-07 15:44:29 -040010179}
10180
Bence Békybac04052022-04-07 15:44:29 -040010181TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10182 if (!connection_.version().UsesTls()) {
10183 return;
10184 }
10185 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10186 QuicFrames frames;
10187 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10188 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10189 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10190}
10191
10192TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10193 if (!connection_.version().UsesTls()) {
10194 return;
10195 }
10196 set_perspective(Perspective::IS_SERVER);
10197 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10198 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
10199 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
10200 }
10201 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10202 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10203 QuicFrames frames;
10204 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10205 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10206 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10207 EXPECT_EQ(1, connection_close_frame_count_);
10208 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10209 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10210}
10211
10212TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10213 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10214 return;
10215 }
Bence Békybac04052022-04-07 15:44:29 -040010216 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010217 connection_.SetEncrypter(
10218 ENCRYPTION_HANDSHAKE,
10219 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010220 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10221 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10222 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080010223 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010224
10225 // Send application data.
10226 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10227 0, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010228 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010229 QuicTime retransmission_time =
10230 connection_.GetRetransmissionAlarm()->deadline();
10231 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10232
10233 // Retransmit handshake data.
10234 clock_.AdvanceTime(retransmission_time - clock_.Now());
10235 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _));
10236 connection_.GetRetransmissionAlarm()->Fire();
10237 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010238 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010239
10240 // Send application data.
10241 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10242 4, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010243 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010244 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10245 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10246
10247 // Retransmit handshake data again.
10248 clock_.AdvanceTime(retransmission_time - clock_.Now());
10249 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _));
10250 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(8), _, _));
10251 connection_.GetRetransmissionAlarm()->Fire();
10252 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010253 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010254
10255 // Discard handshake key.
10256 connection_.OnHandshakeComplete();
10257 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10258 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10259
10260 // Retransmit application data.
10261 clock_.AdvanceTime(retransmission_time - clock_.Now());
10262 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(11), _, _));
10263 connection_.GetRetransmissionAlarm()->Fire();
martinduke9e0811c2022-12-08 20:35:57 -080010264 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010265}
10266
10267void QuicConnectionTest::TestClientRetryHandling(
10268 bool invalid_retry_tag, bool missing_original_id_in_config,
10269 bool wrong_original_id_in_config, bool missing_retry_id_in_config,
10270 bool wrong_retry_id_in_config) {
10271 if (invalid_retry_tag) {
10272 ASSERT_FALSE(missing_original_id_in_config);
10273 ASSERT_FALSE(wrong_original_id_in_config);
10274 ASSERT_FALSE(missing_retry_id_in_config);
10275 ASSERT_FALSE(wrong_retry_id_in_config);
10276 } else {
10277 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10278 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
10279 }
10280 if (!version().UsesTls()) {
10281 return;
10282 }
10283
10284 // These values come from draft-ietf-quic-v2 Appendix A.4.
10285 uint8_t retry_packet_rfcv2[] = {
martindukea2cb68a2022-12-12 17:24:39 -080010286 0xcf, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10287 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xc8, 0x64, 0x6c, 0xe8,
10288 0xbf, 0xe3, 0x39, 0x52, 0xd9, 0x55, 0x54, 0x36, 0x65, 0xdc, 0xc7, 0xb6};
Bence Békybac04052022-04-07 15:44:29 -040010289 // These values come from RFC9001 Appendix A.4.
10290 uint8_t retry_packet_rfcv1[] = {
10291 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10292 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba,
10293 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba};
10294 uint8_t retry_packet29[] = {
10295 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10296 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10297 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
10298
10299 uint8_t* retry_packet;
10300 size_t retry_packet_length;
martindukea2cb68a2022-12-12 17:24:39 -080010301 if (version() == ParsedQuicVersion::V2Draft08()) {
Bence Békybac04052022-04-07 15:44:29 -040010302 retry_packet = retry_packet_rfcv2;
10303 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv2);
10304 } else if (version() == ParsedQuicVersion::RFCv1()) {
10305 retry_packet = retry_packet_rfcv1;
10306 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv1);
10307 } else if (version() == ParsedQuicVersion::Draft29()) {
10308 retry_packet = retry_packet29;
10309 retry_packet_length = ABSL_ARRAYSIZE(retry_packet29);
10310 } else {
10311 // TODO(dschinazi) generate retry packets for all versions once we have
10312 // server-side support for generating these programmatically.
10313 return;
10314 }
10315
10316 uint8_t original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10317 0x3e, 0x51, 0x57, 0x08};
10318 uint8_t new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10319 0x2a, 0x42, 0x62, 0xb5};
10320 uint8_t retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10321
10322 QuicConnectionId original_connection_id(
10323 reinterpret_cast<char*>(original_connection_id_bytes),
10324 ABSL_ARRAYSIZE(original_connection_id_bytes));
10325 QuicConnectionId new_connection_id(
10326 reinterpret_cast<char*>(new_connection_id_bytes),
10327 ABSL_ARRAYSIZE(new_connection_id_bytes));
10328
10329 std::string retry_token(reinterpret_cast<char*>(retry_token_bytes),
10330 ABSL_ARRAYSIZE(retry_token_bytes));
10331
10332 if (invalid_retry_tag) {
10333 // Flip the last bit of the retry packet to prevent the integrity tag
10334 // from validating correctly.
10335 retry_packet[retry_packet_length - 1] ^= 1;
10336 }
10337
10338 QuicConnectionId config_original_connection_id = original_connection_id;
10339 if (wrong_original_id_in_config) {
10340 // Flip the first bit of the connection ID.
10341 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10342 config_original_connection_id.mutable_data()[0] ^= 0x80;
10343 }
10344 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10345 if (wrong_retry_id_in_config) {
10346 // Flip the first bit of the connection ID.
10347 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10348 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10349 }
10350
10351 // Make sure the connection uses the connection ID from the test vectors,
10352 QuicConnectionPeer::SetServerConnectionId(&connection_,
10353 original_connection_id);
10354 // Make sure our fake framer has the new post-retry INITIAL keys so that any
10355 // retransmission triggered by retry can be decrypted.
10356 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10357
10358 // Process the RETRY packet.
10359 connection_.ProcessUdpPacket(
10360 kSelfAddress, kPeerAddress,
10361 QuicReceivedPacket(reinterpret_cast<char*>(retry_packet),
10362 retry_packet_length, clock_.Now()));
10363
10364 if (invalid_retry_tag) {
10365 // Make sure we refuse to process a RETRY with invalid tag.
10366 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10367 EXPECT_EQ(connection_.connection_id(), original_connection_id);
10368 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
10369 QuicConnectionPeer::GetPacketCreator(&connection_))
10370 .empty());
10371 return;
10372 }
10373
10374 // Make sure we correctly parsed the RETRY.
10375 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10376 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10377 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10378 QuicConnectionPeer::GetPacketCreator(&connection_)),
10379 retry_token);
10380
10381 // Test validating the original_connection_id from the config.
10382 QuicConfig received_config;
10383 QuicConfigPeer::SetNegotiated(&received_config, true);
10384 if (connection_.version().UsesTls()) {
10385 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10386 &received_config, connection_.connection_id());
10387 if (!missing_retry_id_in_config) {
10388 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10389 &received_config, config_retry_source_connection_id);
10390 }
10391 }
10392 if (!missing_original_id_in_config) {
10393 QuicConfigPeer::SetReceivedOriginalConnectionId(
10394 &received_config, config_original_connection_id);
10395 }
10396
10397 if (missing_original_id_in_config || wrong_original_id_in_config ||
10398 missing_retry_id_in_config || wrong_retry_id_in_config) {
10399 EXPECT_CALL(visitor_,
10400 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10401 .Times(1);
10402 } else {
10403 EXPECT_CALL(visitor_,
10404 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10405 .Times(0);
10406 }
10407 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10408 connection_.SetFromConfig(received_config);
10409 if (missing_original_id_in_config || wrong_original_id_in_config ||
10410 missing_retry_id_in_config || wrong_retry_id_in_config) {
10411 ASSERT_FALSE(connection_.connected());
10412 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10413 } else {
10414 EXPECT_TRUE(connection_.connected());
10415 }
10416}
10417
10418TEST_P(QuicConnectionTest, ClientParsesRetry) {
10419 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10420 /*missing_original_id_in_config=*/false,
10421 /*wrong_original_id_in_config=*/false,
10422 /*missing_retry_id_in_config=*/false,
10423 /*wrong_retry_id_in_config=*/false);
10424}
10425
10426TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
10427 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10428 /*missing_original_id_in_config=*/false,
10429 /*wrong_original_id_in_config=*/false,
10430 /*missing_retry_id_in_config=*/false,
10431 /*wrong_retry_id_in_config=*/false);
10432}
10433
10434TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
10435 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10436 /*missing_original_id_in_config=*/true,
10437 /*wrong_original_id_in_config=*/false,
10438 /*missing_retry_id_in_config=*/false,
10439 /*wrong_retry_id_in_config=*/false);
10440}
10441
10442TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
10443 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10444 /*missing_original_id_in_config=*/false,
10445 /*wrong_original_id_in_config=*/true,
10446 /*missing_retry_id_in_config=*/false,
10447 /*wrong_retry_id_in_config=*/false);
10448}
10449
10450TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10451 if (!connection_.version().UsesTls()) {
10452 // Versions that do not authenticate connection IDs never send the
10453 // retry_source_connection_id transport parameter.
10454 return;
10455 }
10456 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10457 /*missing_original_id_in_config=*/false,
10458 /*wrong_original_id_in_config=*/false,
10459 /*missing_retry_id_in_config=*/true,
10460 /*wrong_retry_id_in_config=*/false);
10461}
10462
10463TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10464 if (!connection_.version().UsesTls()) {
10465 // Versions that do not authenticate connection IDs never send the
10466 // retry_source_connection_id transport parameter.
10467 return;
10468 }
10469 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10470 /*missing_original_id_in_config=*/false,
10471 /*wrong_original_id_in_config=*/false,
10472 /*missing_retry_id_in_config=*/false,
10473 /*wrong_retry_id_in_config=*/true);
10474}
10475
10476TEST_P(QuicConnectionTest, ClientRetransmitsInitialPacketsOnRetry) {
10477 if (!connection_.version().HasIetfQuicFrames()) {
10478 // TestClientRetryHandling() currently only supports IETF draft versions.
10479 return;
10480 }
10481 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10482
10483 connection_.SendCryptoStreamData();
10484
10485 EXPECT_EQ(1u, writer_->packets_write_attempts());
10486 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10487 /*missing_original_id_in_config=*/false,
10488 /*wrong_original_id_in_config=*/false,
10489 /*missing_retry_id_in_config=*/false,
10490 /*wrong_retry_id_in_config=*/false);
10491
10492 // Verify that initial data is retransmitted immediately after receiving
10493 // RETRY.
10494 if (GetParam().ack_response == AckResponse::kImmediate) {
10495 EXPECT_EQ(2u, writer_->packets_write_attempts());
10496 EXPECT_EQ(1u, writer_->framer()->crypto_frames().size());
10497 }
10498}
10499
10500TEST_P(QuicConnectionTest, NoInitialPacketsRetransmissionOnInvalidRetry) {
10501 if (!connection_.version().HasIetfQuicFrames()) {
10502 return;
10503 }
10504 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10505
10506 connection_.SendCryptoStreamData();
10507
10508 EXPECT_EQ(1u, writer_->packets_write_attempts());
10509 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10510 /*missing_original_id_in_config=*/false,
10511 /*wrong_original_id_in_config=*/false,
10512 /*missing_retry_id_in_config=*/false,
10513 /*wrong_retry_id_in_config=*/false);
10514
10515 EXPECT_EQ(1u, writer_->packets_write_attempts());
10516}
10517
10518TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
10519 if (!connection_.version().UsesTls()) {
10520 // QUIC+TLS is required to transmit connection ID transport parameters.
10521 return;
10522 }
10523 if (connection_.version().UsesTls()) {
10524 // Versions that authenticate connection IDs always send the
10525 // original_destination_connection_id transport parameter.
10526 return;
10527 }
10528 // Make sure that receiving the original_destination_connection_id transport
10529 // parameter fails the handshake when no RETRY packet was received before it.
10530 QuicConfig received_config;
10531 QuicConfigPeer::SetNegotiated(&received_config, true);
10532 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10533 TestConnectionId(0x12345));
10534 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10535 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10536 .Times(1);
10537 connection_.SetFromConfig(received_config);
10538 EXPECT_FALSE(connection_.connected());
10539 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10540}
10541
10542TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10543 if (!connection_.version().UsesTls()) {
10544 // Versions that do not authenticate connection IDs never send the
10545 // retry_source_connection_id transport parameter.
10546 return;
10547 }
10548 // Make sure that receiving the retry_source_connection_id transport parameter
10549 // fails the handshake when no RETRY packet was received before it.
10550 QuicConfig received_config;
10551 QuicConfigPeer::SetNegotiated(&received_config, true);
10552 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10553 TestConnectionId(0x12345));
10554 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10555 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10556 .Times(1);
10557 connection_.SetFromConfig(received_config);
10558 EXPECT_FALSE(connection_.connected());
10559 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10560}
10561
10562// Regression test for http://crbug/1047977
10563TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10564 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10565 return;
10566 }
10567 // Received frame causes connection close.
10568 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10569 .WillOnce(InvokeWithoutArgs([this]() {
10570 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10571 connection_.CloseConnection(
10572 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10573 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10574 return true;
10575 }));
10576 QuicFrames frames;
10577 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10578 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10579 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10580}
10581
10582TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10583 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10584 return;
10585 }
10586 // Received frame causes connection close.
10587 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10588 .WillOnce(InvokeWithoutArgs([this]() {
10589 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10590 connection_.CloseConnection(
10591 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10592 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10593 return true;
10594 }));
10595 QuicFrames frames;
10596 frames.push_back(
10597 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10598 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10599 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10600}
10601
10602TEST_P(QuicConnectionTest,
10603 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10604 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10605 return;
10606 }
10607 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10608 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10609 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10610 // Receives packet 1000 in initial data.
10611 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10612 // Receives packet 2000 in application data.
10613 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10614 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10615 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10616 connection_.CloseConnection(
10617 kQuicErrorCode, "Some random error message",
10618 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10619
10620 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10621
10622 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10623 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10624 // Verify ack is bundled.
10625 EXPECT_EQ(1u, writer_->ack_frames().size());
10626
10627 if (!connection_.version().CanSendCoalescedPackets()) {
10628 // Each connection close packet should be sent in distinct UDP packets.
10629 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10630 writer_->connection_close_packets());
10631 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10632 writer_->packets_write_attempts());
10633 return;
10634 }
10635
10636 // A single UDP packet should be sent with multiple connection close packets
10637 // coalesced together.
10638 EXPECT_EQ(1u, writer_->packets_write_attempts());
10639
10640 // Only the first packet has been processed yet.
10641 EXPECT_EQ(1u, writer_->connection_close_packets());
10642
10643 // ProcessPacket resets the visitor and frees the coalesced packet.
10644 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10645 auto packet = writer_->coalesced_packet()->Clone();
10646 writer_->framer()->ProcessPacket(*packet);
10647 EXPECT_EQ(1u, writer_->connection_close_packets());
10648 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10649 // Verify ack is bundled.
10650 EXPECT_EQ(1u, writer_->ack_frames().size());
10651 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10652}
10653
10654// Regression test for b/151220135.
10655TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10656 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10657 return;
10658 }
10659 QuicConfig config;
10660 QuicTagVector connection_options;
10661 connection_options.push_back(kPTOS);
10662 connection_options.push_back(k1PTO);
10663 config.SetConnectionOptionsToSend(connection_options);
10664 if (connection_.version().UsesTls()) {
10665 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10666 &config, kMaxAcceptedDatagramFrameSize);
10667 }
10668 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10669 connection_.SetFromConfig(config);
10670 connection_.OnHandshakeComplete();
10671 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10672
10673 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10674 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10675
10676 // PTO fires, verify a PING packet gets sent because there is no data to
10677 // send.
10678 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10679 connection_.GetRetransmissionAlarm()->Fire();
10680 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10681 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10682 EXPECT_EQ(1u, writer_->ping_frames().size());
10683}
10684
10685// Regression test for b/155757133
10686TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10687 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10688 return;
10689 }
10690 const size_t kMinRttMs = 40;
10691 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10692 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10693 QuicTime::Delta::Zero(), QuicTime::Zero());
10694 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10695 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10696 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10697 // Discard INITIAL key.
10698 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10699 connection_.NeuterUnencryptedPackets();
10700 EXPECT_CALL(visitor_, GetHandshakeState())
10701 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10702
10703 ProcessPacket(2);
10704 ProcessPacket(3);
10705 ProcessPacket(4);
10706 // Process a packet containing stream frame followed by ACK of packets 1.
10707 QuicFrames frames;
10708 frames.push_back(QuicFrame(QuicStreamFrame(
10709 QuicUtils::GetFirstBidirectionalStreamId(
10710 connection_.version().transport_version, Perspective::IS_CLIENT),
10711 false, 0u, absl::string_view())));
10712 QuicAckFrame ack_frame = InitAckFrame(1);
10713 frames.push_back(QuicFrame(&ack_frame));
10714 // Receiving stream frame causes something to send.
10715 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10716 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
10717 // Verify now the queued ACK contains packet number 2.
10718 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10719 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10720 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10721 }));
10722 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10723 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10724}
10725
martinduke9e0811c2022-12-08 20:35:57 -080010726TEST_P(QuicConnectionTest, DoNotExtendIdleTimeOnUndecryptablePackets) {
Bence Békybac04052022-04-07 15:44:29 -040010727 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10728 QuicConfig config;
10729 connection_.SetFromConfig(config);
10730 // Subtract a second from the idle timeout on the client side.
10731 QuicTime initial_deadline =
10732 clock_.ApproximateNow() +
10733 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10734 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10735
10736 // Received an undecryptable packet.
10737 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080010738 peer_framer_.SetEncrypter(
10739 ENCRYPTION_FORWARD_SECURE,
10740 std::make_unique<quic::NullEncrypter>(Perspective::IS_CLIENT));
Bence Békybac04052022-04-07 15:44:29 -040010741 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10742 // Verify deadline does not get extended.
10743 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10744 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10745 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10746 clock_.AdvanceTime(delay);
10747 connection_.GetTimeoutAlarm()->Fire();
10748 // Verify connection gets closed.
10749 EXPECT_FALSE(connection_.connected());
10750}
10751
10752TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10753 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10754 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10755
10756 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10757 notifier_.WriteOrBufferWindowUpate(0, 0);
10758 }));
10759 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10760 ProcessDataPacket(1);
10761 // Verify ACK is bundled with WINDOW_UPDATE.
10762 EXPECT_FALSE(writer_->ack_frames().empty());
10763 EXPECT_FALSE(connection_.HasPendingAcks());
10764}
10765
10766TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10767 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10768 return;
10769 }
10770 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10771 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10772 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10773 }
10774 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010775 // Receives packet 1000 in initial data.
10776 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10777 EXPECT_TRUE(connection_.HasPendingAcks());
10778
martinduke9e0811c2022-12-08 20:35:57 -080010779 peer_framer_.SetEncrypter(
10780 ENCRYPTION_ZERO_RTT,
10781 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040010782 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080010783 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040010784 // Receives packet 1000 in application data.
10785 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
10786 EXPECT_TRUE(connection_.HasPendingAcks());
10787 // Verify ACK deadline does not change.
10788 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10789 connection_.GetAckAlarm()->deadline());
10790
10791 // Ack alarm fires early.
10792 // Verify the earliest ACK is flushed.
10793 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10794 connection_.GetAckAlarm()->Fire();
10795 EXPECT_TRUE(connection_.HasPendingAcks());
10796 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10797 connection_.GetAckAlarm()->deadline());
10798}
10799
10800TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
10801 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10802 return;
10803 }
10804 QuicConfig config;
10805 QuicTagVector connection_options;
10806 connection_options.push_back(kCBHD);
10807 config.SetConnectionOptionsToSend(connection_options);
10808 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10809 connection_.SetFromConfig(config);
10810 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080010811 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
10812 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -040010813 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10814 // Send stream data.
10815 SendStreamDataToPeer(
10816 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10817 0, FIN, nullptr);
10818 // Verify blackhole detection is in progress.
10819 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10820}
10821
10822TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
10823 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10824 return;
10825 }
10826 set_perspective(Perspective::IS_SERVER);
10827 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10828 if (version().SupportsAntiAmplificationLimit()) {
10829 QuicConnectionPeer::SetAddressValidated(&connection_);
10830 }
10831 QuicConfig config;
10832 QuicTagVector connection_options;
10833 connection_options.push_back(kCBHD);
10834 config.SetInitialReceivedConnectionOptions(connection_options);
10835 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10836 connection_.SetFromConfig(config);
10837 EXPECT_CALL(visitor_, GetHandshakeState())
10838 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10839 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10840 // Send stream data.
10841 SendStreamDataToPeer(
10842 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10843 0, FIN, nullptr);
10844 // Verify blackhole detection is disabled.
10845 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10846}
10847
Bence Békybac04052022-04-07 15:44:29 -040010848// Regresstion test for b/158491591.
10849TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
10850 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10851 return;
10852 }
Bence Békybac04052022-04-07 15:44:29 -040010853 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010854 connection_.SetEncrypter(
10855 ENCRYPTION_HANDSHAKE,
10856 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010857 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10858 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10859 QuicConfig config;
10860 QuicTagVector connection_options;
10861 connection_options.push_back(k5RTO);
10862 config.SetConnectionOptionsToSend(connection_options);
10863 QuicConfigPeer::SetNegotiated(&config, true);
fayang59e518a2022-11-29 11:16:45 -080010864 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10865 GetQuicReloadableFlag(
10866 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040010867 EXPECT_CALL(visitor_, GetHandshakeState())
10868 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10869 }
10870 if (connection_.version().UsesTls()) {
10871 QuicConfigPeer::SetReceivedOriginalConnectionId(
10872 &config, connection_.connection_id());
10873 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10874 &config, connection_.connection_id());
10875 }
10876 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10877 connection_.SetFromConfig(config);
10878
10879 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
fayang59e518a2022-11-29 11:16:45 -080010880 if (GetQuicReloadableFlag(
10881 quic_no_path_degrading_before_handshake_confirmed)) {
10882 // No blackhole detection before handshake confirmed.
10883 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10884 } else {
10885 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10886 }
Bence Békybac04052022-04-07 15:44:29 -040010887 // Discard handshake keys.
fayang59e518a2022-11-29 11:16:45 -080010888 EXPECT_CALL(visitor_, GetHandshakeState())
10889 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040010890 connection_.OnHandshakeComplete();
fayang59e518a2022-11-29 11:16:45 -080010891 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10892 GetQuicReloadableFlag(
10893 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040010894 // Verify blackhole detection stops.
10895 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10896 } else {
10897 // Problematic: although there is nothing in flight, blackhole detection is
10898 // still in progress.
10899 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10900 }
10901}
10902
10903TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
10904 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10905 return;
10906 }
10907 // SetFromConfig is always called after construction from InitializeSession.
10908 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10909 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10910 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10911 QuicConfig config;
10912 connection_.SetFromConfig(config);
10913 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10914 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040010915
martinduke9e0811c2022-12-08 20:35:57 -080010916 peer_framer_.SetEncrypter(
10917 ENCRYPTION_HANDSHAKE,
10918 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10919 peer_framer_.SetEncrypter(
10920 ENCRYPTION_FORWARD_SECURE,
10921 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010922
10923 for (uint64_t i = 1; i <= 3; ++i) {
10924 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10925 }
10926 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10927 for (uint64_t j = 5; j <= 7; ++j) {
10928 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10929 }
10930 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10931 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10932 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080010933 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010934 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080010935 connection_.SetEncrypter(
10936 ENCRYPTION_HANDSHAKE,
10937 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010938 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10939 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
10940 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10941 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
10942 }
10943 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10944 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10945
martinduke9e0811c2022-12-08 20:35:57 -080010946 SetDecrypter(
10947 ENCRYPTION_FORWARD_SECURE,
10948 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010949 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10950 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080010951 connection_.SetEncrypter(
10952 ENCRYPTION_FORWARD_SECURE,
10953 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010954 // Verify the 1-RTT packet gets processed.
10955 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
10956 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10957 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10958}
10959
10960TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
10961 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10962 return;
10963 }
10964 set_perspective(Perspective::IS_SERVER);
10965 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10966 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10967 }
10968 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010969 // Receives packet 1000 in initial data.
10970 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10971 EXPECT_TRUE(connection_.HasPendingAcks());
10972
Bence Békybac04052022-04-07 15:44:29 -040010973 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10974 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10975 QuicTime expected_pto_time =
10976 connection_.sent_packet_manager().GetRetransmissionTime();
10977
10978 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10979 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10980 std::make_unique<TaggingEncrypter>(0x02));
10981 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10982 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10983 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10984 // Verify PTO time does not change.
10985 EXPECT_EQ(expected_pto_time,
10986 connection_.sent_packet_manager().GetRetransmissionTime());
10987
10988 // Receives packet 1001 in initial data.
10989 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
10990 EXPECT_TRUE(connection_.HasPendingAcks());
10991 // Receives packet 1002 in initial data.
10992 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
10993 EXPECT_FALSE(writer_->ack_frames().empty());
10994 // Verify CRYPTO frame is bundled with INITIAL ACK.
10995 EXPECT_FALSE(writer_->crypto_frames().empty());
10996 // Verify PTO time changes.
10997 EXPECT_NE(expected_pto_time,
10998 connection_.sent_packet_manager().GetRetransmissionTime());
10999}
11000
11001TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
11002 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11003 return;
11004 }
11005 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
11006 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11007 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11008 }
11009 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
martinduke9e0811c2022-12-08 20:35:57 -080011010 connection_.SetEncrypter(
11011 ENCRYPTION_HANDSHAKE,
11012 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011013 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11014 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080011015 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
11016 peer_framer_.SetEncrypter(
11017 ENCRYPTION_HANDSHAKE,
11018 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011019 // Receives packet 1000 in handshake data.
11020 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
11021 EXPECT_TRUE(connection_.HasPendingAcks());
11022 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11023 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11024
11025 // Receives packet 1001 in handshake data.
11026 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
11027 EXPECT_TRUE(connection_.HasPendingAcks());
11028 // Receives packet 1002 in handshake data.
11029 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
11030 EXPECT_FALSE(writer_->ack_frames().empty());
11031 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
11032 EXPECT_FALSE(writer_->crypto_frames().empty());
11033}
11034
11035// Regresstion test for b/156232673.
11036TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
11037 if (!connection_.version().CanSendCoalescedPackets()) {
11038 return;
11039 }
11040 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11041 {
11042 QuicConnection::ScopedPacketFlusher flusher(&connection_);
martinduke9e0811c2022-12-08 20:35:57 -080011043 connection_.SetEncrypter(
11044 ENCRYPTION_HANDSHAKE,
11045 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
11046 connection_.SetEncrypter(
11047 ENCRYPTION_FORWARD_SECURE,
11048 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040011049 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11050 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
11051 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11052 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
11053 // Verify soft max packet length gets resumed and handshake packet gets
11054 // successfully sent.
11055 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
11056 }
11057}
11058
11059// Regression test for b/160790422.
11060TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
11061 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11062 return;
11063 }
11064 set_perspective(Perspective::IS_SERVER);
11065 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11066 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11067 }
11068 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040011069 // Receives packet 1000 in initial data.
11070 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11071 EXPECT_TRUE(connection_.HasPendingAcks());
11072
Bence Békybac04052022-04-07 15:44:29 -040011073 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11074 // Send INITIAL 1.
11075 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
11076 QuicTime expected_pto_time =
11077 connection_.sent_packet_manager().GetRetransmissionTime();
11078
11079 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martinduke9e0811c2022-12-08 20:35:57 -080011080 connection_.SetEncrypter(
11081 ENCRYPTION_HANDSHAKE,
11082 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011083 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11084 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11085 // Send HANDSHAKE 2 and 3.
11086 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11087 connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
11088 // Verify PTO time does not change.
11089 EXPECT_EQ(expected_pto_time,
11090 connection_.sent_packet_manager().GetRetransmissionTime());
11091
11092 // Receives ACK for HANDSHAKE 2.
11093 QuicFrames frames;
11094 auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
11095 frames.push_back(QuicFrame(&ack_frame));
11096 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
11097 ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
11098 // Discard INITIAL key.
11099 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11100 connection_.NeuterUnencryptedPackets();
11101 // Receives PING from peer.
11102 frames.clear();
11103 frames.push_back(QuicFrame(QuicPingFrame()));
11104 frames.push_back(QuicFrame(QuicPaddingFrame(3)));
11105 ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
11106 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
11107 connection_.GetAckAlarm()->deadline());
11108 // Fire ACK alarm.
11109 clock_.AdvanceTime(kAlarmGranularity);
11110 connection_.GetAckAlarm()->Fire();
11111 EXPECT_FALSE(writer_->ack_frames().empty());
11112 // Verify handshake data gets retransmitted early.
11113 EXPECT_FALSE(writer_->crypto_frames().empty());
11114}
11115
11116// Regression test for b/161228202
11117TEST_P(QuicConnectionTest, InflatedRttSample) {
11118 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11119 return;
11120 }
11121 // 30ms RTT.
11122 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
11123 set_perspective(Perspective::IS_SERVER);
11124 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
Bence Békybac04052022-04-07 15:44:29 -040011125 // Receives packet 1000 in initial data.
11126 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11127 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11128 }
11129 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11130 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11131 EXPECT_TRUE(connection_.HasPendingAcks());
11132
Bence Békybac04052022-04-07 15:44:29 -040011133 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11134 // Send INITIAL 1.
11135 std::string initial_crypto_data(512, 'a');
11136 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11137 ENCRYPTION_INITIAL);
11138 ASSERT_TRUE(connection_.sent_packet_manager()
11139 .GetRetransmissionTime()
11140 .IsInitialized());
11141 QuicTime::Delta pto_timeout =
11142 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11143 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011144 connection_.SetEncrypter(
11145 ENCRYPTION_HANDSHAKE,
11146 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011147 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11148 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11149 std::string handshake_crypto_data(1024, 'a');
11150 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11151 ENCRYPTION_HANDSHAKE);
11152
11153 // INITIAL 1 gets lost and PTO fires.
11154 clock_.AdvanceTime(pto_timeout);
11155 connection_.GetRetransmissionAlarm()->Fire();
11156
11157 clock_.AdvanceTime(kTestRTT);
11158 // Assume retransmitted INITIAL gets received.
11159 QuicFrames frames;
11160 auto ack_frame = InitAckFrame({{QuicPacketNumber(4), QuicPacketNumber(5)}});
11161 frames.push_back(QuicFrame(&ack_frame));
11162 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
11163 .Times(AnyNumber());
11164 ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
11165 EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
11166 // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
11167 frames.clear();
11168 // HANDSHAKE 5 is also processed.
11169 QuicAckFrame ack_frame2 =
11170 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
11171 {QuicPacketNumber(5), QuicPacketNumber(6)}});
11172 ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
11173 frames.push_back(QuicFrame(&ack_frame2));
11174 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
11175 // Verify RTT inflation gets mitigated.
11176 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
11177}
11178
11179// Regression test for b/161228202
martinduke9e0811c2022-12-08 20:35:57 -080011180TEST_P(QuicConnectionTest, CoalescingPacketCausesInfiniteLoop) {
Bence Békybac04052022-04-07 15:44:29 -040011181 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11182 return;
11183 }
11184 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040011185 // Receives packet 1000 in initial data.
11186 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11187 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11188 }
11189 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11190
11191 // Set anti amplification factor to 2, such that RetransmitDataOfSpaceIfAny
11192 // makes no forward progress and causes infinite loop.
birenroyef686222022-09-12 11:34:34 -070011193 SetQuicFlag(quic_anti_amplification_factor, 2);
Bence Békybac04052022-04-07 15:44:29 -040011194
11195 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11196 EXPECT_TRUE(connection_.HasPendingAcks());
11197
Bence Békybac04052022-04-07 15:44:29 -040011198 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11199 // Send INITIAL 1.
11200 std::string initial_crypto_data(512, 'a');
11201 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11202 ENCRYPTION_INITIAL);
11203 ASSERT_TRUE(connection_.sent_packet_manager()
11204 .GetRetransmissionTime()
11205 .IsInitialized());
11206 QuicTime::Delta pto_timeout =
11207 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11208 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011209 connection_.SetEncrypter(
11210 ENCRYPTION_HANDSHAKE,
11211 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011212 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11213 // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
11214 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11215 std::string handshake_crypto_data(1024, 'a');
11216 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11217 ENCRYPTION_HANDSHAKE);
11218
11219 // INITIAL 1 gets lost and PTO fires.
11220 clock_.AdvanceTime(pto_timeout);
11221 connection_.GetRetransmissionAlarm()->Fire();
11222}
11223
11224TEST_P(QuicConnectionTest, ClientAckDelayForAsyncPacketProcessing) {
11225 if (!version().HasIetfQuicFrames()) {
11226 return;
11227 }
11228 // SetFromConfig is always called after construction from InitializeSession.
11229 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11230 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11231 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11232 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11233 connection_.NeuterUnencryptedPackets();
11234 }));
11235 QuicConfig config;
11236 connection_.SetFromConfig(config);
11237 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080011238 peer_framer_.SetEncrypter(
11239 ENCRYPTION_HANDSHAKE,
11240 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011241 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11242
11243 // Received undecryptable HANDSHAKE 2.
11244 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11245 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11246 // Received INITIAL 4 (which is retransmission of INITIAL 1) after 100ms.
11247 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
11248 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL);
11249 // Generate HANDSHAKE key.
11250 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080011251 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011252 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080011253 connection_.SetEncrypter(
11254 ENCRYPTION_HANDSHAKE,
11255 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011256 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11257 // Verify HANDSHAKE packet gets processed.
fayangfea655c2022-05-17 08:19:12 -070011258 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -040011259 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
fayangfea655c2022-05-17 08:19:12 -070011260 // Verify immediate ACK has been sent out when flush went out of scope.
11261 ASSERT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -040011262 ASSERT_FALSE(writer_->ack_frames().empty());
fayangfea655c2022-05-17 08:19:12 -070011263 // Verify the ack_delay_time in the sent HANDSHAKE ACK frame is 100ms.
11264 EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
Bence Békybac04052022-04-07 15:44:29 -040011265 writer_->ack_frames()[0].ack_delay_time);
11266 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
11267}
11268
11269TEST_P(QuicConnectionTest, TestingLiveness) {
11270 const size_t kMinRttMs = 40;
11271 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11272 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11273 QuicTime::Delta::Zero(), QuicTime::Zero());
11274 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11275 QuicConfig config;
11276
11277 CryptoHandshakeMessage msg;
11278 std::string error_details;
11279 QuicConfig client_config;
11280 client_config.SetInitialStreamFlowControlWindowToSend(
11281 kInitialStreamFlowControlWindowForTest);
11282 client_config.SetInitialSessionFlowControlWindowToSend(
11283 kInitialSessionFlowControlWindowForTest);
11284 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11285 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11286 const QuicErrorCode error =
11287 config.ProcessPeerHello(msg, CLIENT, &error_details);
11288 EXPECT_THAT(error, IsQuicNoError());
11289
11290 if (connection_.version().UsesTls()) {
11291 QuicConfigPeer::SetReceivedOriginalConnectionId(
11292 &config, connection_.connection_id());
11293 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11294 &config, connection_.connection_id());
11295 }
11296
11297 connection_.SetFromConfig(config);
11298 connection_.OnHandshakeComplete();
11299 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11300 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11301 EXPECT_FALSE(connection_.MaybeTestLiveness());
11302
haoyuewang7b43efb2022-04-20 16:26:03 -070011303 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040011304 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11305 // Advance time to near the idle timeout.
11306 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11307 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11308 EXPECT_TRUE(connection_.MaybeTestLiveness());
11309 // Verify idle deadline does not change.
haoyuewang7b43efb2022-04-20 16:26:03 -070011310 EXPECT_EQ(deadline, QuicConnectionPeer::GetIdleNetworkDeadline(&connection_));
Bence Békybac04052022-04-07 15:44:29 -040011311}
11312
fayang5783c332022-12-14 09:30:25 -080011313TEST_P(QuicConnectionTest, DisableLivenessTesting) {
11314 const size_t kMinRttMs = 40;
11315 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11316 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11317 QuicTime::Delta::Zero(), QuicTime::Zero());
11318 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11319 QuicConfig config;
11320
11321 CryptoHandshakeMessage msg;
11322 std::string error_details;
11323 QuicConfig client_config;
11324 client_config.SetInitialStreamFlowControlWindowToSend(
11325 kInitialStreamFlowControlWindowForTest);
11326 client_config.SetInitialSessionFlowControlWindowToSend(
11327 kInitialSessionFlowControlWindowForTest);
11328 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11329 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11330 const QuicErrorCode error =
11331 config.ProcessPeerHello(msg, CLIENT, &error_details);
11332 EXPECT_THAT(error, IsQuicNoError());
11333
11334 if (connection_.version().UsesTls()) {
11335 QuicConfigPeer::SetReceivedOriginalConnectionId(
11336 &config, connection_.connection_id());
11337 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11338 &config, connection_.connection_id());
11339 }
11340
11341 connection_.SetFromConfig(config);
11342 connection_.OnHandshakeComplete();
11343 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11344 connection_.DisableLivenessTesting();
11345 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11346 EXPECT_FALSE(connection_.MaybeTestLiveness());
11347
11348 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
11349 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11350 // Advance time to near the idle timeout.
11351 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11352 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11353 EXPECT_FALSE(connection_.MaybeTestLiveness());
11354}
11355
Bence Békybac04052022-04-07 15:44:29 -040011356TEST_P(QuicConnectionTest, SilentIdleTimeout) {
11357 set_perspective(Perspective::IS_SERVER);
11358 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11359 if (version().SupportsAntiAmplificationLimit()) {
11360 QuicConnectionPeer::SetAddressValidated(&connection_);
11361 }
11362
11363 QuicConfig config;
11364 QuicConfigPeer::SetNegotiated(&config, true);
11365 if (connection_.version().UsesTls()) {
11366 QuicConfigPeer::SetReceivedOriginalConnectionId(
11367 &config, connection_.connection_id());
11368 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
11369 QuicConnectionId());
11370 }
11371 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11372 connection_.SetFromConfig(config);
11373
11374 EXPECT_TRUE(connection_.connected());
11375 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11376
11377 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
11378 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
11379 }
11380 EXPECT_CALL(visitor_,
11381 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11382 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
haoyuewang7b43efb2022-04-20 16:26:03 -070011383 if (!QuicConnectionPeer::GetBandwidthUpdateTimeout(&connection_)
11384 .IsInfinite()) {
11385 // Fires the bandwidth update.
11386 connection_.GetTimeoutAlarm()->Fire();
11387 }
Bence Békybac04052022-04-07 15:44:29 -040011388 connection_.GetTimeoutAlarm()->Fire();
11389 // Verify the connection close packets get serialized and added to
11390 // termination packets list.
11391 EXPECT_NE(nullptr,
11392 QuicConnectionPeer::GetConnectionClosePacket(&connection_));
11393}
11394
martinduke9e0811c2022-12-08 20:35:57 -080011395TEST_P(QuicConnectionTest, DoNotSendPing) {
Bence Békybac04052022-04-07 15:44:29 -040011396 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11397 connection_.OnHandshakeComplete();
11398 EXPECT_TRUE(connection_.connected());
11399 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11400 .WillRepeatedly(Return(true));
11401 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
11402 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11403
11404 SendStreamDataToPeer(
11405 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
11406 "GET /", 0, FIN, nullptr);
11407 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11408 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11409 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
11410 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11411
11412 // Now recevie an ACK and response of the previous packet, which will move the
11413 // ping alarm forward.
11414 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11415 QuicFrames frames;
11416 QuicAckFrame ack_frame = InitAckFrame(1);
11417 frames.push_back(QuicFrame(&ack_frame));
11418 frames.push_back(QuicFrame(QuicStreamFrame(
11419 GetNthClientInitiatedStreamId(0, connection_.transport_version()), true,
11420 0u, absl::string_view())));
11421 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11422 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
11423 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11424 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
11425 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11426 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11427 // The ping timer is set slightly less than 15 seconds in the future, because
11428 // of the 1s ping timer alarm granularity.
11429 EXPECT_EQ(
11430 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
11431 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11432
11433 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
11434 // Suppose now ShouldKeepConnectionAlive returns false.
11435 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11436 .WillRepeatedly(Return(false));
11437 // Verify PING does not get sent.
11438 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11439 connection_.GetPingAlarm()->Fire();
11440}
11441
11442// Regression test for b/159698337
11443TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) {
11444 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11445 return;
11446 }
11447 // Finish handshake.
11448 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11449 notifier_.NeuterUnencryptedData();
11450 connection_.NeuterUnencryptedPackets();
11451 connection_.OnHandshakeComplete();
11452 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080011453 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040011454
11455 std::string data(1200, 'a');
11456 // Send data packets 1 - 5.
11457 for (size_t i = 0; i < 5; ++i) {
11458 SendStreamDataToPeer(
11459 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
11460 i * 1200, i == 4 ? FIN : NO_FIN, nullptr);
11461 }
11462 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
11463
11464 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _)).Times(3);
11465
11466 // ACK packet 5 and 1 and 2 are detected lost.
11467 QuicAckFrame frame =
11468 InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}});
11469 LostPacketVector lost_packets;
11470 lost_packets.push_back(
11471 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
11472 lost_packets.push_back(
11473 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
11474 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11475 .Times(AnyNumber())
11476 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11477 Return(LossDetectionInterface::DetectionStats())));
11478 ProcessAckPacket(1, &frame);
11479 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11480 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
11481 EXPECT_TRUE(retransmission_alarm->IsSet());
11482
11483 // ACK packet 1 - 5 and 7.
11484 QuicAckFrame frame2 =
11485 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)},
11486 {QuicPacketNumber(7), QuicPacketNumber(8)}});
11487 ProcessAckPacket(2, &frame2);
11488 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11489
11490 // ACK packet 7 again and assume packet 6 is detected lost.
11491 QuicAckFrame frame3 =
11492 InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}});
11493 lost_packets.clear();
11494 lost_packets.push_back(
11495 LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize));
11496 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11497 .Times(AnyNumber())
11498 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11499 Return(LossDetectionInterface::DetectionStats())));
11500 ProcessAckPacket(3, &frame3);
11501 // Make sure loss detection is cancelled even there is no new acked packets.
11502 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11503}
11504
11505TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) {
11506 EXPECT_TRUE(connection_.connected());
11507 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11508 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
11509 QuicTime::Delta::Zero(), QuicTime::Zero());
11510
11511 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11512 QuicConfig config;
11513 config.SetClientConnectionOptions(QuicTagVector{kFIDT});
11514 QuicConfigPeer::SetNegotiated(&config, true);
11515 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11516 EXPECT_CALL(visitor_, GetHandshakeState())
11517 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11518 }
11519 if (connection_.version().UsesTls()) {
11520 QuicConfigPeer::SetReceivedOriginalConnectionId(
11521 &config, connection_.connection_id());
11522 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11523 &config, connection_.connection_id());
11524 }
11525 connection_.SetFromConfig(config);
11526
11527 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11528 // Send a packet close to timeout.
11529 QuicTime::Delta timeout =
11530 connection_.GetTimeoutAlarm()->deadline() - clock_.Now();
11531 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1));
11532 // Send stream data.
11533 SendStreamDataToPeer(
11534 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11535 0, FIN, nullptr);
11536 // Verify this sent packet does not extend idle timeout since 1s is > PTO
11537 // delay.
11538 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11539 EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
11540 connection_.GetTimeoutAlarm()->deadline() - clock_.Now());
11541
11542 // Received an ACK 100ms later.
11543 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100));
11544 QuicAckFrame ack = InitAckFrame(1);
11545 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
11546 ProcessAckPacket(1, &ack);
11547 // Verify idle timeout gets extended.
11548 EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline());
11549}
11550
11551// Regression test for b/166255274
11552TEST_P(QuicConnectionTest,
11553 ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) {
11554 if (!connection_.version().CanSendCoalescedPackets()) {
11555 return;
11556 }
Bence Békybac04052022-04-07 15:44:29 -040011557 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11558 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11559 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11560 EXPECT_TRUE(connection_.HasPendingAcks());
11561 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11562 std::make_unique<TaggingEncrypter>(0x02));
11563 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11564 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11565 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11566 connection_.NeuterUnencryptedPackets();
11567 }));
11568 {
11569 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11570 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11571 // Verify the packet is on hold.
11572 EXPECT_EQ(0u, writer_->packets_write_attempts());
11573 // Flush pending ACKs.
11574 connection_.GetAckAlarm()->Fire();
11575 }
11576 EXPECT_FALSE(connection_.packet_creator().HasPendingFrames());
11577 // The ACK frame is deleted along with initial_packet_ in coalescer. Sending
11578 // connection close would cause this (released) ACK frame be serialized (and
11579 // crashes).
11580 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11581 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
11582 EXPECT_TRUE(connection_.connected());
11583}
11584
11585TEST_P(QuicConnectionTest, PathValidationOnNewSocketSuccess) {
danzh87605712022-04-11 14:36:39 -070011586 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011587 return;
11588 }
11589 PathProbeTestInit(Perspective::IS_CLIENT);
11590 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11591 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11592 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11593 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11594 .Times(AtLeast(1u))
11595 .WillOnce(Invoke([&]() {
11596 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11597 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11598 EXPECT_EQ(1u, new_writer.padding_frames().size());
11599 EXPECT_EQ(kNewSelfAddress.host(),
11600 new_writer.last_write_source_address());
11601 }));
11602 bool success = false;
11603 connection_.ValidatePath(
11604 std::make_unique<TestQuicPathValidationContext>(
11605 kNewSelfAddress, connection_.peer_address(), &new_writer),
11606 std::make_unique<TestValidationResultDelegate>(
11607 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11608 EXPECT_EQ(0u, writer_->packets_write_attempts());
11609
11610 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011611 frames.push_back(QuicFrame(QuicPathResponseFrame(
Bence Békybac04052022-04-07 15:44:29 -040011612 99, new_writer.path_challenge_frames().front().data_buffer)));
11613 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
11614 ENCRYPTION_FORWARD_SECURE);
11615 EXPECT_TRUE(success);
11616}
11617
11618TEST_P(QuicConnectionTest, NewPathValidationCancelsPreviousOne) {
danzh87605712022-04-11 14:36:39 -070011619 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011620 return;
11621 }
11622 PathProbeTestInit(Perspective::IS_CLIENT);
11623 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11624 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11625 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11626 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11627 .Times(AtLeast(1u))
11628 .WillOnce(Invoke([&]() {
11629 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11630 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11631 EXPECT_EQ(1u, new_writer.padding_frames().size());
11632 EXPECT_EQ(kNewSelfAddress.host(),
11633 new_writer.last_write_source_address());
11634 }));
11635 bool success = true;
11636 connection_.ValidatePath(
11637 std::make_unique<TestQuicPathValidationContext>(
11638 kNewSelfAddress, connection_.peer_address(), &new_writer),
11639 std::make_unique<TestValidationResultDelegate>(
11640 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11641 EXPECT_EQ(0u, writer_->packets_write_attempts());
11642
11643 // Start another path validation request.
11644 const QuicSocketAddress kNewSelfAddress2(QuicIpAddress::Any4(), 12346);
11645 EXPECT_NE(kNewSelfAddress2, connection_.self_address());
11646 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
11647 if (!connection_.connection_migration_use_new_cid()) {
11648 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11649 .Times(AtLeast(1u))
11650 .WillOnce(Invoke([&]() {
11651 EXPECT_EQ(1u, new_writer2.packets_write_attempts());
11652 EXPECT_EQ(1u, new_writer2.path_challenge_frames().size());
11653 EXPECT_EQ(1u, new_writer2.padding_frames().size());
11654 EXPECT_EQ(kNewSelfAddress2.host(),
11655 new_writer2.last_write_source_address());
11656 }));
11657 }
11658 bool success2 = false;
11659 connection_.ValidatePath(
11660 std::make_unique<TestQuicPathValidationContext>(
11661 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
11662 std::make_unique<TestValidationResultDelegate>(
11663 &connection_, kNewSelfAddress2, connection_.peer_address(),
11664 &success2));
11665 EXPECT_FALSE(success);
11666 if (connection_.connection_migration_use_new_cid()) {
11667 // There is no pening path validation as there is no available connection
11668 // ID.
11669 EXPECT_FALSE(connection_.HasPendingPathValidation());
11670 } else {
11671 EXPECT_TRUE(connection_.HasPendingPathValidation());
11672 }
11673}
11674
11675// Regression test for b/182571515.
11676TEST_P(QuicConnectionTest, PathValidationRetry) {
danzh87605712022-04-11 14:36:39 -070011677 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011678 return;
11679 }
11680 PathProbeTestInit(Perspective::IS_CLIENT);
11681
11682 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11683 .Times(2u)
11684 .WillRepeatedly(Invoke([&]() {
11685 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11686 EXPECT_EQ(1u, writer_->padding_frames().size());
11687 }));
11688 bool success = true;
11689 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11690 connection_.self_address(),
11691 connection_.peer_address(), writer_.get()),
11692 std::make_unique<TestValidationResultDelegate>(
11693 &connection_, connection_.self_address(),
11694 connection_.peer_address(), &success));
11695 EXPECT_EQ(1u, writer_->packets_write_attempts());
11696 EXPECT_TRUE(connection_.HasPendingPathValidation());
11697
11698 // Retry after time out.
11699 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11700 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11701 static_cast<TestAlarmFactory::TestAlarm*>(
11702 QuicPathValidatorPeer::retry_timer(
11703 QuicConnectionPeer::path_validator(&connection_)))
11704 ->Fire();
11705 EXPECT_EQ(2u, writer_->packets_write_attempts());
11706}
11707
11708TEST_P(QuicConnectionTest, PathValidationReceivesStatelessReset) {
danzh87605712022-04-11 14:36:39 -070011709 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011710 return;
11711 }
11712 PathProbeTestInit(Perspective::IS_CLIENT);
11713 QuicConfig config;
11714 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
11715 kTestStatelessResetToken);
11716 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11717 connection_.SetFromConfig(config);
11718 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11719 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11720 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11721 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11722 .Times(AtLeast(1u))
11723 .WillOnce(Invoke([&]() {
11724 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11725 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11726 EXPECT_EQ(1u, new_writer.padding_frames().size());
11727 EXPECT_EQ(kNewSelfAddress.host(),
11728 new_writer.last_write_source_address());
11729 }));
11730 bool success = true;
11731 connection_.ValidatePath(
11732 std::make_unique<TestQuicPathValidationContext>(
11733 kNewSelfAddress, connection_.peer_address(), &new_writer),
11734 std::make_unique<TestValidationResultDelegate>(
11735 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11736 EXPECT_EQ(0u, writer_->packets_write_attempts());
11737 EXPECT_TRUE(connection_.HasPendingPathValidation());
11738
11739 std::unique_ptr<QuicEncryptedPacket> packet(
11740 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
11741 /*received_packet_length=*/100,
11742 kTestStatelessResetToken));
11743 std::unique_ptr<QuicReceivedPacket> received(
11744 ConstructReceivedPacket(*packet, QuicTime::Zero()));
11745 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
11746 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
11747 EXPECT_FALSE(connection_.HasPendingPathValidation());
11748 EXPECT_FALSE(success);
11749}
11750
11751// Tests that PATH_CHALLENGE is dropped if it is sent via a blocked alternative
11752// writer.
11753TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedNewSocket) {
11754 if (!VersionHasIetfQuicFrames(connection_.version().transport_version) ||
11755 !connection_.connection_migration_use_new_cid()) {
11756 return;
11757 }
11758 PathProbeTestInit(Perspective::IS_CLIENT);
11759 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11760 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11761 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11762 new_writer.BlockOnNextWrite();
11763 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
11764 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11765 .Times(AtLeast(1))
11766 .WillOnce(Invoke([&]() {
11767 // Even though the socket is blocked, the PATH_CHALLENGE should still be
11768 // treated as sent.
11769 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11770 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11771 EXPECT_EQ(1u, new_writer.padding_frames().size());
11772 EXPECT_EQ(kNewSelfAddress.host(),
11773 new_writer.last_write_source_address());
11774 }));
11775 bool success = false;
11776 connection_.ValidatePath(
11777 std::make_unique<TestQuicPathValidationContext>(
11778 kNewSelfAddress, connection_.peer_address(), &new_writer),
11779 std::make_unique<TestValidationResultDelegate>(
11780 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11781 EXPECT_EQ(0u, writer_->packets_write_attempts());
11782
11783 new_writer.SetWritable();
11784 // Write event on the default socket shouldn't make any difference.
11785 connection_.OnCanWrite();
11786 // A NEW_CONNECTION_ID frame is received in PathProbeTestInit and OnCanWrite
11787 // will write a acking packet.
11788 EXPECT_EQ(1u, writer_->packets_write_attempts());
11789 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11790}
11791
11792// Tests that PATH_CHALLENGE is dropped if it is sent via the default writer
11793// and the writer is blocked.
11794TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedDefaultSocket) {
danzh87605712022-04-11 14:36:39 -070011795 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011796 return;
11797 }
11798 PathProbeTestInit(Perspective::IS_SERVER);
11799 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11800 writer_->BlockOnNextWrite();
11801 // 1st time is after writer returns WRITE_STATUS_BLOCKED. 2nd time is in
11802 // ShouldGeneratePacket().
11803 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(2));
11804 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
11805 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11806 .Times(AtLeast(1u))
11807 .WillOnce(Invoke([&]() {
11808 // This packet isn't sent actually, instead it is buffered in the
11809 // connection.
11810 EXPECT_EQ(1u, writer_->packets_write_attempts());
11811 if (connection_.validate_client_address()) {
11812 EXPECT_EQ(1u, writer_->path_response_frames().size());
11813 EXPECT_EQ(0,
11814 memcmp(&path_challenge_payload,
11815 &writer_->path_response_frames().front().data_buffer,
11816 sizeof(path_challenge_payload)));
11817 }
11818 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11819 EXPECT_EQ(1u, writer_->padding_frames().size());
11820 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11821 }))
11822 .WillRepeatedly(Invoke([&]() {
11823 // Only one PATH_CHALLENGE should be sent out.
11824 EXPECT_EQ(0u, writer_->path_challenge_frames().size());
11825 }));
11826 bool success = false;
11827 if (connection_.validate_client_address()) {
11828 // Receiving a PATH_CHALLENGE from the new peer address should trigger
11829 // address validation.
11830 QuicFrames frames;
11831 frames.push_back(
wubd0152ca2022-04-08 08:26:44 -070011832 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040011833 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11834 ENCRYPTION_FORWARD_SECURE);
11835 } else {
11836 // Manually start to validate the new peer address.
11837 connection_.ValidatePath(
11838 std::make_unique<TestQuicPathValidationContext>(
11839 connection_.self_address(), kNewPeerAddress, writer_.get()),
11840 std::make_unique<TestValidationResultDelegate>(
11841 &connection_, connection_.self_address(), kNewPeerAddress,
11842 &success));
11843 }
11844 EXPECT_EQ(1u, writer_->packets_write_attempts());
11845
11846 // Try again with the new socket blocked from the beginning. The 2nd
11847 // PATH_CHALLENGE shouldn't be serialized, but be dropped.
11848 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11849 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11850 static_cast<TestAlarmFactory::TestAlarm*>(
11851 QuicPathValidatorPeer::retry_timer(
11852 QuicConnectionPeer::path_validator(&connection_)))
11853 ->Fire();
11854
11855 // No more write attempt should be made.
11856 EXPECT_EQ(1u, writer_->packets_write_attempts());
11857
11858 writer_->SetWritable();
11859 // OnCanWrite() should actually write out the 1st PATH_CHALLENGE packet
11860 // buffered earlier, thus incrementing the write counter. It may also send
11861 // ACKs to previously received packets.
11862 connection_.OnCanWrite();
11863 EXPECT_LE(2u, writer_->packets_write_attempts());
11864}
11865
11866// Tests that write error on the alternate socket should be ignored.
11867TEST_P(QuicConnectionTest, SendPathChallengeFailOnNewSocket) {
danzh87605712022-04-11 14:36:39 -070011868 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011869 return;
11870 }
11871 PathProbeTestInit(Perspective::IS_CLIENT);
11872 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11873 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11874 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11875 new_writer.SetShouldWriteFail();
11876 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11877 .Times(0);
11878 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11879
11880 bool success = false;
11881 connection_.ValidatePath(
11882 std::make_unique<TestQuicPathValidationContext>(
11883 kNewSelfAddress, connection_.peer_address(), &new_writer),
11884 std::make_unique<TestValidationResultDelegate>(
11885 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11886 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11887 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11888 EXPECT_EQ(1u, new_writer.padding_frames().size());
11889 EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address());
11890
11891 EXPECT_EQ(0u, writer_->packets_write_attempts());
11892 // Regardless of the write error, the connection should still be connected.
11893 EXPECT_TRUE(connection_.connected());
11894}
11895
11896// Tests that write error while sending PATH_CHALLANGE from the default socket
11897// should close the connection.
11898TEST_P(QuicConnectionTest, SendPathChallengeFailOnDefaultPath) {
danzh87605712022-04-11 14:36:39 -070011899 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011900 return;
11901 }
11902 PathProbeTestInit(Perspective::IS_CLIENT);
11903
11904 writer_->SetShouldWriteFail();
11905 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11906 .WillOnce(
11907 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11908 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11909 }));
11910 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11911 {
11912 // Add a flusher to force flush, otherwise the frames will remain in the
11913 // packet creator.
11914 bool success = false;
11915 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11916 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11917 connection_.self_address(),
11918 connection_.peer_address(), writer_.get()),
11919 std::make_unique<TestValidationResultDelegate>(
11920 &connection_, connection_.self_address(),
11921 connection_.peer_address(), &success));
11922 }
11923 EXPECT_EQ(1u, writer_->packets_write_attempts());
11924 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11925 EXPECT_EQ(1u, writer_->padding_frames().size());
11926 EXPECT_EQ(connection_.peer_address(), writer_->last_write_peer_address());
11927 EXPECT_FALSE(connection_.connected());
11928 // Closing connection should abandon ongoing path validation.
11929 EXPECT_FALSE(connection_.HasPendingPathValidation());
11930}
11931
11932TEST_P(QuicConnectionTest, SendPathChallengeFailOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011933 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011934 return;
11935 }
11936 PathProbeTestInit(Perspective::IS_CLIENT);
11937
11938 writer_->SetShouldWriteFail();
11939 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11940 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11941 .WillOnce(
11942 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11943 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11944 }));
11945 // Sending PATH_CHALLENGE to trigger a flush write which will fail and close
11946 // the connection.
11947 bool success = false;
11948 connection_.ValidatePath(
11949 std::make_unique<TestQuicPathValidationContext>(
11950 connection_.self_address(), kNewPeerAddress, writer_.get()),
11951 std::make_unique<TestValidationResultDelegate>(
11952 &connection_, connection_.self_address(), kNewPeerAddress, &success));
11953
11954 EXPECT_EQ(1u, writer_->packets_write_attempts());
11955 EXPECT_FALSE(connection_.HasPendingPathValidation());
11956 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11957 EXPECT_EQ(1u, writer_->padding_frames().size());
11958 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11959 EXPECT_FALSE(connection_.connected());
11960}
11961
11962TEST_P(QuicConnectionTest,
11963 SendPathChallengeFailPacketTooBigOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011964 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011965 return;
11966 }
11967 PathProbeTestInit(Perspective::IS_CLIENT);
11968 // Make sure there is no outstanding ACK_FRAME to write.
11969 connection_.OnCanWrite();
11970 uint32_t num_packets_write_attempts = writer_->packets_write_attempts();
11971
11972 writer_->SetShouldWriteFail();
11973 writer_->SetWriteError(*writer_->MessageTooBigErrorCode());
11974 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11975 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11976 .Times(0u);
11977 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11978 // Sending PATH_CHALLENGE to trigger a flush write which will fail with
11979 // MSG_TOO_BIG.
11980 bool success = false;
11981 connection_.ValidatePath(
11982 std::make_unique<TestQuicPathValidationContext>(
11983 connection_.self_address(), kNewPeerAddress, writer_.get()),
11984 std::make_unique<TestValidationResultDelegate>(
11985 &connection_, connection_.self_address(), kNewPeerAddress, &success));
11986 EXPECT_TRUE(connection_.HasPendingPathValidation());
11987 // Connection shouldn't be closed.
11988 EXPECT_TRUE(connection_.connected());
11989 EXPECT_EQ(++num_packets_write_attempts, writer_->packets_write_attempts());
11990 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11991 EXPECT_EQ(1u, writer_->padding_frames().size());
11992 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11993}
11994
11995// Check that if there are two PATH_CHALLENGE frames in the packet, the latter
11996// one is ignored.
11997TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) {
11998 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11999 return;
12000 }
12001 PathProbeTestInit(Perspective::IS_SERVER);
12002
12003 QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7};
12004 QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15};
12005 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070012006 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer1)));
12007 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer2)));
Bence Békybac04052022-04-07 15:44:29 -040012008 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12009 /*port=*/23456);
12010
12011 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
12012
12013 // Expect 2 packets to be sent: the first are padded PATH_RESPONSE(s) to the
12014 // alternative peer address. The 2nd is a ACK-only packet to the original
12015 // peer address.
12016 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12017 .Times(2)
12018 .WillOnce(Invoke([=]() {
12019 EXPECT_EQ(1u, writer_->path_response_frames().size());
12020 // The final check is to ensure that the random data in the response
12021 // matches the random data from the challenge.
12022 EXPECT_EQ(0,
12023 memcmp(path_frame_buffer1.data(),
12024 &(writer_->path_response_frames().front().data_buffer),
12025 sizeof(path_frame_buffer1)));
12026 EXPECT_EQ(1u, writer_->padding_frames().size());
12027 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12028 }))
12029 .WillOnce(Invoke([=]() {
12030 // The last write of ACK-only packet should still use the old peer
12031 // address.
12032 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12033 }));
12034 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12035 ENCRYPTION_FORWARD_SECURE);
12036}
12037
12038TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) {
12039 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12040 return;
12041 }
12042 PathProbeTestInit(Perspective::IS_SERVER);
12043
12044 QuicFrames frames;
12045 frames.push_back(QuicFrame(frame1_));
12046 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012047 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
fayang161ce6e2022-07-01 18:02:11 -070012048 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
Bence Békybac04052022-04-07 15:44:29 -040012049 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
12050 /*port=*/23456);
12051
12052 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
12053 EXPECT_CALL(*send_algorithm_, OnConnectionMigration())
12054 .Times(connection_.validate_client_address() ? 0u : 1u);
12055 EXPECT_CALL(visitor_, OnStreamFrame(_))
12056 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
12057 // Send some data on the stream. The STREAM_FRAME should be built into
12058 // one packet together with the latter PATH_RESPONSE and PATH_CHALLENGE.
12059 const std::string data{"response body"};
12060 connection_.producer()->SaveStreamData(frame.stream_id, data);
12061 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12062 NO_FIN);
12063 }));
12064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12065 .Times(connection_.validate_client_address() ? 0u : 1u);
12066 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12067 ENCRYPTION_FORWARD_SECURE);
12068
12069 // Verify that this packet contains a STREAM_FRAME and a
12070 // PATH_RESPONSE_FRAME.
12071 EXPECT_EQ(1u, writer_->stream_frames().size());
12072 EXPECT_EQ(1u, writer_->path_response_frames().size());
12073 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
12074 writer_->path_challenge_frames().size());
12075 // The final check is to ensure that the random data in the response
12076 // matches the random data from the challenge.
12077 EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
12078 &(writer_->path_response_frames().front().data_buffer),
12079 sizeof(path_frame_buffer)));
12080 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
12081 writer_->path_challenge_frames().size());
12082 EXPECT_EQ(1u, writer_->padding_frames().size());
12083 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12084 if (connection_.validate_client_address()) {
12085 EXPECT_TRUE(connection_.HasPendingPathValidation());
12086 }
12087}
12088
12089TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) {
12090 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12091 return;
12092 }
12093 PathProbeTestInit(Perspective::IS_SERVER);
12094
12095 QuicFrames frames;
12096 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012097 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012098 // PATH_RESPONSE should be flushed out before the rest packet is parsed.
12099 frames.push_back(QuicFrame(frame1_));
12100 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
12101 /*port=*/23456);
12102 QuicByteCount received_packet_size;
12103 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12104 .Times(AtLeast(1u))
12105 .WillOnce(Invoke([=, &received_packet_size]() {
12106 // Verify that this packet contains a PATH_RESPONSE_FRAME.
12107 EXPECT_EQ(0u, writer_->stream_frames().size());
12108 EXPECT_EQ(1u, writer_->path_response_frames().size());
12109 // The final check is to ensure that the random data in the response
12110 // matches the random data from the challenge.
12111 EXPECT_EQ(0,
12112 memcmp(path_frame_buffer.data(),
12113 &(writer_->path_response_frames().front().data_buffer),
12114 sizeof(path_frame_buffer)));
12115 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
12116 writer_->path_challenge_frames().size());
12117 EXPECT_EQ(1u, writer_->padding_frames().size());
12118 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12119 received_packet_size =
12120 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_);
12121 }));
12122 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
12123 EXPECT_CALL(*send_algorithm_, OnConnectionMigration())
12124 .Times(connection_.validate_client_address() ? 0u : 1u);
12125 EXPECT_CALL(visitor_, OnStreamFrame(_))
12126 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
12127 // 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);
12137 if (!connection_.validate_client_address()) {
12138 return;
12139 }
12140 EXPECT_TRUE(connection_.HasPendingPathValidation());
12141 EXPECT_EQ(0u,
12142 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
12143 EXPECT_EQ(
12144 received_packet_size,
12145 QuicConnectionPeer::BytesReceivedBeforeAddressValidation(&connection_));
12146}
12147
12148// Tests that a PATH_CHALLENGE is received in between other frames in an out of
12149// order packet.
12150TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) {
12151 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12152 return;
12153 }
12154 PathProbeTestInit(Perspective::IS_SERVER);
12155
12156 QuicFrames frames;
12157 frames.push_back(QuicFrame(frame1_));
12158 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012159 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012160 frames.push_back(QuicFrame(frame2_));
12161 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12162 /*port=*/23456);
12163
12164 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12165 EXPECT_CALL(visitor_, OnStreamFrame(_))
12166 .Times(2)
12167 .WillRepeatedly(Invoke([=](const QuicStreamFrame& frame) {
12168 // Send some data on the stream. The STREAM_FRAME should be built into
12169 // one packet together with the latter PATH_RESPONSE.
12170 const std::string data{"response body"};
12171 connection_.producer()->SaveStreamData(frame.stream_id, data);
12172 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12173 NO_FIN);
12174 }));
12175 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12176 .WillOnce(Invoke([=]() {
12177 // Verify that this packet contains a STREAM_FRAME and is sent to the
12178 // original peer address.
12179 EXPECT_EQ(1u, writer_->stream_frames().size());
12180 // No connection migration should happen because the packet is received
12181 // out of order.
12182 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12183 }))
12184 .WillOnce(Invoke([=]() {
12185 EXPECT_EQ(1u, writer_->path_response_frames().size());
12186 // The final check is to ensure that the random data in the response
12187 // matches the random data from the challenge.
12188 EXPECT_EQ(0,
12189 memcmp(path_frame_buffer.data(),
12190 &(writer_->path_response_frames().front().data_buffer),
12191 sizeof(path_frame_buffer)));
12192 EXPECT_EQ(1u, writer_->padding_frames().size());
12193 // PATH_RESPONSE should be sent in another packet to a different peer
12194 // address.
12195 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12196 }))
12197 .WillOnce(Invoke([=]() {
12198 // Verify that this packet contains a STREAM_FRAME and is sent to the
12199 // original peer address.
12200 EXPECT_EQ(1u, writer_->stream_frames().size());
12201 // No connection migration should happen because the packet is received
12202 // out of order.
12203 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12204 }));
12205 // Lower the packet number so that receiving this packet shouldn't trigger
12206 // peer migration.
12207 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12208 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12209 ENCRYPTION_FORWARD_SECURE);
12210}
12211
12212// Tests that a PATH_CHALLENGE is cached if its PATH_RESPONSE can't be sent.
12213TEST_P(QuicConnectionTest, FailToWritePathResponse) {
12214 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12215 return;
12216 }
12217 PathProbeTestInit(Perspective::IS_SERVER);
12218
12219 QuicFrames frames;
12220 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012221 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012222 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12223 /*port=*/23456);
12224
12225 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12226 // Lower the packet number so that receiving this packet shouldn't trigger
12227 // peer migration.
12228 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12229 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
12230 writer_->SetWriteBlocked();
12231 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12232 ENCRYPTION_FORWARD_SECURE);
12233}
12234
12235// Regression test for b/168101557.
12236TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) {
12237 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12238 return;
12239 }
12240 set_perspective(Perspective::IS_SERVER);
12241 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
12242 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12243 }
12244 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040012245 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12246 EXPECT_TRUE(connection_.HasPendingAcks());
12247
Bence Békybac04052022-04-07 15:44:29 -040012248 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12249 // Send INITIAL 1.
12250 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12251
martinduke9e0811c2022-12-08 20:35:57 -080012252 connection_.SetEncrypter(
12253 ENCRYPTION_HANDSHAKE,
12254 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012255 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12256 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080012257 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012258 // Send HANDSHAKE packets.
12259 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
12260 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12261
martinduke9e0811c2022-12-08 20:35:57 -080012262 connection_.SetEncrypter(
12263 ENCRYPTION_FORWARD_SECURE,
12264 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012265 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12266 // Send half RTT packet.
12267 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12268
12269 // Receives HANDSHAKE 1.
martinduke9e0811c2022-12-08 20:35:57 -080012270 peer_framer_.SetEncrypter(
12271 ENCRYPTION_HANDSHAKE,
12272 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012273 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
12274 // Discard INITIAL key.
12275 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12276 connection_.NeuterUnencryptedPackets();
12277 // Verify there is pending ACK.
12278 ASSERT_TRUE(connection_.HasPendingAcks());
12279 // Set the send alarm.
12280 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
12281
12282 // Fire ACK alarm.
12283 connection_.GetAckAlarm()->Fire();
12284 // Verify 1-RTT packet is coalesced with handshake packet.
12285 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12286 connection_.GetSendAlarm()->Fire();
12287
12288 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12289 connection_.GetRetransmissionAlarm()->Fire();
12290 // Verify a handshake packet gets PTOed and 1-RTT packet gets coalesced.
12291 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12292}
12293
12294// Regression test for b/168294218.
12295TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) {
12296 if (!connection_.version().CanSendCoalescedPackets()) {
12297 return;
12298 }
12299 SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true);
12300 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
12301 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12302 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12303 connection_.NeuterUnencryptedPackets();
12304 }));
12305 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12306
12307 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
12308 {
12309 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040012310 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
12311 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080012312 connection_.SetEncrypter(
12313 ENCRYPTION_HANDSHAKE,
12314 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012315 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12316 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
12317 // Verify this packet is on hold.
12318 EXPECT_EQ(0u, writer_->packets_write_attempts());
12319 }
12320 EXPECT_TRUE(connection_.connected());
12321}
12322
12323// Regresstion test for b/168294218
12324TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) {
12325 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12326 return;
12327 }
12328 // Not defer send in response to packet.
12329 connection_.set_defer_send_in_response_to_packets(false);
12330 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12331 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12332 connection_.NeuterUnencryptedPackets();
12333 }));
12334 EXPECT_CALL(visitor_, OnCryptoFrame(_))
12335 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
12336 if (frame.level == ENCRYPTION_HANDSHAKE) {
12337 // 0-RTT gets rejected.
12338 connection_.MarkZeroRttPacketsForRetransmission(0);
12339 // Send Crypto data.
martinduke9e0811c2022-12-08 20:35:57 -080012340 connection_.SetEncrypter(
12341 ENCRYPTION_HANDSHAKE,
12342 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012343 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12344 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080012345 connection_.SetEncrypter(
12346 ENCRYPTION_FORWARD_SECURE,
12347 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012348 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12349 // Advance INITIAL ack delay to trigger initial ACK to be sent AFTER
12350 // the retransmission of rejected 0-RTT packets while the HANDSHAKE
12351 // packet is still in the coalescer, such that the INITIAL key gets
12352 // dropped between SendAllPendingAcks and actually send the ack frame,
12353 // bummer.
12354 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12355 }
12356 }));
Bence Békybac04052022-04-07 15:44:29 -040012357 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12358 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080012359 connection_.SetEncrypter(
12360 ENCRYPTION_ZERO_RTT,
12361 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040012362 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12363 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12364
12365 QuicAckFrame frame1 = InitAckFrame(1);
12366 // Received ACK for packet 1.
12367 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
12368 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
12369 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12370
12371 // Fire retransmission alarm.
12372 connection_.GetRetransmissionAlarm()->Fire();
12373
12374 QuicFrames frames1;
12375 frames1.push_back(QuicFrame(&crypto_frame_));
12376 QuicFrames frames2;
12377 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12378 absl::string_view(data1));
12379 frames2.push_back(QuicFrame(&crypto_frame));
12380 ProcessCoalescedPacket(
12381 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
12382}
12383
12384TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) {
12385 if (!connection_.version().UsesTls()) {
12386 return;
12387 }
12388 MockQuicConnectionDebugVisitor debug_visitor;
12389 connection_.set_debug_visitor(&debug_visitor);
Bence Békybac04052022-04-07 15:44:29 -040012390 connection_.SendCryptoStreamData();
12391 // Send 0-RTT packet.
12392 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
12393 std::make_unique<TaggingEncrypter>(0x02));
12394 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12395 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12396 connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN);
12397 // Received ACK for packet 1, HANDSHAKE packet and 1-RTT ACK.
12398 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
12399 .Times(AnyNumber());
12400 QuicFrames frames1;
12401 QuicAckFrame ack_frame1 = InitAckFrame(1);
12402 frames1.push_back(QuicFrame(&ack_frame1));
12403
12404 QuicFrames frames2;
12405 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12406 absl::string_view(data1));
12407 frames2.push_back(QuicFrame(&crypto_frame));
12408 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12409 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
12410 ProcessCoalescedPacket(
12411 {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}});
12412
12413 QuicFrames frames3;
12414 QuicAckFrame ack_frame2 =
12415 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
12416 frames3.push_back(QuicFrame(&ack_frame2));
12417 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1);
12418 ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}});
12419
12420 QuicFrames frames4;
12421 QuicAckFrame ack_frame3 =
12422 InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}});
12423 frames4.push_back(QuicFrame(&ack_frame3));
12424 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12425 ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}});
12426}
12427
12428TEST_P(QuicConnectionTest, InitiateKeyUpdate) {
12429 if (!connection_.version().UsesTls()) {
12430 return;
12431 }
12432
12433 TransportParameters params;
12434 QuicConfig config;
12435 std::string error_details;
12436 EXPECT_THAT(config.ProcessTransportParameters(
12437 params, /* is_resumption = */ false, &error_details),
12438 IsQuicNoError());
12439 QuicConfigPeer::SetNegotiated(&config, true);
12440 if (connection_.version().UsesTls()) {
12441 QuicConfigPeer::SetReceivedOriginalConnectionId(
12442 &config, connection_.connection_id());
12443 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12444 &config, connection_.connection_id());
12445 }
12446 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12447 connection_.SetFromConfig(config);
12448
12449 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12450
12451 MockFramerVisitor peer_framer_visitor_;
12452 peer_framer_.set_visitor(&peer_framer_visitor_);
12453
martinduke9e0811c2022-12-08 20:35:57 -080012454 uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012455 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12456 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012457 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012458 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012459 std::make_unique<StrictTaggingDecrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012460 EXPECT_CALL(visitor_, GetHandshakeState())
12461 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12462 connection_.OnHandshakeComplete();
12463
12464 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012465 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012466
12467 // Key update should still not be allowed, since no packet has been acked
12468 // from the current key phase.
12469 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12470 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12471
12472 // Send packet 1.
12473 QuicPacketNumber last_packet;
12474 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12475 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12476
12477 // Key update should still not be allowed, even though a packet was sent in
12478 // the current key phase it hasn't been acked yet.
12479 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12480 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12481
12482 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12483 // Receive ack for packet 1.
12484 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12485 QuicAckFrame frame1 = InitAckFrame(1);
12486 ProcessAckPacket(&frame1);
12487
12488 // OnDecryptedFirstPacketInKeyPhase is called even on the first key phase,
12489 // so discard_previous_keys_alarm_ should be set now.
12490 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12491 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12492
martinduke9e0811c2022-12-08 20:35:57 -080012493 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012494 // Key update should now be allowed.
12495 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012496 .WillOnce([&correct_tag]() {
12497 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12498 });
12499 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12500 .WillOnce([&correct_tag]() {
12501 return std::make_unique<TaggingEncrypter>(correct_tag);
12502 });
Bence Békybac04052022-04-07 15:44:29 -040012503 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12504 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12505 // discard_previous_keys_alarm_ should not be set until a packet from the new
12506 // key phase has been received. (The alarm that was set above should be
12507 // cleared if it hasn't fired before the next key update happened.)
12508 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12509 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12510
12511 // Pretend that peer accepts the key update.
12512 EXPECT_CALL(peer_framer_visitor_,
12513 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012514 .WillOnce([&correct_tag]() {
12515 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12516 });
Bence Békybac04052022-04-07 15:44:29 -040012517 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012518 .WillOnce([&correct_tag]() {
12519 return std::make_unique<TaggingEncrypter>(correct_tag);
12520 });
Bence Békybac04052022-04-07 15:44:29 -040012521 peer_framer_.SetKeyUpdateSupportForConnection(true);
12522 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12523
12524 // Another key update should not be allowed yet.
12525 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12526
12527 // Send packet 2.
12528 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12529 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12530 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12531 // Receive ack for packet 2.
12532 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12533 QuicAckFrame frame2 = InitAckFrame(2);
12534 ProcessAckPacket(&frame2);
12535 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12536 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12537
martinduke9e0811c2022-12-08 20:35:57 -080012538 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012539 // Key update should be allowed again now that a packet has been acked from
12540 // the current key phase.
12541 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012542 .WillOnce([&correct_tag]() {
12543 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12544 });
12545 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12546 .WillOnce([&correct_tag]() {
12547 return std::make_unique<TaggingEncrypter>(correct_tag);
12548 });
Bence Békybac04052022-04-07 15:44:29 -040012549 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12550 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12551
12552 // Pretend that peer accepts the key update.
12553 EXPECT_CALL(peer_framer_visitor_,
12554 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012555 .WillOnce([&correct_tag]() {
12556 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12557 });
Bence Békybac04052022-04-07 15:44:29 -040012558 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012559 .WillOnce([&correct_tag]() {
12560 return std::make_unique<TaggingEncrypter>(correct_tag);
12561 });
Bence Békybac04052022-04-07 15:44:29 -040012562 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12563
12564 // Another key update should not be allowed yet.
12565 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12566
12567 // Send packet 3.
12568 SendStreamDataToPeer(3, "baz", 0, NO_FIN, &last_packet);
12569 EXPECT_EQ(QuicPacketNumber(3u), last_packet);
12570
12571 // Another key update should not be allowed yet.
12572 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12573 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12574
12575 // Receive ack for packet 3.
12576 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12577 QuicAckFrame frame3 = InitAckFrame(3);
12578 ProcessAckPacket(&frame3);
12579 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12580 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12581
martinduke9e0811c2022-12-08 20:35:57 -080012582 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012583 // Key update should be allowed now.
12584 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012585 .WillOnce([&correct_tag]() {
12586 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12587 });
12588 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12589 .WillOnce([&correct_tag]() {
12590 return std::make_unique<TaggingEncrypter>(correct_tag);
12591 });
Bence Békybac04052022-04-07 15:44:29 -040012592 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12593 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12594 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12595 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12596}
12597
12598TEST_P(QuicConnectionTest, InitiateKeyUpdateApproachingConfidentialityLimit) {
12599 if (!connection_.version().UsesTls()) {
12600 return;
12601 }
12602
birenroyef686222022-09-12 11:34:34 -070012603 SetQuicFlag(quic_key_update_confidentiality_limit, 3U);
Bence Békybac04052022-04-07 15:44:29 -040012604
12605 std::string error_details;
12606 TransportParameters params;
12607 // Key update is enabled.
12608 QuicConfig config;
12609 EXPECT_THAT(config.ProcessTransportParameters(
12610 params, /* is_resumption = */ false, &error_details),
12611 IsQuicNoError());
12612 QuicConfigPeer::SetNegotiated(&config, true);
12613 if (connection_.version().UsesTls()) {
12614 QuicConfigPeer::SetReceivedOriginalConnectionId(
12615 &config, connection_.connection_id());
12616 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12617 &config, connection_.connection_id());
12618 }
12619 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12620 connection_.SetFromConfig(config);
12621
12622 MockFramerVisitor peer_framer_visitor_;
12623 peer_framer_.set_visitor(&peer_framer_visitor_);
12624
martinduke9e0811c2022-12-08 20:35:57 -080012625 uint8_t current_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012626
12627 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12628 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12629 std::make_unique<TaggingEncrypter>(current_tag));
12630 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12631 std::make_unique<StrictTaggingDecrypter>(current_tag));
12632 EXPECT_CALL(visitor_, GetHandshakeState())
12633 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12634 connection_.OnHandshakeComplete();
12635
12636 peer_framer_.SetKeyUpdateSupportForConnection(true);
12637 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12638 std::make_unique<TaggingEncrypter>(current_tag));
12639
12640 const QuicConnectionStats& stats = connection_.GetStats();
12641
12642 for (int packet_num = 1; packet_num <= 8; ++packet_num) {
12643 if (packet_num == 3 || packet_num == 6) {
12644 current_tag++;
12645 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12646 .WillOnce([current_tag]() {
12647 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12648 });
12649 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12650 .WillOnce([current_tag]() {
12651 return std::make_unique<TaggingEncrypter>(current_tag);
12652 });
12653 EXPECT_CALL(visitor_,
12654 OnKeyUpdate(KeyUpdateReason::kLocalKeyUpdateLimitOverride));
12655 }
12656 // Send packet.
12657 QuicPacketNumber last_packet;
12658 SendStreamDataToPeer(packet_num, "foo", 0, NO_FIN, &last_packet);
12659 EXPECT_EQ(QuicPacketNumber(packet_num), last_packet);
12660 if (packet_num >= 6) {
12661 EXPECT_EQ(2U, stats.key_update_count);
12662 } else if (packet_num >= 3) {
12663 EXPECT_EQ(1U, stats.key_update_count);
12664 } else {
12665 EXPECT_EQ(0U, stats.key_update_count);
12666 }
12667
12668 if (packet_num == 4 || packet_num == 7) {
12669 // Pretend that peer accepts the key update.
12670 EXPECT_CALL(peer_framer_visitor_,
12671 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12672 .WillOnce([current_tag]() {
12673 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12674 });
12675 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12676 .WillOnce([current_tag]() {
12677 return std::make_unique<TaggingEncrypter>(current_tag);
12678 });
12679 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12680 }
12681 // Receive ack for packet.
12682 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12683 QuicAckFrame frame1 = InitAckFrame(packet_num);
12684 ProcessAckPacket(&frame1);
12685 }
12686}
12687
12688TEST_P(QuicConnectionTest,
12689 CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed) {
12690 if (!connection_.version().UsesTls()) {
12691 return;
12692 }
12693
12694 // Set key update confidentiality limit to 1 packet.
birenroyef686222022-09-12 11:34:34 -070012695 SetQuicFlag(quic_key_update_confidentiality_limit, 1U);
Bence Békybac04052022-04-07 15:44:29 -040012696 // Use confidentiality limit for connection close of 3 packets.
12697 constexpr size_t kConfidentialityLimit = 3U;
12698
12699 std::string error_details;
12700 TransportParameters params;
12701 // Key update is enabled.
12702 QuicConfig config;
12703 EXPECT_THAT(config.ProcessTransportParameters(
12704 params, /* is_resumption = */ false, &error_details),
12705 IsQuicNoError());
12706 QuicConfigPeer::SetNegotiated(&config, true);
12707 if (connection_.version().UsesTls()) {
12708 QuicConfigPeer::SetReceivedOriginalConnectionId(
12709 &config, connection_.connection_id());
12710 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12711 &config, connection_.connection_id());
12712 }
12713 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12714 connection_.SetFromConfig(config);
12715
12716 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12717 connection_.SetEncrypter(
12718 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012719 std::make_unique<TaggingEncrypterWithConfidentialityLimit>(
12720 ENCRYPTION_FORWARD_SECURE, kConfidentialityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012721 EXPECT_CALL(visitor_, GetHandshakeState())
12722 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12723 connection_.OnHandshakeComplete();
12724
12725 QuicPacketNumber last_packet;
12726 // Send 3 packets without receiving acks for any of them. Key update will not
12727 // be allowed, so the confidentiality limit should be reached, forcing the
12728 // connection to be closed.
12729 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12730 EXPECT_TRUE(connection_.connected());
12731 SendStreamDataToPeer(2, "foo", 0, NO_FIN, &last_packet);
12732 EXPECT_TRUE(connection_.connected());
12733 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12734 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
12735 EXPECT_FALSE(connection_.connected());
12736 const QuicConnectionStats& stats = connection_.GetStats();
12737 EXPECT_EQ(0U, stats.key_update_count);
12738 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12739}
12740
12741TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitDuringHandshake) {
12742 if (!connection_.version().UsesTls()) {
12743 return;
12744 }
12745
martinduke9e0811c2022-12-08 20:35:57 -080012746 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012747 constexpr uint8_t wrong_tag = 0xFE;
12748 constexpr QuicPacketCount kIntegrityLimit = 3;
12749
12750 SetDecrypter(ENCRYPTION_HANDSHAKE,
12751 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12752 correct_tag, kIntegrityLimit));
12753 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12754 std::make_unique<TaggingEncrypter>(correct_tag));
12755 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12756 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12757 std::make_unique<TaggingEncrypter>(wrong_tag));
12758 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12759 EXPECT_TRUE(connection_.connected());
12760 if (i == kIntegrityLimit) {
12761 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12762 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
12763 }
12764 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12765 EXPECT_EQ(
12766 i, connection_.GetStats().num_failed_authentication_packets_received);
12767 }
12768 EXPECT_FALSE(connection_.connected());
12769 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12770}
12771
12772TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAfterHandshake) {
12773 if (!connection_.version().UsesTls()) {
12774 return;
12775 }
12776
martinduke9e0811c2022-12-08 20:35:57 -080012777 constexpr uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012778 constexpr uint8_t wrong_tag = 0xFE;
12779 constexpr QuicPacketCount kIntegrityLimit = 3;
12780
Bence Békybac04052022-04-07 15:44:29 -040012781 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12782 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12783 correct_tag, kIntegrityLimit));
12784 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12785 std::make_unique<TaggingEncrypter>(correct_tag));
12786 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12787 EXPECT_CALL(visitor_, GetHandshakeState())
12788 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12789 connection_.OnHandshakeComplete();
12790 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12791 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12792 std::make_unique<TaggingEncrypter>(wrong_tag));
12793 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12794 EXPECT_TRUE(connection_.connected());
12795 if (i == kIntegrityLimit) {
12796 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12797 }
12798 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12799 EXPECT_EQ(
12800 i, connection_.GetStats().num_failed_authentication_packets_received);
12801 }
12802 EXPECT_FALSE(connection_.connected());
12803 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12804}
12805
12806TEST_P(QuicConnectionTest,
12807 CloseConnectionOnIntegrityLimitAcrossEncryptionLevels) {
12808 if (!connection_.version().UsesTls()) {
12809 return;
12810 }
12811
martinduke9e0811c2022-12-08 20:35:57 -080012812 uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012813 constexpr uint8_t wrong_tag = 0xFE;
12814 constexpr QuicPacketCount kIntegrityLimit = 4;
12815
Bence Békybac04052022-04-07 15:44:29 -040012816 SetDecrypter(ENCRYPTION_HANDSHAKE,
12817 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12818 correct_tag, kIntegrityLimit));
12819 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12820 std::make_unique<TaggingEncrypter>(correct_tag));
12821 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12822 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12823 std::make_unique<TaggingEncrypter>(wrong_tag));
12824 for (uint64_t i = 1; i <= 2; ++i) {
12825 EXPECT_TRUE(connection_.connected());
12826 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12827 EXPECT_EQ(
12828 i, connection_.GetStats().num_failed_authentication_packets_received);
12829 }
12830
martinduke9e0811c2022-12-08 20:35:57 -080012831 correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012832 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12833 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12834 correct_tag, kIntegrityLimit));
12835 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12836 std::make_unique<TaggingEncrypter>(correct_tag));
12837 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12838 EXPECT_CALL(visitor_, GetHandshakeState())
12839 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12840 connection_.OnHandshakeComplete();
12841 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12842 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
12843 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12844 std::make_unique<TaggingEncrypter>(wrong_tag));
12845 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12846 EXPECT_TRUE(connection_.connected());
12847 if (i == kIntegrityLimit) {
12848 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12849 }
12850 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12851 EXPECT_EQ(
12852 i, connection_.GetStats().num_failed_authentication_packets_received);
12853 }
12854 EXPECT_FALSE(connection_.connected());
12855 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12856}
12857
12858TEST_P(QuicConnectionTest, IntegrityLimitDoesNotApplyWithoutDecryptionKey) {
12859 if (!connection_.version().UsesTls()) {
12860 return;
12861 }
12862
martinduke9e0811c2022-12-08 20:35:57 -080012863 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012864 constexpr uint8_t wrong_tag = 0xFE;
12865 constexpr QuicPacketCount kIntegrityLimit = 3;
12866
Bence Békybac04052022-04-07 15:44:29 -040012867 SetDecrypter(ENCRYPTION_HANDSHAKE,
12868 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12869 correct_tag, kIntegrityLimit));
12870 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12871 std::make_unique<TaggingEncrypter>(correct_tag));
12872 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12873 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
12874
12875 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12876 std::make_unique<TaggingEncrypter>(wrong_tag));
12877 for (uint64_t i = 1; i <= kIntegrityLimit * 2; ++i) {
12878 EXPECT_TRUE(connection_.connected());
12879 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12880 EXPECT_EQ(
12881 0u, connection_.GetStats().num_failed_authentication_packets_received);
12882 }
12883 EXPECT_TRUE(connection_.connected());
12884}
12885
12886TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossKeyPhases) {
12887 if (!connection_.version().UsesTls()) {
12888 return;
12889 }
12890
12891 constexpr QuicPacketCount kIntegrityLimit = 4;
12892
12893 TransportParameters params;
12894 QuicConfig config;
12895 std::string error_details;
12896 EXPECT_THAT(config.ProcessTransportParameters(
12897 params, /* is_resumption = */ false, &error_details),
12898 IsQuicNoError());
12899 QuicConfigPeer::SetNegotiated(&config, true);
12900 if (connection_.version().UsesTls()) {
12901 QuicConfigPeer::SetReceivedOriginalConnectionId(
12902 &config, connection_.connection_id());
12903 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12904 &config, connection_.connection_id());
12905 }
12906 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12907 connection_.SetFromConfig(config);
12908
12909 MockFramerVisitor peer_framer_visitor_;
12910 peer_framer_.set_visitor(&peer_framer_visitor_);
12911
Bence Békybac04052022-04-07 15:44:29 -040012912 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12913 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12914 std::make_unique<TaggingEncrypter>(0x01));
12915 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12916 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
martinduke9e0811c2022-12-08 20:35:57 -080012917 ENCRYPTION_FORWARD_SECURE, kIntegrityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012918 EXPECT_CALL(visitor_, GetHandshakeState())
12919 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12920 connection_.OnHandshakeComplete();
12921 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12922
12923 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12924 std::make_unique<TaggingEncrypter>(0xFF));
12925 for (uint64_t i = 1; i <= 2; ++i) {
12926 EXPECT_TRUE(connection_.connected());
12927 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12928 EXPECT_EQ(
12929 i, connection_.GetStats().num_failed_authentication_packets_received);
12930 }
12931
martinduke9e0811c2022-12-08 20:35:57 -080012932 peer_framer_.SetEncrypter(
12933 ENCRYPTION_FORWARD_SECURE,
12934 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012935 // Send packet 1.
12936 QuicPacketNumber last_packet;
12937 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12938 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12939 // Receive ack for packet 1.
12940 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12941 QuicAckFrame frame1 = InitAckFrame(1);
12942 ProcessAckPacket(&frame1);
12943 // Key update should now be allowed, initiate it.
12944 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12945 .WillOnce([kIntegrityLimit]() {
12946 return std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12947 0x02, kIntegrityLimit);
12948 });
12949 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12950 return std::make_unique<TaggingEncrypter>(0x02);
12951 });
12952 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12953 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12954
12955 // Pretend that peer accepts the key update.
12956 EXPECT_CALL(peer_framer_visitor_,
12957 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12958 .WillOnce(
12959 []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
12960 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12961 .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); });
12962 peer_framer_.SetKeyUpdateSupportForConnection(true);
12963 peer_framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests);
12964
12965 // Send packet 2.
12966 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12967 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12968 // Receive ack for packet 2.
12969 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12970 QuicAckFrame frame2 = InitAckFrame(2);
12971 ProcessAckPacket(&frame2);
12972
12973 EXPECT_EQ(2u,
12974 connection_.GetStats().num_failed_authentication_packets_received);
12975
12976 // Do two more undecryptable packets. Integrity limit should be reached.
12977 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12978 std::make_unique<TaggingEncrypter>(0xFF));
12979 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12980 EXPECT_TRUE(connection_.connected());
12981 if (i == kIntegrityLimit) {
12982 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12983 }
12984 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12985 EXPECT_EQ(
12986 i, connection_.GetStats().num_failed_authentication_packets_received);
12987 }
12988 EXPECT_FALSE(connection_.connected());
12989 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12990}
12991
12992TEST_P(QuicConnectionTest, SendAckFrequencyFrame) {
12993 if (!version().HasIetfQuicFrames()) {
12994 return;
12995 }
12996 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12997 set_perspective(Perspective::IS_SERVER);
12998 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
12999 .Times(AnyNumber());
13000 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
13001
13002 QuicConfig config;
13003 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13004 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13005 connection_.SetFromConfig(config);
13006 QuicConnectionPeer::SetAddressValidated(&connection_);
13007 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13008 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
13009
13010 connection_.OnHandshakeComplete();
13011
13012 writer_->SetWritable();
13013 QuicPacketCreatorPeer::SetPacketNumber(creator_, 99);
13014 // Send packet 100
13015 SendStreamDataToPeer(/*id=*/1, "foo", /*offset=*/0, NO_FIN, nullptr);
13016
13017 QuicAckFrequencyFrame captured_frame;
13018 EXPECT_CALL(visitor_, SendAckFrequency(_))
13019 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
13020 captured_frame = frame;
13021 }));
13022 // Send packet 101.
13023 SendStreamDataToPeer(/*id=*/1, "bar", /*offset=*/3, NO_FIN, nullptr);
13024
13025 EXPECT_EQ(captured_frame.packet_tolerance, 10u);
13026 EXPECT_EQ(captured_frame.max_ack_delay,
13027 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
13028
13029 // Sending packet 102 does not trigger sending another AckFrequencyFrame.
13030 SendStreamDataToPeer(/*id=*/1, "baz", /*offset=*/6, NO_FIN, nullptr);
13031}
13032
13033TEST_P(QuicConnectionTest, SendAckFrequencyFrameUponHandshakeCompletion) {
13034 if (!version().HasIetfQuicFrames()) {
13035 return;
13036 }
13037 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13038 set_perspective(Perspective::IS_SERVER);
13039 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
13040 .Times(AnyNumber());
13041 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
13042
13043 QuicConfig config;
13044 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13045 QuicTagVector quic_tag_vector;
13046 // Enable sending AckFrequency upon handshake completion.
13047 quic_tag_vector.push_back(kAFF2);
13048 QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector);
13049 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13050 connection_.SetFromConfig(config);
13051 QuicConnectionPeer::SetAddressValidated(&connection_);
13052 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13053 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
13054
13055 QuicAckFrequencyFrame captured_frame;
13056 EXPECT_CALL(visitor_, SendAckFrequency(_))
13057 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
13058 captured_frame = frame;
13059 }));
13060
13061 connection_.OnHandshakeComplete();
13062
13063 EXPECT_EQ(captured_frame.packet_tolerance, 2u);
13064 EXPECT_EQ(captured_frame.max_ack_delay,
13065 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
13066}
13067
13068TEST_P(QuicConnectionTest, FastRecoveryOfLostServerHello) {
13069 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
13070 return;
13071 }
13072 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13073 QuicConfig config;
13074 connection_.SetFromConfig(config);
13075
Bence Békybac04052022-04-07 15:44:29 -040013076 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13077 connection_.SendCryptoStreamData();
13078 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13079
13080 // Assume ServerHello gets lost.
13081 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13082 std::make_unique<TaggingEncrypter>(0x02));
13083 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13084 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
13085 // Shorten PTO for fast recovery from lost ServerHello.
13086 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
13087 connection_.GetRetransmissionAlarm()->deadline());
13088}
13089
13090TEST_P(QuicConnectionTest, ServerHelloGetsReordered) {
13091 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
13092 return;
13093 }
13094 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13095 QuicConfig config;
13096 connection_.SetFromConfig(config);
13097 EXPECT_CALL(visitor_, OnCryptoFrame(_))
13098 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
13099 if (frame.level == ENCRYPTION_INITIAL) {
13100 // Install handshake read keys.
martinduke9e0811c2022-12-08 20:35:57 -080013101 SetDecrypter(
13102 ENCRYPTION_HANDSHAKE,
13103 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
13104 connection_.SetEncrypter(
13105 ENCRYPTION_HANDSHAKE,
13106 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040013107 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
13108 }
13109 }));
13110
Bence Békybac04052022-04-07 15:44:29 -040013111 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
13112 connection_.SendCryptoStreamData();
13113 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
13114
13115 // Assume ServerHello gets reordered.
13116 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
13117 std::make_unique<TaggingEncrypter>(0x02));
13118 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
13119 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
13120 // Verify fast recovery is not enabled.
13121 EXPECT_EQ(connection_.sent_packet_manager().GetRetransmissionTime(),
13122 connection_.GetRetransmissionAlarm()->deadline());
13123}
13124
13125TEST_P(QuicConnectionTest, MigratePath) {
13126 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
13139 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13140 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
13141 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
13142 &new_writer, /*owns_writer=*/false);
13143
13144 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13145 EXPECT_EQ(&new_writer, QuicConnectionPeer::GetWriter(&connection_));
13146 EXPECT_FALSE(connection_.IsPathDegrading());
13147 // Buffered packet on the old path should be discarded.
13148 if (connection_.connection_migration_use_new_cid()) {
13149 EXPECT_EQ(0u, connection_.NumQueuedPackets());
13150 } else {
13151 EXPECT_EQ(1u, connection_.NumQueuedPackets());
13152 }
13153}
13154
13155TEST_P(QuicConnectionTest, MigrateToNewPathDuringProbing) {
danzh87605712022-04-11 14:36:39 -070013156 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040013157 return;
13158 }
13159 PathProbeTestInit(Perspective::IS_CLIENT);
13160 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13161 EXPECT_NE(kNewSelfAddress, connection_.self_address());
13162 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13163 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13164 bool success = false;
13165 connection_.ValidatePath(
13166 std::make_unique<TestQuicPathValidationContext>(
13167 kNewSelfAddress, connection_.peer_address(), &new_writer),
13168 std::make_unique<TestValidationResultDelegate>(
13169 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
13170 EXPECT_TRUE(connection_.HasPendingPathValidation());
13171 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13172 &connection_, kNewSelfAddress, connection_.peer_address()));
13173
13174 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
13175 &new_writer, /*owns_writer=*/false);
13176 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13177 EXPECT_TRUE(connection_.HasPendingPathValidation());
13178 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13179 &connection_, kNewSelfAddress, connection_.peer_address()));
13180}
13181
renjietang89540a62022-12-01 14:46:26 -080013182TEST_P(QuicConnectionTest, MultiPortConnection) {
renjietangfca5c772022-08-25 13:48:21 -070013183 set_perspective(Perspective::IS_CLIENT);
13184 QuicConfig config;
renjietang89540a62022-12-01 14:46:26 -080013185 config.SetConnectionOptionsToSend(QuicTagVector{kRVCM});
13186 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
renjietangfca5c772022-08-25 13:48:21 -070013187 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13188 connection_.SetFromConfig(config);
13189 if (!connection_.connection_migration_use_new_cid()) {
13190 return;
13191 }
13192 connection_.CreateConnectionIdManager();
13193 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13194 connection_.OnHandshakeComplete();
13195
renjietang864fbda2022-09-08 10:50:07 -070013196 EXPECT_CALL(visitor_, OnPathDegrading());
13197 connection_.OnPathDegradingDetected();
13198
renjietangfca5c772022-08-25 13:48:21 -070013199 auto self_address = connection_.self_address();
13200 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13201 self_address.port() + 1);
13202 EXPECT_NE(kNewSelfAddress, self_address);
13203 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13204
renjietang89540a62022-12-01 14:46:26 -080013205 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
renjietangfca5c772022-08-25 13:48:21 -070013206 QuicNewConnectionIdFrame frame;
13207 frame.connection_id = TestConnectionId(1234);
13208 ASSERT_NE(frame.connection_id, connection_.connection_id());
13209 frame.stateless_reset_token =
13210 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13211 frame.retire_prior_to = 0u;
13212 frame.sequence_number = 1u;
13213 EXPECT_CALL(visitor_, CreateContextForMultiPortPath())
13214 .WillRepeatedly(Return(
13215 testing::ByMove(std::make_unique<TestQuicPathValidationContext>(
13216 kNewSelfAddress, connection_.peer_address(), &new_writer))));
13217 connection_.OnNewConnectionIdFrame(frame);
13218 EXPECT_TRUE(connection_.HasPendingPathValidation());
13219 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13220 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013221 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13222 EXPECT_FALSE(alt_path->validated);
renjietangfca5c772022-08-25 13:48:21 -070013223
renjietang864fbda2022-09-08 10:50:07 -070013224 // 30ms RTT.
13225 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13226 // Fake a response delay.
13227 clock_.AdvanceTime(kTestRTT);
13228
renjietangfca5c772022-08-25 13:48:21 -070013229 QuicFrames frames;
13230 frames.push_back(QuicFrame(QuicPathResponseFrame(
renjietang89540a62022-12-01 14:46:26 -080013231 99, new_writer.path_challenge_frames().back().data_buffer)));
renjietangfca5c772022-08-25 13:48:21 -070013232 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13233 ENCRYPTION_FORWARD_SECURE);
13234 // No migration should happen and the alternative path should still be alive.
13235 EXPECT_FALSE(connection_.HasPendingPathValidation());
13236 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13237 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013238 EXPECT_TRUE(alt_path->validated);
renjietangfca5c772022-08-25 13:48:21 -070013239
renjietang864fbda2022-09-08 10:50:07 -070013240 auto stats = connection_.multi_port_stats();
13241 EXPECT_EQ(1, stats->num_path_degrading);
13242 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13243 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13244 EXPECT_EQ(kTestRTT,
13245 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13246
renjietang89540a62022-12-01 14:46:26 -080013247 // When there's no active request, the probing shouldn't happen. But the
13248 // probing context should be saved.
13249 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
13250 connection_.GetMultiPortProbingAlarm()->Fire();
13251 EXPECT_FALSE(connection_.HasPendingPathValidation());
13252 EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13253
13254 // Simulate the situation where a new request stream is created.
13255 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13256 .WillRepeatedly(Return(true));
13257 random_generator_.ChangeValue();
13258 connection_.MaybeProbeMultiPortPath();
13259 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13260 &connection_, kNewSelfAddress, connection_.peer_address()));
13261 EXPECT_TRUE(alt_path->validated);
13262 // Fake a response delay.
13263 clock_.AdvanceTime(kTestRTT);
13264 QuicFrames frames2;
13265 frames2.push_back(QuicFrame(QuicPathResponseFrame(
13266 99, new_writer.path_challenge_frames().back().data_buffer)));
13267 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress, kPeerAddress,
13268 ENCRYPTION_FORWARD_SECURE);
13269 // No migration should happen and the alternative path should still be alive.
13270 EXPECT_FALSE(connection_.HasPendingPathValidation());
13271 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13272 &connection_, kNewSelfAddress, connection_.peer_address()));
13273 EXPECT_TRUE(alt_path->validated);
13274 EXPECT_EQ(1, stats->num_path_degrading);
13275 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13276 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13277 EXPECT_EQ(kTestRTT,
13278 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13279
13280 EXPECT_TRUE(connection_.GetMultiPortProbingAlarm()->IsSet());
13281 // Since there's already a scheduled probing alarm, manual calls won't have
13282 // any effect.
13283 connection_.MaybeProbeMultiPortPath();
13284 EXPECT_FALSE(connection_.HasPendingPathValidation());
13285
13286 // Simulate the case where the path validation fails after retries.
renjietangfca5c772022-08-25 13:48:21 -070013287 connection_.GetMultiPortProbingAlarm()->Fire();
13288 EXPECT_TRUE(connection_.HasPendingPathValidation());
13289 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13290 &connection_, kNewSelfAddress, connection_.peer_address()));
13291 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13292 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13293 static_cast<TestAlarmFactory::TestAlarm*>(
13294 QuicPathValidatorPeer::retry_timer(
13295 QuicConnectionPeer::path_validator(&connection_)))
13296 ->Fire();
13297 }
13298
13299 EXPECT_FALSE(connection_.HasPendingPathValidation());
13300 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13301 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang864fbda2022-09-08 10:50:07 -070013302 EXPECT_EQ(1, stats->num_path_degrading);
13303 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13304 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_not_degrading);
renjietangfca5c772022-08-25 13:48:21 -070013305}
13306
renjietang89540a62022-12-01 14:46:26 -080013307TEST_P(QuicConnectionTest, TooManyMultiPortPathCreations) {
13308 set_perspective(Perspective::IS_CLIENT);
13309 QuicConfig config;
13310 config.SetConnectionOptionsToSend(QuicTagVector{kRVCM});
13311 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13312 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13313 connection_.SetFromConfig(config);
13314 if (!connection_.connection_migration_use_new_cid()) {
13315 return;
13316 }
13317 connection_.CreateConnectionIdManager();
13318 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13319 connection_.OnHandshakeComplete();
13320
13321 EXPECT_CALL(visitor_, OnPathDegrading());
13322 connection_.OnPathDegradingDetected();
13323
13324 auto self_address = connection_.self_address();
13325 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13326 self_address.port() + 1);
13327 EXPECT_NE(kNewSelfAddress, self_address);
13328 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13329
13330 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13331 .WillRepeatedly(Return(true));
13332
13333 QuicNewConnectionIdFrame frame;
13334 frame.connection_id = TestConnectionId(1234);
13335 ASSERT_NE(frame.connection_id, connection_.connection_id());
13336 frame.stateless_reset_token =
13337 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13338 frame.retire_prior_to = 0u;
13339 frame.sequence_number = 1u;
13340 EXPECT_CALL(visitor_, CreateContextForMultiPortPath())
13341 .WillRepeatedly(Return(
13342 testing::ByMove(std::make_unique<TestQuicPathValidationContext>(
13343 kNewSelfAddress, connection_.peer_address(), &new_writer))));
13344 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13345 EXPECT_TRUE(connection_.HasPendingPathValidation());
13346 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13347 &connection_, kNewSelfAddress, connection_.peer_address()));
13348 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13349 EXPECT_FALSE(alt_path->validated);
13350
13351 EXPECT_TRUE(connection_.HasPendingPathValidation());
13352 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13353 &connection_, kNewSelfAddress, connection_.peer_address()));
13354 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13355 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13356 static_cast<TestAlarmFactory::TestAlarm*>(
13357 QuicPathValidatorPeer::retry_timer(
13358 QuicConnectionPeer::path_validator(&connection_)))
13359 ->Fire();
13360 }
13361
13362 auto stats = connection_.multi_port_stats();
13363 EXPECT_FALSE(connection_.HasPendingPathValidation());
13364 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13365 &connection_, kNewSelfAddress, connection_.peer_address()));
13366 EXPECT_EQ(1, stats->num_path_degrading);
13367 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13368
13369 uint64_t connection_id = 1235;
13370 for (size_t i = 0; i < kMaxNumMultiPortPaths - 1; ++i) {
13371 QuicNewConnectionIdFrame frame;
13372 frame.connection_id = TestConnectionId(connection_id + i);
13373 ASSERT_NE(frame.connection_id, connection_.connection_id());
13374 frame.stateless_reset_token =
13375 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13376 frame.retire_prior_to = 0u;
13377 frame.sequence_number = i + 2;
13378 EXPECT_CALL(visitor_, CreateContextForMultiPortPath())
13379 .WillRepeatedly(Return(
13380 testing::ByMove(std::make_unique<TestQuicPathValidationContext>(
13381 kNewSelfAddress, connection_.peer_address(), &new_writer))));
13382 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13383 EXPECT_TRUE(connection_.HasPendingPathValidation());
13384 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13385 &connection_, kNewSelfAddress, connection_.peer_address()));
13386 EXPECT_FALSE(alt_path->validated);
13387
13388 for (size_t j = 0; j < QuicPathValidator::kMaxRetryTimes + 1; ++j) {
13389 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13390 static_cast<TestAlarmFactory::TestAlarm*>(
13391 QuicPathValidatorPeer::retry_timer(
13392 QuicConnectionPeer::path_validator(&connection_)))
13393 ->Fire();
13394 }
13395
13396 EXPECT_FALSE(connection_.HasPendingPathValidation());
13397 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13398 &connection_, kNewSelfAddress, connection_.peer_address()));
13399 EXPECT_EQ(1, stats->num_path_degrading);
13400 EXPECT_EQ(i + 2, stats->num_multi_port_probe_failures_when_path_degrading);
13401 }
13402
13403 // The 6th attemp should fail.
13404 QuicNewConnectionIdFrame frame2;
13405 frame2.connection_id = TestConnectionId(1239);
13406 ASSERT_NE(frame2.connection_id, connection_.connection_id());
13407 frame2.stateless_reset_token =
13408 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
13409 frame2.retire_prior_to = 0u;
13410 frame2.sequence_number = 6u;
13411 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame2));
13412 EXPECT_FALSE(connection_.HasPendingPathValidation());
13413 EXPECT_EQ(kMaxNumMultiPortPaths,
13414 stats->num_multi_port_probe_failures_when_path_degrading);
13415}
13416
Bence Békybac04052022-04-07 15:44:29 -040013417TEST_P(QuicConnectionTest, SingleAckInPacket) {
13418 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13419 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13420 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13421 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13422 connection_.NeuterUnencryptedPackets();
13423 connection_.OnHandshakeComplete();
13424 EXPECT_CALL(visitor_, GetHandshakeState())
13425 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13426
13427 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13428 connection_.SendStreamData3();
13429 connection_.CloseConnection(
13430 QUIC_INTERNAL_ERROR, "error",
13431 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
13432 }));
13433 QuicFrames frames;
13434 frames.push_back(QuicFrame(frame1_));
13435 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
13436 ENCRYPTION_FORWARD_SECURE);
13437 ASSERT_FALSE(writer_->ack_frames().empty());
13438 EXPECT_EQ(1u, writer_->ack_frames().size());
13439}
13440
13441TEST_P(QuicConnectionTest,
13442 ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey) {
13443 if (!connection_.version().UsesTls()) {
13444 return;
13445 }
13446
13447 set_perspective(Perspective::IS_SERVER);
13448 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080013449 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040013450
13451 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13452 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13453
13454 // Finish handshake.
13455 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13456 notifier_.NeuterUnencryptedData();
13457 connection_.NeuterUnencryptedPackets();
13458 connection_.OnHandshakeComplete();
13459 EXPECT_CALL(visitor_, GetHandshakeState())
13460 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13461
13462 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13463 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13464 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13465
13466 // 0-RTT packet received out of order should be decoded since the decrypter
13467 // is temporarily retained.
13468 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13469 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13470 EXPECT_EQ(
13471 0u,
13472 connection_.GetStats()
13473 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13474
13475 // Simulate the timeout for discarding 0-RTT keys passing.
13476 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
13477
13478 // Another 0-RTT packet received now should not be decoded.
13479 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13480 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
13481 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13482 EXPECT_EQ(
13483 1u,
13484 connection_.GetStats()
13485 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13486
13487 // The |discard_zero_rtt_decryption_keys_alarm_| should only be set on the
13488 // first 1-RTT packet received.
13489 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13490 ProcessDataPacketAtLevel(5, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13491 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13492}
13493
13494TEST_P(QuicConnectionTest, NewTokenFrameInstigateAcks) {
13495 if (!version().HasIetfQuicFrames()) {
13496 return;
13497 }
13498 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13499
13500 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13501 EXPECT_CALL(visitor_, OnNewTokenReceived(_));
13502 ProcessFramePacket(QuicFrame(new_token));
13503
13504 // Ensure that this has caused the ACK alarm to be set.
13505 EXPECT_TRUE(connection_.HasPendingAcks());
13506}
13507
13508TEST_P(QuicConnectionTest, ServerClosesConnectionOnNewTokenFrame) {
13509 if (!version().HasIetfQuicFrames()) {
13510 return;
13511 }
13512 set_perspective(Perspective::IS_SERVER);
13513 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13514 EXPECT_CALL(visitor_, OnNewTokenReceived(_)).Times(0);
13515 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13516 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13517 ProcessFramePacket(QuicFrame(new_token));
13518 EXPECT_FALSE(connection_.connected());
13519}
13520
13521TEST_P(QuicConnectionTest, OverrideRetryTokenWithRetryPacket) {
13522 if (!version().HasIetfQuicFrames()) {
13523 return;
13524 }
13525 std::string address_token = "TestAddressToken";
13526 connection_.SetSourceAddressTokenToSend(address_token);
13527 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13528 QuicConnectionPeer::GetPacketCreator(&connection_)),
13529 address_token);
13530 // Passes valid retry and verify token gets overridden.
13531 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13532 /*missing_original_id_in_config=*/false,
13533 /*wrong_original_id_in_config=*/false,
13534 /*missing_retry_id_in_config=*/false,
13535 /*wrong_retry_id_in_config=*/false);
13536}
13537
13538TEST_P(QuicConnectionTest, DonotOverrideRetryTokenWithAddressToken) {
13539 if (!version().HasIetfQuicFrames()) {
13540 return;
13541 }
13542 // Passes valid retry and verify token gets overridden.
13543 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13544 /*missing_original_id_in_config=*/false,
13545 /*wrong_original_id_in_config=*/false,
13546 /*missing_retry_id_in_config=*/false,
13547 /*wrong_retry_id_in_config=*/false);
13548 std::string retry_token = QuicPacketCreatorPeer::GetRetryToken(
13549 QuicConnectionPeer::GetPacketCreator(&connection_));
13550
13551 std::string address_token = "TestAddressToken";
13552 connection_.SetSourceAddressTokenToSend(address_token);
13553 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13554 QuicConnectionPeer::GetPacketCreator(&connection_)),
13555 retry_token);
13556}
13557
13558TEST_P(QuicConnectionTest,
13559 ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt) {
13560 if (!connection_.version().UsesTls()) {
13561 return;
13562 }
13563
13564 // The code that checks for this error piggybacks on some book-keeping state
13565 // kept for key update, so enable key update for the test.
13566 std::string error_details;
13567 TransportParameters params;
13568 QuicConfig config;
13569 EXPECT_THAT(config.ProcessTransportParameters(
13570 params, /* is_resumption = */ false, &error_details),
13571 IsQuicNoError());
13572 QuicConfigPeer::SetNegotiated(&config, true);
13573 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
13574 connection_.connection_id());
13575 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
13576 &config, connection_.connection_id());
13577 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13578 connection_.SetFromConfig(config);
13579
13580 set_perspective(Perspective::IS_SERVER);
13581 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080013582 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040013583
13584 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13585 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13586
13587 // Finish handshake.
13588 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13589 notifier_.NeuterUnencryptedData();
13590 connection_.NeuterUnencryptedPackets();
13591 connection_.OnHandshakeComplete();
13592 EXPECT_CALL(visitor_, GetHandshakeState())
13593 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13594
13595 // Decrypt a 1-RTT packet.
13596 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13597 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13598 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13599
13600 // 0-RTT packet with higher packet number than a 1-RTT packet is invalid and
13601 // should cause the connection to be closed.
13602 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13603 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13604 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13605 EXPECT_FALSE(connection_.connected());
13606 TestConnectionCloseQuicErrorCode(
13607 QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
13608}
13609
13610// Regression test for b/177312785
13611TEST_P(QuicConnectionTest, PeerMigrateBeforeHandshakeConfirm) {
13612 if (!VersionHasIetfQuicFrames(version().transport_version)) {
13613 return;
13614 }
13615 set_perspective(Perspective::IS_SERVER);
13616 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
13617 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
13618 EXPECT_CALL(visitor_, GetHandshakeState())
13619 .WillRepeatedly(Return(HANDSHAKE_START));
13620
13621 // Clear direct_peer_address.
13622 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
13623 // Clear effective_peer_address, it is the same as direct_peer_address for
13624 // this test.
13625 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
13626 QuicSocketAddress());
13627 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
13628
13629 const QuicSocketAddress kNewPeerAddress =
13630 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
13631 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
13632 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
13633 ENCRYPTION_INITIAL);
13634 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13635 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13636
13637 // Process another packet with a different peer address on server side will
13638 // close connection.
13639 QuicAckFrame frame = InitAckFrame(1);
13640 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13641 EXPECT_CALL(visitor_,
13642 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
13643 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
13644
13645 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _)).Times(0);
13646 ProcessFramePacketWithAddresses(QuicFrame(&frame), kSelfAddress,
13647 kNewPeerAddress, ENCRYPTION_INITIAL);
13648 EXPECT_FALSE(connection_.connected());
13649}
13650
13651// Regresstion test for b/175685916
13652TEST_P(QuicConnectionTest, TryToFlushAckWithAckQueued) {
13653 if (!version().HasIetfQuicFrames()) {
13654 return;
13655 }
13656 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13657 set_perspective(Perspective::IS_SERVER);
13658
13659 QuicConfig config;
13660 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13661 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13662 connection_.SetFromConfig(config);
13663 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13664 connection_.OnHandshakeComplete();
13665 QuicPacketCreatorPeer::SetPacketNumber(creator_, 200);
13666
13667 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13668 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13669 // Sending ACK_FREQUENCY bundles ACK. QuicConnectionPeer::SendPing
13670 // will try to bundle ACK but there is no pending ACK.
13671 EXPECT_CALL(visitor_, SendAckFrequency(_))
13672 .WillOnce(Invoke(&notifier_,
13673 &SimpleSessionNotifier::WriteOrBufferAckFrequency));
13674 QuicConnectionPeer::SendPing(&connection_);
13675}
13676
13677TEST_P(QuicConnectionTest, PathChallengeBeforePeerIpAddressChangeAtServer) {
13678 set_perspective(Perspective::IS_SERVER);
13679 if (!connection_.connection_migration_use_new_cid()) {
13680 return;
13681 }
13682 PathProbeTestInit(Perspective::IS_SERVER);
13683 SetClientConnectionId(TestConnectionId(1));
13684 connection_.CreateConnectionIdManager();
13685
13686 QuicConnectionId server_cid0 = connection_.connection_id();
13687 QuicConnectionId client_cid0 = connection_.client_connection_id();
13688 QuicConnectionId client_cid1 = TestConnectionId(2);
13689 QuicConnectionId server_cid1;
13690 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013691 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013692 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13693 .WillOnce(Return(TestConnectionId(456)));
13694 }
haoyuewangada6b822022-06-23 13:41:18 -070013695 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13696 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13697 server_cid1 = cid;
13698 return true;
13699 }));
Bence Békybac04052022-04-07 15:44:29 -040013700 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13701 connection_.MaybeSendConnectionIdToClient();
13702 // Receives new client CID from client.
13703 QuicNewConnectionIdFrame new_cid_frame;
13704 new_cid_frame.connection_id = client_cid1;
13705 new_cid_frame.sequence_number = 1u;
13706 new_cid_frame.retire_prior_to = 0u;
13707 connection_.OnNewConnectionIdFrame(new_cid_frame);
13708 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13709 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13710 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13711
13712 peer_creator_.SetServerConnectionId(server_cid1);
13713 const QuicSocketAddress kNewPeerAddress =
13714 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
13715 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13716 QuicFrames frames1;
13717 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070013718 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040013719 QuicPathFrameBuffer payload;
13720 EXPECT_CALL(*send_algorithm_,
13721 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13722 .Times(AtLeast(1))
13723 .WillOnce(Invoke([&]() {
13724 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13725 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13726 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13727 EXPECT_FALSE(writer_->path_response_frames().empty());
13728 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13729 payload = writer_->path_challenge_frames().front().data_buffer;
13730 }));
13731 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
13732 ENCRYPTION_FORWARD_SECURE);
13733 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13734 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13735 EXPECT_TRUE(connection_.HasPendingPathValidation());
13736 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13737 const auto* alternative_path =
13738 QuicConnectionPeer::GetAlternativePath(&connection_);
13739 EXPECT_EQ(default_path->client_connection_id, client_cid0);
13740 EXPECT_EQ(default_path->server_connection_id, server_cid0);
13741 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
13742 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
13743 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13744 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13745
13746 // Process another packet with a different peer address on server side will
13747 // start connection migration.
13748 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
13749 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13750 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13751 }));
13752 // IETF QUIC send algorithm should be changed to a different object, so no
13753 // OnPacketSent() called on the old send algorithm.
13754 EXPECT_CALL(*send_algorithm_,
13755 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13756 .Times(0);
13757 QuicFrames frames2;
13758 frames2.push_back(QuicFrame(frame2_));
13759 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
13760 ENCRYPTION_FORWARD_SECURE);
13761 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13762 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
13763 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
13764 connection_.active_effective_peer_migration_type());
13765 EXPECT_TRUE(writer_->path_challenge_frames().empty());
13766 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
13767 send_algorithm_);
13768 // Switch to use the mock send algorithm.
13769 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
13770 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
13771 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
13772 .WillRepeatedly(Return(kDefaultTCPMSS));
13773 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
13774 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
13775 .Times(AnyNumber())
13776 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13777 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
13778 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
13779 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
13780 connection_.SetSendAlgorithm(send_algorithm_);
13781 EXPECT_EQ(default_path->client_connection_id, client_cid1);
13782 EXPECT_EQ(default_path->server_connection_id, server_cid1);
13783 // The previous default path is kept as alternative path before reverse path
13784 // validation finishes.
13785 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
13786 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
13787 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
13788 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
13789
13790 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13791 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
13792 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
13793 connection_.active_effective_peer_migration_type());
13794 EXPECT_EQ(1u, connection_.GetStats()
13795 .num_peer_migration_to_proactively_validated_address);
13796
13797 // The PATH_CHALLENGE and PATH_RESPONSE is expanded upto the max packet size
13798 // which may exceeds the anti-amplification limit. Verify server is throttled
13799 // by anti-amplification limit.
13800 connection_.SendCryptoDataWithString("foo", 0);
13801 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
13802
13803 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
13804 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070013805 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040013806 EXPECT_CALL(visitor_, MaybeSendAddressToken());
13807 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
13808 .Times(testing::AtLeast(1u));
13809 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
13810 ENCRYPTION_FORWARD_SECURE);
13811 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
13812 // Verify that alternative_path_ is cleared and the peer CID is retired.
13813 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
13814 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
13815 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
13816 auto* retire_peer_issued_cid_alarm =
13817 connection_.GetRetirePeerIssuedConnectionIdAlarm();
13818 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
13819 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
13820 retire_peer_issued_cid_alarm->Fire();
13821
13822 // Verify the anti-amplification limit is lifted by sending a packet larger
13823 // than the anti-amplification limit.
13824 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
13825 EXPECT_CALL(*send_algorithm_, PacingRate(_))
13826 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13827 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
13828 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -070013829 EXPECT_EQ(1u, connection_.num_unlinkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -040013830}
13831
13832TEST_P(QuicConnectionTest,
13833 PathValidationSucceedsBeforePeerIpAddressChangeAtServer) {
13834 set_perspective(Perspective::IS_SERVER);
13835 if (!connection_.connection_migration_use_new_cid()) {
13836 return;
13837 }
13838 PathProbeTestInit(Perspective::IS_SERVER);
13839 connection_.CreateConnectionIdManager();
13840
13841 QuicConnectionId server_cid0 = connection_.connection_id();
13842 QuicConnectionId server_cid1;
13843 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013844 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013845 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13846 .WillOnce(Return(TestConnectionId(456)));
13847 }
haoyuewangada6b822022-06-23 13:41:18 -070013848 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13849 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13850 server_cid1 = cid;
13851 return true;
13852 }));
Bence Békybac04052022-04-07 15:44:29 -040013853 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13854 connection_.MaybeSendConnectionIdToClient();
13855 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13856 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13857
13858 // Receive probing packet with new peer address.
13859 peer_creator_.SetServerConnectionId(server_cid1);
13860 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
13861 /*port=*/23456);
13862 QuicPathFrameBuffer payload;
13863 EXPECT_CALL(*send_algorithm_,
13864 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13865 .WillOnce(Invoke([&]() {
13866 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13867 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13868 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13869 EXPECT_FALSE(writer_->path_response_frames().empty());
13870 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13871 payload = writer_->path_challenge_frames().front().data_buffer;
13872 }))
13873 .WillRepeatedly(Invoke([&]() {
13874 // Only start reverse path validation once.
13875 EXPECT_TRUE(writer_->path_challenge_frames().empty());
13876 }));
13877 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13878 QuicFrames frames1;
13879 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070013880 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040013881 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
13882 ENCRYPTION_FORWARD_SECURE);
13883 EXPECT_TRUE(connection_.HasPendingPathValidation());
13884 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13885 const auto* alternative_path =
13886 QuicConnectionPeer::GetAlternativePath(&connection_);
13887 EXPECT_EQ(default_path->server_connection_id, server_cid0);
13888 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
13889 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13890
13891 // Receive PATH_RESPONSE should mark the new peer address validated.
13892 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070013893 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040013894 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
13895 ENCRYPTION_FORWARD_SECURE);
13896
13897 // Process another packet with a newer peer address with the same port will
13898 // start connection migration.
13899 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
13900 // IETF QUIC send algorithm should be changed to a different object, so no
13901 // OnPacketSent() called on the old send algorithm.
13902 EXPECT_CALL(*send_algorithm_,
13903 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13904 .Times(0);
13905 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
13906 /*port=*/34567);
13907 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13908 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
13909 }));
13910 EXPECT_CALL(visitor_, MaybeSendAddressToken());
13911 QuicFrames frames2;
13912 frames2.push_back(QuicFrame(frame2_));
13913 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewerPeerAddress,
13914 ENCRYPTION_FORWARD_SECURE);
13915 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
13916 EXPECT_EQ(kNewerPeerAddress, connection_.effective_peer_address());
13917 // Since the newer address has the same IP as the previously validated probing
13918 // address. The peer migration becomes validated immediately.
13919 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
13920 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
13921 EXPECT_EQ(1u, connection_.GetStats()
13922 .num_peer_migration_to_proactively_validated_address);
13923 EXPECT_FALSE(connection_.HasPendingPathValidation());
13924 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
13925 send_algorithm_);
13926
13927 EXPECT_EQ(default_path->server_connection_id, server_cid1);
13928 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
13929 // Verify that alternative_path_ is cleared.
13930 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
13931 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
13932
13933 // Switch to use the mock send algorithm.
13934 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
13935 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
13936 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
13937 .WillRepeatedly(Return(kDefaultTCPMSS));
13938 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
13939 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
13940 .Times(AnyNumber())
13941 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13942 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
13943 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
13944 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
13945 connection_.SetSendAlgorithm(send_algorithm_);
13946
13947 // Verify the server is not throttled by the anti-amplification limit by
13948 // sending a packet larger than the anti-amplification limit.
13949 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13950 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
13951 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
13952}
13953
danzhb37451f2022-04-19 08:18:54 -070013954// Regression test of b/228645208.
13955TEST_P(QuicConnectionTest, NoNonProbingFrameOnAlternativePath) {
13956 if (!connection_.connection_migration_use_new_cid()) {
13957 return;
13958 }
13959
13960 PathProbeTestInit(Perspective::IS_SERVER);
13961 SetClientConnectionId(TestConnectionId(1));
13962 connection_.CreateConnectionIdManager();
13963
13964 QuicConnectionId server_cid0 = connection_.connection_id();
13965 QuicConnectionId client_cid0 = connection_.client_connection_id();
13966 QuicConnectionId client_cid1 = TestConnectionId(2);
13967 QuicConnectionId server_cid1;
13968 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013969 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013970 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13971 .WillOnce(Return(TestConnectionId(456)));
13972 }
haoyuewangada6b822022-06-23 13:41:18 -070013973 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13974 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13975 server_cid1 = cid;
13976 return true;
13977 }));
danzhb37451f2022-04-19 08:18:54 -070013978 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13979 connection_.MaybeSendConnectionIdToClient();
13980 // Receives new client CID from client.
13981 QuicNewConnectionIdFrame new_cid_frame;
13982 new_cid_frame.connection_id = client_cid1;
13983 new_cid_frame.sequence_number = 1u;
13984 new_cid_frame.retire_prior_to = 0u;
13985 connection_.OnNewConnectionIdFrame(new_cid_frame);
13986 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13987 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13988 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13989
13990 peer_creator_.SetServerConnectionId(server_cid1);
13991 const QuicSocketAddress kNewPeerAddress =
13992 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
13993 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13994 QuicFrames frames1;
13995 frames1.push_back(
13996 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
13997 QuicPathFrameBuffer payload;
13998 EXPECT_CALL(*send_algorithm_,
13999 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14000 .Times(AtLeast(1))
14001 .WillOnce(Invoke([&]() {
14002 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14003 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14004 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14005 EXPECT_FALSE(writer_->path_response_frames().empty());
14006 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14007 payload = writer_->path_challenge_frames().front().data_buffer;
14008 }));
14009 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
14010 ENCRYPTION_FORWARD_SECURE);
14011 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14012 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14013 EXPECT_TRUE(connection_.HasPendingPathValidation());
14014 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14015 const auto* alternative_path =
14016 QuicConnectionPeer::GetAlternativePath(&connection_);
14017 EXPECT_EQ(default_path->client_connection_id, client_cid0);
14018 EXPECT_EQ(default_path->server_connection_id, server_cid0);
14019 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
14020 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
14021 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
14022 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
14023
14024 // Process non-probing packets on the default path.
14025 peer_creator_.SetServerConnectionId(server_cid0);
14026 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillRepeatedly(Invoke([=]() {
14027 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14028 }));
14029 // Receives packets 3 - 39 to send 19 ACK-only packets, which will force the
14030 // connection to reach |kMaxConsecutiveNonRetransmittablePackets| while
14031 // sending the next ACK.
14032 for (size_t i = 3; i <= 39; ++i) {
14033 ProcessDataPacket(i);
14034 }
14035 EXPECT_EQ(kPeerAddress, connection_.peer_address());
14036 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
14037
14038 EXPECT_TRUE(connection_.HasPendingAcks());
14039 QuicTime ack_time = connection_.GetAckAlarm()->deadline();
14040 QuicTime path_validation_retry_time =
14041 connection_.GetRetryTimeout(kNewPeerAddress, writer_.get());
14042 // Advance time to simultaneously fire path validation retry and ACK alarms.
14043 clock_.AdvanceTime(std::max(ack_time, path_validation_retry_time) -
14044 clock_.ApproximateNow());
14045
14046 // The 20th ACK should bundle with a WINDOW_UPDATE frame.
14047 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
14048 .WillOnce(Invoke([this]() {
14049 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
14050 }));
martindukee6444ef2022-09-23 12:32:23 -070014051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14052 .WillOnce(Invoke([&]() {
14053 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
14054 EXPECT_FALSE(writer_->path_challenge_frames().empty());
14055 // Retry path validation shouldn't bundle ACK.
14056 EXPECT_TRUE(writer_->ack_frames().empty());
14057 }))
14058 .WillOnce(Invoke([&]() {
14059 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
14060 EXPECT_FALSE(writer_->ack_frames().empty());
14061 EXPECT_FALSE(writer_->window_update_frames().empty());
14062 }));
14063 static_cast<TestAlarmFactory::TestAlarm*>(
14064 QuicPathValidatorPeer::retry_timer(
14065 QuicConnectionPeer::path_validator(&connection_)))
14066 ->Fire();
danzhb37451f2022-04-19 08:18:54 -070014067}
14068
haoyuewangada6b822022-06-23 13:41:18 -070014069TEST_P(QuicConnectionTest, DoNotIssueNewCidIfVisitorSaysNo) {
14070 set_perspective(Perspective::IS_SERVER);
14071 if (!connection_.connection_migration_use_new_cid()) {
14072 return;
14073 }
14074
14075 connection_.CreateConnectionIdManager();
14076
14077 QuicConnectionId server_cid0 = connection_.connection_id();
14078 QuicConnectionId client_cid1 = TestConnectionId(2);
14079 QuicConnectionId server_cid1;
14080 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070014081 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014082 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14083 .WillOnce(Return(TestConnectionId(456)));
14084 }
haoyuewangada6b822022-06-23 13:41:18 -070014085 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(false));
14086 if (GetQuicReloadableFlag(quic_check_cid_collision_when_issue_new_cid)) {
14087 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(0);
14088 } else {
14089 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(1);
14090 }
14091 connection_.MaybeSendConnectionIdToClient();
14092}
14093
Bence Békybac04052022-04-07 15:44:29 -040014094TEST_P(QuicConnectionTest,
14095 ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer) {
14096 PathProbeTestInit(Perspective::IS_SERVER);
14097 if (!connection_.validate_client_address()) {
14098 return;
14099 }
14100
14101 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
14102 /*port=*/23456);
14103
14104 // Process a packet with a new peer address will start connection migration.
14105 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
14106 // IETF QUIC send algorithm should be changed to a different object, so no
14107 // OnPacketSent() called on the old send algorithm.
14108 EXPECT_CALL(*send_algorithm_,
14109 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
14110 .Times(0);
14111 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
14112 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14113 }));
14114 QuicFrames frames2;
14115 frames2.push_back(QuicFrame(frame2_));
14116 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
14117 ENCRYPTION_FORWARD_SECURE);
14118 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14119 EXPECT_TRUE(connection_.HasPendingPathValidation());
14120
14121 // Switch to use the mock send algorithm.
14122 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
14123 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
14124 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
14125 .WillRepeatedly(Return(kDefaultTCPMSS));
14126 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
14127 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
14128 .Times(AnyNumber())
14129 .WillRepeatedly(Return(QuicBandwidth::Zero()));
14130 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
14131 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
14132 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
14133 connection_.SetSendAlgorithm(send_algorithm_);
14134
14135 // Receive probing packet with a newer peer address shouldn't override the
14136 // on-going path validation.
14137 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
14138 /*port=*/34567);
14139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
14140 .WillOnce(Invoke([&]() {
14141 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
14142 EXPECT_FALSE(writer_->path_response_frames().empty());
14143 EXPECT_TRUE(writer_->path_challenge_frames().empty());
14144 }));
14145 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
14146 QuicFrames frames1;
14147 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070014148 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040014149 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewerPeerAddress,
14150 ENCRYPTION_FORWARD_SECURE);
14151 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
14152 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
14153 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
14154 EXPECT_TRUE(connection_.HasPendingPathValidation());
14155}
14156
14157TEST_P(QuicConnectionTest,
14158 PathValidationFailedOnClientDueToLackOfServerConnectionId) {
14159 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014160 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014161 QuicConfig config;
14162 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14163 connection_.SetFromConfig(config);
14164 config.SetConnectionOptionsToSend({kRVCM});
14165 }
14166 if (!connection_.connection_migration_use_new_cid()) {
14167 return;
14168 }
14169 PathProbeTestInit(Perspective::IS_CLIENT,
14170 /*receive_new_server_connection_id=*/false);
14171
14172 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14173 /*port=*/34567);
14174
14175 bool success;
14176 connection_.ValidatePath(
14177 std::make_unique<TestQuicPathValidationContext>(
14178 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14179 std::make_unique<TestValidationResultDelegate>(
14180 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
14181
14182 EXPECT_FALSE(success);
14183}
14184
14185TEST_P(QuicConnectionTest,
14186 PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime) {
14187 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014188 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014189 QuicConfig config;
14190 config.SetConnectionOptionsToSend({kRVCM});
14191 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14192 connection_.SetFromConfig(config);
14193 }
14194 if (!connection_.connection_migration_use_new_cid()) {
14195 return;
14196 }
14197 PathProbeTestInit(Perspective::IS_CLIENT,
14198 /*receive_new_server_connection_id=*/false);
14199 SetClientConnectionId(TestConnectionId(1));
14200
14201 // Make sure server connection ID is available for the 1st validation.
14202 QuicConnectionId server_cid0 = connection_.connection_id();
14203 QuicConnectionId server_cid1 = TestConnectionId(2);
14204 QuicConnectionId server_cid2 = TestConnectionId(4);
14205 QuicConnectionId client_cid1;
14206 QuicNewConnectionIdFrame frame1;
14207 frame1.connection_id = server_cid1;
14208 frame1.sequence_number = 1u;
14209 frame1.retire_prior_to = 0u;
14210 frame1.stateless_reset_token =
14211 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14212 connection_.OnNewConnectionIdFrame(frame1);
14213 const auto* packet_creator =
14214 QuicConnectionPeer::GetPacketCreator(&connection_);
14215 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid0);
14216
14217 // Client will issue a new client connection ID to server.
martinduke08e3ff82022-10-18 09:06:26 -070014218 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14219 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014220 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14221 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14222 client_cid1 = frame.connection_id;
14223 }));
14224
14225 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14226 ASSERT_NE(kSelfAddress1, connection_.self_address());
14227 bool success1;
14228 connection_.ValidatePath(
14229 std::make_unique<TestQuicPathValidationContext>(
14230 kSelfAddress1, connection_.peer_address(), writer_.get()),
14231 std::make_unique<TestValidationResultDelegate>(
14232 &connection_, kSelfAddress1, connection_.peer_address(), &success1));
14233
14234 // Migrate upon 1st validation success.
14235 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14236 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14237 &new_writer, /*owns_writer=*/false));
14238 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14239 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14240 EXPECT_EQ(default_path->client_connection_id, client_cid1);
14241 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14242 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14243 const auto* alternative_path =
14244 QuicConnectionPeer::GetAlternativePath(&connection_);
14245 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14246 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14247 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14248 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid1);
14249
14250 // Client will retire server connection ID on old default_path.
14251 auto* retire_peer_issued_cid_alarm =
14252 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14253 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14254 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14255 retire_peer_issued_cid_alarm->Fire();
14256
14257 // Another server connection ID is available to client.
14258 QuicNewConnectionIdFrame frame2;
14259 frame2.connection_id = server_cid2;
14260 frame2.sequence_number = 2u;
14261 frame2.retire_prior_to = 1u;
14262 frame2.stateless_reset_token =
14263 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14264 connection_.OnNewConnectionIdFrame(frame2);
14265
14266 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14267 /*port=*/45678);
14268 bool success2;
14269 connection_.ValidatePath(
14270 std::make_unique<TestQuicPathValidationContext>(
14271 kSelfAddress2, connection_.peer_address(), writer_.get()),
14272 std::make_unique<TestValidationResultDelegate>(
14273 &connection_, kSelfAddress2, connection_.peer_address(), &success2));
14274 // Since server does not retire any client connection ID yet, 2nd validation
14275 // would fail due to lack of client connection ID.
14276 EXPECT_FALSE(success2);
14277}
14278
14279TEST_P(QuicConnectionTest, ServerConnectionIdRetiredUponPathValidationFailure) {
14280 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014281 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014282 QuicConfig config;
14283 config.SetConnectionOptionsToSend({kRVCM});
14284 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14285 connection_.SetFromConfig(config);
14286 }
14287 if (!connection_.connection_migration_use_new_cid()) {
14288 return;
14289 }
14290 PathProbeTestInit(Perspective::IS_CLIENT);
14291
14292 // Make sure server connection ID is available for validation.
14293 QuicNewConnectionIdFrame frame;
14294 frame.connection_id = TestConnectionId(2);
14295 frame.sequence_number = 1u;
14296 frame.retire_prior_to = 0u;
14297 frame.stateless_reset_token =
14298 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14299 connection_.OnNewConnectionIdFrame(frame);
14300
14301 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14302 /*port=*/34567);
14303 bool success;
14304 connection_.ValidatePath(
14305 std::make_unique<TestQuicPathValidationContext>(
14306 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14307 std::make_unique<TestValidationResultDelegate>(
14308 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
14309
14310 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
14311 path_validator->CancelPathValidation();
14312 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14313 EXPECT_FALSE(success);
14314 const auto* alternative_path =
14315 QuicConnectionPeer::GetAlternativePath(&connection_);
14316 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14317 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14318 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14319
14320 // Client will retire server connection ID on alternative_path.
14321 auto* retire_peer_issued_cid_alarm =
14322 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14323 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14324 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
14325 retire_peer_issued_cid_alarm->Fire();
14326}
14327
14328TEST_P(QuicConnectionTest,
14329 MigratePathDirectlyFailedDueToLackOfServerConnectionId) {
14330 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014331 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014332 QuicConfig config;
14333 config.SetConnectionOptionsToSend({kRVCM});
14334 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14335 connection_.SetFromConfig(config);
14336 }
14337 if (!connection_.connection_migration_use_new_cid()) {
14338 return;
14339 }
14340 PathProbeTestInit(Perspective::IS_CLIENT,
14341 /*receive_new_server_connection_id=*/false);
14342 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14343 ASSERT_NE(kSelfAddress1, connection_.self_address());
14344
14345 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14346 ASSERT_FALSE(connection_.MigratePath(kSelfAddress1,
14347 connection_.peer_address(), &new_writer,
14348 /*owns_writer=*/false));
14349}
14350
14351TEST_P(QuicConnectionTest,
14352 MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime) {
14353 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014354 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014355 QuicConfig config;
14356 config.SetConnectionOptionsToSend({kRVCM});
14357 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14358 connection_.SetFromConfig(config);
14359 }
14360 if (!connection_.connection_migration_use_new_cid()) {
14361 return;
14362 }
14363 PathProbeTestInit(Perspective::IS_CLIENT,
14364 /*receive_new_server_connection_id=*/false);
14365 SetClientConnectionId(TestConnectionId(1));
14366
14367 // Make sure server connection ID is available for the 1st migration.
14368 QuicNewConnectionIdFrame frame1;
14369 frame1.connection_id = TestConnectionId(2);
14370 frame1.sequence_number = 1u;
14371 frame1.retire_prior_to = 0u;
14372 frame1.stateless_reset_token =
14373 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14374 connection_.OnNewConnectionIdFrame(frame1);
14375
14376 // Client will issue a new client connection ID to server.
14377 QuicConnectionId new_client_connection_id;
martinduke08e3ff82022-10-18 09:06:26 -070014378 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14379 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014380 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14381 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14382 new_client_connection_id = frame.connection_id;
14383 }));
14384
14385 // 1st migration is successful.
14386 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14387 ASSERT_NE(kSelfAddress1, connection_.self_address());
14388 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14389 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14390 &new_writer,
14391 /*owns_writer=*/false));
14392 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14393 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14394 EXPECT_EQ(default_path->client_connection_id, new_client_connection_id);
14395 EXPECT_EQ(default_path->server_connection_id, frame1.connection_id);
14396 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14397
14398 // Client will retire server connection ID on old default_path.
14399 auto* retire_peer_issued_cid_alarm =
14400 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14401 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14402 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14403 retire_peer_issued_cid_alarm->Fire();
14404
14405 // Another server connection ID is available to client.
14406 QuicNewConnectionIdFrame frame2;
14407 frame2.connection_id = TestConnectionId(4);
14408 frame2.sequence_number = 2u;
14409 frame2.retire_prior_to = 1u;
14410 frame2.stateless_reset_token =
14411 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14412 connection_.OnNewConnectionIdFrame(frame2);
14413
14414 // Since server does not retire any client connection ID yet, 2nd migration
14415 // would fail due to lack of client connection ID.
14416 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14417 /*port=*/45678);
14418 auto new_writer2 = std::make_unique<TestPacketWriter>(version(), &clock_,
14419 Perspective::IS_CLIENT);
14420 ASSERT_FALSE(connection_.MigratePath(
14421 kSelfAddress2, connection_.peer_address(), new_writer2.release(),
14422 /*owns_writer=*/true));
14423}
14424
14425TEST_P(QuicConnectionTest,
14426 CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID) {
14427 if (!version().HasIetfQuicFrames()) {
14428 return;
14429 }
14430 set_perspective(Perspective::IS_SERVER);
14431 ASSERT_TRUE(connection_.client_connection_id().IsEmpty());
14432
14433 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14434 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14435 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14436 QuicNewConnectionIdFrame frame;
14437 frame.sequence_number = 1u;
14438 frame.connection_id = TestConnectionId(1);
14439 frame.stateless_reset_token =
14440 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14441 frame.retire_prior_to = 0u;
14442
14443 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14444
14445 EXPECT_FALSE(connection_.connected());
14446 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14447 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14448}
14449
14450TEST_P(QuicConnectionTest, NewConnectionIdFrameResultsInError) {
14451 if (!version().HasIetfQuicFrames()) {
14452 return;
14453 }
14454 connection_.CreateConnectionIdManager();
14455 ASSERT_FALSE(connection_.connection_id().IsEmpty());
14456
14457 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14458 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14459 QuicNewConnectionIdFrame frame;
14460 frame.sequence_number = 1u;
14461 frame.connection_id = connection_id_; // Reuses connection ID casuing error.
14462 frame.stateless_reset_token =
14463 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14464 frame.retire_prior_to = 0u;
14465
14466 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14467
14468 EXPECT_FALSE(connection_.connected());
14469 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14470 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14471}
14472
14473TEST_P(QuicConnectionTest,
14474 ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14475 if (!version().HasIetfQuicFrames()) {
14476 return;
14477 }
14478 connection_.CreateConnectionIdManager();
14479
14480 QuicNewConnectionIdFrame frame;
14481 frame.sequence_number = 1u;
14482 frame.connection_id = TestConnectionId(1);
14483 frame.stateless_reset_token =
14484 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14485 frame.retire_prior_to = 0u;
14486
14487 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14488 auto* retire_peer_issued_cid_alarm =
14489 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14490 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14491
14492 frame.sequence_number = 2u;
14493 frame.connection_id = TestConnectionId(2);
14494 frame.stateless_reset_token =
14495 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14496 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14497
14498 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14499 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14500 EXPECT_EQ(connection_.connection_id(), connection_id_);
14501
14502 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14503 retire_peer_issued_cid_alarm->Fire();
14504 EXPECT_EQ(connection_.connection_id(), TestConnectionId(2));
14505 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14506 TestConnectionId(2));
14507}
14508
14509TEST_P(QuicConnectionTest,
14510 ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14511 if (!version().HasIetfQuicFrames()) {
14512 return;
14513 }
14514 set_perspective(Perspective::IS_SERVER);
14515 SetClientConnectionId(TestConnectionId(0));
14516
14517 QuicNewConnectionIdFrame frame;
14518 frame.sequence_number = 1u;
14519 frame.connection_id = TestConnectionId(1);
14520 frame.stateless_reset_token =
14521 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14522 frame.retire_prior_to = 0u;
14523
14524 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14525 auto* retire_peer_issued_cid_alarm =
14526 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14527 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14528
14529 frame.sequence_number = 2u;
14530 frame.connection_id = TestConnectionId(2);
14531 frame.stateless_reset_token =
14532 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14533 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14534
14535 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14536 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14537 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14538
14539 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14540 retire_peer_issued_cid_alarm->Fire();
14541 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14542 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14543 TestConnectionId(2));
14544}
14545
14546TEST_P(
14547 QuicConnectionTest,
14548 ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame) {
danzhaf2e52a2022-04-20 07:37:03 -070014549 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014550 return;
14551 }
14552 PathProbeTestInit(Perspective::IS_SERVER);
14553 SetClientConnectionId(TestConnectionId(0));
14554
14555 // Populate alternative_path_ with probing packet.
14556 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
14557
14558 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
14559 QuicEncryptedPacket(probing_packet->encrypted_buffer,
14560 probing_packet->encrypted_length),
14561 clock_.Now()));
14562 QuicIpAddress new_host;
14563 new_host.FromString("1.1.1.1");
14564 ProcessReceivedPacket(kSelfAddress,
14565 QuicSocketAddress(new_host, /*port=*/23456), *received);
14566
14567 EXPECT_EQ(
14568 TestConnectionId(0),
14569 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14570
14571 QuicNewConnectionIdFrame frame;
14572 frame.sequence_number = 1u;
14573 frame.connection_id = TestConnectionId(1);
14574 frame.stateless_reset_token =
14575 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14576 frame.retire_prior_to = 0u;
14577
14578 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14579 auto* retire_peer_issued_cid_alarm =
14580 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14581 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14582
14583 frame.sequence_number = 2u;
14584 frame.connection_id = TestConnectionId(2);
14585 frame.stateless_reset_token =
14586 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14587 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14588
14589 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14590 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14591 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14592
14593 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14594 retire_peer_issued_cid_alarm->Fire();
14595 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14596 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14597 TestConnectionId(2));
14598 // Clean up alternative path connection ID.
14599 EXPECT_EQ(
14600 TestConnectionId(2),
14601 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14602}
14603
14604TEST_P(QuicConnectionTest,
14605 CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued) {
14606 if (!version().HasIetfQuicFrames() ||
14607 !connection_.connection_migration_use_new_cid()) {
14608 return;
14609 }
14610 set_perspective(Perspective::IS_SERVER);
14611
14612 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14613 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14614 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14615 QuicRetireConnectionIdFrame frame;
14616 frame.sequence_number = 1u;
14617
14618 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14619
14620 EXPECT_FALSE(connection_.connected());
14621 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14622 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14623}
14624
14625TEST_P(QuicConnectionTest, RetireConnectionIdFrameResultsInError) {
14626 if (!version().HasIetfQuicFrames() ||
14627 !connection_.connection_migration_use_new_cid()) {
14628 return;
14629 }
14630 set_perspective(Perspective::IS_SERVER);
14631 connection_.CreateConnectionIdManager();
14632
martinduke08e3ff82022-10-18 09:06:26 -070014633 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014634 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14635 .WillOnce(Return(TestConnectionId(456)));
14636 }
haoyuewangada6b822022-06-23 13:41:18 -070014637 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_));
Bence Békybac04052022-04-07 15:44:29 -040014638 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14639 connection_.MaybeSendConnectionIdToClient();
14640
14641 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14642 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14643 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14644 QuicRetireConnectionIdFrame frame;
14645 frame.sequence_number = 2u; // The corresponding ID is never issued.
14646
14647 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14648
14649 EXPECT_FALSE(connection_.connected());
14650 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14651 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14652}
14653
14654TEST_P(QuicConnectionTest,
14655 ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore) {
14656 if (!version().HasIetfQuicFrames()) {
14657 return;
14658 }
14659 set_perspective(Perspective::IS_SERVER);
14660 connection_.CreateConnectionIdManager();
14661
14662 auto* retire_self_issued_cid_alarm =
14663 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14664 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14665
14666 QuicConnectionId cid0 = connection_id_;
14667 QuicRetireConnectionIdFrame frame;
14668 frame.sequence_number = 0u;
14669 if (connection_.connection_migration_use_new_cid()) {
martinduke08e3ff82022-10-18 09:06:26 -070014670 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014671 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(cid0))
14672 .WillOnce(Return(TestConnectionId(456)));
14673 EXPECT_CALL(connection_id_generator_,
14674 GenerateNextConnectionId(TestConnectionId(456)))
14675 .WillOnce(Return(TestConnectionId(789)));
14676 }
haoyuewangada6b822022-06-23 13:41:18 -070014677 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14678 .Times(2)
14679 .WillRepeatedly(Return(true));
Bence Békybac04052022-04-07 15:44:29 -040014680 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
14681 }
14682 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(frame));
14683}
14684
14685TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionId) {
14686 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014687 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014688 QuicConfig config;
14689 config.SetConnectionOptionsToSend({kRVCM});
14690 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14691 connection_.SetFromConfig(config);
14692 }
14693 if (!connection_.connection_migration_use_new_cid()) {
14694 return;
14695 }
14696 set_perspective(Perspective::IS_SERVER);
14697 connection_.CreateConnectionIdManager();
14698 QuicConnectionId recorded_cid;
haoyuewangada6b822022-06-23 13:41:18 -070014699 auto cid_recorder = [&recorded_cid](const QuicConnectionId& cid) -> bool {
Bence Békybac04052022-04-07 15:44:29 -040014700 recorded_cid = cid;
haoyuewangada6b822022-06-23 13:41:18 -070014701 return true;
Bence Békybac04052022-04-07 15:44:29 -040014702 };
14703 QuicConnectionId cid0 = connection_id_;
14704 QuicConnectionId cid1;
14705 QuicConnectionId cid2;
14706 EXPECT_EQ(connection_.connection_id(), cid0);
14707 EXPECT_EQ(connection_.GetOneActiveServerConnectionId(), cid0);
14708
14709 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke08e3ff82022-10-18 09:06:26 -070014710 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014711 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14712 .WillOnce(Return(TestConnectionId(456)));
14713 }
haoyuewangada6b822022-06-23 13:41:18 -070014714 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040014715 .WillOnce(Invoke(cid_recorder));
14716 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14717 connection_.MaybeSendConnectionIdToClient();
14718 cid1 = recorded_cid;
14719
14720 auto* retire_self_issued_cid_alarm =
14721 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14722 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14723
14724 // Generate three packets with different connection IDs that will arrive out
14725 // of order (2, 1, 3) later.
14726 char buffers[3][kMaxOutgoingPacketSize];
14727 // Destination connection ID of packet1 is cid0.
14728 auto packet1 =
14729 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14730 buffers[0], kMaxOutgoingPacketSize);
14731 peer_creator_.SetServerConnectionId(cid1);
14732 auto retire_cid_frame = std::make_unique<QuicRetireConnectionIdFrame>();
14733 retire_cid_frame->sequence_number = 0u;
14734 // Destination connection ID of packet2 is cid1.
14735 auto packet2 = ConstructPacket({QuicFrame(retire_cid_frame.release())},
14736 ENCRYPTION_FORWARD_SECURE, buffers[1],
14737 kMaxOutgoingPacketSize);
14738 // Destination connection ID of packet3 is cid1.
14739 auto packet3 =
14740 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14741 buffers[2], kMaxOutgoingPacketSize);
14742
14743 // Packet2 with RetireConnectionId frame trigers sending NewConnectionId
14744 // immediately.
martinduke08e3ff82022-10-18 09:06:26 -070014745 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014746 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14747 .WillOnce(Return(TestConnectionId(456)));
14748 }
haoyuewangada6b822022-06-23 13:41:18 -070014749 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040014750 .WillOnce(Invoke(cid_recorder));
14751 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14752 peer_creator_.SetServerConnectionId(cid1);
14753 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet2);
14754 cid2 = recorded_cid;
14755 // cid0 is not retired immediately.
14756 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
14757 ElementsAre(cid0, cid1, cid2));
14758 ASSERT_TRUE(retire_self_issued_cid_alarm->IsSet());
14759 EXPECT_EQ(connection_.connection_id(), cid1);
14760 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
14761 connection_.GetOneActiveServerConnectionId() == cid1 ||
14762 connection_.GetOneActiveServerConnectionId() == cid2);
14763
14764 // Packet1 updates the connection ID on the default path but not the active
14765 // connection ID.
14766 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet1);
14767 EXPECT_EQ(connection_.connection_id(), cid0);
14768 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
14769 connection_.GetOneActiveServerConnectionId() == cid1 ||
14770 connection_.GetOneActiveServerConnectionId() == cid2);
14771
14772 // cid0 is retired when the retire CID alarm fires.
14773 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(cid0));
14774 retire_self_issued_cid_alarm->Fire();
14775 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
14776 ElementsAre(cid1, cid2));
14777 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
14778 connection_.GetOneActiveServerConnectionId() == cid2);
14779
14780 // Packet3 updates the connection ID on the default path.
14781 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet3);
14782 EXPECT_EQ(connection_.connection_id(), cid1);
14783 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
14784 connection_.GetOneActiveServerConnectionId() == cid2);
14785}
14786
14787TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoAlternativePath) {
14788 if (!version().HasIetfQuicFrames()) {
14789 return;
14790 }
14791 set_perspective(Perspective::IS_SERVER);
14792 connection_.CreateConnectionIdManager();
14793 connection_.set_client_connection_id(TestConnectionId(1));
14794
14795 // Set up the state after path probing.
14796 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14797 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
14798 QuicIpAddress new_host;
14799 new_host.FromString("12.12.12.12");
14800 alternative_path->self_address = default_path->self_address;
14801 alternative_path->peer_address = QuicSocketAddress(new_host, 12345);
14802 alternative_path->server_connection_id = TestConnectionId(3);
14803 ASSERT_TRUE(alternative_path->client_connection_id.IsEmpty());
14804 ASSERT_FALSE(alternative_path->stateless_reset_token.has_value());
14805
14806 QuicNewConnectionIdFrame frame;
14807 frame.sequence_number = 1u;
14808 frame.connection_id = TestConnectionId(5);
14809 frame.stateless_reset_token =
14810 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14811 frame.retire_prior_to = 0u;
14812 // New ID is patched onto the alternative path when the needed
14813 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
14814 connection_.OnNewConnectionIdFrame(frame);
14815
14816 ASSERT_EQ(alternative_path->client_connection_id, frame.connection_id);
14817 ASSERT_EQ(alternative_path->stateless_reset_token,
14818 frame.stateless_reset_token);
14819}
14820
14821TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoDefaultPath) {
14822 if (!version().HasIetfQuicFrames()) {
14823 return;
14824 }
14825 set_perspective(Perspective::IS_SERVER);
14826 connection_.CreateConnectionIdManager();
14827 connection_.set_client_connection_id(TestConnectionId(1));
14828
14829 // Set up the state after peer migration without probing.
14830 auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14831 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
14832 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14833 *alternative_path = std::move(*default_path);
14834 QuicIpAddress new_host;
14835 new_host.FromString("12.12.12.12");
14836 default_path->self_address = default_path->self_address;
14837 default_path->peer_address = QuicSocketAddress(new_host, 12345);
14838 default_path->server_connection_id = TestConnectionId(3);
14839 packet_creator->SetDefaultPeerAddress(default_path->peer_address);
14840 packet_creator->SetServerConnectionId(default_path->server_connection_id);
14841 packet_creator->SetClientConnectionId(default_path->client_connection_id);
14842
14843 ASSERT_FALSE(default_path->validated);
14844 ASSERT_TRUE(default_path->client_connection_id.IsEmpty());
14845 ASSERT_FALSE(default_path->stateless_reset_token.has_value());
14846
14847 QuicNewConnectionIdFrame frame;
14848 frame.sequence_number = 1u;
14849 frame.connection_id = TestConnectionId(5);
14850 frame.stateless_reset_token =
14851 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14852 frame.retire_prior_to = 0u;
14853 // New ID is patched onto the default path when the needed
14854 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
14855 connection_.OnNewConnectionIdFrame(frame);
14856
14857 ASSERT_EQ(default_path->client_connection_id, frame.connection_id);
14858 ASSERT_EQ(default_path->stateless_reset_token, frame.stateless_reset_token);
14859 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), frame.connection_id);
14860}
14861
14862TEST_P(QuicConnectionTest, ShouldGeneratePacketBlockedByMissingConnectionId) {
14863 if (!version().HasIetfQuicFrames()) {
14864 return;
14865 }
14866 set_perspective(Perspective::IS_SERVER);
14867 connection_.set_client_connection_id(TestConnectionId(1));
14868 connection_.CreateConnectionIdManager();
14869 if (version().SupportsAntiAmplificationLimit()) {
14870 QuicConnectionPeer::SetAddressValidated(&connection_);
14871 }
14872
14873 ASSERT_TRUE(
14874 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
14875
14876 QuicPacketCreator* packet_creator =
14877 QuicConnectionPeer::GetPacketCreator(&connection_);
14878 QuicIpAddress peer_host1;
14879 peer_host1.FromString("12.12.12.12");
14880 QuicSocketAddress peer_address1(peer_host1, 1235);
14881
14882 {
14883 // No connection ID is available as context is created without any.
14884 QuicPacketCreator::ScopedPeerAddressContext context(
14885 packet_creator, peer_address1, EmptyQuicConnectionId(),
14886 EmptyQuicConnectionId(),
14887 /*update_connection_id=*/true);
14888 ASSERT_FALSE(connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
14889 NOT_HANDSHAKE));
14890 }
14891 ASSERT_TRUE(
14892 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
14893}
14894
14895// Regression test for b/182571515
14896TEST_P(QuicConnectionTest, LostDataThenGetAcknowledged) {
14897 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -070014898 if (!connection_.validate_client_address() ||
birenroyef686222022-09-12 11:34:34 -070014899 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040014900 return;
14901 }
14902
14903 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
14904 if (version().SupportsAntiAmplificationLimit()) {
14905 QuicConnectionPeer::SetAddressValidated(&connection_);
14906 }
14907 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14908 // Discard INITIAL key.
14909 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
14910 connection_.NeuterUnencryptedPackets();
14911 EXPECT_CALL(visitor_, GetHandshakeState())
14912 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
14913
14914 QuicPacketNumber last_packet;
14915 // Send packets 1 to 4.
14916 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
14917 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 2
14918 SendStreamDataToPeer(3, "foo", 6, NO_FIN, &last_packet); // Packet 3
14919 SendStreamDataToPeer(3, "foo", 9, NO_FIN, &last_packet); // Packet 4
14920
14921 // Process a PING packet to set peer address.
14922 ProcessFramePacket(QuicFrame(QuicPingFrame()));
14923
14924 // Process a packet containing a STREAM_FRAME and an ACK with changed peer
14925 // address.
14926 QuicFrames frames;
14927 frames.push_back(QuicFrame(frame1_));
14928 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}});
14929 frames.push_back(QuicFrame(&ack));
14930
Bence Békybac04052022-04-07 15:44:29 -040014931 // Invoke OnCanWrite.
Bence Békybac04052022-04-07 15:44:29 -040014932 QuicIpAddress ip_address;
14933 ASSERT_TRUE(ip_address.FromString("127.0.52.223"));
vasilvvac2e30d2022-06-02 14:26:59 -070014934 EXPECT_QUIC_BUG(
14935 {
14936 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(1);
14937 EXPECT_CALL(visitor_, OnStreamFrame(_))
14938 .WillOnce(InvokeWithoutArgs(&notifier_,
14939 &SimpleSessionNotifier::OnCanWrite));
14940 ProcessFramesPacketWithAddresses(frames, kSelfAddress,
14941 QuicSocketAddress(ip_address, 1000),
14942 ENCRYPTION_FORWARD_SECURE);
14943 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
14944
14945 // Verify stream frame will not be retransmitted.
14946 EXPECT_TRUE(writer_->stream_frames().empty());
14947 },
14948 "Try to write mid packet processing");
Bence Békybac04052022-04-07 15:44:29 -040014949}
14950
14951TEST_P(QuicConnectionTest, PtoSendStreamData) {
14952 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14953 return;
14954 }
14955 set_perspective(Perspective::IS_SERVER);
14956 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
14957 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
14958 }
14959 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040014960 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
14961 EXPECT_TRUE(connection_.HasPendingAcks());
14962
Bence Békybac04052022-04-07 15:44:29 -040014963 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14964 // Send INITIAL 1.
14965 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
14966
martinduke9e0811c2022-12-08 20:35:57 -080014967 connection_.SetEncrypter(
14968 ENCRYPTION_HANDSHAKE,
14969 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040014970 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
14971 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080014972 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040014973 // Send HANDSHAKE packets.
14974 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
14975 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
14976
martinduke9e0811c2022-12-08 20:35:57 -080014977 connection_.SetEncrypter(
14978 ENCRYPTION_FORWARD_SECURE,
14979 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040014980 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14981
14982 // Send half RTT packet with congestion control blocked.
14983 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
14984 connection_.SendStreamDataWithString(2, std::string(1500, 'a'), 0, NO_FIN);
14985
14986 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14987 connection_.GetRetransmissionAlarm()->Fire();
14988 // Verify INITIAL and HANDSHAKE get retransmitted.
martinduke9e0811c2022-12-08 20:35:57 -080014989 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040014990}
14991
14992TEST_P(QuicConnectionTest, SendingZeroRttPacketsDoesNotPostponePTO) {
14993 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14994 return;
14995 }
Bence Békybac04052022-04-07 15:44:29 -040014996 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14997 // Send CHLO.
14998 connection_.SendCryptoStreamData();
14999 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15000 // Install 0-RTT keys.
15001 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15002 std::make_unique<TaggingEncrypter>(0x02));
15003 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15004
15005 // CHLO gets acknowledged after 10ms.
15006 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15007 QuicAckFrame frame1 = InitAckFrame(1);
15008 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
15009 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15010 // Verify PTO is still armed since address validation is not finished yet.
15011 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15012 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15013
15014 // Send 0-RTT packet.
15015 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15016 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15017 std::make_unique<TaggingEncrypter>(0x02));
15018 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15019 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15020 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15021 // PTO deadline should be unchanged.
15022 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15023}
15024
15025TEST_P(QuicConnectionTest, QueueingUndecryptablePacketsDoesntPostponePTO) {
15026 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15027 return;
15028 }
15029 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15030 QuicConfig config;
15031 config.set_max_undecryptable_packets(3);
15032 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040015033 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15034 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15035 // Send CHLO.
15036 connection_.SendCryptoStreamData();
15037
15038 // Send 0-RTT packet.
15039 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15040 std::make_unique<TaggingEncrypter>(0x02));
15041 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15042 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15043
15044 // CHLO gets acknowledged after 10ms.
15045 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15046 QuicAckFrame frame1 = InitAckFrame(1);
15047 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
15048 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15049 // Verify PTO is still armed since address validation is not finished yet.
15050 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15051 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15052
15053 // Receive an undecryptable packets.
15054 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15055 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15056 std::make_unique<TaggingEncrypter>(0xFF));
15057 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15058 // Verify PTO deadline is sooner.
15059 EXPECT_GT(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15060 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15061
15062 // PTO fires.
15063 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15064 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15065 connection_.GetRetransmissionAlarm()->Fire();
15066 // Verify PTO is still armed since address validation is not finished yet.
15067 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15068 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15069
15070 // Verify PTO deadline does not change.
15071 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
15072 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
15073}
15074
15075TEST_P(QuicConnectionTest, QueueUndecryptableHandshakePackets) {
15076 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15077 return;
15078 }
15079 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15080 QuicConfig config;
15081 config.set_max_undecryptable_packets(3);
15082 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040015083 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15084 connection_.RemoveDecrypter(ENCRYPTION_HANDSHAKE);
15085 // Send CHLO.
15086 connection_.SendCryptoStreamData();
15087
15088 // Send 0-RTT packet.
15089 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15090 std::make_unique<TaggingEncrypter>(0x02));
15091 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15092 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15093 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15094
15095 // Receive an undecryptable handshake packet.
15096 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
15097 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15098 std::make_unique<TaggingEncrypter>(0xFF));
15099 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
15100 // Verify this handshake packet gets queued.
15101 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15102}
15103
15104TEST_P(QuicConnectionTest, PingNotSentAt0RTTLevelWhenInitialAvailable) {
15105 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15106 return;
15107 }
Bence Békybac04052022-04-07 15:44:29 -040015108 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15109 // Send CHLO.
15110 connection_.SendCryptoStreamData();
15111 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080015112 connection_.SetEncrypter(
15113 ENCRYPTION_ZERO_RTT,
15114 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015115 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15116 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
15117
15118 // CHLO gets acknowledged after 10ms.
15119 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15120 QuicAckFrame frame1 = InitAckFrame(1);
15121 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
15122 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
15123 // Verify PTO is still armed since address validation is not finished yet.
15124 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15125 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
15126
15127 // PTO fires.
15128 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
15129 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
15130 connection_.GetRetransmissionAlarm()->Fire();
15131 // Verify the PING gets sent in ENCRYPTION_INITIAL.
martinduke9e0811c2022-12-08 20:35:57 -080015132 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015133}
15134
15135TEST_P(QuicConnectionTest, AckElicitingFrames) {
15136 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070015137 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040015138 QuicConfig config;
15139 config.SetConnectionOptionsToSend({kRVCM});
15140 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15141 connection_.SetFromConfig(config);
15142 }
15143 if (!version().HasIetfQuicFrames() ||
15144 !connection_.connection_migration_use_new_cid()) {
15145 return;
15146 }
martinduke08e3ff82022-10-18 09:06:26 -070015147 EXPECT_CALL(connection_id_generator_,
15148 GenerateNextConnectionId(TestConnectionId(12)))
15149 .WillOnce(Return(TestConnectionId(456)));
15150 EXPECT_CALL(connection_id_generator_,
15151 GenerateNextConnectionId(TestConnectionId(456)))
15152 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040015153 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
15154 EXPECT_CALL(visitor_, OnRstStream(_));
15155 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
15156 EXPECT_CALL(visitor_, OnBlockedFrame(_));
15157 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
15158 EXPECT_CALL(visitor_, OnStreamFrame(_));
15159 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
15160 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_));
15161 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_));
15162 EXPECT_CALL(visitor_, OnStopSendingFrame(_));
15163 EXPECT_CALL(visitor_, OnMessageReceived(""));
15164 EXPECT_CALL(visitor_, OnNewTokenReceived(""));
15165
15166 SetClientConnectionId(TestConnectionId(12));
15167 connection_.CreateConnectionIdManager();
15168 QuicConnectionPeer::GetSelfIssuedConnectionIdManager(&connection_)
15169 ->MaybeSendNewConnectionIds();
15170 connection_.set_can_receive_ack_frequency_frame();
15171
15172 QuicAckFrame ack_frame = InitAckFrame(1);
15173 QuicRstStreamFrame rst_stream_frame;
15174 QuicWindowUpdateFrame window_update_frame;
15175 QuicPathChallengeFrame path_challenge_frame;
15176 QuicNewConnectionIdFrame new_connection_id_frame;
15177 QuicRetireConnectionIdFrame retire_connection_id_frame;
15178 retire_connection_id_frame.sequence_number = 1u;
15179 QuicStopSendingFrame stop_sending_frame;
15180 QuicPathResponseFrame path_response_frame;
15181 QuicMessageFrame message_frame;
15182 QuicNewTokenFrame new_token_frame;
15183 QuicAckFrequencyFrame ack_frequency_frame;
15184 QuicBlockedFrame blocked_frame;
15185 size_t packet_number = 1;
15186
15187 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15188
15189 for (uint8_t i = 0; i < NUM_FRAME_TYPES; ++i) {
15190 QuicFrameType frame_type = static_cast<QuicFrameType>(i);
15191 bool skipped = false;
15192 QuicFrame frame;
15193 QuicFrames frames;
15194 // Add some padding to fullfill the min size requirement of header
15195 // protection.
15196 frames.push_back(QuicFrame(QuicPaddingFrame(10)));
15197 switch (frame_type) {
15198 case PADDING_FRAME:
15199 frame = QuicFrame(QuicPaddingFrame(10));
15200 break;
15201 case MTU_DISCOVERY_FRAME:
15202 frame = QuicFrame(QuicMtuDiscoveryFrame());
15203 break;
15204 case PING_FRAME:
15205 frame = QuicFrame(QuicPingFrame());
15206 break;
15207 case MAX_STREAMS_FRAME:
15208 frame = QuicFrame(QuicMaxStreamsFrame());
15209 break;
15210 case STOP_WAITING_FRAME:
15211 // Not supported.
15212 skipped = true;
15213 break;
15214 case STREAMS_BLOCKED_FRAME:
15215 frame = QuicFrame(QuicStreamsBlockedFrame());
15216 break;
15217 case STREAM_FRAME:
15218 frame = QuicFrame(QuicStreamFrame());
15219 break;
15220 case HANDSHAKE_DONE_FRAME:
15221 frame = QuicFrame(QuicHandshakeDoneFrame());
15222 break;
15223 case ACK_FRAME:
15224 frame = QuicFrame(&ack_frame);
15225 break;
15226 case RST_STREAM_FRAME:
15227 frame = QuicFrame(&rst_stream_frame);
15228 break;
15229 case CONNECTION_CLOSE_FRAME:
15230 // Do not test connection close.
15231 skipped = true;
15232 break;
15233 case GOAWAY_FRAME:
15234 // Does not exist in IETF QUIC.
15235 skipped = true;
15236 break;
15237 case BLOCKED_FRAME:
15238 frame = QuicFrame(blocked_frame);
15239 break;
15240 case WINDOW_UPDATE_FRAME:
15241 frame = QuicFrame(window_update_frame);
15242 break;
15243 case PATH_CHALLENGE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015244 frame = QuicFrame(path_challenge_frame);
Bence Békybac04052022-04-07 15:44:29 -040015245 break;
15246 case STOP_SENDING_FRAME:
15247 frame = QuicFrame(stop_sending_frame);
15248 break;
15249 case NEW_CONNECTION_ID_FRAME:
15250 frame = QuicFrame(&new_connection_id_frame);
15251 break;
15252 case RETIRE_CONNECTION_ID_FRAME:
15253 frame = QuicFrame(&retire_connection_id_frame);
15254 break;
15255 case PATH_RESPONSE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015256 frame = QuicFrame(path_response_frame);
Bence Békybac04052022-04-07 15:44:29 -040015257 break;
15258 case MESSAGE_FRAME:
15259 frame = QuicFrame(&message_frame);
15260 break;
15261 case CRYPTO_FRAME:
15262 // CRYPTO_FRAME is ack eliciting is covered by other tests.
15263 skipped = true;
15264 break;
15265 case NEW_TOKEN_FRAME:
15266 frame = QuicFrame(&new_token_frame);
15267 break;
15268 case ACK_FREQUENCY_FRAME:
15269 frame = QuicFrame(&ack_frequency_frame);
15270 break;
15271 case NUM_FRAME_TYPES:
15272 skipped = true;
15273 break;
15274 }
15275 if (skipped) {
15276 continue;
15277 }
15278 ASSERT_EQ(frame_type, frame.type);
15279 frames.push_back(frame);
15280 EXPECT_FALSE(connection_.HasPendingAcks());
15281 // Process frame.
15282 ProcessFramesPacketAtLevel(packet_number++, frames,
15283 ENCRYPTION_FORWARD_SECURE);
15284 if (QuicUtils::IsAckElicitingFrame(frame_type)) {
15285 ASSERT_TRUE(connection_.HasPendingAcks()) << frame;
15286 // Flush ACK.
15287 clock_.AdvanceTime(DefaultDelayedAckTime());
15288 connection_.GetAckAlarm()->Fire();
15289 }
15290 EXPECT_FALSE(connection_.HasPendingAcks());
15291 ASSERT_TRUE(connection_.connected());
15292 }
15293}
15294
15295TEST_P(QuicConnectionTest, ReceivedChloAndAck) {
15296 if (!version().HasIetfQuicFrames()) {
15297 return;
15298 }
15299 set_perspective(Perspective::IS_SERVER);
15300 QuicFrames frames;
15301 QuicAckFrame ack_frame = InitAckFrame(1);
15302 frames.push_back(MakeCryptoFrame());
15303 frames.push_back(QuicFrame(&ack_frame));
15304
15305 EXPECT_CALL(visitor_, OnCryptoFrame(_))
15306 .WillOnce(IgnoreResult(InvokeWithoutArgs(
15307 &connection_, &TestConnection::SendCryptoStreamData)));
15308 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15309 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15310 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
15311 ENCRYPTION_INITIAL);
15312}
15313
15314// Regression test for b/201643321.
15315TEST_P(QuicConnectionTest, FailedToRetransmitShlo) {
fayang161ce6e2022-07-01 18:02:11 -070015316 if (!version().HasIetfQuicFrames() ||
birenroyef686222022-09-12 11:34:34 -070015317 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040015318 return;
15319 }
15320 set_perspective(Perspective::IS_SERVER);
15321 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15322 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015323 // Received INITIAL 1.
15324 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15325 EXPECT_TRUE(connection_.HasPendingAcks());
15326
martinduke9e0811c2022-12-08 20:35:57 -080015327 peer_framer_.SetEncrypter(
15328 ENCRYPTION_ZERO_RTT,
15329 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015330
martinduke9e0811c2022-12-08 20:35:57 -080015331 connection_.SetEncrypter(
15332 ENCRYPTION_HANDSHAKE,
15333 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015334 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015335 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015336 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015337 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15338 connection_.SetEncrypter(
15339 ENCRYPTION_FORWARD_SECURE,
15340 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015341 // Received ENCRYPTION_ZERO_RTT 1.
15342 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15343 {
15344 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15345 // Send INITIAL 1.
15346 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15347 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15348 // Send HANDSHAKE 2.
15349 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15350 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15351 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15352 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15353 // Send half RTT data to exhaust amplification credit.
15354 connection_.SendStreamDataWithString(0, std::string(100 * 1024, 'a'), 0,
15355 NO_FIN);
15356 }
15357 // Received INITIAL 2.
15358 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
15359 ASSERT_TRUE(connection_.HasPendingAcks());
15360 // Verify ACK delay is 1ms.
15361 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
15362 connection_.GetAckAlarm()->deadline());
15363 // ACK is not throttled by amplification limit, and SHLO is bundled. Also
15364 // HANDSHAKE + 1RTT packets get coalesced.
fayange9753892022-05-17 03:57:11 -070015365 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -040015366 // ACK alarm fires.
15367 clock_.AdvanceTime(kAlarmGranularity);
15368 connection_.GetAckAlarm()->Fire();
fayange9753892022-05-17 03:57:11 -070015369 // Verify 1-RTT packet is coalesced.
martinduke9e0811c2022-12-08 20:35:57 -080015370 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015371 // Only the first packet in the coalesced packet has been processed,
15372 // verify SHLO is bundled with INITIAL ACK.
15373 EXPECT_EQ(1u, writer_->ack_frames().size());
15374 EXPECT_EQ(1u, writer_->crypto_frames().size());
15375 // Process the coalesced HANDSHAKE packet.
15376 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15377 auto packet = writer_->coalesced_packet()->Clone();
15378 writer_->framer()->ProcessPacket(*packet);
15379 EXPECT_EQ(0u, writer_->ack_frames().size());
15380 EXPECT_EQ(1u, writer_->crypto_frames().size());
fayange9753892022-05-17 03:57:11 -070015381 // Process the coalesced 1-RTT packet.
15382 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15383 packet = writer_->coalesced_packet()->Clone();
15384 writer_->framer()->ProcessPacket(*packet);
15385 EXPECT_EQ(0u, writer_->crypto_frames().size());
15386 EXPECT_EQ(1u, writer_->stream_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040015387
15388 // Received INITIAL 3.
15389 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
15390 ProcessCryptoPacketAtLevel(3, ENCRYPTION_INITIAL);
15391 EXPECT_TRUE(connection_.HasPendingAcks());
15392}
15393
15394// Regression test for b/216133388.
15395TEST_P(QuicConnectionTest, FailedToConsumeCryptoData) {
15396 if (!version().HasIetfQuicFrames()) {
15397 return;
15398 }
15399 set_perspective(Perspective::IS_SERVER);
15400 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15401 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015402 // Received INITIAL 1.
15403 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15404 EXPECT_TRUE(connection_.HasPendingAcks());
15405
martinduke9e0811c2022-12-08 20:35:57 -080015406 peer_framer_.SetEncrypter(
15407 ENCRYPTION_ZERO_RTT,
15408 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15409 connection_.SetEncrypter(
15410 ENCRYPTION_HANDSHAKE,
15411 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015412 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015413 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015414 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015415 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15416 connection_.SetEncrypter(
15417 ENCRYPTION_FORWARD_SECURE,
15418 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015419 // Received ENCRYPTION_ZERO_RTT 1.
15420 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15421 {
15422 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15423 // Send INITIAL 1.
15424 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15425 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15426 // Send HANDSHAKE 2.
15427 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15428 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15429 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15430 ENCRYPTION_HANDSHAKE);
15431 // Send 1-RTT 3.
15432 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15433 connection_.SendStreamDataWithString(0, std::string(40, 'a'), 0, NO_FIN);
15434 }
15435 // Received HANDSHAKE Ping, hence discard INITIAL keys.
15436 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15437 std::make_unique<TaggingEncrypter>(0x03));
15438 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15439 connection_.NeuterUnencryptedPackets();
15440 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
15441 clock_.AdvanceTime(kAlarmGranularity);
15442 {
15443 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15444 // Sending this 1-RTT data would leave the coalescer only have space to
15445 // accommodate the HANDSHAKE ACK. The crypto data cannot be bundled with the
15446 // ACK.
15447 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15448 connection_.SendStreamDataWithString(0, std::string(1395, 'a'), 40, NO_FIN);
15449 }
15450 // Verify retransmission alarm is armed.
15451 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15452 const QuicTime retransmission_time =
15453 connection_.GetRetransmissionAlarm()->deadline();
15454 clock_.AdvanceTime(retransmission_time - clock_.Now());
15455 connection_.GetRetransmissionAlarm()->Fire();
15456
fayang43294412022-04-21 09:22:12 -070015457 // Verify the retransmission is a coalesced packet with HANDSHAKE 2 and
15458 // 1-RTT 3.
martinduke9e0811c2022-12-08 20:35:57 -080015459 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
fayang43294412022-04-21 09:22:12 -070015460 // Only the first packet in the coalesced packet has been processed.
15461 EXPECT_EQ(1u, writer_->crypto_frames().size());
15462 // Process the coalesced 1-RTT packet.
15463 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15464 auto packet = writer_->coalesced_packet()->Clone();
15465 writer_->framer()->ProcessPacket(*packet);
15466 EXPECT_EQ(1u, writer_->stream_frames().size());
15467 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
Bence Békybac04052022-04-07 15:44:29 -040015468 // Verify retransmission alarm is still armed.
15469 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15470}
15471
15472TEST_P(QuicConnectionTest,
15473 RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing) {
15474 // An endpoint might postpone the processing of ACK when the corresponding
15475 // decryption key is not available. This test makes sure the RTT sample does
15476 // not include the queuing delay.
15477 if (!version().HasIetfQuicFrames()) {
15478 return;
15479 }
15480 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15481 QuicConfig config;
15482 config.set_max_undecryptable_packets(3);
15483 connection_.SetFromConfig(config);
15484
15485 // 30ms RTT.
15486 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
15487 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
15488 rtt_stats->UpdateRtt(kTestRTT, QuicTime::Delta::Zero(), QuicTime::Zero());
Bence Békybac04052022-04-07 15:44:29 -040015489
15490 // Send 0-RTT packet.
15491 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015492 connection_.SetEncrypter(
15493 ENCRYPTION_ZERO_RTT,
15494 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015495 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15496 connection_.SendStreamDataWithString(0, std::string(10, 'a'), 0, FIN);
15497
15498 // Receives 1-RTT ACK for 0-RTT packet after RTT + ack_delay.
15499 clock_.AdvanceTime(
15500 kTestRTT + QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
15501 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
martinduke9e0811c2022-12-08 20:35:57 -080015502 peer_framer_.SetEncrypter(
15503 ENCRYPTION_FORWARD_SECURE,
15504 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015505 QuicAckFrame ack_frame = InitAckFrame(1);
15506 // Peer reported ACK delay.
15507 ack_frame.ack_delay_time =
15508 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
15509 QuicFrames frames;
15510 frames.push_back(QuicFrame(&ack_frame));
15511 QuicPacketHeader header =
15512 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15513 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15514
15515 char buffer[kMaxOutgoingPacketSize];
15516 size_t encrypted_length = peer_framer_.EncryptPayload(
15517 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15518 kMaxOutgoingPacketSize);
15519 connection_.ProcessUdpPacket(
15520 kSelfAddress, kPeerAddress,
15521 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15522 if (connection_.GetSendAlarm()->IsSet()) {
15523 connection_.GetSendAlarm()->Fire();
15524 }
15525 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15526
15527 // Assume 1-RTT decrypter is available after 10ms.
15528 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15529 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080015530 SetDecrypter(
15531 ENCRYPTION_FORWARD_SECURE,
15532 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015533 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15534
15535 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
15536 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15537 // Verify RTT sample does not include queueing delay.
15538 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
15539}
15540
15541// Regression test for b/112480134.
15542TEST_P(QuicConnectionTest, NoExtraPaddingInReserializedInitial) {
15543 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
15544 if (!IsDefaultTestConfiguration() ||
15545 !connection_.version().CanSendCoalescedPackets()) {
15546 return;
15547 }
15548
15549 set_perspective(Perspective::IS_SERVER);
15550 MockQuicConnectionDebugVisitor debug_visitor;
15551 connection_.set_debug_visitor(&debug_visitor);
15552
15553 uint64_t debug_visitor_sent_count = 0;
15554 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _))
15555 .WillRepeatedly([&]() { debug_visitor_sent_count++; });
15556
15557 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15558 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015559
15560 // Received INITIAL 1.
15561 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15562
martinduke9e0811c2022-12-08 20:35:57 -080015563 peer_framer_.SetEncrypter(
15564 ENCRYPTION_ZERO_RTT,
15565 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15566 connection_.SetEncrypter(
15567 ENCRYPTION_HANDSHAKE,
15568 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015569 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015570 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015571 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015572 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15573 connection_.SetEncrypter(
15574 ENCRYPTION_FORWARD_SECURE,
15575 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015576
15577 // Received ENCRYPTION_ZERO_RTT 2.
15578 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15579
15580 {
15581 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15582 // Send INITIAL 1.
15583 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15584 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15585 // Send HANDSHAKE 2.
15586 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15587 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15588 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15589 ENCRYPTION_HANDSHAKE);
15590 // Send 1-RTT 3.
15591 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15592 connection_.SendStreamDataWithString(0, std::string(400, 'b'), 0, NO_FIN);
15593 }
15594
15595 // Arrange the stream data to be sent in response to ENCRYPTION_INITIAL 3.
15596 const std::string data4(1000, '4'); // Data to send in stream id 4
15597 const std::string data8(3000, '8'); // Data to send in stream id 8
15598 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce([&]() {
15599 connection_.producer()->SaveStreamData(4, data4);
15600 connection_.producer()->SaveStreamData(8, data8);
15601
15602 notifier_.WriteOrBufferData(4, data4.size(), FIN_AND_PADDING);
15603
15604 // This should trigger FlushCoalescedPacket.
15605 notifier_.WriteOrBufferData(8, data8.size(), FIN);
15606 });
15607
15608 QuicByteCount pending_padding_after_serialize_2nd_1rtt_packet = 0;
15609 QuicPacketCount num_1rtt_packets_serialized = 0;
15610 EXPECT_CALL(connection_, OnSerializedPacket(_))
15611 .WillRepeatedly([&](SerializedPacket packet) {
15612 if (packet.encryption_level == ENCRYPTION_FORWARD_SECURE) {
15613 num_1rtt_packets_serialized++;
15614 if (num_1rtt_packets_serialized == 2) {
15615 pending_padding_after_serialize_2nd_1rtt_packet =
15616 connection_.packet_creator().pending_padding_bytes();
15617 }
15618 }
15619 connection_.QuicConnection::OnSerializedPacket(std::move(packet));
15620 });
15621
15622 // Server receives INITIAL 3, this will serialzie FS 7 (stream 4, stream 8),
15623 // which will trigger a flush of a coalesced packet consists of INITIAL 4,
15624 // HS 5 and FS 6 (stream 4).
wub08efde42022-05-09 12:25:02 -070015625
15626 // Expect no QUIC_BUG.
15627 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15628 EXPECT_EQ(
15629 debug_visitor_sent_count,
15630 connection_.sent_packet_manager().GetLargestSentPacket().ToUint64());
Bence Békybac04052022-04-07 15:44:29 -040015631
15632 // The error only happens if after serializing the second 1RTT packet(pkt #7),
15633 // the pending padding bytes is non zero.
15634 EXPECT_GT(pending_padding_after_serialize_2nd_1rtt_packet, 0u);
15635 EXPECT_TRUE(connection_.connected());
15636}
15637
15638TEST_P(QuicConnectionTest, ReportedAckDelayIncludesQueuingDelay) {
15639 if (!version().HasIetfQuicFrames()) {
15640 return;
15641 }
15642 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15643 QuicConfig config;
15644 config.set_max_undecryptable_packets(3);
15645 connection_.SetFromConfig(config);
15646
15647 // Receive 1-RTT ack-eliciting packet while keys are not available.
15648 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015649 peer_framer_.SetEncrypter(
15650 ENCRYPTION_FORWARD_SECURE,
15651 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015652 QuicFrames frames;
15653 frames.push_back(QuicFrame(QuicPingFrame()));
15654 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
15655 QuicPacketHeader header =
15656 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15657 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15658
15659 char buffer[kMaxOutgoingPacketSize];
15660 size_t encrypted_length = peer_framer_.EncryptPayload(
15661 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15662 kMaxOutgoingPacketSize);
15663 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15664 const QuicTime packet_receipt_time = clock_.Now();
15665 connection_.ProcessUdpPacket(
15666 kSelfAddress, kPeerAddress,
15667 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15668 if (connection_.GetSendAlarm()->IsSet()) {
15669 connection_.GetSendAlarm()->Fire();
15670 }
15671 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15672 // 1-RTT keys become available after 10ms.
15673 const QuicTime::Delta kQueuingDelay = QuicTime::Delta::FromMilliseconds(10);
15674 clock_.AdvanceTime(kQueuingDelay);
15675 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15676 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015677 SetDecrypter(
15678 ENCRYPTION_FORWARD_SECURE,
15679 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015680 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15681
15682 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15683 ASSERT_TRUE(connection_.HasPendingAcks());
fayangfea655c2022-05-17 08:19:12 -070015684 EXPECT_EQ(packet_receipt_time + DefaultDelayedAckTime(),
15685 connection_.GetAckAlarm()->deadline());
15686 clock_.AdvanceTime(packet_receipt_time + DefaultDelayedAckTime() -
15687 clock_.Now());
Bence Békybac04052022-04-07 15:44:29 -040015688 // Fire ACK alarm.
15689 connection_.GetAckAlarm()->Fire();
15690 ASSERT_EQ(1u, writer_->ack_frames().size());
fayangfea655c2022-05-17 08:19:12 -070015691 // Verify ACK delay time does not include queuing delay.
15692 EXPECT_EQ(DefaultDelayedAckTime(), writer_->ack_frames()[0].ack_delay_time);
Bence Békybac04052022-04-07 15:44:29 -040015693}
15694
15695TEST_P(QuicConnectionTest, CoalesceOneRTTPacketWithInitialAndHandshakePackets) {
15696 if (!version().HasIetfQuicFrames()) {
15697 return;
15698 }
15699 set_perspective(Perspective::IS_SERVER);
15700 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15701 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015702
15703 // Received INITIAL 1.
15704 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15705
martinduke9e0811c2022-12-08 20:35:57 -080015706 peer_framer_.SetEncrypter(
15707 ENCRYPTION_ZERO_RTT,
15708 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015709
martinduke9e0811c2022-12-08 20:35:57 -080015710 connection_.SetEncrypter(
15711 ENCRYPTION_HANDSHAKE,
15712 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015713 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015714 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015715 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015716 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15717 connection_.SetEncrypter(
15718 ENCRYPTION_FORWARD_SECURE,
15719 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015720
15721 // Received ENCRYPTION_ZERO_RTT 2.
15722 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15723
15724 {
15725 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15726 // Send INITIAL 1.
15727 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15728 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15729 // Send HANDSHAKE 2.
15730 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15731 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15732 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15733 ENCRYPTION_HANDSHAKE);
15734 // Send 1-RTT data.
15735 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15736 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
15737 }
15738 // Verify coalesced packet [INITIAL 1 + HANDSHAKE 2 + part of 1-RTT data] +
15739 // rest of 1-RTT data get sent.
15740 EXPECT_EQ(2u, writer_->packets_write_attempts());
15741
15742 // Received ENCRYPTION_INITIAL 3.
15743 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15744
15745 // Verify a coalesced packet gets sent.
15746 EXPECT_EQ(3u, writer_->packets_write_attempts());
15747
15748 // Only the first INITIAL packet has been processed yet.
15749 EXPECT_EQ(1u, writer_->ack_frames().size());
15750 EXPECT_EQ(1u, writer_->crypto_frames().size());
15751
15752 // Process HANDSHAKE packet.
15753 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15754 auto packet = writer_->coalesced_packet()->Clone();
15755 writer_->framer()->ProcessPacket(*packet);
15756 EXPECT_EQ(1u, writer_->crypto_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040015757 // Process 1-RTT packet.
15758 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15759 packet = writer_->coalesced_packet()->Clone();
15760 writer_->framer()->ProcessPacket(*packet);
15761 EXPECT_EQ(1u, writer_->stream_frames().size());
15762}
15763
15764// Regression test for b/180103273
15765TEST_P(QuicConnectionTest, SendMultipleConnectionCloses) {
15766 if (!version().HasIetfQuicFrames() ||
15767 !GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
15768 return;
15769 }
15770 set_perspective(Perspective::IS_SERVER);
15771 // Finish handshake.
15772 QuicConnectionPeer::SetAddressValidated(&connection_);
15773 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15774 notifier_.NeuterUnencryptedData();
15775 connection_.NeuterUnencryptedPackets();
15776 connection_.OnHandshakeComplete();
15777 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15778 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
15779 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080015780 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040015781
15782 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
15783 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
bnc3000cba2022-04-18 12:19:14 -070015784 // Verify that BeforeConnectionCloseSent() gets called twice,
15785 // while OnConnectionClosed() is called only once.
Bence Békybac04052022-04-07 15:44:29 -040015786 EXPECT_CALL(visitor_, BeforeConnectionCloseSent()).Times(2);
15787 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15788 // Send connection close w/o closing connection.
15789 QuicConnectionPeer::SendConnectionClosePacket(
15790 &connection_, INTERNAL_ERROR, QUIC_INTERNAL_ERROR, "internal error");
bnc3000cba2022-04-18 12:19:14 -070015791 // Fire blackhole detection alarm. This will invoke
15792 // SendConnectionClosePacket() a second time.
15793 connection_.GetBlackholeDetectorAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -040015794}
15795
15796// Regression test for b/157895910.
15797TEST_P(QuicConnectionTest, EarliestSentTimeNotInitializedWhenPtoFires) {
15798 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15799 return;
15800 }
15801 set_perspective(Perspective::IS_SERVER);
15802 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15803 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015804
15805 // Received INITIAL 1.
15806 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080015807 connection_.SetEncrypter(
15808 ENCRYPTION_HANDSHAKE,
15809 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015810 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015811 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
15812 connection_.SetEncrypter(
15813 ENCRYPTION_FORWARD_SECURE,
15814 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015815 {
15816 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15817 // Send INITIAL 1.
15818 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15819 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15820 // Send HANDSHAKE 2.
15821 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15822 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15823 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15824 ENCRYPTION_HANDSHAKE);
15825 // Send half RTT data.
15826 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15827 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
15828 }
15829
15830 // Received ACKs for both INITIAL and HANDSHAKE packets.
15831 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
15832 .Times(AnyNumber());
15833 QuicFrames frames1;
15834 QuicAckFrame ack_frame1 = InitAckFrame(1);
15835 frames1.push_back(QuicFrame(&ack_frame1));
15836
15837 QuicFrames frames2;
15838 QuicAckFrame ack_frame2 =
15839 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
15840 frames2.push_back(QuicFrame(&ack_frame2));
15841 ProcessCoalescedPacket(
15842 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
15843 // Verify PTO is not armed given the only outstanding data is half RTT data.
15844 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15845}
15846
wub47bb7282022-06-14 09:40:33 -070015847TEST_P(QuicConnectionTest, CalculateNetworkBlackholeDelay) {
15848 if (!IsDefaultTestConfiguration()) {
15849 return;
15850 }
15851
15852 const QuicTime::Delta kOneSec = QuicTime::Delta::FromSeconds(1);
15853 const QuicTime::Delta kTwoSec = QuicTime::Delta::FromSeconds(2);
15854 const QuicTime::Delta kFourSec = QuicTime::Delta::FromSeconds(4);
15855
15856 // Normal case: blackhole_delay longer than path_degrading_delay +
15857 // 2*pto_delay.
15858 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
15859 kOneSec),
15860 kFourSec);
15861
15862 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
15863 kTwoSec),
15864 QuicTime::Delta::FromSeconds(5));
15865}
15866
fayangb225e172022-06-27 17:45:38 -070015867TEST_P(QuicConnectionTest, FixBytesAccountingForBufferedCoalescedPackets) {
15868 if (!connection_.version().CanSendCoalescedPackets()) {
15869 return;
15870 }
fayangb225e172022-06-27 17:45:38 -070015871 // Write is blocked.
15872 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
15873 writer_->SetWriteBlocked();
15874 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15875 QuicConnectionPeer::SendPing(&connection_);
15876 const QuicConnectionStats& stats = connection_.GetStats();
fayang4e283832022-09-01 12:47:07 -070015877 // Verify padding is accounted.
15878 EXPECT_EQ(stats.bytes_sent, connection_.max_packet_length());
fayangb225e172022-06-27 17:45:38 -070015879}
15880
fayang161ce6e2022-07-01 18:02:11 -070015881TEST_P(QuicConnectionTest, StrictAntiAmplificationLimit) {
15882 if (!connection_.version().SupportsAntiAmplificationLimit()) {
15883 return;
15884 }
15885 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
15886 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -070015887 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15888 // Verify no data can be sent at the beginning because bytes received is 0.
15889 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
15890 connection_.SendCryptoDataWithString("foo", 0);
15891 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
15892 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
15893 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15894
15895 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -070015896 GetQuicFlag(quic_anti_amplification_factor);
fayang161ce6e2022-07-01 18:02:11 -070015897 // Receives packet 1.
15898 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
15899 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
15900 .Times(anti_amplification_factor);
15901 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15902 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15903 std::make_unique<TaggingEncrypter>(0x02));
15904 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15905 std::make_unique<TaggingEncrypter>(0x03));
15906
15907 for (size_t i = 1; i < anti_amplification_factor - 1; ++i) {
15908 connection_.SendCryptoDataWithString("foo", i * 3);
15909 }
15910 // Send an addtion packet with max_packet_size - 1.
15911 connection_.SetMaxPacketLength(connection_.max_packet_length() - 1);
15912 connection_.SendCryptoDataWithString("bar",
15913 (anti_amplification_factor - 1) * 3);
15914 EXPECT_LT(writer_->total_bytes_written(),
15915 anti_amplification_factor *
15916 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
birenroyef686222022-09-12 11:34:34 -070015917 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070015918 // 3 connection closes which will be buffered.
15919 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
15920 // Verify retransmission alarm is not set.
15921 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15922 } else {
15923 // Crypto + 3 connection closes.
15924 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
15925 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15926 }
15927 // Try to send another packet with max_packet_size.
15928 connection_.SetMaxPacketLength(connection_.max_packet_length() + 1);
15929 connection_.SendCryptoDataWithString("bar", anti_amplification_factor * 3);
15930 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15931 // Close connection.
15932 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15933 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15934 connection_.CloseConnection(
15935 QUIC_INTERNAL_ERROR, "error",
15936 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
15937 EXPECT_EQ(0u, connection_.NumQueuedPackets());
birenroyef686222022-09-12 11:34:34 -070015938 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070015939 EXPECT_LT(writer_->total_bytes_written(),
15940 anti_amplification_factor *
15941 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15942 } else {
15943 EXPECT_LT(writer_->total_bytes_written(),
15944 (anti_amplification_factor + 2) *
15945 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15946 EXPECT_GT(writer_->total_bytes_written(),
15947 (anti_amplification_factor + 1) *
15948 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15949 }
15950}
15951
martinduke96840a02022-07-14 07:09:06 -070015952TEST_P(QuicConnectionTest, OriginalConnectionId) {
15953 set_perspective(Perspective::IS_SERVER);
15954 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
15955 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
15956 connection_.connection_id());
15957 QuicConnectionId original({0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
15958 connection_.SetOriginalDestinationConnectionId(original);
15959 EXPECT_EQ(original, connection_.GetOriginalDestinationConnectionId());
15960 // Send a 1-RTT packet to start the DiscardZeroRttDecryptionKeys timer.
15961 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
15962 ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE);
martindukee6444ef2022-09-23 12:32:23 -070015963 if (connection_.version().UsesTls()) {
martinduke96840a02022-07-14 07:09:06 -070015964 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
15965 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(original));
15966 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
15967 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
15968 connection_.connection_id());
15969 } else {
15970 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), original);
15971 }
15972}
15973
martindukebae24052022-10-06 15:27:46 -070015974ACTION_P2(InstallKeys, conn, level) {
15975 uint8_t crypto_input = (level == ENCRYPTION_FORWARD_SECURE) ? 0x03 : 0x02;
15976 conn->SetEncrypter(level, std::make_unique<TaggingEncrypter>(crypto_input));
15977 conn->InstallDecrypter(
15978 level, std::make_unique<StrictTaggingDecrypter>(crypto_input));
15979 conn->SetDefaultEncryptionLevel(level);
martindukec2a33062022-09-30 16:04:13 -070015980}
15981
martindukebae24052022-10-06 15:27:46 -070015982TEST_P(QuicConnectionTest, ServerConnectionIdChangeWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070015983 if (!connection_.version().HasIetfQuicFrames()) {
15984 return;
15985 }
15986 // Call SetFromConfig so that the undecrypted packet buffer size is
15987 // initialized above zero.
15988 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
15989 QuicConfig config;
15990 connection_.SetFromConfig(config);
martindukebae24052022-10-06 15:27:46 -070015991 connection_.RemoveEncrypter(ENCRYPTION_FORWARD_SECURE);
15992 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martindukec2a33062022-09-30 16:04:13 -070015993
15994 // Send Client Initial.
15995 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15996 connection_.SendCryptoStreamData();
15997
15998 EXPECT_EQ(1u, writer_->packets_write_attempts());
martindukebae24052022-10-06 15:27:46 -070015999 // Server Handshake packet with new connection ID is buffered.
martindukec2a33062022-09-30 16:04:13 -070016000 QuicConnectionId old_id = connection_id_;
16001 connection_id_ = TestConnectionId(2);
16002 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16003 std::make_unique<TaggingEncrypter>(0x02));
16004 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
martindukec2a33062022-09-30 16:04:13 -070016005 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16006 EXPECT_EQ(connection_.connection_id(), old_id);
16007
martindukebae24052022-10-06 15:27:46 -070016008 // Server 1-RTT Packet is buffered.
16009 peer_creator_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
16010 std::make_unique<TaggingEncrypter>(0x03));
16011 ProcessDataPacket(0);
16012 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 2u);
16013
martindukec2a33062022-09-30 16:04:13 -070016014 // Pretend the server Initial packet will yield the Handshake keys.
16015 EXPECT_CALL(visitor_, OnCryptoFrame(_))
16016 .Times(2)
martindukebae24052022-10-06 15:27:46 -070016017 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE))
16018 .WillOnce(InstallKeys(&connection_, ENCRYPTION_FORWARD_SECURE));
16019 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martindukec2a33062022-09-30 16:04:13 -070016020 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16021 // Two packets processed, connection ID changed.
16022 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16023 EXPECT_EQ(connection_.connection_id(), connection_id_);
16024}
16025
martindukebae24052022-10-06 15:27:46 -070016026TEST_P(QuicConnectionTest, ServerConnectionIdChangeTwiceWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070016027 if (!connection_.version().HasIetfQuicFrames()) {
16028 return;
16029 }
16030 // Call SetFromConfig so that the undecrypted packet buffer size is
16031 // initialized above zero.
16032 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
16033 QuicConfig config;
16034 connection_.SetFromConfig(config);
16035
16036 // Send Client Initial.
16037 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
16038 connection_.SendCryptoStreamData();
16039
16040 EXPECT_EQ(1u, writer_->packets_write_attempts());
16041 // Server Handshake Packet Arrives with new connection ID.
16042 QuicConnectionId old_id = connection_id_;
16043 connection_id_ = TestConnectionId(2);
16044 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
16045 std::make_unique<TaggingEncrypter>(0x02));
16046 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
16047 // Packet is buffered.
16048 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
16049 EXPECT_EQ(connection_.connection_id(), old_id);
16050
16051 // Pretend the server Initial packet will yield the Handshake keys.
16052 EXPECT_CALL(visitor_, OnCryptoFrame(_))
martindukebae24052022-10-06 15:27:46 -070016053 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE));
martindukec2a33062022-09-30 16:04:13 -070016054 connection_id_ = TestConnectionId(1);
16055 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
16056 // Handshake packet discarded because there's a different connection ID.
16057 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
16058 EXPECT_EQ(connection_.connection_id(), connection_id_);
16059}
16060
fayangdbd6a302022-12-21 16:24:27 -080016061TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress) {
16062 // Test the scenario where the client validates server preferred address by
16063 // receiving PATH_RESPONSE from server preferred address.
16064 if (!connection_.version().HasIetfQuicFrames()) {
16065 return;
16066 }
fayanga0618a62022-12-28 19:31:24 -080016067 QuicConfig config;
16068 config.SetClientConnectionOptions(QuicTagVector{kSPAD});
16069 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016070 const QuicSocketAddress kNewSelfAddress =
16071 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16072 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016073 const StatelessResetToken kNewStatelessResetToken =
16074 QuicUtils::GenerateStatelessResetToken(TestConnectionId(17));
16075 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16076 EXPECT_CALL(visitor_, GetHandshakeState())
16077 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16078 // Kick off path validation of server preferred address on handshake
16079 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016080 EXPECT_CALL(visitor_,
16081 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16082 .WillOnce(Invoke([&]() {
16083 connection_.ValidatePath(
16084 std::make_unique<TestQuicPathValidationContext>(
16085 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16086 std::make_unique<ServerPreferredAddressTestResultDelegate>(
16087 &connection_));
16088 }));
fayangdbd6a302022-12-21 16:24:27 -080016089 connection_.OnHandshakeComplete();
16090 EXPECT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016091 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16092 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016093 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016094 new_writer.last_packet_header().destination_connection_id);
16095 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016096
fayang37765f62022-12-27 17:49:13 -080016097 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016098 QuicPathFrameBuffer payload =
fayang37765f62022-12-27 17:49:13 -080016099 new_writer.path_challenge_frames().front().data_buffer;
fayangdbd6a302022-12-21 16:24:27 -080016100 // Send data packet while path validation is pending.
16101 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016102 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016103 // While path validation is pending, packet is sent on default path.
16104 EXPECT_EQ(TestConnectionId(),
16105 writer_->last_packet_header().destination_connection_id);
16106 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16107 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16108 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16109
danzh8fdee2e2023-01-05 15:33:02 -080016110 // Receive path response from server preferred address.
fayangdbd6a302022-12-21 16:24:27 -080016111 QuicFrames frames;
16112 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16113 // Verify send_algorithm gets reset after migration (new sent packet is not
16114 // updated to exsting send_algorithm_).
16115 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
fayang37765f62022-12-27 17:49:13 -080016116 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress,
16117 kServerPreferredAddress,
16118 ENCRYPTION_FORWARD_SECURE);
fayangdbd6a302022-12-21 16:24:27 -080016119 ASSERT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016120 EXPECT_TRUE(QuicConnectionPeer::IsDefaultPath(&connection_, kNewSelfAddress,
16121 kServerPreferredAddress));
16122 ASSERT_FALSE(new_writer.stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016123 // Verify stream data is retransmitted on new path.
16124 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016125 new_writer.last_packet_header().destination_connection_id);
16126 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016127 // Verify stateless reset token gets changed.
16128 EXPECT_FALSE(
16129 connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
16130 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kNewStatelessResetToken));
16131
16132 auto* retire_peer_issued_cid_alarm =
16133 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16134 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16135 // Verify client retires connection ID with sequence number 0.
16136 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16137 retire_peer_issued_cid_alarm->Fire();
fayang37765f62022-12-27 17:49:13 -080016138 EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16139 EXPECT_FALSE(
16140 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016141}
16142
16143TEST_P(QuicConnectionTest, ClientValidatedServerPreferredAddress2) {
16144 // Test the scenario where the client validates server preferred address by
16145 // receiving PATH_RESPONSE from original server address.
16146 if (!connection_.version().HasIetfQuicFrames()) {
16147 return;
16148 }
fayanga0618a62022-12-28 19:31:24 -080016149 QuicConfig config;
16150 config.SetClientConnectionOptions(QuicTagVector{kSPAD});
16151 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016152 const QuicSocketAddress kNewSelfAddress =
16153 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16154 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016155 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16156 EXPECT_CALL(visitor_, GetHandshakeState())
16157 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16158 // Kick off path validation of server preferred address on handshake
16159 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016160 EXPECT_CALL(visitor_,
16161 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16162 .WillOnce(Invoke([&]() {
16163 connection_.ValidatePath(
16164 std::make_unique<TestQuicPathValidationContext>(
16165 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16166 std::make_unique<ServerPreferredAddressTestResultDelegate>(
16167 &connection_));
16168 }));
fayangdbd6a302022-12-21 16:24:27 -080016169 connection_.OnHandshakeComplete();
16170 EXPECT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016171 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016172 QuicPathFrameBuffer payload =
fayang37765f62022-12-27 17:49:13 -080016173 new_writer.path_challenge_frames().front().data_buffer;
fayangdbd6a302022-12-21 16:24:27 -080016174 // Send data packet while path validation is pending.
16175 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016176 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016177 EXPECT_EQ(TestConnectionId(),
16178 writer_->last_packet_header().destination_connection_id);
16179 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16180
danzh8fdee2e2023-01-05 15:33:02 -080016181 // Receive path response from original server address.
fayangdbd6a302022-12-21 16:24:27 -080016182 QuicFrames frames;
16183 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
fayang37765f62022-12-27 17:49:13 -080016184 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
fayangdbd6a302022-12-21 16:24:27 -080016185 ENCRYPTION_FORWARD_SECURE);
16186 ASSERT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016187 ASSERT_FALSE(new_writer.stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016188 // Verify stream data is retransmitted on new path.
16189 EXPECT_EQ(TestConnectionId(17),
fayang37765f62022-12-27 17:49:13 -080016190 new_writer.last_packet_header().destination_connection_id);
16191 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
fayangdbd6a302022-12-21 16:24:27 -080016192
16193 auto* retire_peer_issued_cid_alarm =
16194 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16195 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16196 // Verify client retires connection ID with sequence number 0.
16197 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16198 retire_peer_issued_cid_alarm->Fire();
16199
16200 // Verify another packet from original server address gets processed.
16201 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
16202 frames.clear();
16203 frames.push_back(QuicFrame(frame1_));
16204 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
16205 ENCRYPTION_FORWARD_SECURE);
fayang37765f62022-12-27 17:49:13 -080016206 EXPECT_TRUE(connection_.GetStats().server_preferred_address_validated);
16207 EXPECT_FALSE(
16208 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016209}
16210
16211TEST_P(QuicConnectionTest, ClientFailedToValidateServerPreferredAddress) {
16212 // Test the scenario where the client fails to validate server preferred
16213 // address.
16214 if (!connection_.version().HasIetfQuicFrames()) {
16215 return;
16216 }
fayanga0618a62022-12-28 19:31:24 -080016217 QuicConfig config;
16218 config.SetClientConnectionOptions(QuicTagVector{kSPAD});
16219 ServerPreferredAddressInit(config);
fayang37765f62022-12-27 17:49:13 -080016220 const QuicSocketAddress kNewSelfAddress =
16221 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16222 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
fayangdbd6a302022-12-21 16:24:27 -080016223 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16224 EXPECT_CALL(visitor_, GetHandshakeState())
16225 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16226 // Kick off path validation of server preferred address on handshake
16227 // confirmed.
danzh8fdee2e2023-01-05 15:33:02 -080016228 EXPECT_CALL(visitor_,
16229 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16230 .WillOnce(Invoke([&]() {
16231 connection_.ValidatePath(
16232 std::make_unique<TestQuicPathValidationContext>(
16233 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16234 std::make_unique<ServerPreferredAddressTestResultDelegate>(
16235 &connection_));
16236 }));
fayangdbd6a302022-12-21 16:24:27 -080016237 connection_.OnHandshakeComplete();
danzh8fdee2e2023-01-05 15:33:02 -080016238 EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
fayang37765f62022-12-27 17:49:13 -080016239 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16240 &connection_, kNewSelfAddress, kServerPreferredAddress));
16241 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016242
16243 // Receive mismatched path challenge from original server address.
16244 QuicFrames frames;
16245 frames.push_back(
16246 QuicFrame(QuicPathResponseFrame(99, {0, 1, 2, 3, 4, 5, 6, 7})));
fayang37765f62022-12-27 17:49:13 -080016247 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
fayangdbd6a302022-12-21 16:24:27 -080016248 ENCRYPTION_FORWARD_SECURE);
16249 ASSERT_TRUE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016250 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16251 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016252
16253 // Simluate path validation times out.
16254 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16255 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16256 static_cast<TestAlarmFactory::TestAlarm*>(
16257 QuicPathValidatorPeer::retry_timer(
16258 QuicConnectionPeer::path_validator(&connection_)))
16259 ->Fire();
16260 }
16261 EXPECT_FALSE(connection_.HasPendingPathValidation());
fayang37765f62022-12-27 17:49:13 -080016262 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
16263 &connection_, kNewSelfAddress, kServerPreferredAddress));
fayangdbd6a302022-12-21 16:24:27 -080016264 // Verify stream data is sent on the default path.
16265 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
fayang37765f62022-12-27 17:49:13 -080016266 ASSERT_FALSE(writer_->stream_frames().empty());
fayangdbd6a302022-12-21 16:24:27 -080016267 EXPECT_EQ(TestConnectionId(),
16268 writer_->last_packet_header().destination_connection_id);
16269 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
16270
16271 auto* retire_peer_issued_cid_alarm =
16272 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16273 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16274 // Verify client retires connection ID with sequence number 1.
16275 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
16276 retire_peer_issued_cid_alarm->Fire();
16277 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestStatelessResetToken));
fayang37765f62022-12-27 17:49:13 -080016278 EXPECT_FALSE(connection_.GetStats().server_preferred_address_validated);
16279 EXPECT_TRUE(
16280 connection_.GetStats().failed_to_validate_server_preferred_address);
fayangdbd6a302022-12-21 16:24:27 -080016281}
16282
fayanga0618a62022-12-28 19:31:24 -080016283TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress) {
16284 if (!connection_.version().HasIetfQuicFrames()) {
16285 return;
16286 }
fayanga0618a62022-12-28 19:31:24 -080016287 const QuicSocketAddress kNewSelfAddress =
16288 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16289 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016290 EXPECT_CALL(visitor_,
16291 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16292 .WillOnce(Invoke([&]() {
16293 connection_.ValidatePath(
16294 std::make_unique<TestQuicPathValidationContext>(
16295 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16296 std::make_unique<ServerPreferredAddressTestResultDelegate>(
16297 &connection_));
16298 }));
fayanga0618a62022-12-28 19:31:24 -080016299 QuicConfig config;
16300 config.SetClientConnectionOptions(QuicTagVector{kSPAD, kSPA2});
16301 ServerPreferredAddressInit(config);
16302 EXPECT_TRUE(connection_.HasPendingPathValidation());
16303 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16304
16305 // Send data packet while path validation is pending.
16306 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16307 // Verify the packet is sent on both paths.
16308 EXPECT_FALSE(writer_->stream_frames().empty());
16309 EXPECT_FALSE(new_writer.stream_frames().empty());
16310
16311 // Verify packet duplication stops on handshake confirmed.
16312 EXPECT_CALL(visitor_, GetHandshakeState())
16313 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16314 connection_.OnHandshakeComplete();
16315 SendPing();
16316 EXPECT_FALSE(writer_->ping_frames().empty());
16317 EXPECT_TRUE(new_writer.ping_frames().empty());
16318}
16319
16320TEST_P(QuicConnectionTest, OptimizedServerPreferredAddress2) {
16321 if (!connection_.version().HasIetfQuicFrames()) {
16322 return;
16323 }
fayanga0618a62022-12-28 19:31:24 -080016324 const QuicSocketAddress kNewSelfAddress =
16325 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16326 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016327 EXPECT_CALL(visitor_,
16328 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16329 .WillOnce(Invoke([&]() {
16330 connection_.ValidatePath(
16331 std::make_unique<TestQuicPathValidationContext>(
16332 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16333 std::make_unique<ServerPreferredAddressTestResultDelegate>(
16334 &connection_));
16335 }));
fayanga0618a62022-12-28 19:31:24 -080016336 QuicConfig config;
16337 config.SetClientConnectionOptions(QuicTagVector{kSPAD, kSPA2});
16338 ServerPreferredAddressInit(config);
16339 EXPECT_TRUE(connection_.HasPendingPathValidation());
16340 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16341
16342 // Send data packet while path validation is pending.
16343 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
16344 // Verify the packet is sent on both paths.
16345 EXPECT_FALSE(writer_->stream_frames().empty());
16346 EXPECT_FALSE(new_writer.stream_frames().empty());
16347
16348 // Simluate path validation times out.
16349 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
16350 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
16351 static_cast<TestAlarmFactory::TestAlarm*>(
16352 QuicPathValidatorPeer::retry_timer(
16353 QuicConnectionPeer::path_validator(&connection_)))
16354 ->Fire();
16355 }
16356 EXPECT_FALSE(connection_.HasPendingPathValidation());
16357 // Verify packet duplication stops if there is no pending validation.
16358 SendPing();
16359 EXPECT_FALSE(writer_->ping_frames().empty());
16360 EXPECT_TRUE(new_writer.ping_frames().empty());
16361}
16362
16363TEST_P(QuicConnectionTest, MaxDuplicatedPacketsSentToServerPreferredAddress) {
16364 if (!connection_.version().HasIetfQuicFrames()) {
16365 return;
16366 }
fayanga0618a62022-12-28 19:31:24 -080016367 const QuicSocketAddress kNewSelfAddress =
16368 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16369 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
danzh8fdee2e2023-01-05 15:33:02 -080016370 EXPECT_CALL(visitor_,
16371 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16372 .WillOnce(Invoke([&]() {
16373 connection_.ValidatePath(
16374 std::make_unique<TestQuicPathValidationContext>(
16375 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16376 std::make_unique<ServerPreferredAddressTestResultDelegate>(
16377 &connection_));
16378 }));
fayanga0618a62022-12-28 19:31:24 -080016379 QuicConfig config;
16380 config.SetClientConnectionOptions(QuicTagVector{kSPAD, kSPA2});
16381 ServerPreferredAddressInit(config);
16382 EXPECT_TRUE(connection_.HasPendingPathValidation());
16383 ASSERT_FALSE(new_writer.path_challenge_frames().empty());
16384
16385 // Send data packet while path validation is pending.
16386 size_t write_limit = writer_->packets_write_attempts();
16387 size_t new_write_limit = new_writer.packets_write_attempts();
16388 for (size_t i = 0; i < kMaxDuplicatedPacketsSentToServerPreferredAddress;
16389 ++i) {
16390 connection_.SendStreamDataWithString(3, "foo", i * 3, NO_FIN);
16391 // Verify the packet is sent on both paths.
16392 ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
16393 ASSERT_EQ(new_write_limit + 1, new_writer.packets_write_attempts());
16394 ++write_limit;
16395 ++new_write_limit;
16396 EXPECT_FALSE(writer_->stream_frames().empty());
16397 EXPECT_FALSE(new_writer.stream_frames().empty());
16398 }
16399
16400 // Verify packet duplication stops if duplication limit is hit.
16401 SendPing();
16402 ASSERT_EQ(write_limit + 1, writer_->packets_write_attempts());
16403 ASSERT_EQ(new_write_limit, new_writer.packets_write_attempts());
16404 EXPECT_FALSE(writer_->ping_frames().empty());
16405 EXPECT_TRUE(new_writer.ping_frames().empty());
16406}
16407
danzh8fdee2e2023-01-05 15:33:02 -080016408TEST_P(QuicConnectionTest, MultiPortCreationAfterServerMigration) {
16409 if (!GetParam().version.HasIetfQuicFrames()) {
16410 return;
16411 }
16412 QuicConfig config;
16413 config.SetClientConnectionOptions(QuicTagVector{kMPQC, kSPAD});
16414 ServerPreferredAddressInit(config);
16415 if (!connection_.connection_migration_use_new_cid()) {
16416 return;
16417 }
16418 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
16419 QuicConnectionId cid_for_preferred_address = TestConnectionId(17);
16420 const QuicSocketAddress kNewSelfAddress =
16421 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
16422 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
16423 EXPECT_CALL(visitor_,
16424 OnServerPreferredAddressAvailable(kServerPreferredAddress))
16425 .WillOnce(Invoke([&]() {
16426 connection_.ValidatePath(
16427 std::make_unique<TestQuicPathValidationContext>(
16428 kNewSelfAddress, kServerPreferredAddress, &new_writer),
16429 std::make_unique<ServerPreferredAddressTestResultDelegate>(
16430 &connection_));
16431 }));
16432 // The connection should start probing the preferred address after handshake
16433 // confirmed.
16434 QuicPathFrameBuffer payload;
16435 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
16436 .Times(testing::AtLeast(1u))
16437 .WillOnce(Invoke([&]() {
16438 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
16439 payload = new_writer.path_challenge_frames().front().data_buffer;
16440 EXPECT_EQ(kServerPreferredAddress,
16441 new_writer.last_write_peer_address());
16442 }));
16443 EXPECT_CALL(visitor_, GetHandshakeState())
16444 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
16445 connection_.OnHandshakeComplete();
16446 EXPECT_TRUE(connection_.IsValidatingServerPreferredAddress());
16447
16448 // Receiving PATH_RESPONSE should cause the connection to migrate to the
16449 // preferred address.
16450 QuicFrames frames;
16451 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16452 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
16453 ENCRYPTION_FORWARD_SECURE);
16454 EXPECT_FALSE(connection_.IsValidatingServerPreferredAddress());
16455 EXPECT_EQ(kServerPreferredAddress, connection_.effective_peer_address());
16456 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
16457 EXPECT_EQ(connection_.connection_id(), cid_for_preferred_address);
16458
16459 // As the default path changed, the server issued CID 1 should be retired.
16460 auto* retire_peer_issued_cid_alarm =
16461 connection_.GetRetirePeerIssuedConnectionIdAlarm();
16462 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
16463 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
16464 retire_peer_issued_cid_alarm->Fire();
16465
16466 const QuicSocketAddress kNewSelfAddress2(kNewSelfAddress.host(),
16467 kNewSelfAddress.port() + 1);
16468 EXPECT_NE(kNewSelfAddress2, kNewSelfAddress);
16469 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
16470 QuicNewConnectionIdFrame frame;
16471 frame.connection_id = TestConnectionId(789);
16472 ASSERT_NE(frame.connection_id, connection_.connection_id());
16473 frame.stateless_reset_token =
16474 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
16475 frame.retire_prior_to = 0u;
16476 frame.sequence_number = 2u;
16477 EXPECT_CALL(visitor_, CreateContextForMultiPortPath())
16478 .WillOnce(Return(
16479 testing::ByMove(std::make_unique<TestQuicPathValidationContext>(
16480 kNewSelfAddress2, connection_.peer_address(), &new_writer2))));
16481 connection_.OnNewConnectionIdFrame(frame);
16482 EXPECT_TRUE(connection_.HasPendingPathValidation());
16483 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
16484 payload = new_writer.path_challenge_frames().front().data_buffer;
16485 EXPECT_EQ(kServerPreferredAddress, new_writer.last_write_peer_address());
16486 EXPECT_EQ(kNewSelfAddress2.host(), new_writer.last_write_source_address());
16487 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
16488 &connection_, kNewSelfAddress2, connection_.peer_address()));
16489 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
16490 EXPECT_FALSE(alt_path->validated);
16491 QuicFrames frames2;
16492 frames2.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
16493 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress2, kPeerAddress,
16494 ENCRYPTION_FORWARD_SECURE);
16495 EXPECT_TRUE(alt_path->validated);
16496}
16497
Bence Békybac04052022-04-07 15:44:29 -040016498} // namespace
16499} // namespace test
16500} // namespace quic