blob: b9d4dd8a870e2b3433bab0b4b73061cfda88cb74 [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);
105
106QuicStreamId GetNthClientInitiatedStreamId(int n,
107 QuicTransportVersion version) {
108 return QuicUtils::GetFirstBidirectionalStreamId(version,
109 Perspective::IS_CLIENT) +
110 n * 2;
111}
112
113QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
114 switch (level) {
115 case ENCRYPTION_INITIAL:
116 return INITIAL;
117 case ENCRYPTION_HANDSHAKE:
118 return HANDSHAKE;
119 case ENCRYPTION_ZERO_RTT:
120 return ZERO_RTT_PROTECTED;
121 case ENCRYPTION_FORWARD_SECURE:
122 QUICHE_DCHECK(false);
123 return INVALID_PACKET_TYPE;
124 default:
125 QUICHE_DCHECK(false);
126 return INVALID_PACKET_TYPE;
127 }
128}
129
martinduke9e0811c2022-12-08 20:35:57 -0800130// A TaggingEncrypterWithConfidentialityLimit is a TaggingEncrypter that allows
Bence Békybac04052022-04-07 15:44:29 -0400131// specifying the confidentiality limit on the maximum number of packets that
132// may be encrypted per key phase in TLS+QUIC.
martinduke9e0811c2022-12-08 20:35:57 -0800133class TaggingEncrypterWithConfidentialityLimit : public TaggingEncrypter {
Bence Békybac04052022-04-07 15:44:29 -0400134 public:
martinduke9e0811c2022-12-08 20:35:57 -0800135 TaggingEncrypterWithConfidentialityLimit(
136 uint8_t tag, QuicPacketCount confidentiality_limit)
137 : TaggingEncrypter(tag), confidentiality_limit_(confidentiality_limit) {}
Bence Békybac04052022-04-07 15:44:29 -0400138
139 QuicPacketCount GetConfidentialityLimit() const override {
140 return confidentiality_limit_;
141 }
142
143 private:
144 QuicPacketCount confidentiality_limit_;
145};
146
147class StrictTaggingDecrypterWithIntegrityLimit : public StrictTaggingDecrypter {
148 public:
149 StrictTaggingDecrypterWithIntegrityLimit(uint8_t tag,
150 QuicPacketCount integrity_limit)
151 : StrictTaggingDecrypter(tag), integrity_limit_(integrity_limit) {}
152
153 QuicPacketCount GetIntegrityLimit() const override {
154 return integrity_limit_;
155 }
156
157 private:
158 QuicPacketCount integrity_limit_;
159};
160
161class TestConnectionHelper : public QuicConnectionHelperInterface {
162 public:
163 TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
164 : clock_(clock), random_generator_(random_generator) {
165 clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
166 }
167 TestConnectionHelper(const TestConnectionHelper&) = delete;
168 TestConnectionHelper& operator=(const TestConnectionHelper&) = delete;
169
170 // QuicConnectionHelperInterface
171 const QuicClock* GetClock() const override { return clock_; }
172
173 QuicRandom* GetRandomGenerator() override { return random_generator_; }
174
175 quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override {
176 return &buffer_allocator_;
177 }
178
179 private:
180 MockClock* clock_;
181 MockRandom* random_generator_;
182 quiche::SimpleBufferAllocator buffer_allocator_;
183};
184
185class TestConnection : public QuicConnection {
186 public:
187 TestConnection(QuicConnectionId connection_id,
188 QuicSocketAddress initial_self_address,
189 QuicSocketAddress initial_peer_address,
190 TestConnectionHelper* helper, TestAlarmFactory* alarm_factory,
191 TestPacketWriter* writer, Perspective perspective,
martinduke605dca22022-09-01 10:40:19 -0700192 ParsedQuicVersion version,
193 ConnectionIdGeneratorInterface& generator)
Bence Békybac04052022-04-07 15:44:29 -0400194 : QuicConnection(connection_id, initial_self_address,
195 initial_peer_address, helper, alarm_factory, writer,
196 /* owns_writer= */ false, perspective,
martinduke605dca22022-09-01 10:40:19 -0700197 SupportedVersions(version), generator),
Bence Békybac04052022-04-07 15:44:29 -0400198 notifier_(nullptr) {
199 writer->set_perspective(perspective);
200 SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800201 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -0400202 SetDataProducer(&producer_);
203 ON_CALL(*this, OnSerializedPacket(_))
204 .WillByDefault([this](SerializedPacket packet) {
205 QuicConnection::OnSerializedPacket(std::move(packet));
206 });
207 }
208 TestConnection(const TestConnection&) = delete;
209 TestConnection& operator=(const TestConnection&) = delete;
210
211 MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket packet), (override));
212
renjietangff3e9602022-10-25 12:16:49 -0700213 void OnEffectivePeerMigrationValidated(bool is_migration_linkable) override {
214 QuicConnection::OnEffectivePeerMigrationValidated(is_migration_linkable);
215 if (is_migration_linkable) {
216 num_linkable_client_migration_++;
217 } else {
218 num_unlinkable_client_migration_++;
219 }
220 }
221
222 uint32_t num_unlinkable_client_migration() const {
223 return num_unlinkable_client_migration_;
224 }
225
226 uint32_t num_linkable_client_migration() const {
227 return num_linkable_client_migration_;
228 }
229
Bence Békybac04052022-04-07 15:44:29 -0400230 void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
231 QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
232 }
233
234 void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
235 QuicConnectionPeer::SetLossAlgorithm(this, loss_algorithm);
236 }
237
238 void SendPacket(EncryptionLevel /*level*/, uint64_t packet_number,
239 std::unique_ptr<QuicPacket> packet,
240 HasRetransmittableData retransmittable, bool has_ack,
241 bool has_pending_frames) {
242 ScopedPacketFlusher flusher(this);
243 char buffer[kMaxOutgoingPacketSize];
244 size_t encrypted_length =
245 QuicConnectionPeer::GetFramer(this)->EncryptPayload(
246 ENCRYPTION_INITIAL, QuicPacketNumber(packet_number), *packet,
247 buffer, kMaxOutgoingPacketSize);
248 SerializedPacket serialized_packet(
249 QuicPacketNumber(packet_number), PACKET_4BYTE_PACKET_NUMBER, buffer,
250 encrypted_length, has_ack, has_pending_frames);
251 serialized_packet.peer_address = kPeerAddress;
252 if (retransmittable == HAS_RETRANSMITTABLE_DATA) {
253 serialized_packet.retransmittable_frames.push_back(
254 QuicFrame(QuicPingFrame()));
255 }
256 OnSerializedPacket(std::move(serialized_packet));
257 }
258
259 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
260 absl::string_view data,
261 QuicStreamOffset offset,
262 StreamSendingState state) {
QUICHE teamac0a8082022-06-13 09:17:05 -0700263 return SaveAndSendStreamData(id, data, offset, state, NOT_RETRANSMISSION);
264 }
265
266 QuicConsumedData SaveAndSendStreamData(QuicStreamId id,
267 absl::string_view data,
268 QuicStreamOffset offset,
269 StreamSendingState state,
270 TransmissionType transmission_type) {
Bence Békybac04052022-04-07 15:44:29 -0400271 ScopedPacketFlusher flusher(this);
272 producer_.SaveStreamData(id, data);
273 if (notifier_ != nullptr) {
QUICHE teamac0a8082022-06-13 09:17:05 -0700274 return notifier_->WriteOrBufferData(id, data.length(), state,
275 transmission_type);
Bence Békybac04052022-04-07 15:44:29 -0400276 }
277 return QuicConnection::SendStreamData(id, data.length(), offset, state);
278 }
279
280 QuicConsumedData SendStreamDataWithString(QuicStreamId id,
281 absl::string_view data,
282 QuicStreamOffset offset,
283 StreamSendingState state) {
284 ScopedPacketFlusher flusher(this);
285 if (!QuicUtils::IsCryptoStreamId(transport_version(), id) &&
286 this->encryption_level() == ENCRYPTION_INITIAL) {
287 this->SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
288 if (perspective() == Perspective::IS_CLIENT && !IsHandshakeComplete()) {
289 OnHandshakeComplete();
290 }
291 if (version().SupportsAntiAmplificationLimit()) {
292 QuicConnectionPeer::SetAddressValidated(this);
293 }
294 }
295 return SaveAndSendStreamData(id, data, offset, state);
296 }
297
298 QuicConsumedData SendApplicationDataAtLevel(EncryptionLevel encryption_level,
299 QuicStreamId id,
300 absl::string_view data,
301 QuicStreamOffset offset,
302 StreamSendingState state) {
303 ScopedPacketFlusher flusher(this);
304 QUICHE_DCHECK(encryption_level >= ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -0800305 SetEncrypter(encryption_level,
306 std::make_unique<TaggingEncrypter>(encryption_level));
Bence Békybac04052022-04-07 15:44:29 -0400307 SetDefaultEncryptionLevel(encryption_level);
308 return SaveAndSendStreamData(id, data, offset, state);
309 }
310
311 QuicConsumedData SendStreamData3() {
312 return SendStreamDataWithString(
313 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
314 NO_FIN);
315 }
316
317 QuicConsumedData SendStreamData5() {
318 return SendStreamDataWithString(
319 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
320 NO_FIN);
321 }
322
323 // Ensures the connection can write stream data before writing.
324 QuicConsumedData EnsureWritableAndSendStreamData5() {
325 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
326 return SendStreamData5();
327 }
328
329 // The crypto stream has special semantics so that it is not blocked by a
330 // congestion window limitation, and also so that it gets put into a separate
331 // packet (so that it is easier to reason about a crypto frame not being
332 // split needlessly across packet boundaries). As a result, we have separate
333 // tests for some cases for this stream.
334 QuicConsumedData SendCryptoStreamData() {
335 QuicStreamOffset offset = 0;
336 absl::string_view data("chlo");
337 if (!QuicVersionUsesCryptoFrames(transport_version())) {
338 return SendCryptoDataWithString(data, offset);
339 }
340 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
341 size_t bytes_written;
342 if (notifier_) {
343 bytes_written =
344 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
345 } else {
346 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
347 data.length(), offset);
348 }
349 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
350 }
351
352 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
353 QuicStreamOffset offset) {
354 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
355 }
356
357 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
358 QuicStreamOffset offset,
359 EncryptionLevel encryption_level) {
360 if (!QuicVersionUsesCryptoFrames(transport_version())) {
361 return SendStreamDataWithString(
362 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
363 NO_FIN);
364 }
365 producer_.SaveCryptoData(encryption_level, offset, data);
366 size_t bytes_written;
367 if (notifier_) {
368 bytes_written =
369 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
370 } else {
371 bytes_written = QuicConnection::SendCryptoData(encryption_level,
372 data.length(), offset);
373 }
374 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
375 }
376
377 void set_version(ParsedQuicVersion version) {
378 QuicConnectionPeer::GetFramer(this)->set_version(version);
379 }
380
381 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
382 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
383 writer()->SetSupportedVersions(versions);
384 }
385
386 // This should be called before setting customized encrypters/decrypters for
387 // connection and peer creator.
388 void set_perspective(Perspective perspective) {
389 writer()->set_perspective(perspective);
390 QuicConnectionPeer::ResetPeerIssuedConnectionIdManager(this);
391 QuicConnectionPeer::SetPerspective(this, perspective);
392 QuicSentPacketManagerPeer::SetPerspective(
393 QuicConnectionPeer::GetSentPacketManager(this), perspective);
394 QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators(
395 TestConnectionId());
Bence Békybac04052022-04-07 15:44:29 -0400396 }
397
398 // Enable path MTU discovery. Assumes that the test is performed from the
399 // server perspective and the higher value of MTU target is used.
400 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
401 ASSERT_EQ(Perspective::IS_SERVER, perspective());
402
403 if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) {
404 OnConfigNegotiated();
405 } else {
406 QuicConfig config;
407 QuicTagVector connection_options;
408 connection_options.push_back(kMTUH);
409 config.SetInitialReceivedConnectionOptions(connection_options);
410 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
411 SetFromConfig(config);
412 }
413
414 // Normally, the pacing would be disabled in the test, but calling
415 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
416 // pacing algorithm work.
417 EXPECT_CALL(*send_algorithm, PacingRate(_))
418 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
419 }
420
421 TestAlarmFactory::TestAlarm* GetAckAlarm() {
422 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
423 QuicConnectionPeer::GetAckAlarm(this));
424 }
425
426 TestAlarmFactory::TestAlarm* GetPingAlarm() {
427 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
428 QuicConnectionPeer::GetPingAlarm(this));
429 }
430
431 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
432 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
433 QuicConnectionPeer::GetRetransmissionAlarm(this));
434 }
435
436 TestAlarmFactory::TestAlarm* GetSendAlarm() {
437 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
438 QuicConnectionPeer::GetSendAlarm(this));
439 }
440
441 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
442 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
443 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
444 }
445
446 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
447 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
448 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
449 }
450
451 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
452 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
453 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
454 }
455
456 TestAlarmFactory::TestAlarm* GetDiscardPreviousOneRttKeysAlarm() {
457 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
458 QuicConnectionPeer::GetDiscardPreviousOneRttKeysAlarm(this));
459 }
460
461 TestAlarmFactory::TestAlarm* GetDiscardZeroRttDecryptionKeysAlarm() {
462 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
463 QuicConnectionPeer::GetDiscardZeroRttDecryptionKeysAlarm(this));
464 }
465
466 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
467 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
468 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
469 }
470
471 TestAlarmFactory::TestAlarm* GetRetirePeerIssuedConnectionIdAlarm() {
472 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
473 QuicConnectionPeer::GetRetirePeerIssuedConnectionIdAlarm(this));
474 }
475
476 TestAlarmFactory::TestAlarm* GetRetireSelfIssuedConnectionIdAlarm() {
477 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
478 QuicConnectionPeer::GetRetireSelfIssuedConnectionIdAlarm(this));
479 }
480
renjietangfca5c772022-08-25 13:48:21 -0700481 TestAlarmFactory::TestAlarm* GetMultiPortProbingAlarm() {
482 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
483 QuicConnectionPeer::GetMultiPortProbingAlarm(this));
484 }
485
Bence Békybac04052022-04-07 15:44:29 -0400486 void PathDegradingTimeout() {
487 QUICHE_DCHECK(PathDegradingDetectionInProgress());
488 GetBlackholeDetectorAlarm()->Fire();
489 }
490
491 bool PathDegradingDetectionInProgress() {
492 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
493 }
494
495 bool BlackholeDetectionInProgress() {
496 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
497 .IsInitialized();
498 }
499
500 bool PathMtuReductionDetectionInProgress() {
501 return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this)
502 .IsInitialized();
503 }
504
Bence Békybac04052022-04-07 15:44:29 -0400505 QuicByteCount GetBytesInFlight() {
506 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
507 }
508
509 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
510
511 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
512 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
513 }
514
Bence Békybac04052022-04-07 15:44:29 -0400515 void SendOrQueuePacket(SerializedPacket packet) override {
516 QuicConnection::SendOrQueuePacket(std::move(packet));
517 self_address_on_default_path_while_sending_packet_ = self_address();
518 }
519
520 QuicSocketAddress self_address_on_default_path_while_sending_packet() {
521 return self_address_on_default_path_while_sending_packet_;
522 }
523
524 SimpleDataProducer* producer() { return &producer_; }
525
526 using QuicConnection::active_effective_peer_migration_type;
527 using QuicConnection::IsCurrentPacketConnectivityProbing;
528 using QuicConnection::SelectMutualVersion;
Bence Békybac04052022-04-07 15:44:29 -0400529 using QuicConnection::set_defer_send_in_response_to_packets;
530
531 protected:
532 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
533 if (next_effective_peer_addr_) {
534 return *std::move(next_effective_peer_addr_);
535 }
536 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
537 }
538
539 private:
540 TestPacketWriter* writer() {
541 return static_cast<TestPacketWriter*>(QuicConnection::writer());
542 }
543
544 SimpleDataProducer producer_;
545
546 SimpleSessionNotifier* notifier_;
547
548 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
549
550 QuicSocketAddress self_address_on_default_path_while_sending_packet_;
renjietangff3e9602022-10-25 12:16:49 -0700551
552 uint32_t num_unlinkable_client_migration_ = 0;
553
554 uint32_t num_linkable_client_migration_ = 0;
Bence Békybac04052022-04-07 15:44:29 -0400555};
556
557enum class AckResponse { kDefer, kImmediate };
558
559// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
560struct TestParams {
561 TestParams(ParsedQuicVersion version, AckResponse ack_response,
562 bool no_stop_waiting)
563 : version(version),
564 ack_response(ack_response),
565 no_stop_waiting(no_stop_waiting) {}
566
567 ParsedQuicVersion version;
568 AckResponse ack_response;
569 bool no_stop_waiting;
570};
571
572// Used by ::testing::PrintToStringParamName().
573std::string PrintToString(const TestParams& p) {
574 return absl::StrCat(
575 ParsedQuicVersionToString(p.version), "_",
576 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
577 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
578}
579
580// Constructs various test permutations.
581std::vector<TestParams> GetTestParams() {
582 QuicFlagSaver flags;
583 std::vector<TestParams> params;
584 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
585 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
586 for (AckResponse ack_response :
587 {AckResponse::kDefer, AckResponse::kImmediate}) {
588 params.push_back(
589 TestParams(all_supported_versions[i], ack_response, true));
590 if (!all_supported_versions[i].HasIetfInvariantHeader()) {
591 params.push_back(
592 TestParams(all_supported_versions[i], ack_response, false));
593 }
594 }
595 }
596 return params;
597}
598
599class QuicConnectionTest : public QuicTestWithParam<TestParams> {
600 public:
601 // For tests that do silent connection closes, no such packet is generated. In
602 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
603 // should invoke this method, saving the frame, and then the test can verify
604 // the contents.
605 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
606 ConnectionCloseSource /*source*/) {
607 saved_connection_close_frame_ = frame;
608 connection_close_frame_count_++;
609 }
610
611 protected:
612 QuicConnectionTest()
613 : connection_id_(TestConnectionId()),
614 framer_(SupportedVersions(version()), QuicTime::Zero(),
615 Perspective::IS_CLIENT, connection_id_.length()),
616 send_algorithm_(new StrictMock<MockSendAlgorithm>),
617 loss_algorithm_(new MockLossAlgorithm()),
618 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
619 alarm_factory_(new TestAlarmFactory()),
620 peer_framer_(SupportedVersions(version()), QuicTime::Zero(),
621 Perspective::IS_SERVER, connection_id_.length()),
622 peer_creator_(connection_id_, &peer_framer_,
623 /*delegate=*/nullptr),
624 writer_(
625 new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)),
626 connection_(connection_id_, kSelfAddress, kPeerAddress, helper_.get(),
627 alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT,
martinduke605dca22022-09-01 10:40:19 -0700628 version(), connection_id_generator_),
Bence Békybac04052022-04-07 15:44:29 -0400629 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
630 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
631 frame1_(0, false, 0, absl::string_view(data1)),
632 frame2_(0, false, 3, absl::string_view(data2)),
633 crypto_frame_(ENCRYPTION_INITIAL, 0, absl::string_view(data1)),
634 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
635 connection_id_included_(CONNECTION_ID_PRESENT),
636 notifier_(&connection_),
637 connection_close_frame_count_(0) {
638 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
639 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
640 AckResponse::kDefer);
641 framer_.SetInitialObfuscators(TestConnectionId());
642 connection_.InstallInitialCrypters(TestConnectionId());
643 CrypterPair crypters;
644 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
645 TestConnectionId(), &crypters);
646 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
647 std::move(crypters.encrypter));
648 if (version().KnowsWhichDecrypterToUse()) {
649 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
650 std::move(crypters.decrypter));
651 } else {
652 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
653 std::move(crypters.decrypter));
654 }
655 for (EncryptionLevel level :
656 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
martinduke9e0811c2022-12-08 20:35:57 -0800657 peer_creator_.SetEncrypter(level,
658 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400659 }
660 QuicFramerPeer::SetLastSerializedServerConnectionId(
661 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
662 QuicFramerPeer::SetLastWrittenPacketNumberLength(
663 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
664 if (version().HasIetfInvariantHeader()) {
665 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
666 } else {
667 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
668 GetParam().no_stop_waiting);
669 }
670 QuicStreamId stream_id;
671 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
672 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
673 version().transport_version, Perspective::IS_CLIENT);
674 } else {
675 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
676 }
677 frame1_.stream_id = stream_id;
678 frame2_.stream_id = stream_id;
679 connection_.set_visitor(&visitor_);
680 connection_.SetSessionNotifier(&notifier_);
681 connection_.set_notifier(&notifier_);
682 connection_.SetSendAlgorithm(send_algorithm_);
683 connection_.SetLossAlgorithm(loss_algorithm_.get());
684 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
685 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
686 .Times(AnyNumber());
687 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
688 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
689 .WillRepeatedly(Return(kDefaultTCPMSS));
690 EXPECT_CALL(*send_algorithm_, PacingRate(_))
691 .WillRepeatedly(Return(QuicBandwidth::Zero()));
692 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
693 .Times(AnyNumber())
694 .WillRepeatedly(Return(QuicBandwidth::Zero()));
695 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
696 .Times(AnyNumber());
697 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
698 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
699 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
700 .Times(AnyNumber());
701 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
702 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
703 .Times(AnyNumber());
704 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
705 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
706 EXPECT_CALL(visitor_, OnCanWrite())
707 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
708 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
709 .WillRepeatedly(Return(false));
710 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
711 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
712 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
713 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
714 .Times(testing::AtMost(1));
715 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
716 .WillRepeatedly(Return(QuicTime::Zero()));
717 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
718 .Times(AnyNumber());
719 EXPECT_CALL(visitor_, GetHandshakeState())
720 .WillRepeatedly(Return(HANDSHAKE_START));
721 if (connection_.version().KnowsWhichDecrypterToUse()) {
722 connection_.InstallDecrypter(
723 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -0800724 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
725 } else {
726 connection_.SetAlternativeDecrypter(
727 ENCRYPTION_FORWARD_SECURE,
728 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE),
729 false);
Bence Békybac04052022-04-07 15:44:29 -0400730 }
731 peer_creator_.SetDefaultPeerAddress(kSelfAddress);
732 }
733
734 QuicConnectionTest(const QuicConnectionTest&) = delete;
735 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
736
737 ParsedQuicVersion version() { return GetParam().version; }
738
739 QuicStopWaitingFrame* stop_waiting() {
740 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
741 return &stop_waiting_;
742 }
743
744 QuicPacketNumber least_unacked() {
745 if (writer_->stop_waiting_frames().empty()) {
746 return QuicPacketNumber();
747 }
748 return writer_->stop_waiting_frames()[0].least_unacked;
749 }
750
Bence Békybac04052022-04-07 15:44:29 -0400751 void SetClientConnectionId(const QuicConnectionId& client_connection_id) {
752 connection_.set_client_connection_id(client_connection_id);
753 writer_->framer()->framer()->SetExpectedClientConnectionIdLength(
754 client_connection_id.length());
755 }
756
757 void SetDecrypter(EncryptionLevel level,
758 std::unique_ptr<QuicDecrypter> decrypter) {
759 if (connection_.version().KnowsWhichDecrypterToUse()) {
760 connection_.InstallDecrypter(level, std::move(decrypter));
761 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800762 connection_.SetAlternativeDecrypter(level, std::move(decrypter), false);
Bence Békybac04052022-04-07 15:44:29 -0400763 }
764 }
765
766 void ProcessPacket(uint64_t number) {
767 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
768 ProcessDataPacket(number);
769 if (connection_.GetSendAlarm()->IsSet()) {
770 connection_.GetSendAlarm()->Fire();
771 }
772 }
773
774 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
775 const QuicSocketAddress& peer_address,
776 const QuicReceivedPacket& packet) {
777 connection_.ProcessUdpPacket(self_address, peer_address, packet);
778 if (connection_.GetSendAlarm()->IsSet()) {
779 connection_.GetSendAlarm()->Fire();
780 }
781 }
782
783 QuicFrame MakeCryptoFrame() const {
784 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
785 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
786 }
787 return QuicFrame(QuicStreamFrame(
788 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
789 0u, absl::string_view()));
790 }
791
792 void ProcessFramePacket(QuicFrame frame) {
793 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress,
794 ENCRYPTION_FORWARD_SECURE);
795 }
796
797 void ProcessFramePacketWithAddresses(QuicFrame frame,
798 QuicSocketAddress self_address,
799 QuicSocketAddress peer_address,
800 EncryptionLevel level) {
801 QuicFrames frames;
802 frames.push_back(QuicFrame(frame));
803 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address,
804 level);
805 }
806
807 std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames,
808 EncryptionLevel level,
809 char* buffer,
810 size_t buffer_len) {
811 QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level));
812 peer_creator_.set_encryption_level(level);
813 QuicPacketCreatorPeer::SetSendVersionInPacket(
814 &peer_creator_,
815 level < ENCRYPTION_FORWARD_SECURE &&
816 connection_.perspective() == Perspective::IS_SERVER);
817
818 SerializedPacket serialized_packet =
819 QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
820 buffer, buffer_len);
821 return std::make_unique<QuicReceivedPacket>(
822 serialized_packet.encrypted_buffer, serialized_packet.encrypted_length,
823 clock_.Now());
824 }
825
826 void ProcessFramesPacketWithAddresses(QuicFrames frames,
827 QuicSocketAddress self_address,
828 QuicSocketAddress peer_address,
829 EncryptionLevel level) {
830 char buffer[kMaxOutgoingPacketSize];
831 connection_.ProcessUdpPacket(
832 self_address, peer_address,
833 *ConstructPacket(std::move(frames), level, buffer,
834 kMaxOutgoingPacketSize));
835 if (connection_.GetSendAlarm()->IsSet()) {
836 connection_.GetSendAlarm()->Fire();
837 }
838 }
839
840 // Bypassing the packet creator is unrealistic, but allows us to process
841 // packets the QuicPacketCreator won't allow us to create.
842 void ForceProcessFramePacket(QuicFrame frame) {
843 QuicFrames frames;
844 frames.push_back(QuicFrame(frame));
845 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
846 if (connection_.version().KnowsWhichDecrypterToUse()) {
847 send_version = true;
848 }
849 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
850 QuicPacketHeader header;
851 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
852 char encrypted_buffer[kMaxOutgoingPacketSize];
853 size_t length = peer_framer_.BuildDataPacket(
854 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
855 ENCRYPTION_INITIAL);
856 QUICHE_DCHECK_GT(length, 0u);
857
858 const size_t encrypted_length = peer_framer_.EncryptInPlace(
859 ENCRYPTION_INITIAL, header.packet_number,
860 GetStartOfEncryptedData(peer_framer_.version().transport_version,
861 header),
862 length, kMaxOutgoingPacketSize, encrypted_buffer);
863 QUICHE_DCHECK_GT(encrypted_length, 0u);
864
865 connection_.ProcessUdpPacket(
866 kSelfAddress, kPeerAddress,
867 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
868 }
869
870 size_t ProcessFramePacketAtLevel(uint64_t number, QuicFrame frame,
871 EncryptionLevel level) {
872 QuicFrames frames;
873 frames.push_back(frame);
874 return ProcessFramesPacketAtLevel(number, frames, level);
875 }
876
877 size_t ProcessFramesPacketAtLevel(uint64_t number, const QuicFrames& frames,
878 EncryptionLevel level) {
879 QuicPacketHeader header = ConstructPacketHeader(number, level);
880 // Set the correct encryption level and encrypter on peer_creator and
881 // peer_framer, respectively.
882 peer_creator_.set_encryption_level(level);
martinduke9e0811c2022-12-08 20:35:57 -0800883 if (level > ENCRYPTION_INITIAL) {
884 peer_framer_.SetEncrypter(level,
885 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400886 // Set the corresponding decrypter.
887 if (connection_.version().KnowsWhichDecrypterToUse()) {
888 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800889 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400890 } else {
martinduke9e0811c2022-12-08 20:35:57 -0800891 connection_.SetAlternativeDecrypter(
892 level, std::make_unique<StrictTaggingDecrypter>(level), false);
Bence Békybac04052022-04-07 15:44:29 -0400893 }
894 }
895 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
896
897 char buffer[kMaxOutgoingPacketSize];
898 size_t encrypted_length =
899 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
900 buffer, kMaxOutgoingPacketSize);
901 connection_.ProcessUdpPacket(
902 kSelfAddress, kPeerAddress,
903 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
904 if (connection_.GetSendAlarm()->IsSet()) {
905 connection_.GetSendAlarm()->Fire();
906 }
907 return encrypted_length;
908 }
909
910 struct PacketInfo {
911 PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level)
912 : packet_number(packet_number), frames(frames), level(level) {}
913
914 uint64_t packet_number;
915 QuicFrames frames;
916 EncryptionLevel level;
917 };
918
919 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) {
920 char coalesced_buffer[kMaxOutgoingPacketSize];
921 size_t coalesced_size = 0;
922 bool contains_initial = false;
923 for (const auto& packet : packets) {
924 QuicPacketHeader header =
925 ConstructPacketHeader(packet.packet_number, packet.level);
926 // Set the correct encryption level and encrypter on peer_creator and
927 // peer_framer, respectively.
928 peer_creator_.set_encryption_level(packet.level);
929 if (packet.level == ENCRYPTION_INITIAL) {
930 contains_initial = true;
931 }
martinduke9e0811c2022-12-08 20:35:57 -0800932 EncryptionLevel level =
933 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_);
934 if (level > ENCRYPTION_INITIAL) {
935 peer_framer_.SetEncrypter(level,
936 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400937 // Set the corresponding decrypter.
938 if (connection_.version().KnowsWhichDecrypterToUse()) {
939 connection_.InstallDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800940 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400941 } else {
942 connection_.SetDecrypter(
martinduke9e0811c2022-12-08 20:35:57 -0800943 level, std::make_unique<StrictTaggingDecrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -0400944 }
945 }
946 std::unique_ptr<QuicPacket> constructed_packet(
947 ConstructPacket(header, packet.frames));
948
949 char buffer[kMaxOutgoingPacketSize];
950 size_t encrypted_length = peer_framer_.EncryptPayload(
951 packet.level, QuicPacketNumber(packet.packet_number),
952 *constructed_packet, buffer, kMaxOutgoingPacketSize);
953 QUICHE_DCHECK_LE(coalesced_size + encrypted_length,
954 kMaxOutgoingPacketSize);
955 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
956 coalesced_size += encrypted_length;
957 }
958 if (contains_initial) {
959 // Padded coalesced packet to full if it contains initial packet.
960 memset(coalesced_buffer + coalesced_size, '0',
961 kMaxOutgoingPacketSize - coalesced_size);
962 }
963 connection_.ProcessUdpPacket(
964 kSelfAddress, kPeerAddress,
965 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(),
966 false));
967 if (connection_.GetSendAlarm()->IsSet()) {
968 connection_.GetSendAlarm()->Fire();
969 }
970 return coalesced_size;
971 }
972
973 size_t ProcessDataPacket(uint64_t number) {
974 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
975 }
976
977 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
978 return ProcessDataPacketAtLevel(packet_number, false,
979 ENCRYPTION_FORWARD_SECURE);
980 }
981
982 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
983 bool has_stop_waiting,
984 EncryptionLevel level) {
985 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
986 level);
987 }
988
989 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
990 QuicPacketHeader header = ConstructPacketHeader(number, level);
991 QuicFrames frames;
992 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
993 frames.push_back(QuicFrame(&crypto_frame_));
994 } else {
995 frames.push_back(QuicFrame(frame1_));
996 }
997 if (level == ENCRYPTION_INITIAL) {
998 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
999 }
1000 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1001 char buffer[kMaxOutgoingPacketSize];
1002 peer_creator_.set_encryption_level(level);
1003 size_t encrypted_length =
1004 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1005 buffer, kMaxOutgoingPacketSize);
1006 connection_.ProcessUdpPacket(
1007 kSelfAddress, kPeerAddress,
1008 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1009 if (connection_.GetSendAlarm()->IsSet()) {
1010 connection_.GetSendAlarm()->Fire();
1011 }
1012 return encrypted_length;
1013 }
1014
1015 size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting,
1016 EncryptionLevel level) {
1017 std::unique_ptr<QuicPacket> packet(
1018 ConstructDataPacket(number, has_stop_waiting, level));
1019 char buffer[kMaxOutgoingPacketSize];
1020 peer_creator_.set_encryption_level(level);
1021 size_t encrypted_length =
1022 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1023 buffer, kMaxOutgoingPacketSize);
1024 connection_.ProcessUdpPacket(
1025 kSelfAddress, kPeerAddress,
1026 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1027 if (connection_.GetSendAlarm()->IsSet()) {
1028 connection_.GetSendAlarm()->Fire();
1029 }
1030 return encrypted_length;
1031 }
1032
1033 void ProcessClosePacket(uint64_t number) {
1034 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
1035 char buffer[kMaxOutgoingPacketSize];
1036 size_t encrypted_length = peer_framer_.EncryptPayload(
1037 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
1038 kMaxOutgoingPacketSize);
1039 connection_.ProcessUdpPacket(
1040 kSelfAddress, kPeerAddress,
1041 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1042 }
1043
1044 QuicByteCount SendStreamDataToPeer(QuicStreamId id, absl::string_view data,
1045 QuicStreamOffset offset,
1046 StreamSendingState state,
1047 QuicPacketNumber* last_packet) {
QUICHE team24a23852022-10-31 18:03:52 -07001048 QuicByteCount packet_size = 0;
Bence Békybac04052022-04-07 15:44:29 -04001049 // Save the last packet's size.
1050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1051 .Times(AnyNumber())
1052 .WillRepeatedly(SaveArg<3>(&packet_size));
1053 connection_.SendStreamDataWithString(id, data, offset, state);
1054 if (last_packet != nullptr) {
1055 *last_packet = creator_->packet_number();
1056 }
1057 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1058 .Times(AnyNumber());
1059 return packet_size;
1060 }
1061
1062 void SendAckPacketToPeer() {
1063 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1064 {
1065 QuicConnection::ScopedPacketFlusher flusher(&connection_);
1066 connection_.SendAck();
1067 }
1068 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1069 .Times(AnyNumber());
1070 }
1071
1072 void SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error,
1073 QuicStreamOffset bytes_written) {
1074 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1075 connection_.OnStreamReset(id, error);
1076 }
1077
1078 void SendPing() { notifier_.WriteOrBufferPing(); }
1079
1080 MessageStatus SendMessage(absl::string_view message) {
1081 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1082 quiche::QuicheMemSlice slice(quiche::QuicheBuffer::Copy(
1083 connection_.helper()->GetStreamSendBufferAllocator(), message));
1084 return connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false);
1085 }
1086
1087 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1088 if (packet_number > 1) {
1089 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1090 } else {
1091 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1092 }
1093 ProcessFramePacket(QuicFrame(frame));
1094 }
1095
1096 void ProcessAckPacket(QuicAckFrame* frame) {
1097 ProcessFramePacket(QuicFrame(frame));
1098 }
1099
1100 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1101 ProcessFramePacket(QuicFrame(frame));
1102 }
1103
1104 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1105 QuicStopWaitingFrame frame,
1106 EncryptionLevel /*level*/) {
1107 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1108 ENCRYPTION_ZERO_RTT);
1109 }
1110
1111 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1112 ProcessFramePacket(QuicFrame(frame));
1113 }
1114
1115 bool IsMissing(uint64_t number) {
1116 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
1117 QuicPacketNumber());
1118 }
1119
1120 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1121 const QuicFrames& frames) {
1122 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1123 EXPECT_NE(nullptr, packet.get());
1124 return packet;
1125 }
1126
1127 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1128 EncryptionLevel level) {
1129 QuicPacketHeader header;
1130 if (peer_framer_.version().HasIetfInvariantHeader() &&
1131 level < ENCRYPTION_FORWARD_SECURE) {
1132 // Set long header type accordingly.
1133 header.version_flag = true;
1134 header.form = IETF_QUIC_LONG_HEADER_PACKET;
1135 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1136 if (QuicVersionHasLongHeaderLengths(
1137 peer_framer_.version().transport_version)) {
dschinazi35c0ff72022-08-16 12:10:06 -07001138 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04001139 if (header.long_packet_type == INITIAL) {
dschinazi35c0ff72022-08-16 12:10:06 -07001140 header.retry_token_length_length =
1141 quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
Bence Békybac04052022-04-07 15:44:29 -04001142 }
1143 }
1144 }
1145 // Set connection_id to peer's in memory representation as this data packet
1146 // is created by peer_framer.
1147 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1148 header.source_connection_id = connection_id_;
1149 header.source_connection_id_included = connection_id_included_;
1150 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1151 } else {
1152 header.destination_connection_id = connection_id_;
1153 header.destination_connection_id_included = connection_id_included_;
1154 }
1155 if (peer_framer_.version().HasIetfInvariantHeader() &&
1156 peer_framer_.perspective() == Perspective::IS_SERVER) {
1157 if (!connection_.client_connection_id().IsEmpty()) {
1158 header.destination_connection_id = connection_.client_connection_id();
1159 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
1160 } else {
1161 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1162 }
1163 if (header.version_flag) {
1164 header.source_connection_id = connection_id_;
1165 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1166 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1167 header.long_packet_type == ZERO_RTT_PROTECTED) {
1168 header.nonce = &kTestDiversificationNonce;
1169 }
1170 }
1171 }
martinduke9e0811c2022-12-08 20:35:57 -08001172 if (!peer_framer_.version().HasIetfInvariantHeader() &&
1173 peer_framer_.perspective() == Perspective::IS_SERVER &&
1174 GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1175 level == ENCRYPTION_ZERO_RTT) {
1176 header.nonce = &kTestDiversificationNonce;
1177 }
Bence Békybac04052022-04-07 15:44:29 -04001178 header.packet_number_length = packet_number_length_;
1179 header.packet_number = QuicPacketNumber(number);
1180 return header;
1181 }
1182
1183 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1184 bool has_stop_waiting,
1185 EncryptionLevel level) {
1186 QuicPacketHeader header = ConstructPacketHeader(number, level);
1187 QuicFrames frames;
1188 if (VersionHasIetfQuicFrames(version().transport_version) &&
1189 (level == ENCRYPTION_INITIAL || level == ENCRYPTION_HANDSHAKE)) {
1190 frames.push_back(QuicFrame(QuicPingFrame()));
1191 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
1192 } else {
1193 frames.push_back(QuicFrame(frame1_));
1194 if (has_stop_waiting) {
1195 frames.push_back(QuicFrame(stop_waiting_));
1196 }
1197 }
1198 return ConstructPacket(header, frames);
1199 }
1200
1201 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
1202 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1203 if (VersionHasIetfQuicFrames(version().transport_version)) {
1204 QuicPathFrameBuffer payload = {
1205 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1206 return QuicPacketCreatorPeer::
1207 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1208 payload);
1209 }
1210 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1211 &peer_creator_);
1212 }
1213
1214 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1215 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1216 QuicPacketHeader header;
1217 // Set connection_id to peer's in memory representation as this connection
1218 // close packet is created by peer_framer.
1219 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1220 header.source_connection_id = connection_id_;
1221 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1222 if (!peer_framer_.version().HasIetfInvariantHeader()) {
1223 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1224 }
1225 } else {
1226 header.destination_connection_id = connection_id_;
1227 if (peer_framer_.version().HasIetfInvariantHeader()) {
1228 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1229 }
1230 }
1231
1232 header.packet_number = QuicPacketNumber(number);
1233
1234 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
1235 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1236 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
1237 /*transport_close_frame_type=*/0);
1238 QuicFrames frames;
1239 frames.push_back(QuicFrame(&qccf));
1240 return ConstructPacket(header, frames);
1241 }
1242
1243 QuicTime::Delta DefaultRetransmissionTime() {
1244 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1245 }
1246
1247 QuicTime::Delta DefaultDelayedAckTime() {
1248 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1249 }
1250
1251 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1252 QuicStopWaitingFrame frame;
1253 frame.least_unacked = QuicPacketNumber(least_unacked);
1254 return frame;
1255 }
1256
1257 // Construct a ack_frame that acks all packet numbers between 1 and
1258 // |largest_acked|, except |missing|.
1259 // REQUIRES: 1 <= |missing| < |largest_acked|
1260 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1261 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1262 QuicPacketNumber(missing));
1263 }
1264
1265 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1266 QuicPacketNumber missing) {
1267 if (missing == QuicPacketNumber(1)) {
1268 return InitAckFrame({{missing + 1, largest_acked + 1}});
1269 }
1270 return InitAckFrame(
1271 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1272 }
1273
1274 // Undo nacking a packet within the frame.
1275 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1276 EXPECT_FALSE(frame->packets.Contains(arrived));
1277 frame->packets.Add(arrived);
1278 }
1279
1280 void TriggerConnectionClose() {
1281 // Send an erroneous packet to close the connection.
1282 EXPECT_CALL(visitor_,
1283 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1284 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1285
1286 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1287 // Triggers a connection by receiving ACK of unsent packet.
1288 QuicAckFrame frame = InitAckFrame(10000);
1289 ProcessAckPacket(1, &frame);
1290 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1291 nullptr);
1292 EXPECT_EQ(1, connection_close_frame_count_);
1293 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1294 IsError(QUIC_INVALID_ACK_DATA));
1295 }
1296
1297 void BlockOnNextWrite() {
1298 writer_->BlockOnNextWrite();
1299 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1300 }
1301
1302 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1303
fayangf6607db2022-04-21 18:10:41 -07001304 void ExpectNextPacketUnprocessable() {
1305 writer_->ExpectNextPacketUnprocessable();
1306 }
1307
Bence Békybac04052022-04-07 15:44:29 -04001308 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1309
1310 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1311 writer_->SetWritePauseTimeDelta(delta);
1312 }
1313
1314 void CongestionBlockWrites() {
1315 EXPECT_CALL(*send_algorithm_, CanSend(_))
1316 .WillRepeatedly(testing::Return(false));
1317 }
1318
1319 void CongestionUnblockWrites() {
1320 EXPECT_CALL(*send_algorithm_, CanSend(_))
1321 .WillRepeatedly(testing::Return(true));
1322 }
1323
1324 void set_perspective(Perspective perspective) {
1325 connection_.set_perspective(perspective);
1326 if (perspective == Perspective::IS_SERVER) {
1327 QuicConfig config;
1328 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -07001329 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -04001330 QuicTagVector connection_options;
1331 connection_options.push_back(kRVCM);
1332 config.SetInitialReceivedConnectionOptions(connection_options);
1333 }
1334 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1335 connection_.SetFromConfig(config);
1336
1337 connection_.set_can_truncate_connection_ids(true);
1338 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
1339 connection_.OnSuccessfulVersionNegotiation();
1340 }
1341 QuicFramerPeer::SetPerspective(&peer_framer_,
1342 QuicUtils::InvertPerspective(perspective));
1343 peer_framer_.SetInitialObfuscators(TestConnectionId());
1344 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
1345 ENCRYPTION_FORWARD_SECURE}) {
1346 if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) {
martinduke9e0811c2022-12-08 20:35:57 -08001347 peer_creator_.SetEncrypter(level,
1348 std::make_unique<TaggingEncrypter>(level));
Bence Békybac04052022-04-07 15:44:29 -04001349 }
1350 }
1351 }
1352
1353 void set_packets_between_probes_base(
1354 const QuicPacketCount packets_between_probes_base) {
1355 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1356 &connection_, packets_between_probes_base,
1357 QuicPacketNumber(packets_between_probes_base));
1358 }
1359
1360 bool IsDefaultTestConfiguration() {
1361 TestParams p = GetParam();
1362 return p.ack_response == AckResponse::kImmediate &&
1363 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1364 }
1365
1366 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1367 // Not strictly needed for this test, but is commonly done.
1368 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1369 nullptr);
1370 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1371 writer_->connection_close_frames();
1372 ASSERT_EQ(1u, connection_close_frames.size());
1373
1374 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1375 IsError(expected_code));
1376
1377 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1378 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1379 IsError(expected_code));
1380 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1381 connection_close_frames[0].close_type);
1382 return;
1383 }
1384
1385 QuicErrorCodeToIetfMapping mapping =
1386 QuicErrorCodeToTransportErrorCode(expected_code);
1387
1388 if (mapping.is_transport_close) {
1389 // This Google QUIC Error Code maps to a transport close,
1390 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1391 connection_close_frames[0].close_type);
1392 } else {
1393 // This maps to an application close.
1394 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1395 connection_close_frames[0].close_type);
1396 }
1397 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
1398 }
1399
1400 void MtuDiscoveryTestInit() {
1401 set_perspective(Perspective::IS_SERVER);
1402 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1403 if (version().SupportsAntiAmplificationLimit()) {
1404 QuicConnectionPeer::SetAddressValidated(&connection_);
1405 }
1406 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1407 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04001408 // Prevent packets from being coalesced.
1409 EXPECT_CALL(visitor_, GetHandshakeState())
1410 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1411 EXPECT_TRUE(connection_.connected());
1412 }
1413
1414 void PathProbeTestInit(Perspective perspective,
1415 bool receive_new_server_connection_id = true) {
1416 set_perspective(perspective);
1417 connection_.CreateConnectionIdManager();
1418 EXPECT_EQ(connection_.perspective(), perspective);
1419 if (perspective == Perspective::IS_SERVER) {
1420 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1421 }
1422 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1423 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1424 // Discard INITIAL key.
1425 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1426 connection_.NeuterUnencryptedPackets();
1427 // Prevent packets from being coalesced.
1428 EXPECT_CALL(visitor_, GetHandshakeState())
1429 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1430 if (version().SupportsAntiAmplificationLimit() &&
1431 perspective == Perspective::IS_SERVER) {
1432 QuicConnectionPeer::SetAddressValidated(&connection_);
1433 }
1434 // Clear direct_peer_address.
1435 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1436 // Clear effective_peer_address, it is the same as direct_peer_address for
1437 // this test.
1438 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1439 QuicSocketAddress());
1440 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1441
1442 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1443 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1444 } else {
1445 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1446 }
1447 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1448 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1449 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1450 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1451 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1452 if (perspective == Perspective::IS_CLIENT &&
1453 receive_new_server_connection_id && version().HasIetfQuicFrames()) {
1454 QuicNewConnectionIdFrame frame;
1455 frame.connection_id = TestConnectionId(1234);
1456 ASSERT_NE(frame.connection_id, connection_.connection_id());
1457 frame.stateless_reset_token =
1458 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
1459 frame.retire_prior_to = 0u;
1460 frame.sequence_number = 1u;
1461 connection_.OnNewConnectionIdFrame(frame);
1462 }
1463 }
1464
1465 void TestClientRetryHandling(bool invalid_retry_tag,
1466 bool missing_original_id_in_config,
1467 bool wrong_original_id_in_config,
1468 bool missing_retry_id_in_config,
1469 bool wrong_retry_id_in_config);
1470
1471 void TestReplaceConnectionIdFromInitial();
1472
1473 QuicConnectionId connection_id_;
1474 QuicFramer framer_;
1475
1476 MockSendAlgorithm* send_algorithm_;
1477 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1478 MockClock clock_;
1479 MockRandom random_generator_;
1480 quiche::SimpleBufferAllocator buffer_allocator_;
1481 std::unique_ptr<TestConnectionHelper> helper_;
1482 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1483 QuicFramer peer_framer_;
1484 QuicPacketCreator peer_creator_;
1485 std::unique_ptr<TestPacketWriter> writer_;
1486 TestConnection connection_;
1487 QuicPacketCreator* creator_;
1488 QuicSentPacketManager* manager_;
1489 StrictMock<MockQuicConnectionVisitor> visitor_;
1490
1491 QuicStreamFrame frame1_;
1492 QuicStreamFrame frame2_;
1493 QuicCryptoFrame crypto_frame_;
1494 QuicAckFrame ack_;
1495 QuicStopWaitingFrame stop_waiting_;
1496 QuicPacketNumberLength packet_number_length_;
1497 QuicConnectionIdIncluded connection_id_included_;
1498
1499 SimpleSessionNotifier notifier_;
1500
1501 QuicConnectionCloseFrame saved_connection_close_frame_;
1502 int connection_close_frame_count_;
martinduke605dca22022-09-01 10:40:19 -07001503 MockConnectionIdGenerator connection_id_generator_;
Bence Békybac04052022-04-07 15:44:29 -04001504};
1505
1506// Run all end to end tests with all supported versions.
1507INSTANTIATE_TEST_SUITE_P(QuicConnectionTests, QuicConnectionTest,
1508 ::testing::ValuesIn(GetTestParams()),
1509 ::testing::PrintToStringParamName());
1510
1511// These two tests ensure that the QuicErrorCode mapping works correctly.
1512// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1513// If running IETF QUIC, the first will generate a transport connection
1514// close, the second an application connection close.
1515// The connection close codes for the two tests are manually chosen;
1516// they are expected to always map to transport- and application-
1517// closes, respectively. If that changes, new codes should be chosen.
1518TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1519 EXPECT_TRUE(connection_.connected());
1520 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1521 connection_.CloseConnection(
1522 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1523 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1524 EXPECT_FALSE(connection_.connected());
1525 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1526}
1527
1528// Test that the IETF QUIC Error code mapping function works
1529// properly for application connection close codes.
1530TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1531 EXPECT_TRUE(connection_.connected());
1532 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1533 connection_.CloseConnection(
1534 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1535 "Should be application close",
1536 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1537 EXPECT_FALSE(connection_.connected());
1538 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1539}
1540
1541TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1542 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1543
1544 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1545 EXPECT_TRUE(connection_.connected());
1546
1547 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1548 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1549 } else {
1550 EXPECT_CALL(visitor_, OnStreamFrame(_));
1551 }
1552 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1553 ENCRYPTION_INITIAL);
1554 // Cause change in self_address.
1555 QuicIpAddress host;
1556 host.FromString("1.1.1.1");
1557 QuicSocketAddress self_address(host, 123);
1558 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1559 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1560 } else {
1561 EXPECT_CALL(visitor_, OnStreamFrame(_));
1562 }
1563 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1564 ENCRYPTION_INITIAL);
1565 EXPECT_TRUE(connection_.connected());
1566}
1567
1568TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1569 set_perspective(Perspective::IS_SERVER);
1570 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1571
1572 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1573 EXPECT_TRUE(connection_.connected());
1574
1575 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1576 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1577 } else {
1578 EXPECT_CALL(visitor_, OnStreamFrame(_));
1579 }
1580 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1581 ENCRYPTION_INITIAL);
1582 // Cause change in self_address.
1583 QuicIpAddress host;
1584 host.FromString("1.1.1.1");
1585 QuicSocketAddress self_address(host, 123);
1586 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
1587 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fayang19027942022-05-16 10:29:29 -07001588 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1589 ENCRYPTION_INITIAL);
1590 EXPECT_TRUE(connection_.connected());
Bence Békybac04052022-04-07 15:44:29 -04001591 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
1592}
1593
1594TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1595 set_perspective(Perspective::IS_SERVER);
1596 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1597
1598 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1599 EXPECT_TRUE(connection_.connected());
1600
1601 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1602 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1603 } else {
1604 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1605 }
1606 QuicIpAddress host;
1607 host.FromString("1.1.1.1");
1608 QuicSocketAddress self_address1(host, 443);
1609 connection_.SetSelfAddress(self_address1);
1610 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1611 kPeerAddress, ENCRYPTION_INITIAL);
1612 // Cause self_address change to mapped Ipv4 address.
1613 QuicIpAddress host2;
1614 host2.FromString(
1615 absl::StrCat("::ffff:", connection_.self_address().host().ToString()));
1616 QuicSocketAddress self_address2(host2, connection_.self_address().port());
1617 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1618 kPeerAddress, ENCRYPTION_INITIAL);
1619 EXPECT_TRUE(connection_.connected());
1620 // self_address change back to Ipv4 address.
1621 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1622 kPeerAddress, ENCRYPTION_INITIAL);
1623 EXPECT_TRUE(connection_.connected());
1624}
1625
1626TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1627 set_perspective(Perspective::IS_SERVER);
1628 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1629 EXPECT_CALL(visitor_, GetHandshakeState())
1630 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1631
1632 // Clear direct_peer_address.
1633 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1634 // Clear effective_peer_address, it is the same as direct_peer_address for
1635 // this test.
1636 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1637 QuicSocketAddress());
1638
1639 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1640 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1641 } else {
1642 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1643 }
1644 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1645 const QuicSocketAddress kNewPeerAddress =
1646 QuicSocketAddress(QuicIpAddress::Loopback6(),
1647 /*port=*/23456);
1648 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1649 kNewPeerAddress, ENCRYPTION_INITIAL);
1650 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1651 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1652
1653 // Decrease packet number to simulate out-of-order packets.
1654 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1655 // This is an old packet, do not migrate.
1656 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1657 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1658 ENCRYPTION_INITIAL);
1659 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1660 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1661}
1662
1663TEST_P(QuicConnectionTest, PeerPortChangeAtServer) {
1664 set_perspective(Perspective::IS_SERVER);
1665 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1666 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1667 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1668 // Prevent packets from being coalesced.
1669 EXPECT_CALL(visitor_, GetHandshakeState())
1670 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1671 if (version().SupportsAntiAmplificationLimit()) {
1672 QuicConnectionPeer::SetAddressValidated(&connection_);
1673 }
1674
1675 // Clear direct_peer_address.
1676 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1677 // Clear effective_peer_address, it is the same as direct_peer_address for
1678 // this test.
1679 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1680 QuicSocketAddress());
1681 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1682
1683 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
1684 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
1685 rtt_stats->set_initial_rtt(default_init_rtt * 2);
1686 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
1687
fayang339f0c82022-04-30 14:20:02 -07001688 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
1689 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001690
1691 const QuicSocketAddress kNewPeerAddress =
1692 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1693 EXPECT_CALL(visitor_, OnStreamFrame(_))
1694 .WillOnce(Invoke(
1695 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1696 .WillOnce(Invoke(
1697 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1698 QuicFrames frames;
1699 frames.push_back(QuicFrame(frame1_));
1700 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1701 ENCRYPTION_FORWARD_SECURE);
1702 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1703 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1704
1705 // Process another packet with a different peer address on server side will
1706 // start connection migration.
1707 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1708 QuicFrames frames2;
1709 frames2.push_back(QuicFrame(frame2_));
1710 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1711 ENCRYPTION_FORWARD_SECURE);
1712 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1713 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1714 // PORT_CHANGE shouldn't state change in sent packet manager.
1715 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07001716 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001717 EXPECT_EQ(manager_->GetSendAlgorithm(), send_algorithm_);
1718 if (connection_.validate_client_address()) {
1719 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1720 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001721 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001722 }
1723}
1724
1725TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServer) {
1726 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07001727 if (!connection_.validate_client_address() ||
birenroyef686222022-09-12 11:34:34 -07001728 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04001729 return;
1730 }
1731 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1732 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1733 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1734 // Discard INITIAL key.
1735 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1736 connection_.NeuterUnencryptedPackets();
1737 // Prevent packets from being coalesced.
1738 EXPECT_CALL(visitor_, GetHandshakeState())
1739 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1740 QuicConnectionPeer::SetAddressValidated(&connection_);
1741 connection_.OnHandshakeComplete();
1742
1743 // Enable 5 RTO
1744 QuicConfig config;
1745 QuicTagVector connection_options;
1746 connection_options.push_back(k5RTO);
1747 config.SetInitialReceivedConnectionOptions(connection_options);
1748 QuicConfigPeer::SetNegotiated(&config, true);
1749 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
1750 connection_.connection_id());
1751 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
1752 QuicConnectionId());
1753 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1754 connection_.SetFromConfig(config);
1755
1756 // Clear direct_peer_address.
1757 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1758 // Clear effective_peer_address, it is the same as direct_peer_address for
1759 // this test.
1760 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1761 QuicSocketAddress());
1762 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1763
1764 const QuicSocketAddress kNewPeerAddress =
1765 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1766 EXPECT_CALL(visitor_, OnStreamFrame(_))
1767 .WillOnce(Invoke(
1768 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1769 .WillOnce(Invoke(
1770 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1771 QuicFrames frames;
1772 frames.push_back(QuicFrame(frame1_));
1773 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1774 ENCRYPTION_FORWARD_SECURE);
1775 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1776 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1777
1778 // Send some data to make connection has packets in flight.
1779 connection_.SendStreamData3();
1780 EXPECT_EQ(1u, writer_->packets_write_attempts());
1781 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
1782 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1783
1784 // Process another packet with a different peer address on server side will
1785 // start connection migration.
1786 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1787 // IETF QUIC send algorithm should be changed to a different object, so no
1788 // OnPacketSent() called on the old send algorithm.
1789 EXPECT_CALL(*send_algorithm_,
1790 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
1791 .Times(0);
1792 // Do not propagate OnCanWrite() to session notifier.
1793 EXPECT_CALL(visitor_, OnCanWrite()).Times(AtLeast(1u));
1794
1795 QuicFrames frames2;
1796 frames2.push_back(QuicFrame(frame2_));
1797 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1798 ENCRYPTION_FORWARD_SECURE);
1799 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1800 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1801 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1802 connection_.active_effective_peer_migration_type());
1803 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
1804 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1805
1806 EXPECT_EQ(2u, writer_->packets_write_attempts());
1807 EXPECT_FALSE(writer_->path_challenge_frames().empty());
1808 QuicPathFrameBuffer payload =
1809 writer_->path_challenge_frames().front().data_buffer;
1810 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
1811 send_algorithm_);
1812 // Switch to use the mock send algorithm.
1813 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
1814 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1815 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1816 .WillRepeatedly(Return(kDefaultTCPMSS));
1817 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1818 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1819 .Times(AnyNumber())
1820 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1821 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1822 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1823 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
1824 connection_.SetSendAlgorithm(send_algorithm_);
1825
1826 // PATH_CHALLENGE is expanded upto the max packet size which may exceeds the
1827 // anti-amplification limit.
1828 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
1829 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1830 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1831 EXPECT_EQ(1u,
1832 connection_.GetStats().num_reverse_path_validtion_upon_migration);
1833
1834 // Verify server is throttled by anti-amplification limit.
1835 connection_.SendCryptoDataWithString("foo", 0);
1836 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1837
1838 // Receiving an ACK to the packet sent after changing peer address doesn't
1839 // finish migration validation.
1840 QuicAckFrame ack_frame = InitAckFrame(2);
1841 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1842 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1843 kNewPeerAddress, 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
1849 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
1850 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -07001851 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04001852 EXPECT_CALL(visitor_, MaybeSendAddressToken());
1853 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1854 .Times(testing::AtLeast(1u));
1855 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
1856 ENCRYPTION_FORWARD_SECURE);
1857 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1858
1859 // Verify the anti-amplification limit is lifted by sending a packet larger
1860 // than the anti-amplification limit.
1861 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
1862 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001863 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001864}
1865
1866TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServerWithMissingConnectionId) {
1867 set_perspective(Perspective::IS_SERVER);
1868 if (!connection_.connection_migration_use_new_cid()) {
1869 return;
1870 }
1871 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1872 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1873
1874 QuicConnectionId client_cid0 = TestConnectionId(1);
1875 QuicConnectionId client_cid1 = TestConnectionId(3);
1876 QuicConnectionId server_cid1;
1877 SetClientConnectionId(client_cid0);
1878 connection_.CreateConnectionIdManager();
1879 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1880 // Prevent packets from being coalesced.
1881 EXPECT_CALL(visitor_, GetHandshakeState())
1882 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1883 QuicConnectionPeer::SetAddressValidated(&connection_);
1884
1885 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07001886 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07001887 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
1888 .WillOnce(Return(TestConnectionId(456)));
1889 }
haoyuewangada6b822022-06-23 13:41:18 -07001890 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
1891 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
1892 server_cid1 = cid;
1893 return true;
1894 }));
Bence Békybac04052022-04-07 15:44:29 -04001895 EXPECT_CALL(visitor_, SendNewConnectionId(_));
1896 connection_.OnHandshakeComplete();
1897
1898 // Clear direct_peer_address.
1899 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1900 // Clear effective_peer_address, it is the same as direct_peer_address for
1901 // this test.
1902 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1903 QuicSocketAddress());
1904 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1905
1906 const QuicSocketAddress kNewPeerAddress =
1907 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1908 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
1909 QuicFrames frames;
1910 frames.push_back(QuicFrame(frame1_));
1911 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1912 ENCRYPTION_FORWARD_SECURE);
1913 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1914 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1915
1916 // Send some data to make connection has packets in flight.
1917 connection_.SendStreamData3();
1918 EXPECT_EQ(1u, writer_->packets_write_attempts());
1919
1920 // Process another packet with a different peer address on server side will
1921 // start connection migration.
1922 peer_creator_.SetServerConnectionId(server_cid1);
1923 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1924 // Do not propagate OnCanWrite() to session notifier.
1925 EXPECT_CALL(visitor_, OnCanWrite()).Times(AtLeast(1u));
1926
1927 QuicFrames frames2;
1928 frames2.push_back(QuicFrame(frame2_));
birenroyef686222022-09-12 11:34:34 -07001929 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07001930 frames2.push_back(QuicFrame(QuicPaddingFrame(-1)));
1931 }
Bence Békybac04052022-04-07 15:44:29 -04001932 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1933 ENCRYPTION_FORWARD_SECURE);
1934 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1935 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1936
1937 // Writing path response & reverse path challenge is blocked due to missing
1938 // client connection ID, i.e., packets_write_attempts is unchanged.
1939 EXPECT_EQ(1u, writer_->packets_write_attempts());
1940
1941 // Receives new client CID from client would unblock write.
1942 QuicNewConnectionIdFrame new_cid_frame;
1943 new_cid_frame.connection_id = client_cid1;
1944 new_cid_frame.sequence_number = 1u;
1945 new_cid_frame.retire_prior_to = 0u;
1946 connection_.OnNewConnectionIdFrame(new_cid_frame);
1947 connection_.SendStreamData3();
1948
1949 EXPECT_EQ(2u, writer_->packets_write_attempts());
1950}
1951
1952TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
birenroyef686222022-09-12 11:34:34 -07001953 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07001954 return;
1955 }
Bence Békybac04052022-04-07 15:44:29 -04001956 set_perspective(Perspective::IS_SERVER);
1957 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1958 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1959 if (version().SupportsAntiAmplificationLimit()) {
1960 QuicConnectionPeer::SetAddressValidated(&connection_);
1961 }
1962 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1963 // Discard INITIAL key.
1964 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1965 connection_.NeuterUnencryptedPackets();
1966 EXPECT_CALL(visitor_, GetHandshakeState())
1967 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1968
1969 // Clear direct_peer_address.
1970 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1971 // Clear effective_peer_address, it is different from direct_peer_address for
1972 // this test.
1973 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1974 QuicSocketAddress());
1975 const QuicSocketAddress kEffectivePeerAddress =
1976 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1977 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1978
1979 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1980 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1981 } else {
1982 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1983 }
1984 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1985 ENCRYPTION_FORWARD_SECURE);
1986 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1987 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
1988
1989 // Process another packet with the same direct peer address and different
1990 // effective peer address on server side will start connection migration.
1991 const QuicSocketAddress kNewEffectivePeerAddress =
1992 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
1993 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
1994 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1995 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1996 ENCRYPTION_FORWARD_SECURE);
1997 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1998 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
1999 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
2000 if (connection_.validate_client_address()) {
2001 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2002 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07002003 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04002004 }
2005
2006 // Process another packet with a different direct peer address and the same
2007 // effective peer address on server side will not start connection migration.
2008 const QuicSocketAddress kNewPeerAddress =
2009 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2010 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2011 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2012
2013 if (!connection_.validate_client_address()) {
2014 // ack_frame is used to complete the migration started by the last packet,
2015 // we need to make sure a new migration does not start after the previous
2016 // one is completed.
2017 QuicAckFrame ack_frame = InitAckFrame(1);
2018 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2019 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2020 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2021 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2022 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2023 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2024 }
2025
2026 // Process another packet with different direct peer address and different
2027 // effective peer address on server side will start connection migration.
2028 const QuicSocketAddress kNewerEffectivePeerAddress =
2029 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2030 const QuicSocketAddress kFinalPeerAddress =
2031 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2032 connection_.ReturnEffectivePeerAddressForNextPacket(
2033 kNewerEffectivePeerAddress);
2034 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2035 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2036 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2037 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2038 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2039 if (connection_.validate_client_address()) {
2040 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2041 EXPECT_EQ(send_algorithm_,
2042 connection_.sent_packet_manager().GetSendAlgorithm());
2043 EXPECT_EQ(2u, connection_.GetStats().num_validated_peer_migration);
2044 }
2045
2046 // While the previous migration is ongoing, process another packet with the
2047 // same direct peer address and different effective peer address on server
2048 // side will start a new connection migration.
2049 const QuicSocketAddress kNewestEffectivePeerAddress =
2050 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2051 connection_.ReturnEffectivePeerAddressForNextPacket(
2052 kNewestEffectivePeerAddress);
2053 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2054 if (!connection_.validate_client_address()) {
2055 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
2056 }
2057 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2058 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2059 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2060 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2061 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2062 connection_.active_effective_peer_migration_type());
2063 if (connection_.validate_client_address()) {
2064 EXPECT_NE(send_algorithm_,
2065 connection_.sent_packet_manager().GetSendAlgorithm());
2066 EXPECT_EQ(kFinalPeerAddress, writer_->last_write_peer_address());
2067 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2068 EXPECT_EQ(0u, connection_.GetStats()
2069 .num_peer_migration_while_validating_default_path);
2070 EXPECT_TRUE(connection_.HasPendingPathValidation());
2071 }
2072}
2073
2074// Regression test for b/200020764.
2075TEST_P(QuicConnectionTest, ConnectionMigrationWithPendingPaddingBytes) {
2076 // TODO(haoyuewang) Move these test setup code to a common member function.
2077 set_perspective(Perspective::IS_SERVER);
2078 if (!connection_.connection_migration_use_new_cid()) {
2079 return;
2080 }
2081 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2082 connection_.CreateConnectionIdManager();
2083 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2084 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2085 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2086 QuicConnectionPeer::SetAddressValidated(&connection_);
2087
2088 // Sends new server CID to client.
2089 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002090 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002091 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2092 .WillOnce(Return(TestConnectionId(456)));
2093 }
haoyuewangada6b822022-06-23 13:41:18 -07002094 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2095 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2096 new_cid = cid;
2097 return true;
2098 }));
Bence Békybac04052022-04-07 15:44:29 -04002099 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2100 // Discard INITIAL key.
2101 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2102 connection_.NeuterUnencryptedPackets();
2103 connection_.OnHandshakeComplete();
2104 EXPECT_CALL(visitor_, GetHandshakeState())
2105 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2106
2107 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2108 packet_creator->FlushCurrentPacket();
2109 packet_creator->AddPendingPadding(50u);
2110 const QuicSocketAddress kPeerAddress3 =
2111 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2112 auto ack_frame = InitAckFrame(1);
2113 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2114 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2115 ProcessFramesPacketWithAddresses({QuicFrame(&ack_frame)}, kSelfAddress,
2116 kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
2117 if (GetQuicReloadableFlag(
2118 quic_flush_pending_frames_and_padding_bytes_on_migration)) {
2119 // Any pending frames/padding should be flushed before default_path_ is
2120 // temporarily reset.
2121 ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2122 .host()
2123 .address_family(),
2124 IpAddressFamily::IP_V6);
2125 } else {
2126 ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2127 .host()
2128 .address_family(),
2129 IpAddressFamily::IP_UNSPEC);
2130 }
2131}
2132
2133// Regression test for b/196208556.
2134TEST_P(QuicConnectionTest,
2135 ReversePathValidationResponseReceivedFromUnexpectedPeerAddress) {
2136 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07002137 if (!connection_.connection_migration_use_new_cid() ||
birenroyef686222022-09-12 11:34:34 -07002138 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04002139 return;
2140 }
2141 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2142 connection_.CreateConnectionIdManager();
2143 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2144 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2145 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2146 QuicConnectionPeer::SetAddressValidated(&connection_);
2147 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2148 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2149
2150 // Sends new server CID to client.
2151 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002152 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002153 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2154 .WillOnce(Return(TestConnectionId(456)));
2155 }
haoyuewangada6b822022-06-23 13:41:18 -07002156 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2157 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2158 new_cid = cid;
2159 return true;
2160 }));
Bence Békybac04052022-04-07 15:44:29 -04002161 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2162 // Discard INITIAL key.
2163 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2164 connection_.NeuterUnencryptedPackets();
2165 connection_.OnHandshakeComplete();
2166 EXPECT_CALL(visitor_, GetHandshakeState())
2167 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2168
2169 // Process a non-probing packet to migrate to path 2 and kick off reverse path
2170 // validation.
2171 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2172 const QuicSocketAddress kPeerAddress2 =
2173 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2174 peer_creator_.SetServerConnectionId(new_cid);
2175 ProcessFramesPacketWithAddresses({QuicFrame(QuicPingFrame())}, kSelfAddress,
2176 kPeerAddress2, ENCRYPTION_FORWARD_SECURE);
2177 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2178 QuicPathFrameBuffer reverse_path_challenge_payload =
2179 writer_->path_challenge_frames().front().data_buffer;
2180
2181 // Receiveds a packet from path 3 with PATH_RESPONSE frame intended to
2182 // validate path 2 and a non-probing frame.
2183 {
2184 QuicConnection::ScopedPacketFlusher flusher(&connection_);
2185 const QuicSocketAddress kPeerAddress3 =
2186 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2187 auto ack_frame = InitAckFrame(1);
2188 EXPECT_CALL(visitor_, OnConnectionMigration(IPV4_TO_IPV6_CHANGE)).Times(1);
2189 EXPECT_CALL(visitor_, MaybeSendAddressToken()).WillOnce(Invoke([this]() {
2190 connection_.SendControlFrame(
2191 QuicFrame(new QuicNewTokenFrame(1, "new_token")));
2192 return true;
2193 }));
wubd0152ca2022-04-08 08:26:44 -07002194 ProcessFramesPacketWithAddresses(
2195 {QuicFrame(QuicPathResponseFrame(0, reverse_path_challenge_payload)),
2196 QuicFrame(&ack_frame)},
2197 kSelfAddress, kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04002198 }
2199}
2200
2201TEST_P(QuicConnectionTest, ReversePathValidationFailureAtServer) {
2202 set_perspective(Perspective::IS_SERVER);
2203 if (!connection_.connection_migration_use_new_cid()) {
2204 return;
2205 }
2206 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2207 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2208 SetClientConnectionId(TestConnectionId(1));
2209 connection_.CreateConnectionIdManager();
2210 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2211 // Discard INITIAL key.
2212 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2213 connection_.NeuterUnencryptedPackets();
2214 // Prevent packets from being coalesced.
2215 EXPECT_CALL(visitor_, GetHandshakeState())
2216 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2217 QuicConnectionPeer::SetAddressValidated(&connection_);
2218
2219 QuicConnectionId client_cid0 = connection_.client_connection_id();
2220 QuicConnectionId client_cid1 = TestConnectionId(2);
2221 QuicConnectionId server_cid0 = connection_.connection_id();
2222 QuicConnectionId server_cid1;
2223 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07002224 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002225 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2226 .WillOnce(Return(TestConnectionId(456)));
2227 }
haoyuewangada6b822022-06-23 13:41:18 -07002228 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2229 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2230 server_cid1 = cid;
2231 return true;
2232 }));
Bence Békybac04052022-04-07 15:44:29 -04002233 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2234 connection_.OnHandshakeComplete();
2235 // Receives new client CID from client.
2236 QuicNewConnectionIdFrame new_cid_frame;
2237 new_cid_frame.connection_id = client_cid1;
2238 new_cid_frame.sequence_number = 1u;
2239 new_cid_frame.retire_prior_to = 0u;
2240 connection_.OnNewConnectionIdFrame(new_cid_frame);
2241 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2242 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2243 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2244
2245 // Clear direct_peer_address.
2246 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2247 // Clear effective_peer_address, it is the same as direct_peer_address for
2248 // this test.
2249 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2250 QuicSocketAddress());
2251 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2252
2253 const QuicSocketAddress kNewPeerAddress =
2254 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2255 EXPECT_CALL(visitor_, OnStreamFrame(_))
2256 .WillOnce(Invoke(
2257 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
2258 .WillOnce(Invoke(
2259 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
2260 QuicFrames frames;
2261 frames.push_back(QuicFrame(frame1_));
2262 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
2263 ENCRYPTION_FORWARD_SECURE);
2264 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2265 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2266
2267 // Process another packet with a different peer address on server side will
2268 // start connection migration.
2269 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2270 // IETF QUIC send algorithm should be changed to a different object, so no
2271 // OnPacketSent() called on the old send algorithm.
2272 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0);
2273
2274 QuicFrames frames2;
2275 frames2.push_back(QuicFrame(frame2_));
2276 QuicPaddingFrame padding;
2277 frames2.push_back(QuicFrame(padding));
2278 peer_creator_.SetServerConnectionId(server_cid1);
2279 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2280 ENCRYPTION_FORWARD_SECURE);
2281 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2282 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2283 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2284 connection_.active_effective_peer_migration_type());
2285 EXPECT_LT(0u, writer_->packets_write_attempts());
2286 EXPECT_TRUE(connection_.HasPendingPathValidation());
2287 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
2288 send_algorithm_);
2289 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2290 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2291 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2292 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
2293 const auto* alternative_path =
2294 QuicConnectionPeer::GetAlternativePath(&connection_);
2295 EXPECT_EQ(default_path->client_connection_id, client_cid1);
2296 EXPECT_EQ(default_path->server_connection_id, server_cid1);
2297 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
2298 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
2299 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
2300 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
2301
2302 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes; ++i) {
2303 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2304 static_cast<TestAlarmFactory::TestAlarm*>(
2305 QuicPathValidatorPeer::retry_timer(
2306 QuicConnectionPeer::path_validator(&connection_)))
2307 ->Fire();
2308 }
2309 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2310 connection_.active_effective_peer_migration_type());
2311
2312 // Make sure anti-amplification limit is not reached.
2313 ProcessFramesPacketWithAddresses(
2314 {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
2315 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2316 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2317 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2318
2319 // Advance the time so that the reverse path validation times out.
2320 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2321 static_cast<TestAlarmFactory::TestAlarm*>(
2322 QuicPathValidatorPeer::retry_timer(
2323 QuicConnectionPeer::path_validator(&connection_)))
2324 ->Fire();
2325 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2326 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2327 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2328 EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
2329 send_algorithm_);
2330 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2331
2332 // Verify that default_path_ is reverted and alternative_path_ is cleared.
2333 EXPECT_EQ(default_path->client_connection_id, client_cid0);
2334 EXPECT_EQ(default_path->server_connection_id, server_cid0);
2335 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
2336 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
2337 auto* retire_peer_issued_cid_alarm =
2338 connection_.GetRetirePeerIssuedConnectionIdAlarm();
2339 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
2340 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
2341 retire_peer_issued_cid_alarm->Fire();
2342 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2343 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2344}
2345
2346TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
2347 PathProbeTestInit(Perspective::IS_SERVER);
2348
2349 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2350 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
2351
2352 // Process a padded PING packet with no peer address change on server side
2353 // will be ignored. But a PATH CHALLENGE packet with no peer address change
2354 // will be considered as path probing.
2355 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2356
2357 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2358 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2359 probing_packet->encrypted_length),
2360 clock_.Now()));
2361
2362 uint64_t num_probing_received =
2363 connection_.GetStats().num_connectivity_probing_received;
2364 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2365
2366 EXPECT_EQ(
2367 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2368 connection_.GetStats().num_connectivity_probing_received);
2369 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2370 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2371}
2372
2373// Regression test for b/150161358.
2374TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
2375 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2376 writer_->SetWriteBlocked();
2377
2378 // Send a MTU packet while blocked. It should be buffered.
2379 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2380 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2381 EXPECT_TRUE(writer_->IsWriteBlocked());
2382
2383 writer_->AlwaysGetPacketTooLarge();
2384 writer_->SetWritable();
2385 connection_.OnCanWrite();
2386}
2387
2388TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2389 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2390 if (!IsDefaultTestConfiguration()) {
2391 return;
2392 }
2393
2394 set_perspective(Perspective::IS_CLIENT);
2395
2396 BlockOnNextWrite();
2397
2398 QuicStreamId stream_id = 2;
2399 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2400
2401 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2402
2403 writer_->SetWritable();
2404 connection_.SendConnectivityProbingPacket(writer_.get(),
2405 connection_.peer_address());
2406 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2407 connection_.OnCanWrite();
2408}
2409
2410TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2411 // Regression test for b/74073386.
2412 {
2413 InSequence seq;
2414 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2415 .Times(AtLeast(1));
2416 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
2417 }
2418
2419 set_perspective(Perspective::IS_CLIENT);
2420
2421 writer_->SimulateNextPacketTooLarge();
2422
2423 // This packet write should fail, which should cause the connection to close
2424 // after sending a connection close packet, then the failed packet should be
2425 // queued.
2426 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2427
2428 EXPECT_FALSE(connection_.connected());
2429 // No need to buffer packets.
2430 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2431
2432 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2433 connection_.OnCanWrite();
2434 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2435}
2436
2437class TestQuicPathValidationContext : public QuicPathValidationContext {
2438 public:
2439 TestQuicPathValidationContext(const QuicSocketAddress& self_address,
2440 const QuicSocketAddress& peer_address,
2441
2442 QuicPacketWriter* writer)
2443 : QuicPathValidationContext(self_address, peer_address),
2444 writer_(writer) {}
2445
2446 QuicPacketWriter* WriterToUse() override { return writer_; }
2447
2448 private:
2449 QuicPacketWriter* writer_;
2450};
2451
2452class TestValidationResultDelegate : public QuicPathValidator::ResultDelegate {
2453 public:
2454 TestValidationResultDelegate(QuicConnection* connection,
2455 const QuicSocketAddress& expected_self_address,
2456 const QuicSocketAddress& expected_peer_address,
2457 bool* success)
2458 : QuicPathValidator::ResultDelegate(),
2459 connection_(connection),
2460 expected_self_address_(expected_self_address),
2461 expected_peer_address_(expected_peer_address),
2462 success_(success) {}
2463 void OnPathValidationSuccess(
wub130bde92022-08-01 14:33:14 -07002464 std::unique_ptr<QuicPathValidationContext> context,
2465 QuicTime /*start_time*/) override {
Bence Békybac04052022-04-07 15:44:29 -04002466 EXPECT_EQ(expected_self_address_, context->self_address());
2467 EXPECT_EQ(expected_peer_address_, context->peer_address());
2468 *success_ = true;
2469 }
2470
2471 void OnPathValidationFailure(
2472 std::unique_ptr<QuicPathValidationContext> context) override {
2473 EXPECT_EQ(expected_self_address_, context->self_address());
2474 EXPECT_EQ(expected_peer_address_, context->peer_address());
2475 if (connection_->perspective() == Perspective::IS_CLIENT) {
renjietang864fbda2022-09-08 10:50:07 -07002476 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false);
Bence Békybac04052022-04-07 15:44:29 -04002477 }
2478 *success_ = false;
2479 }
2480
2481 private:
2482 QuicConnection* connection_;
2483 QuicSocketAddress expected_self_address_;
2484 QuicSocketAddress expected_peer_address_;
2485 bool* success_;
2486};
2487
2488// Receive a path probe request at the server side, i.e.,
2489// in non-IETF version: receive a padded PING packet with a peer addess change;
2490// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2491// change.
2492TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
2493 PathProbeTestInit(Perspective::IS_SERVER);
2494
2495 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2496 QuicPathFrameBuffer payload;
2497 if (!GetParam().version.HasIetfQuicFrames()) {
2498 EXPECT_CALL(visitor_,
2499 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2500 .Times(1);
2501 } else {
2502 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2503 if (connection_.validate_client_address()) {
2504 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2505 .Times(AtLeast(1u))
2506 .WillOnce(Invoke([&]() {
2507 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2508 EXPECT_EQ(1u, writer_->path_response_frames().size());
2509 payload = writer_->path_challenge_frames().front().data_buffer;
2510 }));
2511 }
2512 }
2513 // Process a probing packet from a new peer address on server side
2514 // is effectively receiving a connectivity probing.
2515 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2516 /*port=*/23456);
2517
2518 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2519 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2520 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2521 probing_packet->encrypted_length),
2522 clock_.Now()));
2523 uint64_t num_probing_received =
2524 connection_.GetStats().num_connectivity_probing_received;
2525 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2526
2527 EXPECT_EQ(num_probing_received + 1,
2528 connection_.GetStats().num_connectivity_probing_received);
2529 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2530 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhaf2e52a2022-04-20 07:37:03 -07002531 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002532 QuicByteCount bytes_sent =
2533 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_);
2534 EXPECT_LT(0u, bytes_sent);
2535 EXPECT_EQ(received->length(),
2536 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2537
2538 // Receiving one more probing packet should update the bytes count.
2539 probing_packet = ConstructProbingPacket();
2540 received.reset(ConstructReceivedPacket(
2541 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2542 probing_packet->encrypted_length),
2543 clock_.Now()));
2544 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2545
2546 EXPECT_EQ(num_probing_received + 2,
2547 connection_.GetStats().num_connectivity_probing_received);
2548 EXPECT_EQ(2 * bytes_sent,
2549 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2550 EXPECT_EQ(2 * received->length(),
2551 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2552
2553 bool success = false;
2554 if (!connection_.validate_client_address()) {
2555 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2556 .Times(AtLeast(1u))
2557 .WillOnce(Invoke([&]() {
2558 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2559 payload = writer_->path_challenge_frames().front().data_buffer;
2560 }));
2561
2562 connection_.ValidatePath(
2563 std::make_unique<TestQuicPathValidationContext>(
2564 connection_.self_address(), kNewPeerAddress, writer_.get()),
2565 std::make_unique<TestValidationResultDelegate>(
2566 &connection_, connection_.self_address(), kNewPeerAddress,
2567 &success));
2568 }
2569 EXPECT_EQ((connection_.validate_client_address() ? 2 : 3) * bytes_sent,
2570 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2571 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -07002572 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04002573 ProcessFramesPacketWithAddresses(frames, connection_.self_address(),
2574 kNewPeerAddress,
2575 ENCRYPTION_FORWARD_SECURE);
2576 EXPECT_LT(2 * received->length(),
2577 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2578 if (connection_.validate_client_address()) {
2579 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
2580 }
2581 // Receiving another probing packet from a newer address with a different
2582 // port shouldn't trigger another reverse path validation.
2583 QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
2584 /*port=*/34567);
2585 probing_packet = ConstructProbingPacket();
2586 received.reset(ConstructReceivedPacket(
2587 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2588 probing_packet->encrypted_length),
2589 clock_.Now()));
2590 ProcessReceivedPacket(kSelfAddress, kNewerPeerAddress, *received);
2591 EXPECT_FALSE(connection_.HasPendingPathValidation());
2592 EXPECT_EQ(connection_.validate_client_address(),
2593 QuicConnectionPeer::IsAlternativePathValidated(&connection_));
2594 }
2595
2596 // Process another packet with the old peer address on server side will not
2597 // start peer migration.
2598 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2599 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2600 ENCRYPTION_INITIAL);
2601 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2602 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2603}
2604
2605// Receive a padded PING packet with a port change on server side.
2606TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2607 set_perspective(Perspective::IS_SERVER);
2608 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2609 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2610 if (version().SupportsAntiAmplificationLimit()) {
2611 QuicConnectionPeer::SetAddressValidated(&connection_);
2612 }
2613
2614 // Clear direct_peer_address.
2615 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2616 // Clear effective_peer_address, it is the same as direct_peer_address for
2617 // this test.
2618 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2619 QuicSocketAddress());
2620 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2621
2622 if (GetParam().version.UsesCryptoFrames()) {
2623 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2624 } else {
2625 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2626 }
2627 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2628 ENCRYPTION_INITIAL);
2629 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2630 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2631
2632 if (GetParam().version.HasIetfQuicFrames()) {
2633 // In IETF version, a padded PING packet with port change is not taken as
2634 // connectivity probe.
2635 EXPECT_CALL(visitor_, GetHandshakeState())
2636 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2637 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2638 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2639 } else {
2640 // In non-IETF version, process a padded PING packet from a new peer
2641 // address on server side is effectively receiving a connectivity probing.
2642 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2643 EXPECT_CALL(visitor_,
2644 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2645 .Times(1);
2646 }
2647 const QuicSocketAddress kNewPeerAddress =
2648 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2649
2650 QuicFrames frames;
2651 // Write a PING frame, which has no data payload.
2652 QuicPingFrame ping_frame;
2653 frames.push_back(QuicFrame(ping_frame));
2654
2655 // Add padding to the rest of the packet.
2656 QuicPaddingFrame padding_frame;
2657 frames.push_back(QuicFrame(padding_frame));
2658
2659 uint64_t num_probing_received =
2660 connection_.GetStats().num_connectivity_probing_received;
2661
2662 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
2663 ENCRYPTION_INITIAL);
2664
2665 if (GetParam().version.HasIetfQuicFrames()) {
2666 // Padded PING with port changen is not considered as connectivity probe but
2667 // a PORT CHANGE.
2668 EXPECT_EQ(num_probing_received,
2669 connection_.GetStats().num_connectivity_probing_received);
2670 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2671 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2672 } else {
2673 EXPECT_EQ(num_probing_received + 1,
2674 connection_.GetStats().num_connectivity_probing_received);
2675 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2676 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2677 }
2678
2679 if (GetParam().version.HasIetfQuicFrames()) {
2680 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2681 }
2682 // Process another packet with the old peer address on server side. gQUIC
2683 // shouldn't regard this as a peer migration.
2684 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2685 ENCRYPTION_INITIAL);
2686 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2687 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2688}
2689
2690TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
2691 PathProbeTestInit(Perspective::IS_SERVER);
2692
2693 // Decrease packet number to simulate out-of-order packets.
2694 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2695
2696 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2697 if (!GetParam().version.HasIetfQuicFrames()) {
2698 EXPECT_CALL(visitor_,
2699 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2700 .Times(1);
2701 } else {
2702 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2703 }
2704
2705 // Process a padded PING packet from a new peer address on server side
2706 // is effectively receiving a connectivity probing, even if a newer packet has
2707 // been received before this one.
2708 const QuicSocketAddress kNewPeerAddress =
2709 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2710
2711 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2712 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2713 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2714 probing_packet->encrypted_length),
2715 clock_.Now()));
2716
2717 uint64_t num_probing_received =
2718 connection_.GetStats().num_connectivity_probing_received;
2719 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2720
2721 EXPECT_EQ(num_probing_received + 1,
2722 connection_.GetStats().num_connectivity_probing_received);
2723 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2724 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2725}
2726
2727TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2728 PathProbeTestInit(Perspective::IS_SERVER);
2729
2730 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2731 if (!GetParam().version.HasIetfQuicFrames()) {
2732 EXPECT_CALL(visitor_,
2733 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2734 .Times(1);
2735 } else {
2736 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2737 }
2738
2739 // Process a padded PING packet from a new peer address on server side
2740 // is effectively receiving a connectivity probing.
2741 const QuicSocketAddress kNewPeerAddress =
2742 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2743
2744 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2745 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2746 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2747 probing_packet->encrypted_length),
2748 clock_.Now()));
2749 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2750 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2751 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2752
2753 // Process another non-probing packet with the new peer address on server
2754 // side will start peer migration.
2755 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2756
2757 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2758 kNewPeerAddress, ENCRYPTION_INITIAL);
2759 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2760 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2761}
2762
2763TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) {
2764 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2765 PathProbeTestInit(Perspective::IS_CLIENT);
2766
2767 // Client takes all padded PING packet as speculative connectivity
2768 // probing packet, and reports to visitor.
2769 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2770
2771 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2772 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2773 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2774 probing_packet->encrypted_length),
2775 clock_.Now()));
2776 uint64_t num_probing_received =
2777 connection_.GetStats().num_connectivity_probing_received;
2778 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2779
2780 EXPECT_EQ(
2781 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2782 connection_.GetStats().num_connectivity_probing_received);
2783 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2784 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2785}
2786
2787TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2788 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2789 // PATH RESPONSE with peer address change as correct validation on the new
2790 // path.
2791 if (GetParam().version.HasIetfQuicFrames()) {
2792 return;
2793 }
2794 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2795 PathProbeTestInit(Perspective::IS_CLIENT);
2796
2797 // Process a padded PING packet with a different self address on client side
2798 // is effectively receiving a connectivity probing.
2799 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2800 if (!GetParam().version.HasIetfQuicFrames()) {
2801 EXPECT_CALL(visitor_,
2802 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2803 .Times(1);
2804 } else {
2805 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2806 }
2807
2808 const QuicSocketAddress kNewSelfAddress =
2809 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2810
2811 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2812 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2813 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2814 probing_packet->encrypted_length),
2815 clock_.Now()));
2816 uint64_t num_probing_received =
2817 connection_.GetStats().num_connectivity_probing_received;
2818 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2819
2820 EXPECT_EQ(num_probing_received + 1,
2821 connection_.GetStats().num_connectivity_probing_received);
2822 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2823 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2824}
2825
2826TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2827 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2828 set_perspective(Perspective::IS_CLIENT);
2829 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2830
2831 // Clear direct_peer_address.
2832 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2833 // Clear effective_peer_address, it is the same as direct_peer_address for
2834 // this test.
2835 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2836 QuicSocketAddress());
2837 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2838
2839 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2840 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2841 } else {
2842 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2843 }
2844 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2845 ENCRYPTION_INITIAL);
2846 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2847 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2848
2849 // Process another packet with a different peer address on client side will
2850 // only update peer address.
2851 const QuicSocketAddress kNewPeerAddress =
2852 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2853 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2854 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2855 kNewPeerAddress, ENCRYPTION_INITIAL);
2856 if (connection_.version().HasIetfQuicFrames()) {
2857 // IETF QUIC disallows server initiated address change.
2858 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2859 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2860 } else {
2861 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2862 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2863 }
2864}
2865
2866TEST_P(QuicConnectionTest, MaxPacketSize) {
2867 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2868 EXPECT_EQ(1250u, connection_.max_packet_length());
2869}
2870
2871TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2872 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2873
2874 // SetFromConfig is always called after construction from InitializeSession.
2875 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2876 constexpr uint32_t kTestMaxPacketSize = 1233u;
2877 QuicConfig config;
2878 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2879 connection_.SetFromConfig(config);
2880
2881 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2882}
2883
2884TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2885 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2886
2887 // SetFromConfig is always called after construction from InitializeSession.
2888 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2889 constexpr uint32_t kTestMaxPacketSize = 1450u;
2890 QuicConfig config;
2891 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2892 connection_.SetFromConfig(config);
2893
2894 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2895}
2896
2897TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2898 TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress,
2899 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07002900 Perspective::IS_SERVER, version(),
2901 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04002902 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2903 EXPECT_EQ(1000u, connection.max_packet_length());
2904}
2905
2906TEST_P(QuicConnectionTest, LowerServerResponseMtuTest) {
2907 set_perspective(Perspective::IS_SERVER);
2908 connection_.SetMaxPacketLength(1000);
2909 EXPECT_EQ(1000u, connection_.max_packet_length());
2910
birenroyef686222022-09-12 11:34:34 -07002911 SetQuicFlag(quic_use_lower_server_response_mtu_for_test, true);
Bence Békybac04052022-04-07 15:44:29 -04002912 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(::testing::AtMost(1));
2913 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(::testing::AtMost(1));
2914 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
2915 EXPECT_EQ(1250u, connection_.max_packet_length());
2916}
2917
2918TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
2919 set_perspective(Perspective::IS_SERVER);
2920 connection_.SetMaxPacketLength(1000);
2921
2922 QuicPacketHeader header;
2923 header.destination_connection_id = connection_id_;
2924 header.version_flag = true;
2925 header.packet_number = QuicPacketNumber(12);
2926
2927 if (QuicVersionHasLongHeaderLengths(
2928 peer_framer_.version().transport_version)) {
2929 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07002930 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
2931 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04002932 }
2933
2934 QuicFrames frames;
2935 QuicPaddingFrame padding;
2936 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2937 frames.push_back(QuicFrame(&crypto_frame_));
2938 } else {
2939 frames.push_back(QuicFrame(frame1_));
2940 }
2941 frames.push_back(QuicFrame(padding));
2942 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
2943 char buffer[kMaxOutgoingPacketSize];
2944 size_t encrypted_length =
2945 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
2946 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08002947 EXPECT_EQ(kMaxOutgoingPacketSize,
2948 encrypted_length +
2949 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04002950
2951 framer_.set_version(version());
2952 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2953 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2954 } else {
2955 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2956 }
2957 connection_.ProcessUdpPacket(
2958 kSelfAddress, kPeerAddress,
2959 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
2960 false));
2961
martinduke9e0811c2022-12-08 20:35:57 -08002962 EXPECT_EQ(kMaxOutgoingPacketSize,
2963 connection_.max_packet_length() +
2964 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04002965}
2966
2967TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
2968 const QuicByteCount lower_max_packet_size = 1240;
2969 writer_->set_max_packet_size(lower_max_packet_size);
2970 set_perspective(Perspective::IS_SERVER);
2971 connection_.SetMaxPacketLength(1000);
2972 EXPECT_EQ(1000u, connection_.max_packet_length());
2973
2974 QuicPacketHeader header;
2975 header.destination_connection_id = connection_id_;
2976 header.version_flag = true;
2977 header.packet_number = QuicPacketNumber(12);
2978
2979 if (QuicVersionHasLongHeaderLengths(
2980 peer_framer_.version().transport_version)) {
2981 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07002982 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
2983 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04002984 }
2985
2986 QuicFrames frames;
2987 QuicPaddingFrame padding;
2988 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2989 frames.push_back(QuicFrame(&crypto_frame_));
2990 } else {
2991 frames.push_back(QuicFrame(frame1_));
2992 }
2993 frames.push_back(QuicFrame(padding));
2994 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
2995 char buffer[kMaxOutgoingPacketSize];
2996 size_t encrypted_length =
2997 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
2998 *packet, buffer, kMaxOutgoingPacketSize);
martinduke9e0811c2022-12-08 20:35:57 -08002999 EXPECT_EQ(kMaxOutgoingPacketSize,
3000 encrypted_length +
3001 (connection_.version().KnowsWhichDecrypterToUse() ? 0 : 4));
Bence Békybac04052022-04-07 15:44:29 -04003002
3003 framer_.set_version(version());
3004 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3005 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3006 } else {
3007 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3008 }
3009 connection_.ProcessUdpPacket(
3010 kSelfAddress, kPeerAddress,
3011 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3012 false));
3013
3014 // Here, the limit imposed by the writer is lower than the size of the packet
3015 // received, so the writer max packet size is used.
3016 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3017}
3018
3019TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
3020 const QuicByteCount lower_max_packet_size = 1240;
3021 writer_->set_max_packet_size(lower_max_packet_size);
3022
3023 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
3024 "Default maximum packet size is too low");
3025 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
3026
3027 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3028}
3029
3030TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
3031 const QuicConnectionId connection_id = TestConnectionId(17);
3032 const QuicByteCount lower_max_packet_size = 1240;
3033 writer_->set_max_packet_size(lower_max_packet_size);
3034 TestConnection connection(connection_id, kSelfAddress, kPeerAddress,
3035 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003036 Perspective::IS_CLIENT, version(),
3037 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003038 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
3039 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
3040}
3041
3042TEST_P(QuicConnectionTest, PacketsInOrder) {
3043 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3044
3045 ProcessPacket(1);
3046 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
3047 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3048
3049 ProcessPacket(2);
3050 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
3051 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3052
3053 ProcessPacket(3);
3054 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3055 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3056}
3057
3058TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
3059 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3060
3061 ProcessPacket(3);
3062 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3063 EXPECT_TRUE(IsMissing(2));
3064 EXPECT_TRUE(IsMissing(1));
3065
3066 ProcessPacket(2);
3067 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3068 EXPECT_FALSE(IsMissing(2));
3069 EXPECT_TRUE(IsMissing(1));
3070
3071 ProcessPacket(1);
3072 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3073 EXPECT_FALSE(IsMissing(2));
3074 EXPECT_FALSE(IsMissing(1));
3075}
3076
3077TEST_P(QuicConnectionTest, DuplicatePacket) {
3078 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3079
3080 ProcessPacket(3);
3081 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3082 EXPECT_TRUE(IsMissing(2));
3083 EXPECT_TRUE(IsMissing(1));
3084
3085 // Send packet 3 again, but do not set the expectation that
3086 // the visitor OnStreamFrame() will be called.
3087 ProcessDataPacket(3);
3088 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3089 EXPECT_TRUE(IsMissing(2));
3090 EXPECT_TRUE(IsMissing(1));
3091}
3092
3093TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
3094 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3095 return;
3096 }
3097 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3098
3099 ProcessPacket(3);
3100 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3101 EXPECT_TRUE(IsMissing(2));
3102 EXPECT_TRUE(IsMissing(1));
3103
3104 ProcessPacket(2);
3105 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3106 EXPECT_TRUE(IsMissing(1));
3107
3108 ProcessPacket(5);
3109 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
3110 EXPECT_TRUE(IsMissing(1));
3111 EXPECT_TRUE(IsMissing(4));
3112
3113 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
3114 // packet the peer will not retransmit. It indicates this by sending 'least
3115 // awaiting' is 4. The connection should then realize 1 will not be
3116 // retransmitted, and will remove it from the missing list.
3117 QuicAckFrame frame = InitAckFrame(1);
3118 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3119 ProcessAckPacket(6, &frame);
3120
3121 // Force an ack to be sent.
3122 SendAckPacketToPeer();
3123 EXPECT_TRUE(IsMissing(4));
3124}
3125
3126TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
3127 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
3128 if (!IsDefaultTestConfiguration() ||
3129 VersionHasIetfQuicFrames(version().transport_version)) {
3130 return;
3131 }
3132
3133 // Process an unencrypted packet from the non-crypto stream.
3134 frame1_.stream_id = 3;
3135 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3136 EXPECT_CALL(visitor_,
3137 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3138 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
3139 "");
3140 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
3141}
3142
3143TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
3144 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3145
3146 ProcessPacket(3);
3147 // Should not cause an ack.
3148 EXPECT_EQ(0u, writer_->packets_write_attempts());
3149
3150 ProcessPacket(2);
3151 // Should ack immediately, since this fills the last hole.
3152 EXPECT_EQ(1u, writer_->packets_write_attempts());
3153
3154 ProcessPacket(1);
3155 // Should ack immediately, since this fills the last hole.
3156 EXPECT_EQ(2u, writer_->packets_write_attempts());
3157
3158 ProcessPacket(4);
3159 // Should not cause an ack.
3160 EXPECT_EQ(2u, writer_->packets_write_attempts());
3161}
3162
3163TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
3164 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3165
3166 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3167 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3168 EXPECT_EQ(2u, writer_->packets_write_attempts());
3169
3170 QuicAckFrame ack1 = InitAckFrame(1);
3171 QuicAckFrame ack2 = InitAckFrame(2);
3172 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3173 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3174 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
3175 }
3176 ProcessAckPacket(2, &ack2);
3177 // Should ack immediately since we have missing packets.
3178 EXPECT_EQ(2u, writer_->packets_write_attempts());
3179
3180 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3181 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
3182 }
3183 ProcessAckPacket(1, &ack1);
3184 // Should not ack an ack filling a missing packet.
3185 EXPECT_EQ(2u, writer_->packets_write_attempts());
3186}
3187
3188TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
3189 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3190 QuicPacketNumber original, second;
3191
3192 QuicByteCount packet_size =
3193 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3194 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3195
3196 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3197 // First nack triggers early retransmit.
3198 LostPacketVector lost_packets;
3199 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
3200 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3201 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3202 Return(LossDetectionInterface::DetectionStats())));
3203 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3204 QuicPacketNumber retransmission;
3205 // Packet 1 is short header for IETF QUIC because the encryption level
3206 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
3207 EXPECT_CALL(*send_algorithm_,
3208 OnPacketSent(_, _, _,
3209 GetParam().version.HasIetfInvariantHeader()
3210 ? packet_size
3211 : packet_size - kQuicVersionSize,
3212 _))
3213 .WillOnce(SaveArg<2>(&retransmission));
3214
3215 ProcessAckPacket(&frame);
3216
3217 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
3218 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3219 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3220 ProcessAckPacket(&frame2);
3221
3222 // Now if the peer sends an ack which still reports the retransmitted packet
3223 // as missing, that will bundle an ack with data after two acks in a row
3224 // indicate the high water mark needs to be raised.
3225 EXPECT_CALL(*send_algorithm_,
3226 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3227 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
3228 // No ack sent.
3229 size_t padding_frame_count = writer_->padding_frames().size();
3230 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3231 EXPECT_EQ(1u, writer_->stream_frames().size());
3232
3233 // No more packet loss for the rest of the test.
3234 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3235 .Times(AnyNumber());
3236 ProcessAckPacket(&frame2);
3237 EXPECT_CALL(*send_algorithm_,
3238 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3239 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
3240 // Ack bundled.
3241 if (GetParam().no_stop_waiting) {
3242 // Do not ACK acks.
3243 EXPECT_EQ(1u, writer_->frame_count());
3244 } else {
3245 EXPECT_EQ(3u, writer_->frame_count());
3246 }
3247 EXPECT_EQ(1u, writer_->stream_frames().size());
3248 if (GetParam().no_stop_waiting) {
3249 EXPECT_TRUE(writer_->ack_frames().empty());
3250 } else {
3251 EXPECT_FALSE(writer_->ack_frames().empty());
3252 }
3253
3254 // But an ack with no missing packets will not send an ack.
3255 AckPacket(original, &frame2);
3256 ProcessAckPacket(&frame2);
3257 ProcessAckPacket(&frame2);
3258}
3259
3260TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) {
3261 if (!GetParam().version.HasIetfQuicFrames()) {
3262 return;
3263 }
3264 connection_.set_can_receive_ack_frequency_frame();
3265
3266 // Expect 13 acks, every 3rd packet including the first packet with
3267 // AckFrequencyFrame.
3268 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
3269 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3270
3271 QuicAckFrequencyFrame ack_frequency_frame;
3272 ack_frequency_frame.packet_tolerance = 3;
3273 ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
3274 ENCRYPTION_FORWARD_SECURE);
3275
3276 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38);
3277 // Receives packets 2 - 39.
3278 for (size_t i = 2; i <= 39; ++i) {
3279 ProcessDataPacket(i);
3280 }
3281}
3282
3283TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
3284 const size_t kMinRttMs = 40;
3285 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
3286 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
3287 QuicTime::Delta::Zero(), QuicTime::Zero());
3288 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
3289
3290 // Start ack decimation from 10th packet.
3291 connection_.set_min_received_before_ack_decimation(10);
3292
3293 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3294 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
3295
3296 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
3297 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
3298 // Receives packets 1 - 29.
3299 for (size_t i = 1; i <= 29; ++i) {
3300 ProcessDataPacket(i);
3301 }
3302
3303 // We now receive the 30th packet, and so we send an ack.
3304 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3305 ProcessDataPacket(30);
3306}
3307
3308TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
3309 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3310 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3311 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3312
3313 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3314 // Receives packets 1 - 39.
3315 for (size_t i = 1; i <= 39; ++i) {
3316 ProcessDataPacket(i);
3317 }
3318 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3319 // WINDOW_UPDATE.
3320 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3321 .WillOnce(Invoke([this]() {
3322 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3323 }));
3324 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3325 EXPECT_EQ(0u, writer_->window_update_frames().size());
3326 ProcessDataPacket(40);
3327 EXPECT_EQ(1u, writer_->window_update_frames().size());
3328
3329 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3330 // Receives packets 41 - 59.
3331 for (size_t i = 41; i <= 59; ++i) {
3332 ProcessDataPacket(i);
3333 }
3334 // Send a packet containing stream frame.
3335 SendStreamDataToPeer(
3336 QuicUtils::GetFirstBidirectionalStreamId(
3337 connection_.version().transport_version, Perspective::IS_CLIENT),
3338 "bar", 0, NO_FIN, nullptr);
3339
3340 // Session will not be informed until receiving another 20 packets.
3341 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3342 for (size_t i = 60; i <= 98; ++i) {
3343 ProcessDataPacket(i);
3344 EXPECT_EQ(0u, writer_->window_update_frames().size());
3345 }
3346 // Session does not add a retransmittable frame.
3347 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3348 .WillOnce(Invoke([this]() {
3349 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3350 }));
3351 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3352 EXPECT_EQ(0u, writer_->ping_frames().size());
3353 ProcessDataPacket(99);
3354 EXPECT_EQ(0u, writer_->window_update_frames().size());
3355 // A ping frame will be added.
3356 EXPECT_EQ(1u, writer_->ping_frames().size());
3357}
3358
3359TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
Bence Békybac04052022-04-07 15:44:29 -04003360 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3361 QuicConfig config;
3362 QuicTagVector connection_options;
3363 connection_options.push_back(kEACK);
3364 config.SetConnectionOptionsToSend(connection_options);
3365 connection_.SetFromConfig(config);
3366
3367 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3368 connection_.OnHandshakeComplete();
3369
3370 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3371 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3372
3373 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3374 // Receive packets 1 - 9.
3375 for (size_t i = 1; i <= 9; ++i) {
3376 ProcessDataPacket(i);
3377 }
3378
3379 // Send a ping and fire the retransmission alarm.
3380 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3381 SendPing();
3382 QuicTime retransmission_time =
3383 connection_.GetRetransmissionAlarm()->deadline();
3384 clock_.AdvanceTime(retransmission_time - clock_.Now());
3385 connection_.GetRetransmissionAlarm()->Fire();
fayang339f0c82022-04-30 14:20:02 -07003386 ASSERT_LT(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04003387
3388 // Process a packet, which requests a retransmittable frame be bundled
3389 // with the ACK.
3390 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3391 .WillOnce(Invoke([this]() {
3392 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3393 }));
3394 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3395 ProcessDataPacket(11);
3396 EXPECT_EQ(1u, writer_->window_update_frames().size());
3397}
3398
3399TEST_P(QuicConnectionTest, LeastUnackedLower) {
3400 if (GetParam().version.HasIetfInvariantHeader()) {
3401 return;
3402 }
3403 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3404
3405 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3406 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3407 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3408
3409 // Start out saying the least unacked is 2.
3410 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3411 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3412
3413 // Change it to 1, but lower the packet number to fake out-of-order packets.
3414 // This should be fine.
3415 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3416 // The scheduler will not process out of order acks, but all packet processing
3417 // causes the connection to try to write.
3418 if (!GetParam().no_stop_waiting) {
3419 EXPECT_CALL(visitor_, OnCanWrite());
3420 }
3421 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3422
3423 // Now claim it's one, but set the ordering so it was sent "after" the first
3424 // one. This should cause a connection error.
3425 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3426 if (!GetParam().no_stop_waiting) {
3427 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3428 .Times(AtLeast(1));
3429 EXPECT_CALL(visitor_,
3430 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3431 .Times(AtLeast(1));
3432 }
3433 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3434 if (!GetParam().no_stop_waiting) {
3435 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3436 }
3437}
3438
3439TEST_P(QuicConnectionTest, TooManySentPackets) {
3440 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3441
3442 QuicPacketCount max_tracked_packets = 50;
3443 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3444
3445 const int num_packets = max_tracked_packets + 5;
3446
3447 for (int i = 0; i < num_packets; ++i) {
3448 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3449 }
3450
3451 EXPECT_CALL(visitor_,
3452 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3453
3454 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3455
3456 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
3457}
3458
3459TEST_P(QuicConnectionTest, LargestObservedLower) {
3460 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3461
3462 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3463 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3464 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3465 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3466
3467 // Start out saying the largest observed is 2.
3468 QuicAckFrame frame1 = InitAckFrame(1);
3469 QuicAckFrame frame2 = InitAckFrame(2);
3470 ProcessAckPacket(&frame2);
3471
3472 EXPECT_CALL(visitor_, OnCanWrite());
3473 ProcessAckPacket(&frame1);
3474}
3475
3476TEST_P(QuicConnectionTest, AckUnsentData) {
3477 // Ack a packet which has not been sent.
3478 EXPECT_CALL(visitor_,
3479 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3480 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3481 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3482 QuicAckFrame frame = InitAckFrame(1);
3483 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3484 ProcessAckPacket(&frame);
3485 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
3486}
3487
3488TEST_P(QuicConnectionTest, BasicSending) {
3489 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3490 return;
3491 }
3492 const QuicConnectionStats& stats = connection_.GetStats();
3493 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
3494 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3495 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3496 ProcessDataPacket(1);
3497 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3498 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3499 QuicPacketNumber last_packet;
3500 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3501 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3502 SendAckPacketToPeer(); // Packet 2
3503
3504 if (GetParam().no_stop_waiting) {
3505 // Expect no stop waiting frame is sent.
3506 EXPECT_FALSE(least_unacked().IsInitialized());
3507 } else {
3508 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3509 }
3510
3511 SendAckPacketToPeer(); // Packet 3
3512 if (GetParam().no_stop_waiting) {
3513 // Expect no stop waiting frame is sent.
3514 EXPECT_FALSE(least_unacked().IsInitialized());
3515 } else {
3516 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3517 }
3518
3519 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3520 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3521 SendAckPacketToPeer(); // Packet 5
3522 if (GetParam().no_stop_waiting) {
3523 // Expect no stop waiting frame is sent.
3524 EXPECT_FALSE(least_unacked().IsInitialized());
3525 } else {
3526 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3527 }
3528
3529 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3530
3531 // Peer acks up to packet 3.
3532 QuicAckFrame frame = InitAckFrame(3);
3533 ProcessAckPacket(&frame);
3534 SendAckPacketToPeer(); // Packet 6
3535
3536 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3537 // ack for 4.
3538 if (GetParam().no_stop_waiting) {
3539 // Expect no stop waiting frame is sent.
3540 EXPECT_FALSE(least_unacked().IsInitialized());
3541 } else {
3542 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3543 }
3544
3545 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3546
3547 // Peer acks up to packet 4, the last packet.
3548 QuicAckFrame frame2 = InitAckFrame(6);
3549 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3550
3551 // Verify that we did not send an ack.
3552 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3553
3554 // So the last ack has not changed.
3555 if (GetParam().no_stop_waiting) {
3556 // Expect no stop waiting frame is sent.
3557 EXPECT_FALSE(least_unacked().IsInitialized());
3558 } else {
3559 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3560 }
3561
3562 // If we force an ack, we shouldn't change our retransmit state.
3563 SendAckPacketToPeer(); // Packet 7
3564 if (GetParam().no_stop_waiting) {
3565 // Expect no stop waiting frame is sent.
3566 EXPECT_FALSE(least_unacked().IsInitialized());
3567 } else {
3568 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3569 }
3570
3571 // But if we send more data it should.
3572 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3573 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3574 SendAckPacketToPeer(); // Packet 9
3575 if (GetParam().no_stop_waiting) {
3576 // Expect no stop waiting frame is sent.
3577 EXPECT_FALSE(least_unacked().IsInitialized());
3578 } else {
3579 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3580 }
3581 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3582}
3583
3584// QuicConnection should record the packet sent-time prior to sending the
3585// packet.
3586TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3587 // We're using a MockClock for the tests, so we have complete control over the
3588 // time.
3589 // Our recorded timestamp for the last packet sent time will be passed in to
3590 // the send_algorithm. Make sure that it is set to the correct value.
3591 QuicTime actual_recorded_send_time = QuicTime::Zero();
3592 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3593 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3594
3595 // First send without any pause and check the result.
3596 QuicTime expected_recorded_send_time = clock_.Now();
3597 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3598 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3599 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3600 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3601
3602 // Now pause during the write, and check the results.
3603 actual_recorded_send_time = QuicTime::Zero();
3604 const QuicTime::Delta write_pause_time_delta =
3605 QuicTime::Delta::FromMilliseconds(5000);
3606 SetWritePauseTimeDelta(write_pause_time_delta);
3607 expected_recorded_send_time = clock_.Now();
3608
3609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3610 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3611 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3612 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3613 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3614 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3615}
3616
QUICHE teamac0a8082022-06-13 09:17:05 -07003617TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithRetransmissions) {
3618 // Send two stream frames in 1 packet by queueing them.
3619 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3620
3621 {
3622 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3623 connection_.SaveAndSendStreamData(
3624 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3625 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3626 connection_.SaveAndSendStreamData(
3627 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3628 "helloworld", 0, NO_FIN, LOSS_RETRANSMISSION);
3629 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3630 }
3631
3632 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3633 EXPECT_FALSE(connection_.HasQueuedData());
3634
3635 EXPECT_EQ(2u, writer_->frame_count());
3636 for (auto& frame : writer_->stream_frames()) {
3637 EXPECT_EQ(frame->data_length, 10u);
3638 }
3639
3640 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3641 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 20u);
3642}
3643
3644TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithMixedFrames) {
3645 // Send two stream frames in 1 packet by queueing them.
3646 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3647
3648 {
3649 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3650 // First frame is retransmission. Second is NOT_RETRANSMISSION but the
3651 // packet retains the PTO_RETRANSMISSION type.
3652 connection_.SaveAndSendStreamData(
3653 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3654 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3655 connection_.SaveAndSendStreamData(
3656 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3657 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3658 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3659 }
3660
3661 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3662 EXPECT_FALSE(connection_.HasQueuedData());
3663
3664 EXPECT_EQ(2u, writer_->frame_count());
3665 for (auto& frame : writer_->stream_frames()) {
3666 EXPECT_EQ(frame->data_length, 10u);
3667 }
3668
3669 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3670 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 10u);
3671}
3672
3673TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_NoRetransmission) {
3674 // Send two stream frames in 1 packet by queueing them.
3675 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3676
3677 {
3678 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3679 // Both frames are NOT_RETRANSMISSION
3680 connection_.SaveAndSendStreamData(
3681 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3682 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3683 connection_.SaveAndSendStreamData(
3684 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3685 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3687 }
3688
3689 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3690 EXPECT_FALSE(connection_.HasQueuedData());
3691
3692 EXPECT_EQ(2u, writer_->frame_count());
3693 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 0u);
3694 ASSERT_EQ(connection_.GetStats().bytes_retransmitted, 0u);
3695}
3696
Bence Békybac04052022-04-07 15:44:29 -04003697TEST_P(QuicConnectionTest, FramePacking) {
3698 // Send two stream frames in 1 packet by queueing them.
3699 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3700 {
3701 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3702 connection_.SendStreamData3();
3703 connection_.SendStreamData5();
3704 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3705 }
3706 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3707 EXPECT_FALSE(connection_.HasQueuedData());
3708
3709 // Parse the last packet and ensure it's an ack and two stream frames from
3710 // two different streams.
3711 if (GetParam().no_stop_waiting) {
3712 EXPECT_EQ(2u, writer_->frame_count());
3713 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3714 } else {
3715 EXPECT_EQ(2u, writer_->frame_count());
3716 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3717 }
3718
3719 EXPECT_TRUE(writer_->ack_frames().empty());
3720
3721 ASSERT_EQ(2u, writer_->stream_frames().size());
3722 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3723 writer_->stream_frames()[0]->stream_id);
3724 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3725 writer_->stream_frames()[1]->stream_id);
3726}
3727
3728TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3729 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3730 // queueing them.
3731 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3732 {
3733 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3734 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3735 connection_.SendStreamData3();
3736 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08003737 // Set the crypters for INITIAL packets in the TestPacketWriter.
3738 if (!connection_.version().KnowsWhichDecrypterToUse()) {
3739 writer_->framer()->framer()->SetAlternativeDecrypter(
3740 ENCRYPTION_INITIAL,
3741 std::make_unique<NullDecrypter>(Perspective::IS_SERVER), false);
3742 }
Bence Békybac04052022-04-07 15:44:29 -04003743 connection_.SendCryptoStreamData();
3744 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3745 }
3746 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3747 EXPECT_FALSE(connection_.HasQueuedData());
3748
3749 // Parse the last packet and ensure it contains a crypto stream frame.
3750 EXPECT_LE(2u, writer_->frame_count());
3751 ASSERT_LE(1u, writer_->padding_frames().size());
3752 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3753 ASSERT_EQ(1u, writer_->stream_frames().size());
3754 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3755 writer_->stream_frames()[0]->stream_id);
3756 } else {
3757 EXPECT_LE(1u, writer_->crypto_frames().size());
3758 }
3759}
3760
3761TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3762 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3763 // queueing them.
3764 {
3765 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3766 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3767 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3768 connection_.SendCryptoStreamData();
3769 connection_.SendStreamData3();
3770 }
3771 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3772 EXPECT_FALSE(connection_.HasQueuedData());
3773
3774 // Parse the last packet and ensure it's the stream frame from stream 3.
3775 size_t padding_frame_count = writer_->padding_frames().size();
3776 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3777 ASSERT_EQ(1u, writer_->stream_frames().size());
3778 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3779 writer_->stream_frames()[0]->stream_id);
3780}
3781
3782TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3783 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3784 // Process a data packet to queue up a pending ack.
3785 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3786 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3787 } else {
3788 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3789 }
3790 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3791
3792 QuicPacketNumber last_packet;
3793 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3794 connection_.SendCryptoDataWithString("foo", 0);
3795 } else {
3796 SendStreamDataToPeer(
3797 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3798 NO_FIN, &last_packet);
3799 }
3800 // Verify ack is bundled with outging packet.
3801 EXPECT_FALSE(writer_->ack_frames().empty());
3802
3803 EXPECT_CALL(visitor_, OnCanWrite())
3804 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3805 &connection_, &TestConnection::SendStreamData3)),
3806 IgnoreResult(InvokeWithoutArgs(
3807 &connection_, &TestConnection::SendStreamData5))));
3808
3809 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3810
3811 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3812 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martinduke9e0811c2022-12-08 20:35:57 -08003813 peer_framer_.SetEncrypter(
3814 ENCRYPTION_FORWARD_SECURE,
3815 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
3816 SetDecrypter(
3817 ENCRYPTION_FORWARD_SECURE,
3818 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04003819 ProcessDataPacket(2);
3820
3821 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3822 EXPECT_FALSE(connection_.HasQueuedData());
3823
3824 // Parse the last packet and ensure it's an ack and two stream frames from
3825 // two different streams.
3826 if (GetParam().no_stop_waiting) {
3827 EXPECT_EQ(3u, writer_->frame_count());
3828 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3829 } else {
3830 EXPECT_EQ(4u, writer_->frame_count());
3831 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3832 }
3833 EXPECT_FALSE(writer_->ack_frames().empty());
3834 ASSERT_EQ(2u, writer_->stream_frames().size());
3835 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3836 writer_->stream_frames()[0]->stream_id);
3837 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3838 writer_->stream_frames()[1]->stream_id);
3839}
3840
3841TEST_P(QuicConnectionTest, FramePackingSendv) {
3842 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3843 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3844
3845 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3846 connection_.transport_version(), Perspective::IS_CLIENT);
3847 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
3848
3849 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3850 EXPECT_FALSE(connection_.HasQueuedData());
3851
3852 // Parse the last packet and ensure multiple iovector blocks have
3853 // been packed into a single stream frame from one stream.
3854 EXPECT_EQ(1u, writer_->frame_count());
3855 EXPECT_EQ(1u, writer_->stream_frames().size());
3856 EXPECT_EQ(0u, writer_->padding_frames().size());
3857 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
3858 EXPECT_EQ(stream_id, frame->stream_id);
3859 EXPECT_EQ("ABCDEF",
3860 absl::string_view(frame->data_buffer, frame->data_length));
3861}
3862
3863TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
3864 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3865 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3866
3867 BlockOnNextWrite();
3868 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3869 connection_.transport_version(), Perspective::IS_CLIENT);
3870 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
3871
3872 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3873 EXPECT_TRUE(connection_.HasQueuedData());
3874
3875 // Unblock the writes and actually send.
3876 writer_->SetWritable();
3877 connection_.OnCanWrite();
3878 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3879
3880 // Parse the last packet and ensure it's one stream frame from one stream.
3881 EXPECT_EQ(1u, writer_->frame_count());
3882 EXPECT_EQ(1u, writer_->stream_frames().size());
3883 EXPECT_EQ(0u, writer_->padding_frames().size());
3884 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
3885 EXPECT_EQ(stream_id, frame->stream_id);
3886 EXPECT_EQ("ABCDEF",
3887 absl::string_view(frame->data_buffer, frame->data_length));
3888}
3889
3890TEST_P(QuicConnectionTest, SendingZeroBytes) {
3891 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3892 // Send a zero byte write with a fin using writev.
3893 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3894 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3895 connection_.transport_version(), Perspective::IS_CLIENT);
3896 connection_.SaveAndSendStreamData(stream_id, {}, 0, FIN);
3897
3898 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3899 EXPECT_FALSE(connection_.HasQueuedData());
3900
3901 // Padding frames are added by v99 to ensure a minimum packet size.
3902 size_t extra_padding_frames = 0;
3903 if (GetParam().version.HasHeaderProtection()) {
3904 extra_padding_frames = 1;
3905 }
3906
3907 // Parse the last packet and ensure it's one stream frame from one stream.
3908 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3909 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3910 ASSERT_EQ(1u, writer_->stream_frames().size());
3911 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
3912 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3913}
3914
3915TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3916 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3917 EXPECT_CALL(visitor_, GetHandshakeState())
3918 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
3919 // Set the ack alarm by processing a ping frame.
3920 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3921
3922 // Processs a PING frame.
3923 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3924 // Ensure that this has caused the ACK alarm to be set.
3925 EXPECT_TRUE(connection_.HasPendingAcks());
3926
3927 // Send data and ensure the ack is bundled.
3928 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3929 const std::string data(10000, '?');
3930 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
3931 GetNthClientInitiatedStreamId(0, connection_.transport_version()), data,
3932 0, FIN);
3933 EXPECT_EQ(data.length(), consumed.bytes_consumed);
3934 EXPECT_TRUE(consumed.fin_consumed);
3935 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3936 EXPECT_FALSE(connection_.HasQueuedData());
3937
3938 // Parse the last packet and ensure it's one stream frame with a fin.
3939 EXPECT_EQ(1u, writer_->frame_count());
3940 ASSERT_EQ(1u, writer_->stream_frames().size());
3941 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
3942 writer_->stream_frames()[0]->stream_id);
3943 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3944 // Ensure the ack alarm was cancelled when the ack was sent.
3945 EXPECT_FALSE(connection_.HasPendingAcks());
3946}
3947
3948TEST_P(QuicConnectionTest, OnCanWrite) {
3949 // Visitor's OnCanWrite will send data, but will have more pending writes.
3950 EXPECT_CALL(visitor_, OnCanWrite())
3951 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3952 &connection_, &TestConnection::SendStreamData3)),
3953 IgnoreResult(InvokeWithoutArgs(
3954 &connection_, &TestConnection::SendStreamData5))));
3955 {
3956 InSequence seq;
3957 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3958 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3959 .WillRepeatedly(Return(false));
3960 }
3961
3962 EXPECT_CALL(*send_algorithm_, CanSend(_))
3963 .WillRepeatedly(testing::Return(true));
3964
3965 connection_.OnCanWrite();
3966
3967 // Parse the last packet and ensure it's the two stream frames from
3968 // two different streams.
3969 EXPECT_EQ(2u, writer_->frame_count());
3970 EXPECT_EQ(2u, writer_->stream_frames().size());
3971 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3972 writer_->stream_frames()[0]->stream_id);
3973 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3974 writer_->stream_frames()[1]->stream_id);
3975}
3976
3977TEST_P(QuicConnectionTest, RetransmitOnNack) {
3978 QuicPacketNumber last_packet;
3979 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
3980 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet);
3981 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet);
3982
3983 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3984
3985 // Don't lose a packet on an ack, and nothing is retransmitted.
3986 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3987 QuicAckFrame ack_one = InitAckFrame(1);
3988 ProcessAckPacket(&ack_one);
3989
3990 // Lose a packet and ensure it triggers retransmission.
3991 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3992 LostPacketVector lost_packets;
3993 lost_packets.push_back(
3994 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
3995 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3996 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3997 Return(LossDetectionInterface::DetectionStats())));
3998 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3999 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4000 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4001 ProcessAckPacket(&nack_two);
4002}
4003
4004TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
4005 // Block the connection to queue the packet.
4006 BlockOnNextWrite();
4007
4008 QuicStreamId stream_id = 2;
4009 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4010
4011 // Now that there is a queued packet, reset the stream.
4012 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4013
4014 // Unblock the connection and verify that only the RST_STREAM is sent.
4015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4016 writer_->SetWritable();
4017 connection_.OnCanWrite();
4018 size_t padding_frame_count = writer_->padding_frames().size();
4019 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4020 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4021}
4022
4023TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
4024 // Block the connection to queue the packet.
4025 BlockOnNextWrite();
4026
4027 QuicStreamId stream_id = 2;
4028 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4029 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4030
4031 // Now that there is a queued packet, reset the stream.
4032 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4033
4034 // Unblock the connection and verify that the RST_STREAM is sent and the data
4035 // packet is sent.
4036 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4037 writer_->SetWritable();
4038 connection_.OnCanWrite();
4039 size_t padding_frame_count = writer_->padding_frames().size();
4040 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4041 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4042}
4043
4044TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
4045 QuicStreamId stream_id = 2;
4046 QuicPacketNumber last_packet;
4047 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4048 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4049 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4050
4051 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4052 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4053
4054 // Lose a packet and ensure it does not trigger retransmission.
4055 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4056 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4057 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4058 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4059 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4060 ProcessAckPacket(&nack_two);
4061}
4062
4063TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
4064 QuicStreamId stream_id = 2;
4065 QuicPacketNumber last_packet;
4066 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4067 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4068 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4069
4070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4071 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4072
4073 // Lose a packet, ensure it triggers retransmission.
4074 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4075 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4076 LostPacketVector lost_packets;
4077 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4078 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4079 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4080 Return(LossDetectionInterface::DetectionStats())));
4081 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4082 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4083 ProcessAckPacket(&nack_two);
4084}
4085
4086TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
4087 QuicStreamId stream_id = 2;
4088 QuicPacketNumber last_packet;
4089 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4090
4091 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4092 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4093
4094 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
4095 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4096 clock_.AdvanceTime(DefaultRetransmissionTime());
4097 connection_.GetRetransmissionAlarm()->Fire();
4098 size_t padding_frame_count = writer_->padding_frames().size();
4099 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4100 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4101 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4102}
4103
4104// Ensure that if the only data in flight is non-retransmittable, the
4105// retransmission alarm is not set.
4106TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
4107 QuicStreamId stream_id = 2;
4108 QuicPacketNumber last_data_packet;
4109 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
4110
4111 // Cancel the stream.
4112 const QuicPacketNumber rst_packet = last_data_packet + 1;
4113 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
4114 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4115
4116 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
4117 // packet, which is no longer retransmittable since the stream was cancelled.
4118 QuicAckFrame nack_stream_data =
4119 ConstructAckFrame(rst_packet, last_data_packet);
4120 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4121 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4122 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4123 ProcessAckPacket(&nack_stream_data);
4124
4125 // Ensure that the data is still in flight, but the retransmission alarm is no
4126 // longer set.
4127 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
4128 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4129}
4130
fayang339f0c82022-04-30 14:20:02 -07004131TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnPTO) {
Bence Békybac04052022-04-07 15:44:29 -04004132 QuicStreamId stream_id = 2;
4133 QuicPacketNumber last_packet;
4134 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4135
4136 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4137 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4138
4139 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
4140 // is sent.
fayang339f0c82022-04-30 14:20:02 -07004141 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
Bence Békybac04052022-04-07 15:44:29 -04004142 clock_.AdvanceTime(DefaultRetransmissionTime());
4143 connection_.GetRetransmissionAlarm()->Fire();
4144 size_t padding_frame_count = writer_->padding_frames().size();
4145 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04004146}
4147
4148TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
4149 QuicStreamId stream_id = 2;
4150 QuicPacketNumber last_packet;
4151 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4152 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4153 BlockOnNextWrite();
4154 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4155
4156 // Lose a packet which will trigger a pending retransmission.
4157 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4158 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4159 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4160 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4161 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4162 ProcessAckPacket(&ack);
4163
4164 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4165
4166 // Unblock the connection and verify that the RST_STREAM is sent but not the
4167 // second data packet nor a retransmit.
4168 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4169 writer_->SetWritable();
4170 connection_.OnCanWrite();
4171 size_t padding_frame_count = writer_->padding_frames().size();
4172 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4173 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
4174 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4175}
4176
4177TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
4178 QuicStreamId stream_id = 2;
4179 QuicPacketNumber last_packet;
4180 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4181 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4182 BlockOnNextWrite();
4183 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4184
4185 // Lose a packet which will trigger a pending retransmission.
4186 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4187 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4188 LostPacketVector lost_packets;
4189 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4190 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4191 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4192 Return(LossDetectionInterface::DetectionStats())));
4193 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4194 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4195 ProcessAckPacket(&ack);
4196
4197 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4198
4199 // Unblock the connection and verify that the RST_STREAM is sent and the
4200 // second data packet or a retransmit is sent.
4201 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
4202 writer_->SetWritable();
4203 connection_.OnCanWrite();
4204 // The RST_STREAM_FRAME is sent after queued packets and pending
4205 // retransmission.
4206 connection_.SendControlFrame(QuicFrame(
4207 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
4208 size_t padding_frame_count = writer_->padding_frames().size();
4209 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4210 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4211}
4212
4213TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
4214 QuicPacketNumber last_packet;
4215 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4216 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
4217 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
4218
4219 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4220
4221 // Instigate a loss with an ack.
4222 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4223 // The first nack should trigger a fast retransmission, but we'll be
4224 // write blocked, so the packet will be queued.
4225 BlockOnNextWrite();
4226
4227 LostPacketVector lost_packets;
4228 lost_packets.push_back(
4229 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4230 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4231 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4232 Return(LossDetectionInterface::DetectionStats())));
4233 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4234 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4235 .Times(1);
4236 ProcessAckPacket(&nack_two);
4237 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4238
4239 // Now, ack the previous transmission.
4240 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4241 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
4242 QuicAckFrame ack_all = InitAckFrame(3);
4243 ProcessAckPacket(&ack_all);
4244
4245 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4246 .Times(0);
4247
4248 writer_->SetWritable();
4249 connection_.OnCanWrite();
4250
4251 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4252 // We do not store retransmittable frames of this retransmission.
4253 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
4254}
4255
4256TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
4257 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4258 QuicPacketNumber original, second;
4259
4260 QuicByteCount packet_size =
4261 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
4262 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
4263
4264 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
4265 // The first nack should retransmit the largest observed packet.
4266 LostPacketVector lost_packets;
4267 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
4268 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4269 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4270 Return(LossDetectionInterface::DetectionStats())));
4271 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4272 // Packet 1 is short header for IETF QUIC because the encryption level
4273 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
4274 EXPECT_CALL(*send_algorithm_,
4275 OnPacketSent(_, _, _,
4276 GetParam().version.HasIetfInvariantHeader()
4277 ? packet_size
4278 : packet_size - kQuicVersionSize,
4279 _));
4280 ProcessAckPacket(&frame);
4281}
4282
Bence Békybac04052022-04-07 15:44:29 -04004283TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
4284 BlockOnNextWrite();
4285 writer_->set_is_write_blocked_data_buffered(true);
4286 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4287 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4288 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4289
4290 writer_->SetWritable();
4291 connection_.OnCanWrite();
4292 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4293}
4294
4295TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
4296 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4297 BlockOnNextWrite();
4298 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4299 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4300 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4301 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4302
4303 // The second packet should also be queued, in order to ensure packets are
4304 // never sent out of order.
4305 writer_->SetWritable();
4306 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4307 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4308 EXPECT_EQ(2u, connection_.NumQueuedPackets());
4309
4310 // Now both are sent in order when we unblock.
4311 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4312 connection_.OnCanWrite();
4313 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4314 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4315}
4316
4317TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
4318 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4319 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4320 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4321
4322 BlockOnNextWrite();
4323 writer_->set_is_write_blocked_data_buffered(true);
4324 // Simulate the retransmission alarm firing.
4325 clock_.AdvanceTime(DefaultRetransmissionTime());
4326 connection_.GetRetransmissionAlarm()->Fire();
4327
4328 // Ack the sent packet before the callback returns, which happens in
4329 // rare circumstances with write blocked sockets.
4330 QuicAckFrame ack = InitAckFrame(1);
4331 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4332 ProcessAckPacket(&ack);
4333
4334 writer_->SetWritable();
4335 connection_.OnCanWrite();
4336 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang339f0c82022-04-30 14:20:02 -07004337 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 3));
Bence Békybac04052022-04-07 15:44:29 -04004338}
4339
4340TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4341 // Block the connection.
4342 BlockOnNextWrite();
4343 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4344 EXPECT_EQ(1u, writer_->packets_write_attempts());
4345 EXPECT_TRUE(writer_->IsWriteBlocked());
4346
4347 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4348 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4349 connection_.GetSendAlarm()->Fire();
4350 EXPECT_TRUE(writer_->IsWriteBlocked());
4351 EXPECT_EQ(1u, writer_->packets_write_attempts());
4352}
4353
4354TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4355 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4356
4357 // Block the connection.
4358 BlockOnNextWrite();
4359 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4360 EXPECT_TRUE(writer_->IsWriteBlocked());
4361 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4362 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4363
4364 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4365 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4366 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4367 // is returned.
4368 const uint64_t received_packet_num = 1;
4369 const bool has_stop_waiting = false;
4370 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4371 std::unique_ptr<QuicPacket> packet(
4372 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4373 char buffer[kMaxOutgoingPacketSize];
4374 size_t encrypted_length =
4375 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4376 *packet, buffer, kMaxOutgoingPacketSize);
4377 connection_.ProcessUdpPacket(
4378 kSelfAddress, kPeerAddress,
4379 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4380
4381 EXPECT_TRUE(writer_->IsWriteBlocked());
4382 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4383}
4384
4385TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4386 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4387 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4388
4389 // Simulate the case where a shared writer gets blocked by another connection.
4390 writer_->SetWriteBlocked();
4391
4392 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4393 QuicAckFrame ack1 = InitAckFrame(1);
4394 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4395 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4396 ProcessAckPacket(1, &ack1);
4397}
4398
4399TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4400 writer_->SetBatchMode(true);
4401 EXPECT_TRUE(connection_.connected());
4402 // Have to explicitly grab the OnConnectionClosed frame and check
4403 // its parameters because this is a silent connection close and the
4404 // frame is not also transmitted to the peer.
4405 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4406 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4407
4408 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4409
4410 {
4411 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4412 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4413 ConnectionCloseBehavior::SILENT_CLOSE);
4414
4415 EXPECT_FALSE(connection_.connected());
4416 writer_->SetWriteBlocked();
4417 }
4418 EXPECT_EQ(1, connection_close_frame_count_);
4419 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4420 IsError(QUIC_PEER_GOING_AWAY));
4421}
4422
4423TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4424 writer_->SetBatchMode(true);
4425 writer_->BlockOnNextFlush();
4426
4427 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4428 {
4429 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4430 // flusher's destructor will call connection_.FlushPackets, which should add
4431 // the connection to the write blocked list.
4432 }
4433}
4434
4435TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4436 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4437 int offset = 0;
4438 // Send packets 1 to 15.
4439 for (int i = 0; i < 15; ++i) {
4440 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4441 offset += 3;
4442 }
4443
4444 // Ack 15, nack 1-14.
4445
4446 QuicAckFrame nack =
4447 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4448
4449 // 14 packets have been NACK'd and lost.
4450 LostPacketVector lost_packets;
4451 for (int i = 1; i < 15; ++i) {
4452 lost_packets.push_back(
4453 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
4454 }
4455 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4456 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4457 Return(LossDetectionInterface::DetectionStats())));
4458 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4459 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4460 ProcessAckPacket(&nack);
4461}
4462
4463// Test sending multiple acks from the connection to the session.
4464TEST_P(QuicConnectionTest, MultipleAcks) {
4465 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4466 return;
4467 }
4468 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4469 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4470 ProcessDataPacket(1);
4471 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4472 QuicPacketNumber last_packet;
4473 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4474 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4475 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4476 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4477 SendAckPacketToPeer(); // Packet 3
4478 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4479 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4480 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4481 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4482 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4483 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4484
4485 // Client will ack packets 1, 2, [!3], 4, 5.
4486 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4487 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4488 ProcessAckPacket(&frame1);
4489
4490 // Now the client implicitly acks 3, and explicitly acks 6.
4491 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4492 QuicAckFrame frame2 = InitAckFrame(6);
4493 ProcessAckPacket(&frame2);
4494}
4495
4496TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
4497 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4498 return;
4499 }
4500 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4501 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4502 ProcessDataPacket(1);
4503 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4504 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4505 // From now on, we send acks, so the send algorithm won't mark them pending.
4506 SendAckPacketToPeer(); // Packet 2
4507
4508 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4509 QuicAckFrame frame = InitAckFrame(1);
4510 ProcessAckPacket(&frame);
4511
4512 // Verify that our internal state has least-unacked as 2, because we're still
4513 // waiting for a potential ack for 2.
4514
4515 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4516
4517 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4518 frame = InitAckFrame(2);
4519 ProcessAckPacket(&frame);
4520 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4521
4522 // When we send an ack, we make sure our least-unacked makes sense. In this
4523 // case since we're not waiting on an ack for 2 and all packets are acked, we
4524 // set it to 3.
4525 SendAckPacketToPeer(); // Packet 3
4526 // Least_unacked remains at 3 until another ack is received.
4527 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4528 if (GetParam().no_stop_waiting) {
4529 // Expect no stop waiting frame is sent.
4530 EXPECT_FALSE(least_unacked().IsInitialized());
4531 } else {
4532 // Check that the outgoing ack had its packet number as least_unacked.
4533 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4534 }
4535
4536 // Ack the ack, which updates the rtt and raises the least unacked.
4537 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4538 frame = InitAckFrame(3);
4539 ProcessAckPacket(&frame);
4540
4541 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4542 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4543 SendAckPacketToPeer(); // Packet 5
4544 if (GetParam().no_stop_waiting) {
4545 // Expect no stop waiting frame is sent.
4546 EXPECT_FALSE(least_unacked().IsInitialized());
4547 } else {
4548 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4549 }
4550
4551 // Send two data packets at the end, and ensure if the last one is acked,
4552 // the least unacked is raised above the ack packets.
4553 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4554 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4555
4556 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4557 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4558 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4559 ProcessAckPacket(&frame);
4560
4561 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4562}
4563
Bence Békybac04052022-04-07 15:44:29 -04004564TEST_P(QuicConnectionTest, SendHandshakeMessages) {
Bence Békybac04052022-04-07 15:44:29 -04004565 // Attempt to send a handshake message and have the socket block.
4566 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4567 BlockOnNextWrite();
4568 connection_.SendCryptoDataWithString("foo", 0);
4569 // The packet should be serialized, but not queued.
4570 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4571
4572 // Switch to the new encrypter.
martinduke9e0811c2022-12-08 20:35:57 -08004573 connection_.SetEncrypter(
4574 ENCRYPTION_ZERO_RTT,
4575 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004576 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4577
4578 // Now become writeable and flush the packets.
4579 writer_->SetWritable();
4580 EXPECT_CALL(visitor_, OnCanWrite());
4581 connection_.OnCanWrite();
4582 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4583
martinduke9e0811c2022-12-08 20:35:57 -08004584 // Verify that the handshake packet went out with Initial encryption.
4585 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -04004586}
4587
martinduke9e0811c2022-12-08 20:35:57 -08004588TEST_P(QuicConnectionTest, DropRetransmitsForInitialPacketAfterForwardSecure) {
Bence Békybac04052022-04-07 15:44:29 -04004589 connection_.SendCryptoStreamData();
Bence Békybac04052022-04-07 15:44:29 -04004590 // Simulate the retransmission alarm firing and the socket blocking.
4591 BlockOnNextWrite();
4592 clock_.AdvanceTime(DefaultRetransmissionTime());
4593 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4594 connection_.GetRetransmissionAlarm()->Fire();
4595 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4596
4597 // Go forward secure.
4598 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4599 std::make_unique<TaggingEncrypter>(0x02));
4600 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4601 notifier_.NeuterUnencryptedData();
4602 connection_.NeuterUnencryptedPackets();
4603 connection_.OnHandshakeComplete();
4604
4605 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4606 // Unblock the socket and ensure that no packets are sent.
4607 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4608 writer_->SetWritable();
4609 connection_.OnCanWrite();
4610}
4611
4612TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
Bence Békybac04052022-04-07 15:44:29 -04004613 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
4614
4615 connection_.SendCryptoDataWithString("foo", 0);
4616
martinduke9e0811c2022-12-08 20:35:57 -08004617 connection_.SetEncrypter(
4618 ENCRYPTION_ZERO_RTT,
4619 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004620 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
martinduke9e0811c2022-12-08 20:35:57 -08004621 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4622 writer_->framer()->framer()->SetAlternativeDecrypter(
4623 ENCRYPTION_ZERO_RTT,
4624 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT), false);
4625 }
Bence Békybac04052022-04-07 15:44:29 -04004626
4627 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4628 EXPECT_FALSE(notifier_.HasLostStreamData());
4629 connection_.MarkZeroRttPacketsForRetransmission(0);
4630 EXPECT_TRUE(notifier_.HasLostStreamData());
4631}
4632
4633TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
4634 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4635 return;
4636 }
4637 // SetFromConfig is always called after construction from InitializeSession.
4638 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4639 QuicConfig config;
4640 connection_.SetFromConfig(config);
4641 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004642
martinduke9e0811c2022-12-08 20:35:57 -08004643 peer_framer_.SetEncrypter(
4644 ENCRYPTION_ZERO_RTT,
4645 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
4646 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4647 writer_->framer()->framer()->SetDecrypter(
4648 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4649 }
Bence Békybac04052022-04-07 15:44:29 -04004650
4651 // Process an encrypted packet which can not yet be decrypted which should
4652 // result in the packet being buffered.
4653 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4654
4655 // Transition to the new encryption state and process another encrypted packet
4656 // which should result in the original packet being processed.
4657 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004658 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
4659 connection_.SetEncrypter(
4660 ENCRYPTION_ZERO_RTT,
4661 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004662 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4663 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4664 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4665
4666 // Finally, process a third packet and note that we do not reprocess the
4667 // buffered packet.
4668 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4669 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4670}
4671
Bence Békybac04052022-04-07 15:44:29 -04004672TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
4673 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4674 return;
4675 }
4676 // SetFromConfig is always called after construction from InitializeSession.
4677 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4678 QuicConfig config;
4679 config.set_max_undecryptable_packets(100);
4680 connection_.SetFromConfig(config);
4681 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
Bence Békybac04052022-04-07 15:44:29 -04004682
martinduke9e0811c2022-12-08 20:35:57 -08004683 peer_framer_.SetEncrypter(
4684 ENCRYPTION_ZERO_RTT,
4685 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004686
4687 // Process an encrypted packet which can not yet be decrypted which should
4688 // result in the packet being buffered.
4689 for (uint64_t i = 1; i <= 100; ++i) {
4690 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4691 }
4692
4693 // Transition to the new encryption state and process another encrypted packet
4694 // which should result in the original packets being processed.
4695 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4696 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08004697 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004698 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -08004699 connection_.SetEncrypter(
4700 ENCRYPTION_ZERO_RTT,
4701 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04004702 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4703
4704 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
martinduke9e0811c2022-12-08 20:35:57 -08004705 if (!connection_.version().KnowsWhichDecrypterToUse()) {
4706 writer_->framer()->framer()->SetDecrypter(
4707 ENCRYPTION_ZERO_RTT, std::make_unique<TaggingDecrypter>());
4708 }
Bence Békybac04052022-04-07 15:44:29 -04004709 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4710
4711 // Finally, process a third packet and note that we do not reprocess the
4712 // buffered packet.
4713 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4714 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4715}
4716
4717TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4718 BlockOnNextWrite();
4719 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4720 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4721 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4722
4723 // Test that RTO is started once we write to the socket.
4724 writer_->SetWritable();
4725 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4726 connection_.OnCanWrite();
4727 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4728}
4729
Bence Békybac04052022-04-07 15:44:29 -04004730TEST_P(QuicConnectionTest, TestQueued) {
Bence Békybac04052022-04-07 15:44:29 -04004731 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4732 BlockOnNextWrite();
4733 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4734 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4735
4736 // Unblock the writes and actually send.
4737 writer_->SetWritable();
4738 connection_.OnCanWrite();
4739 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4740}
4741
4742TEST_P(QuicConnectionTest, InitialTimeout) {
4743 EXPECT_TRUE(connection_.connected());
4744 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4745 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4746
4747 // SetFromConfig sets the initial timeouts before negotiation.
4748 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4749 QuicConfig config;
4750 connection_.SetFromConfig(config);
4751 // Subtract a second from the idle timeout on the client side.
4752 QuicTime default_timeout =
4753 clock_.ApproximateNow() +
4754 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4755 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4756
4757 EXPECT_CALL(visitor_,
4758 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4759 // Simulate the timeout alarm firing.
4760 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4761 connection_.GetTimeoutAlarm()->Fire();
4762
4763 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4764 EXPECT_FALSE(connection_.connected());
4765
4766 EXPECT_FALSE(connection_.HasPendingAcks());
4767 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4768 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4769 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4770 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4771 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4772 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4773}
4774
4775TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4776 EXPECT_TRUE(connection_.connected());
4777 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4778 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4779
4780 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4781 QuicConfig config;
4782 connection_.SetFromConfig(config);
4783 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4784 QuicTime initial_ddl =
4785 clock_.ApproximateNow() +
4786 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4787 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4788 EXPECT_TRUE(connection_.connected());
4789
4790 // Advance the time and send the first packet to the peer.
4791 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4792 QuicPacketNumber last_packet;
4793 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4794 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4795 // This will be the updated deadline for the connection to idle time out.
4796 QuicTime new_ddl = clock_.ApproximateNow() +
4797 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4798
4799 // Simulate the timeout alarm firing, the connection should not be closed as
4800 // a new packet has been sent.
4801 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
4802 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4803 clock_.AdvanceTime(delay);
4804 // Verify the timeout alarm deadline is updated.
4805 EXPECT_TRUE(connection_.connected());
4806 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4807 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4808
4809 // Simulate the timeout alarm firing again, the connection now should be
4810 // closed.
4811 EXPECT_CALL(visitor_,
4812 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4813 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4814 connection_.GetTimeoutAlarm()->Fire();
4815 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4816 EXPECT_FALSE(connection_.connected());
4817
4818 EXPECT_FALSE(connection_.HasPendingAcks());
4819 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4820 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4821 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4822 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4823 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4824}
4825
4826TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4827 EXPECT_TRUE(connection_.connected());
4828 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4829 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4830
4831 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4832 QuicConfig config;
4833 connection_.SetFromConfig(config);
4834 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4835 QuicTime initial_ddl =
4836 clock_.ApproximateNow() +
4837 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4838 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4839 EXPECT_TRUE(connection_.connected());
4840
4841 // Immediately send the first packet, this is a rare case but test code will
4842 // hit this issue often as MockClock used for tests doesn't move with code
4843 // execution until manually adjusted.
4844 QuicPacketNumber last_packet;
4845 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4846 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4847
4848 // Advance the time and send the second packet to the peer.
4849 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4850 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4851 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4852
4853 // Simulate the timeout alarm firing, the connection will be closed.
4854 EXPECT_CALL(visitor_,
4855 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4856 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4857 connection_.GetTimeoutAlarm()->Fire();
4858
4859 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4860 EXPECT_FALSE(connection_.connected());
4861
4862 EXPECT_FALSE(connection_.HasPendingAcks());
4863 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4864 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4865 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4866 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4867 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4868}
4869
4870TEST_P(QuicConnectionTest, HandshakeTimeout) {
4871 // Use a shorter handshake timeout than idle timeout for this test.
4872 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4873 connection_.SetNetworkTimeouts(timeout, timeout);
4874 EXPECT_TRUE(connection_.connected());
4875 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4876
4877 QuicTime handshake_timeout =
4878 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4879 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4880 EXPECT_TRUE(connection_.connected());
4881
4882 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4883 SendStreamDataToPeer(
4884 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4885 "GET /", 0, FIN, nullptr);
4886 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4887 QuicAckFrame frame = InitAckFrame(1);
4888 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4889 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4890 ProcessAckPacket(&frame);
4891
4892 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4893 EXPECT_TRUE(connection_.connected());
4894
4895 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4896
4897 EXPECT_CALL(visitor_,
4898 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4899 // Simulate the timeout alarm firing.
4900 connection_.GetTimeoutAlarm()->Fire();
4901
4902 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4903 EXPECT_FALSE(connection_.connected());
4904
4905 EXPECT_FALSE(connection_.HasPendingAcks());
4906 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4907 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4908 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4909 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
4910}
4911
4912TEST_P(QuicConnectionTest, PingAfterSend) {
4913 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4914 return;
4915 }
4916 EXPECT_TRUE(connection_.connected());
4917 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4918 .WillRepeatedly(Return(true));
4919 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4920
4921 // Advance to 5ms, and send a packet to the peer, which will set
4922 // the ping alarm.
4923 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4924 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4925 SendStreamDataToPeer(
4926 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4927 "GET /", 0, FIN, nullptr);
4928 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4929 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4930 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4931
4932 // Now recevie an ACK of the previous packet, which will move the
4933 // ping alarm forward.
4934 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4935 QuicAckFrame frame = InitAckFrame(1);
4936 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4937 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4938 ProcessAckPacket(&frame);
4939 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4940 // The ping timer is set slightly less than 15 seconds in the future, because
4941 // of the 1s ping timer alarm granularity.
4942 EXPECT_EQ(
4943 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4944 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4945
4946 writer_->Reset();
4947 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
4948 connection_.GetPingAlarm()->Fire();
4949 size_t padding_frame_count = writer_->padding_frames().size();
4950 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4951 ASSERT_EQ(1u, writer_->ping_frames().size());
4952 writer_->Reset();
4953
4954 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4955 .WillRepeatedly(Return(false));
4956 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4957 SendAckPacketToPeer();
4958
4959 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4960}
4961
4962TEST_P(QuicConnectionTest, ReducedPingTimeout) {
4963 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4964 return;
4965 }
4966 EXPECT_TRUE(connection_.connected());
4967 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4968 .WillRepeatedly(Return(true));
4969 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4970
4971 // Use a reduced ping timeout for this connection.
fayang5d393332022-04-18 13:34:54 -07004972 connection_.set_keep_alive_ping_timeout(QuicTime::Delta::FromSeconds(10));
Bence Békybac04052022-04-07 15:44:29 -04004973
4974 // Advance to 5ms, and send a packet to the peer, which will set
4975 // the ping alarm.
4976 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4977 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4978 SendStreamDataToPeer(
4979 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4980 "GET /", 0, FIN, nullptr);
4981 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4982 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4983 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4984
4985 // Now recevie an ACK of the previous packet, which will move the
4986 // ping alarm forward.
4987 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4988 QuicAckFrame frame = InitAckFrame(1);
4989 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4990 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4991 ProcessAckPacket(&frame);
4992 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4993 // The ping timer is set slightly less than 10 seconds in the future, because
4994 // of the 1s ping timer alarm granularity.
4995 EXPECT_EQ(
4996 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
4997 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4998
4999 writer_->Reset();
5000 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5001 connection_.GetPingAlarm()->Fire();
5002 size_t padding_frame_count = writer_->padding_frames().size();
5003 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5004 ASSERT_EQ(1u, writer_->ping_frames().size());
5005 writer_->Reset();
5006
5007 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5008 .WillRepeatedly(Return(false));
5009 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5010 SendAckPacketToPeer();
5011
5012 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5013}
5014
5015// Tests whether sending an MTU discovery packet to peer successfully causes the
5016// maximum packet size to increase.
5017TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
5018 MtuDiscoveryTestInit();
5019
5020 // Send an MTU probe.
5021 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5022 QuicByteCount mtu_probe_size;
5023 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5024 .WillOnce(SaveArg<3>(&mtu_probe_size));
5025 connection_.SendMtuDiscoveryPacket(new_mtu);
5026 EXPECT_EQ(new_mtu, mtu_probe_size);
5027 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5028
5029 // Send more than MTU worth of data. No acknowledgement was received so far,
5030 // so the MTU should be at its old value.
5031 const std::string data(kDefaultMaxPacketSize + 1, '.');
5032 QuicByteCount size_before_mtu_change;
5033 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5034 .Times(2)
5035 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5036 .WillOnce(Return());
5037 connection_.SendStreamDataWithString(3, data, 0, FIN);
5038 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5039 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5040
5041 // Acknowledge all packets so far.
5042 QuicAckFrame probe_ack = InitAckFrame(3);
5043 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5044 ProcessAckPacket(&probe_ack);
5045 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5046
5047 // Send the same data again. Check that it fits into a single packet now.
5048 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5049 connection_.SendStreamDataWithString(3, data, 0, FIN);
5050 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5051}
5052
5053// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5054// the writer is flushed immediately.
5055TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5056 writer_->SetBatchMode(true);
5057 MtuDiscoveryTestInit();
5058
5059 // Send an MTU probe.
5060 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5061 QuicByteCount mtu_probe_size;
5062 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5063 .WillOnce(SaveArg<3>(&mtu_probe_size));
5064 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5065 connection_.SendMtuDiscoveryPacket(target_mtu);
5066 EXPECT_EQ(target_mtu, mtu_probe_size);
5067 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
5068}
5069
5070// Tests whether MTU discovery does not happen when it is not explicitly enabled
5071// by the connection options.
5072TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
5073 MtuDiscoveryTestInit();
5074
5075 const QuicPacketCount packets_between_probes_base = 10;
5076 set_packets_between_probes_base(packets_between_probes_base);
5077
5078 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5079 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5080 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5081 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5082 EXPECT_EQ(0u, connection_.mtu_probe_count());
5083 }
5084}
5085
5086// Tests whether MTU discovery works when all probes are acknowledged on the
5087// first try.
5088TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
5089 MtuDiscoveryTestInit();
5090
5091 const QuicPacketCount packets_between_probes_base = 5;
5092 set_packets_between_probes_base(packets_between_probes_base);
5093
5094 connection_.EnablePathMtuDiscovery(send_algorithm_);
5095
5096 // Send enough packets so that the next one triggers path MTU discovery.
5097 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5098 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5099 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5100 }
5101
5102 // Trigger the probe.
5103 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5104 nullptr);
5105 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5106 QuicByteCount probe_size;
5107 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5108 .WillOnce(SaveArg<3>(&probe_size));
5109 connection_.GetMtuDiscoveryAlarm()->Fire();
5110
5111 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5112 kMtuDiscoveryTargetPacketSizeHigh));
5113
5114 const QuicPacketNumber probe_packet_number =
5115 FirstSendingPacketNumber() + packets_between_probes_base;
5116 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5117
5118 // Acknowledge all packets sent so far.
5119 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5120 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5121 .Times(AnyNumber());
5122 ProcessAckPacket(&probe_ack);
5123 EXPECT_EQ(probe_size, connection_.max_packet_length());
5124 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5125
5126 EXPECT_EQ(1u, connection_.mtu_probe_count());
5127
5128 QuicStreamOffset stream_offset = packets_between_probes_base;
5129 QuicByteCount last_probe_size = 0;
5130 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5131 ++num_probes) {
5132 // Send just enough packets without triggering the next probe.
5133 for (QuicPacketCount i = 0;
5134 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5135 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5136 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5137 }
5138
5139 // Trigger the next probe.
5140 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5141 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5142 QuicByteCount new_probe_size;
5143 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5144 .WillOnce(SaveArg<3>(&new_probe_size));
5145 connection_.GetMtuDiscoveryAlarm()->Fire();
5146 EXPECT_THAT(new_probe_size,
5147 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5148 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5149
5150 // Acknowledge all packets sent so far.
5151 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5152 ProcessAckPacket(&probe_ack);
5153 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5154 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5155
5156 last_probe_size = probe_size;
5157 probe_size = new_probe_size;
5158 }
5159
5160 // The last probe size should be equal to the target.
5161 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
5162
5163 writer_->SetShouldWriteFail();
5164
5165 // Ignore PACKET_WRITE_ERROR once.
5166 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5167 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5168 EXPECT_TRUE(connection_.connected());
5169
5170 // Close connection on another PACKET_WRITE_ERROR.
5171 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5172 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5173 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5174 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5175 EXPECT_FALSE(connection_.connected());
5176 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5177 IsError(QUIC_PACKET_WRITE_ERROR));
5178}
5179
5180// After a successful MTU probe, one and only one write error should be ignored
5181// if it happened in QuicConnection::FlushPacket.
5182TEST_P(QuicConnectionTest,
5183 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5184 MtuDiscoveryTestInit();
5185 writer_->SetBatchMode(true);
5186
5187 const QuicPacketCount packets_between_probes_base = 5;
5188 set_packets_between_probes_base(packets_between_probes_base);
5189
5190 connection_.EnablePathMtuDiscovery(send_algorithm_);
5191
5192 const QuicByteCount original_max_packet_length =
5193 connection_.max_packet_length();
5194 // Send enough packets so that the next one triggers path MTU discovery.
5195 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5196 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5197 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5198 }
5199
5200 // Trigger the probe.
5201 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5202 nullptr);
5203 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5204 QuicByteCount probe_size;
5205 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5206 .WillOnce(SaveArg<3>(&probe_size));
5207 connection_.GetMtuDiscoveryAlarm()->Fire();
5208
5209 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5210 kMtuDiscoveryTargetPacketSizeHigh));
5211
5212 const QuicPacketNumber probe_packet_number =
5213 FirstSendingPacketNumber() + packets_between_probes_base;
5214 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5215
5216 // Acknowledge all packets sent so far.
5217 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5218 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5219 .Times(AnyNumber());
5220 ProcessAckPacket(&probe_ack);
5221 EXPECT_EQ(probe_size, connection_.max_packet_length());
5222 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5223
5224 EXPECT_EQ(1u, connection_.mtu_probe_count());
5225
5226 writer_->SetShouldWriteFail();
5227
5228 // Ignore PACKET_WRITE_ERROR once.
5229 {
5230 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5231 // flusher's destructor will call connection_.FlushPackets, which should
5232 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5233 }
5234 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5235 EXPECT_TRUE(connection_.connected());
5236
5237 // Close connection on another PACKET_WRITE_ERROR.
5238 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5239 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5240 {
5241 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5242 // flusher's destructor will call connection_.FlushPackets, which should
5243 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5244 }
5245 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5246 EXPECT_FALSE(connection_.connected());
5247 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5248 IsError(QUIC_PACKET_WRITE_ERROR));
5249}
5250
5251// Simulate the case where the first attempt to send a probe is write blocked,
5252// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5253TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
5254 MtuDiscoveryTestInit();
5255
5256 const QuicPacketCount packets_between_probes_base = 5;
5257 set_packets_between_probes_base(packets_between_probes_base);
5258
5259 connection_.EnablePathMtuDiscovery(send_algorithm_);
5260
5261 // Send enough packets so that the next one triggers path MTU discovery.
5262 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5263 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5264 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5265 }
5266
5267 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5268
5269 // Trigger the probe.
5270 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5271 nullptr);
5272 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5273 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5274 BlockOnNextWrite();
5275 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5276 connection_.GetMtuDiscoveryAlarm()->Fire();
5277 EXPECT_EQ(1u, connection_.mtu_probe_count());
5278 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5279 ASSERT_TRUE(connection_.connected());
5280
5281 writer_->SetWritable();
5282 SimulateNextPacketTooLarge();
5283 connection_.OnCanWrite();
5284 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5285 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5286 EXPECT_TRUE(connection_.connected());
5287}
5288
5289// Tests whether MTU discovery works correctly when the probes never get
5290// acknowledged.
5291TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5292 MtuDiscoveryTestInit();
5293
5294 // Lower the number of probes between packets in order to make the test go
5295 // much faster.
5296 const QuicPacketCount packets_between_probes_base = 5;
5297 set_packets_between_probes_base(packets_between_probes_base);
5298
5299 connection_.EnablePathMtuDiscovery(send_algorithm_);
5300
5301 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5302
5303 EXPECT_EQ(packets_between_probes_base,
5304 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5305
5306 // This tests sends more packets than strictly necessary to make sure that if
5307 // the connection was to send more discovery packets than needed, those would
5308 // get caught as well.
5309 const QuicPacketCount number_of_packets =
5310 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5311 std::vector<QuicPacketNumber> mtu_discovery_packets;
5312 // Called on many acks.
5313 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5314 .Times(AnyNumber());
5315 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5316 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5317 clock_.AdvanceTime(rtt);
5318
5319 // Receive an ACK, which marks all data packets as received, and all MTU
5320 // discovery packets as missing.
5321
5322 QuicAckFrame ack;
5323
5324 if (!mtu_discovery_packets.empty()) {
5325 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5326 mtu_discovery_packets.end());
5327 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5328 mtu_discovery_packets.end());
5329 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5330 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5331 creator_->packet_number() + 1);
5332 ack.largest_acked = creator_->packet_number();
5333
5334 } else {
5335 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5336 ack.largest_acked = creator_->packet_number();
5337 }
5338
5339 ProcessAckPacket(&ack);
5340
5341 // Trigger MTU probe if it would be scheduled now.
5342 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5343 continue;
5344 }
5345
5346 // Fire the alarm. The alarm should cause a packet to be sent.
5347 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5348 connection_.GetMtuDiscoveryAlarm()->Fire();
5349 // Record the packet number of the MTU discovery packet in order to
5350 // mark it as NACK'd.
5351 mtu_discovery_packets.push_back(creator_->packet_number());
5352 }
5353
5354 // Ensure the number of packets between probes grows exponentially by checking
5355 // it against the closed-form expression for the packet number.
5356 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5357 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5358 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5359 const QuicPacketCount packets_between_probes =
5360 packets_between_probes_base * ((1 << (i + 1)) - 1);
5361 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5362 mtu_discovery_packets[i]);
5363 }
5364
5365 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5366 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5367 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5368}
5369
5370// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5371TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
5372 MtuDiscoveryTestInit();
5373
5374 const QuicPacketCount packets_between_probes_base = 5;
5375 set_packets_between_probes_base(packets_between_probes_base);
5376
5377 connection_.EnablePathMtuDiscovery(send_algorithm_);
5378
5379 // Send enough packets so that the next one triggers path MTU discovery.
5380 QuicStreamOffset stream_offset = 0;
5381 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5382 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5383 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5384 }
5385
5386 // Trigger the probe.
5387 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5388 nullptr);
5389 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5390 QuicByteCount probe_size;
5391 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5392 .WillOnce(SaveArg<3>(&probe_size));
5393 connection_.GetMtuDiscoveryAlarm()->Fire();
5394 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5395 kMtuDiscoveryTargetPacketSizeHigh));
5396
5397 const QuicPacketNumber probe_packet_number =
5398 FirstSendingPacketNumber() + packets_between_probes_base;
5399 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5400
5401 // Acknowledge all packets sent so far.
5402 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
5403 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5404 .Times(AnyNumber());
5405 ProcessAckPacket(&first_ack);
5406 EXPECT_EQ(probe_size, connection_.max_packet_length());
5407 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5408
5409 EXPECT_EQ(1u, connection_.mtu_probe_count());
5410
5411 // Send just enough packets without triggering the second probe.
5412 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5413 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5414 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5415 }
5416
5417 // Trigger the second probe.
5418 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5419 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5420 QuicByteCount second_probe_size;
5421 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5422 .WillOnce(SaveArg<3>(&second_probe_size));
5423 connection_.GetMtuDiscoveryAlarm()->Fire();
5424 EXPECT_THAT(second_probe_size,
5425 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5426 EXPECT_EQ(2u, connection_.mtu_probe_count());
5427
5428 // Acknowledge all packets sent so far, except the second probe.
5429 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5430 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5431 ProcessAckPacket(&first_ack);
5432 EXPECT_EQ(probe_size, connection_.max_packet_length());
5433
5434 // Send just enough packets without triggering the third probe.
5435 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5436 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5437 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5438 }
5439
5440 // Trigger the third probe.
5441 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5442 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5443 QuicByteCount third_probe_size;
5444 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5445 .WillOnce(SaveArg<3>(&third_probe_size));
5446 connection_.GetMtuDiscoveryAlarm()->Fire();
5447 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5448 EXPECT_EQ(3u, connection_.mtu_probe_count());
5449
5450 // Acknowledge all packets sent so far, except the second probe.
5451 QuicAckFrame third_ack =
5452 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5453 ProcessAckPacket(&third_ack);
5454 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5455
5456 SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr);
5457 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5458
5459 if (connection_.PathDegradingDetectionInProgress() &&
5460 QuicConnectionPeer::GetPathDegradingDeadline(&connection_) <
5461 QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(
5462 &connection_)) {
5463 // Fire path degrading alarm first.
5464 connection_.PathDegradingTimeout();
5465 }
5466
5467 // Verify the max packet size has not reduced.
5468 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5469
5470 // Fire alarm to get path mtu reduction callback called.
5471 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5472 connection_.GetBlackholeDetectorAlarm()->Fire();
5473
5474 // Verify the max packet size has reduced to the previous value.
5475 EXPECT_EQ(probe_size, connection_.max_packet_length());
5476}
5477
5478// Tests whether MTU discovery works when the writer has a limit on how large a
5479// packet can be.
5480TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5481 MtuDiscoveryTestInit();
5482
5483 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5484 writer_->set_max_packet_size(mtu_limit);
5485
5486 const QuicPacketCount packets_between_probes_base = 5;
5487 set_packets_between_probes_base(packets_between_probes_base);
5488
5489 connection_.EnablePathMtuDiscovery(send_algorithm_);
5490
5491 // Send enough packets so that the next one triggers path MTU discovery.
5492 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5493 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5494 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5495 }
5496
5497 // Trigger the probe.
5498 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5499 nullptr);
5500 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5501 QuicByteCount probe_size;
5502 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5503 .WillOnce(SaveArg<3>(&probe_size));
5504 connection_.GetMtuDiscoveryAlarm()->Fire();
5505
5506 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
5507
5508 const QuicPacketNumber probe_sequence_number =
5509 FirstSendingPacketNumber() + packets_between_probes_base;
5510 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5511
5512 // Acknowledge all packets sent so far.
5513 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5514 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5515 .Times(AnyNumber());
5516 ProcessAckPacket(&probe_ack);
5517 EXPECT_EQ(probe_size, connection_.max_packet_length());
5518 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5519
5520 EXPECT_EQ(1u, connection_.mtu_probe_count());
5521
5522 QuicStreamOffset stream_offset = packets_between_probes_base;
5523 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5524 ++num_probes) {
5525 // Send just enough packets without triggering the next probe.
5526 for (QuicPacketCount i = 0;
5527 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5528 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5529 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5530 }
5531
5532 // Trigger the next probe.
5533 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5534 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5535 QuicByteCount new_probe_size;
5536 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5537 .WillOnce(SaveArg<3>(&new_probe_size));
5538 connection_.GetMtuDiscoveryAlarm()->Fire();
5539 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5540 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5541
5542 // Acknowledge all packets sent so far.
5543 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5544 ProcessAckPacket(&probe_ack);
5545 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5546 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5547
5548 probe_size = new_probe_size;
5549 }
5550
5551 // The last probe size should be equal to the target.
5552 EXPECT_EQ(probe_size, mtu_limit);
5553}
5554
5555// Tests whether MTU discovery works when the writer returns an error despite
5556// advertising higher packet length.
5557TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5558 MtuDiscoveryTestInit();
5559
5560 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5561 const QuicByteCount initial_mtu = connection_.max_packet_length();
5562 EXPECT_LT(initial_mtu, mtu_limit);
5563 writer_->set_max_packet_size(mtu_limit);
5564
5565 const QuicPacketCount packets_between_probes_base = 5;
5566 set_packets_between_probes_base(packets_between_probes_base);
5567
5568 connection_.EnablePathMtuDiscovery(send_algorithm_);
5569
5570 // Send enough packets so that the next one triggers path MTU discovery.
5571 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5572 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5573 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5574 }
5575
5576 // Trigger the probe.
5577 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5578 nullptr);
5579 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5580 writer_->SimulateNextPacketTooLarge();
5581 connection_.GetMtuDiscoveryAlarm()->Fire();
5582 ASSERT_TRUE(connection_.connected());
5583
5584 // Send more data.
5585 QuicPacketNumber probe_number = creator_->packet_number();
5586 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5587 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5588 connection_.EnsureWritableAndSendStreamData5();
5589 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5590 }
5591
5592 // Acknowledge all packets sent so far, except for the lost probe.
5593 QuicAckFrame probe_ack =
5594 ConstructAckFrame(creator_->packet_number(), probe_number);
5595 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5596 ProcessAckPacket(&probe_ack);
5597 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5598
5599 // Send more packets, and ensure that none of them sets the alarm.
5600 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5601 connection_.EnsureWritableAndSendStreamData5();
5602 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5603 }
5604
5605 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5606 EXPECT_EQ(1u, connection_.mtu_probe_count());
5607}
5608
5609TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5610 MtuDiscoveryTestInit();
5611
5612 const QuicPacketCount packets_between_probes_base = 10;
5613 set_packets_between_probes_base(packets_between_probes_base);
5614
5615 connection_.EnablePathMtuDiscovery(send_algorithm_);
5616
5617 // Send enough packets so that the next one triggers path MTU discovery.
5618 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5619 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5620 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5621 }
5622
5623 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5624 nullptr);
5625 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5626
5627 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
5628 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5629 ConnectionCloseBehavior::SILENT_CLOSE);
5630 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5631}
5632
5633TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
5634 EXPECT_TRUE(connection_.connected());
5635 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5636 QuicConfig config;
5637 connection_.SetFromConfig(config);
5638
5639 const QuicTime::Delta initial_idle_timeout =
5640 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5641 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5642 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5643
5644 // When we send a packet, the timeout will change to 5ms +
5645 // kInitialIdleTimeoutSecs.
5646 clock_.AdvanceTime(five_ms);
5647 SendStreamDataToPeer(
5648 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5649 0, FIN, nullptr);
5650 EXPECT_EQ(default_timeout + five_ms,
5651 connection_.GetTimeoutAlarm()->deadline());
5652
5653 // Now send more data. This will not move the timeout because
5654 // no data has been received since the previous write.
5655 clock_.AdvanceTime(five_ms);
5656 SendStreamDataToPeer(
5657 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5658 3, FIN, nullptr);
5659 EXPECT_EQ(default_timeout + five_ms,
5660 connection_.GetTimeoutAlarm()->deadline());
5661
5662 // The original alarm will fire. We should not time out because we had a
5663 // network event at t=5ms. The alarm will reregister.
5664 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5665 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5666 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5667 EXPECT_TRUE(connection_.connected());
5668 EXPECT_EQ(default_timeout + five_ms,
5669 connection_.GetTimeoutAlarm()->deadline());
5670
5671 // This time, we should time out.
5672 EXPECT_CALL(visitor_,
5673 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5674 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5675 clock_.AdvanceTime(five_ms);
5676 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5677 connection_.GetTimeoutAlarm()->Fire();
5678 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5679 EXPECT_FALSE(connection_.connected());
5680 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5681}
5682
Bence Békybac04052022-04-07 15:44:29 -04005683TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5684 // When the idle timeout fires, verify that by default we do not send any
5685 // connection close packets.
5686 EXPECT_TRUE(connection_.connected());
5687 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5688 QuicConfig config;
5689
5690 // Create a handshake message that also enables silent close.
5691 CryptoHandshakeMessage msg;
5692 std::string error_details;
5693 QuicConfig client_config;
5694 client_config.SetInitialStreamFlowControlWindowToSend(
5695 kInitialStreamFlowControlWindowForTest);
5696 client_config.SetInitialSessionFlowControlWindowToSend(
5697 kInitialSessionFlowControlWindowForTest);
5698 client_config.SetIdleNetworkTimeout(
5699 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5700 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5701 const QuicErrorCode error =
5702 config.ProcessPeerHello(msg, CLIENT, &error_details);
5703 EXPECT_THAT(error, IsQuicNoError());
5704
5705 if (connection_.version().UsesTls()) {
5706 QuicConfigPeer::SetReceivedOriginalConnectionId(
5707 &config, connection_.connection_id());
5708 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5709 &config, connection_.connection_id());
5710 }
5711 connection_.SetFromConfig(config);
haoyuewang7b43efb2022-04-20 16:26:03 -07005712 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04005713
5714 const QuicTime::Delta default_idle_timeout =
5715 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5716 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5717 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5718
5719 // When we send a packet, the timeout will change to 5ms +
5720 // kInitialIdleTimeoutSecs.
5721 clock_.AdvanceTime(five_ms);
5722 SendStreamDataToPeer(
5723 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5724 0, FIN, nullptr);
5725 EXPECT_EQ(default_timeout + five_ms,
5726 connection_.GetTimeoutAlarm()->deadline());
5727
5728 // Now send more data. This will not move the timeout because
5729 // no data has been received since the previous write.
5730 clock_.AdvanceTime(five_ms);
5731 SendStreamDataToPeer(
5732 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5733 3, FIN, nullptr);
5734 EXPECT_EQ(default_timeout + five_ms,
5735 connection_.GetTimeoutAlarm()->deadline());
5736
5737 // The original alarm will fire. We should not time out because we had a
5738 // network event at t=5ms. The alarm will reregister.
5739 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5740 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5741 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5742 EXPECT_TRUE(connection_.connected());
5743 EXPECT_EQ(default_timeout + five_ms,
5744 connection_.GetTimeoutAlarm()->deadline());
5745
5746 // This time, we should time out.
5747 // This results in a SILENT_CLOSE, so the writer will not be invoked
5748 // and will not save the frame. Grab the frame from OnConnectionClosed
5749 // directly.
5750 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5751 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5752
5753 clock_.AdvanceTime(five_ms);
5754 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5755 connection_.GetTimeoutAlarm()->Fire();
5756 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5757 EXPECT_FALSE(connection_.connected());
5758 EXPECT_EQ(1, connection_close_frame_count_);
5759 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5760 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
5761}
5762
Bence Békybac04052022-04-07 15:44:29 -04005763TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5764 // Same test as above, but having open streams causes a connection close
5765 // to be sent.
5766 EXPECT_TRUE(connection_.connected());
5767 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5768 QuicConfig config;
5769
5770 // Create a handshake message that also enables silent close.
5771 CryptoHandshakeMessage msg;
5772 std::string error_details;
5773 QuicConfig client_config;
5774 client_config.SetInitialStreamFlowControlWindowToSend(
5775 kInitialStreamFlowControlWindowForTest);
5776 client_config.SetInitialSessionFlowControlWindowToSend(
5777 kInitialSessionFlowControlWindowForTest);
5778 client_config.SetIdleNetworkTimeout(
5779 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5780 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5781 const QuicErrorCode error =
5782 config.ProcessPeerHello(msg, CLIENT, &error_details);
5783 EXPECT_THAT(error, IsQuicNoError());
5784
5785 if (connection_.version().UsesTls()) {
5786 QuicConfigPeer::SetReceivedOriginalConnectionId(
5787 &config, connection_.connection_id());
5788 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5789 &config, connection_.connection_id());
5790 }
5791 connection_.SetFromConfig(config);
haoyuewang7b43efb2022-04-20 16:26:03 -07005792 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04005793
5794 const QuicTime::Delta default_idle_timeout =
5795 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5796 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5797 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5798
5799 // When we send a packet, the timeout will change to 5ms +
5800 // kInitialIdleTimeoutSecs.
5801 clock_.AdvanceTime(five_ms);
5802 SendStreamDataToPeer(
5803 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5804 0, FIN, nullptr);
5805 EXPECT_EQ(default_timeout + five_ms,
5806 connection_.GetTimeoutAlarm()->deadline());
5807
5808 // Indicate streams are still open.
5809 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5810 .WillRepeatedly(Return(true));
5811 if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) {
5812 EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return(""));
5813 }
5814
5815 // This time, we should time out and send a connection close due to the TLP.
5816 EXPECT_CALL(visitor_,
5817 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5818 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5819 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5820 clock_.ApproximateNow() + five_ms);
5821 connection_.GetTimeoutAlarm()->Fire();
5822 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5823 EXPECT_FALSE(connection_.connected());
5824 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5825}
5826
5827TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5828 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5829 EXPECT_TRUE(connection_.connected());
5830 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5831 QuicConfig config;
5832 connection_.SetFromConfig(config);
5833
5834 const QuicTime::Delta initial_idle_timeout =
5835 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5836 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5837 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5838
5839 connection_.SendStreamDataWithString(
5840 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5841 0, NO_FIN);
5842 connection_.SendStreamDataWithString(
5843 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5844 3, NO_FIN);
5845
5846 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5847 clock_.AdvanceTime(five_ms);
5848
5849 // When we receive a packet, the timeout will change to 5ms +
5850 // kInitialIdleTimeoutSecs.
5851 QuicAckFrame ack = InitAckFrame(2);
5852 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5853 ProcessAckPacket(&ack);
5854
5855 // The original alarm will fire. We should not time out because we had a
5856 // network event at t=5ms. The alarm will reregister.
5857 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5858 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5859 EXPECT_TRUE(connection_.connected());
5860 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5861 EXPECT_EQ(default_timeout + five_ms,
5862 connection_.GetTimeoutAlarm()->deadline());
5863
5864 // This time, we should time out.
5865 EXPECT_CALL(visitor_,
5866 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5867 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5868 clock_.AdvanceTime(five_ms);
5869 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5870 connection_.GetTimeoutAlarm()->Fire();
5871 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5872 EXPECT_FALSE(connection_.connected());
5873 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5874}
5875
5876TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5877 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5878 EXPECT_TRUE(connection_.connected());
5879 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5880 QuicConfig config;
5881 connection_.SetFromConfig(config);
5882
5883 const QuicTime::Delta initial_idle_timeout =
5884 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5885 connection_.SetNetworkTimeouts(
5886 QuicTime::Delta::Infinite(),
5887 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
haoyuewang7b43efb2022-04-20 16:26:03 -07005888 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04005889 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5890 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5891
5892 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5893 connection_.SendStreamDataWithString(
5894 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5895 0, NO_FIN);
5896 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5897 connection_.SendStreamDataWithString(
5898 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5899 3, NO_FIN);
5900
5901 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5902
5903 clock_.AdvanceTime(five_ms);
5904
5905 // When we receive a packet, the timeout will change to 5ms +
5906 // kInitialIdleTimeoutSecs.
5907 QuicAckFrame ack = InitAckFrame(2);
5908 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5909 ProcessAckPacket(&ack);
5910
5911 // The original alarm will fire. We should not time out because we had a
5912 // network event at t=5ms. The alarm will reregister.
5913 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5914 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5915 EXPECT_TRUE(connection_.connected());
5916 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5917 EXPECT_EQ(default_timeout + five_ms,
5918 connection_.GetTimeoutAlarm()->deadline());
5919
5920 // Now, send packets while advancing the time and verify that the connection
5921 // eventually times out.
5922 EXPECT_CALL(visitor_,
5923 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5924 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5925 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5926 QUIC_LOG(INFO) << "sending data packet";
5927 connection_.SendStreamDataWithString(
5928 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5929 "foo", 0, NO_FIN);
5930 connection_.GetTimeoutAlarm()->Fire();
5931 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5932 }
5933 EXPECT_FALSE(connection_.connected());
5934 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5935 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5936}
5937
Bence Békybac04052022-04-07 15:44:29 -04005938TEST_P(QuicConnectionTest, SendScheduler) {
5939 // Test that if we send a packet without delay, it is not queued.
5940 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5941 std::unique_ptr<QuicPacket> packet =
5942 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
5943 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5944 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5945 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
5946 HAS_RETRANSMITTABLE_DATA, false, false);
5947 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5948}
5949
5950TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5951 // Test that the connection does not crash when it fails to send the first
5952 // packet at which point self_address_ might be uninitialized.
5953 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5954 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
5955 std::unique_ptr<QuicPacket> packet =
5956 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
5957 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5958 writer_->SetShouldWriteFail();
5959 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
5960 HAS_RETRANSMITTABLE_DATA, false, false);
5961}
5962
5963TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5964 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5965 std::unique_ptr<QuicPacket> packet =
5966 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
5967 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5968 BlockOnNextWrite();
5969 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5970 .Times(0);
5971 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
5972 HAS_RETRANSMITTABLE_DATA, false, false);
5973 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5974}
5975
5976TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
5977 // Queue the first packet.
5978 size_t payload_length = connection_.max_packet_length();
5979 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
5980 const std::string payload(payload_length, 'a');
5981 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5982 connection_.version().transport_version, Perspective::IS_CLIENT));
5983 EXPECT_EQ(0u, connection_
5984 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5985 NO_FIN)
5986 .bytes_consumed);
5987 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5988}
5989
5990TEST_P(QuicConnectionTest, SendingThreePackets) {
5991 // Make the payload twice the size of the packet, so 3 packets are written.
5992 size_t total_payload_length = 2 * connection_.max_packet_length();
5993 const std::string payload(total_payload_length, 'a');
5994 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5995 connection_.version().transport_version, Perspective::IS_CLIENT));
5996 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5997 EXPECT_EQ(payload.size(), connection_
5998 .SendStreamDataWithString(first_bidi_stream_id,
5999 payload, 0, NO_FIN)
6000 .bytes_consumed);
6001}
6002
6003TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6004 set_perspective(Perspective::IS_SERVER);
6005 if (!GetParam().version.HasIetfInvariantHeader()) {
6006 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6007 // SendStreamDataWithString.
6008 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6009 }
6010 // Set up a larger payload than will fit in one packet.
6011 const std::string payload(connection_.max_packet_length(), 'a');
6012 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6013
6014 // Now send some packets with no truncation.
6015 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6016 EXPECT_EQ(payload.size(),
6017 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6018 .bytes_consumed);
6019 // Track the size of the second packet here. The overhead will be the largest
6020 // we see in this test, due to the non-truncated connection id.
6021 size_t non_truncated_packet_size = writer_->last_packet_size();
6022
6023 // Change to a 0 byte connection id.
6024 QuicConfig config;
6025 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6026 connection_.SetFromConfig(config);
6027 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6028 EXPECT_EQ(payload.size(),
6029 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6030 .bytes_consumed);
6031 if (connection_.version().HasIetfInvariantHeader()) {
6032 // Short header packets sent from server omit connection ID already, and
6033 // stream offset size increases from 0 to 2.
6034 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6035 } else {
6036 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6037 // because stream offset size is 2 instead of 0.
6038 EXPECT_EQ(non_truncated_packet_size,
6039 writer_->last_packet_size() + 8 * 2 - 2);
6040 }
6041}
6042
6043TEST_P(QuicConnectionTest, SendDelayedAck) {
6044 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6045 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6046 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006047 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006048 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6049 peer_framer_.SetEncrypter(
6050 ENCRYPTION_ZERO_RTT,
6051 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006052 // Process a packet from the non-crypto stream.
6053 frame1_.stream_id = 3;
6054
6055 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6056 // instead of ENCRYPTION_INITIAL.
6057 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6058 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6059
6060 // Check if delayed ack timer is running for the expected interval.
6061 EXPECT_TRUE(connection_.HasPendingAcks());
6062 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6063 // Simulate delayed ack alarm firing.
6064 clock_.AdvanceTime(DefaultDelayedAckTime());
6065 connection_.GetAckAlarm()->Fire();
6066 // Check that ack is sent and that delayed ack alarm is reset.
6067 size_t padding_frame_count = writer_->padding_frames().size();
6068 if (GetParam().no_stop_waiting) {
6069 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6070 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6071 } else {
6072 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6073 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6074 }
6075 EXPECT_FALSE(writer_->ack_frames().empty());
6076 EXPECT_FALSE(connection_.HasPendingAcks());
6077}
6078
6079TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6080 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6081
6082 const size_t kMinRttMs = 40;
6083 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6084 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6085 QuicTime::Delta::Zero(), QuicTime::Zero());
6086 // The ack time should be based on min_rtt/4, since it's less than the
6087 // default delayed ack time.
6088 QuicTime ack_time = clock_.ApproximateNow() +
6089 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6090 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6091 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006092 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006093 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6094 peer_framer_.SetEncrypter(
6095 ENCRYPTION_ZERO_RTT,
6096 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006097 // Process a packet from the non-crypto stream.
6098 frame1_.stream_id = 3;
6099
6100 // Process all the initial packets in order so there aren't missing packets.
6101 uint64_t kFirstDecimatedPacket = 101;
6102 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6103 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6104 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6105 }
6106 EXPECT_FALSE(connection_.HasPendingAcks());
6107 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6108 // instead of ENCRYPTION_INITIAL.
6109 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6110 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6111 ENCRYPTION_ZERO_RTT);
6112
6113 // Check if delayed ack timer is running for the expected interval.
6114 EXPECT_TRUE(connection_.HasPendingAcks());
6115 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6116
6117 // The 10th received packet causes an ack to be sent.
6118 for (int i = 0; i < 9; ++i) {
6119 EXPECT_TRUE(connection_.HasPendingAcks());
6120 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6121 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6122 ENCRYPTION_ZERO_RTT);
6123 }
6124 // Check that ack is sent and that delayed ack alarm is reset.
6125 size_t padding_frame_count = writer_->padding_frames().size();
6126 if (GetParam().no_stop_waiting) {
6127 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6128 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6129 } else {
6130 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6131 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6132 }
6133 EXPECT_FALSE(writer_->ack_frames().empty());
6134 EXPECT_FALSE(connection_.HasPendingAcks());
6135}
6136
6137TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6138 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6139 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6140 QuicConfig config;
6141 QuicTagVector connection_options;
6142 // No limit on the number of packets received before sending an ack.
6143 connection_options.push_back(kAKDU);
6144 config.SetConnectionOptionsToSend(connection_options);
6145 connection_.SetFromConfig(config);
6146
6147 const size_t kMinRttMs = 40;
6148 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6149 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6150 QuicTime::Delta::Zero(), QuicTime::Zero());
6151 // The ack time should be based on min_rtt/4, since it's less than the
6152 // default delayed ack time.
6153 QuicTime ack_time = clock_.ApproximateNow() +
6154 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6155 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6156 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006157 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006158 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6159 peer_framer_.SetEncrypter(
6160 ENCRYPTION_ZERO_RTT,
6161 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006162 // Process a packet from the non-crypto stream.
6163 frame1_.stream_id = 3;
6164
6165 // Process all the initial packets in order so there aren't missing packets.
6166 uint64_t kFirstDecimatedPacket = 101;
6167 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6168 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6169 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6170 }
6171 EXPECT_FALSE(connection_.HasPendingAcks());
6172 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6173 // instead of ENCRYPTION_INITIAL.
6174 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6175 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6176 ENCRYPTION_ZERO_RTT);
6177
6178 // Check if delayed ack timer is running for the expected interval.
6179 EXPECT_TRUE(connection_.HasPendingAcks());
6180 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6181
6182 // 18 packets will not cause an ack to be sent. 19 will because when
6183 // stop waiting frames are in use, we ack every 20 packets no matter what.
6184 for (int i = 0; i < 18; ++i) {
6185 EXPECT_TRUE(connection_.HasPendingAcks());
6186 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6187 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6188 ENCRYPTION_ZERO_RTT);
6189 }
6190 // The delayed ack timer should still be set to the expected deadline.
6191 EXPECT_TRUE(connection_.HasPendingAcks());
6192 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6193}
6194
6195TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6196 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6197 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6198
6199 const size_t kMinRttMs = 40;
6200 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6201 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6202 QuicTime::Delta::Zero(), QuicTime::Zero());
6203 // The ack time should be based on min_rtt/8, since it's less than the
6204 // default delayed ack time.
6205 QuicTime ack_time = clock_.ApproximateNow() +
6206 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6207 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6208 EXPECT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -04006209 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08006210 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
6211 peer_framer_.SetEncrypter(
6212 ENCRYPTION_ZERO_RTT,
6213 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04006214 // Process a packet from the non-crypto stream.
6215 frame1_.stream_id = 3;
6216
6217 // Process all the initial packets in order so there aren't missing packets.
6218 uint64_t kFirstDecimatedPacket = 101;
6219 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6220 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6221 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6222 }
6223 EXPECT_FALSE(connection_.HasPendingAcks());
6224 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6225 // instead of ENCRYPTION_INITIAL.
6226 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6227 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6228 ENCRYPTION_ZERO_RTT);
6229
6230 // Check if delayed ack timer is running for the expected interval.
6231 EXPECT_TRUE(connection_.HasPendingAcks());
6232 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6233
6234 // The 10th received packet causes an ack to be sent.
6235 for (int i = 0; i < 9; ++i) {
6236 EXPECT_TRUE(connection_.HasPendingAcks());
6237 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6238 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6239 ENCRYPTION_ZERO_RTT);
6240 }
6241 // Check that ack is sent and that delayed ack alarm is reset.
6242 size_t padding_frame_count = writer_->padding_frames().size();
6243 if (GetParam().no_stop_waiting) {
6244 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6245 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6246 } else {
6247 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6248 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6249 }
6250 EXPECT_FALSE(writer_->ack_frames().empty());
6251 EXPECT_FALSE(connection_.HasPendingAcks());
6252}
6253
6254TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6255 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6256 ProcessPacket(1);
6257 // Check that ack is sent and that delayed ack alarm is set.
6258 EXPECT_TRUE(connection_.HasPendingAcks());
6259 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6260 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6261
6262 // Completing the handshake as the server does nothing.
6263 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6264 connection_.OnHandshakeComplete();
6265 EXPECT_TRUE(connection_.HasPendingAcks());
6266 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6267
6268 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6269 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6270 connection_.OnHandshakeComplete();
6271 EXPECT_TRUE(connection_.HasPendingAcks());
6272 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6273 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6274 connection_.GetAckAlarm()->deadline());
6275 } else {
6276 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6277 }
6278}
6279
6280TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6281 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6282 ProcessPacket(1);
6283 ProcessPacket(2);
6284 // Check that ack is sent and that delayed ack alarm is reset.
6285 size_t padding_frame_count = writer_->padding_frames().size();
6286 if (GetParam().no_stop_waiting) {
6287 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6288 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6289 } else {
6290 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6291 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6292 }
6293 EXPECT_FALSE(writer_->ack_frames().empty());
6294 EXPECT_FALSE(connection_.HasPendingAcks());
6295}
6296
6297TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6298 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6299 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6300 ProcessPacket(2);
6301 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
6302
6303 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6304 ProcessPacket(3);
6305 size_t padding_frame_count = writer_->padding_frames().size();
6306 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6307 EXPECT_FALSE(writer_->ack_frames().empty());
6308 writer_->Reset();
6309
6310 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6311 ProcessPacket(4);
6312 EXPECT_EQ(0u, writer_->frame_count());
6313
6314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6315 ProcessPacket(5);
6316 padding_frame_count = writer_->padding_frames().size();
6317 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6318 EXPECT_FALSE(writer_->ack_frames().empty());
6319 writer_->Reset();
6320
6321 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6322 // Now only set the timer on the 6th packet, instead of sending another ack.
6323 ProcessPacket(6);
6324 padding_frame_count = writer_->padding_frames().size();
6325 EXPECT_EQ(padding_frame_count, writer_->frame_count());
6326 EXPECT_TRUE(connection_.HasPendingAcks());
6327}
6328
6329TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6330 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6331 EXPECT_CALL(visitor_, OnStreamFrame(_));
martinduke9e0811c2022-12-08 20:35:57 -08006332 peer_framer_.SetEncrypter(
6333 ENCRYPTION_FORWARD_SECURE,
6334 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
6335 SetDecrypter(
6336 ENCRYPTION_FORWARD_SECURE,
6337 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04006338 ProcessDataPacket(1);
6339 connection_.SendStreamDataWithString(
6340 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6341 0, NO_FIN);
6342 // Check that ack is bundled with outgoing data and that delayed ack
6343 // alarm is reset.
6344 if (GetParam().no_stop_waiting) {
6345 EXPECT_EQ(2u, writer_->frame_count());
6346 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6347 } else {
6348 EXPECT_EQ(3u, writer_->frame_count());
6349 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6350 }
6351 EXPECT_FALSE(writer_->ack_frames().empty());
6352 EXPECT_FALSE(connection_.HasPendingAcks());
6353}
6354
6355TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingCryptoPacket) {
6356 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6357 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6358 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6359 } else {
6360 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6361 }
6362 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6363 connection_.SendCryptoDataWithString("foo", 0);
6364 // Check that ack is bundled with outgoing crypto data.
6365 if (GetParam().no_stop_waiting) {
6366 EXPECT_EQ(3u, writer_->frame_count());
6367 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6368 } else {
6369 EXPECT_EQ(4u, writer_->frame_count());
6370 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6371 }
6372 EXPECT_FALSE(connection_.HasPendingAcks());
6373}
6374
6375TEST_P(QuicConnectionTest, BlockAndBufferOnFirstCHLOPacketOfTwo) {
6376 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6377 ProcessPacket(1);
6378 BlockOnNextWrite();
6379 writer_->set_is_write_blocked_data_buffered(true);
6380 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6381 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6382 } else {
6383 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6384 }
6385 connection_.SendCryptoDataWithString("foo", 0);
6386 EXPECT_TRUE(writer_->IsWriteBlocked());
6387 EXPECT_FALSE(connection_.HasQueuedData());
6388 connection_.SendCryptoDataWithString("bar", 3);
6389 EXPECT_TRUE(writer_->IsWriteBlocked());
6390 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6391 // CRYPTO frames are not flushed when writer is blocked.
6392 EXPECT_FALSE(connection_.HasQueuedData());
6393 } else {
6394 EXPECT_TRUE(connection_.HasQueuedData());
6395 }
6396}
6397
6398TEST_P(QuicConnectionTest, BundleAckForSecondCHLO) {
6399 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6400 EXPECT_FALSE(connection_.HasPendingAcks());
6401 EXPECT_CALL(visitor_, OnCanWrite())
6402 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6403 &connection_, &TestConnection::SendCryptoStreamData)));
6404 // Process a packet from the crypto stream, which is frame1_'s default.
6405 // Receiving the CHLO as packet 2 first will cause the connection to
6406 // immediately send an ack, due to the packet gap.
6407 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6408 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6409 } else {
6410 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6411 }
6412 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6413 // Check that ack is sent and that delayed ack alarm is reset.
6414 if (GetParam().no_stop_waiting) {
6415 EXPECT_EQ(3u, writer_->frame_count());
6416 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6417 } else {
6418 EXPECT_EQ(4u, writer_->frame_count());
6419 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6420 }
6421 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6422 EXPECT_EQ(1u, writer_->stream_frames().size());
6423 } else {
6424 EXPECT_EQ(1u, writer_->crypto_frames().size());
6425 }
6426 EXPECT_EQ(1u, writer_->padding_frames().size());
6427 ASSERT_FALSE(writer_->ack_frames().empty());
6428 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6429 EXPECT_FALSE(connection_.HasPendingAcks());
6430}
6431
6432TEST_P(QuicConnectionTest, BundleAckForSecondCHLOTwoPacketReject) {
6433 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6434 EXPECT_FALSE(connection_.HasPendingAcks());
6435
6436 // Process two packets from the crypto stream, which is frame1_'s default,
6437 // simulating a 2 packet reject.
6438 {
6439 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6440 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
6441 } else {
6442 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6443 }
6444 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
6445 // Send the new CHLO when the REJ is processed.
6446 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6447 EXPECT_CALL(visitor_, OnCryptoFrame(_))
6448 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6449 &connection_, &TestConnection::SendCryptoStreamData)));
6450 } else {
6451 EXPECT_CALL(visitor_, OnStreamFrame(_))
6452 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6453 &connection_, &TestConnection::SendCryptoStreamData)));
6454 }
6455 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
6456 }
6457 // Check that ack is sent and that delayed ack alarm is reset.
6458 if (GetParam().no_stop_waiting) {
6459 EXPECT_EQ(3u, writer_->frame_count());
6460 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6461 } else {
6462 EXPECT_EQ(4u, writer_->frame_count());
6463 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6464 }
6465 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
6466 EXPECT_EQ(1u, writer_->stream_frames().size());
6467 } else {
6468 EXPECT_EQ(1u, writer_->crypto_frames().size());
6469 }
6470 EXPECT_EQ(1u, writer_->padding_frames().size());
6471 ASSERT_FALSE(writer_->ack_frames().empty());
6472 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(writer_->ack_frames().front()));
6473 EXPECT_FALSE(connection_.HasPendingAcks());
6474}
6475
6476TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
6477 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6478 connection_.SendStreamDataWithString(
6479 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6480 0, NO_FIN);
6481 connection_.SendStreamDataWithString(
6482 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
6483 3, NO_FIN);
6484 // Ack the second packet, which will retransmit the first packet.
6485 QuicAckFrame ack = ConstructAckFrame(2, 1);
6486 LostPacketVector lost_packets;
6487 lost_packets.push_back(
6488 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
6489 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
6490 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
6491 Return(LossDetectionInterface::DetectionStats())));
6492 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6493 ProcessAckPacket(&ack);
6494 size_t padding_frame_count = writer_->padding_frames().size();
6495 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6496 EXPECT_EQ(1u, writer_->stream_frames().size());
6497 writer_->Reset();
6498
6499 // Now ack the retransmission, which will both raise the high water mark
6500 // and see if there is more data to send.
6501 ack = ConstructAckFrame(3, 1);
6502 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6503 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
6504 ProcessAckPacket(&ack);
6505
6506 // Check that no packet is sent and the ack alarm isn't set.
6507 EXPECT_EQ(0u, writer_->frame_count());
6508 EXPECT_FALSE(connection_.HasPendingAcks());
6509 writer_->Reset();
6510
6511 // Send the same ack, but send both data and an ack together.
6512 ack = ConstructAckFrame(3, 1);
6513 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
6514 EXPECT_CALL(visitor_, OnCanWrite())
6515 .WillOnce(IgnoreResult(InvokeWithoutArgs(
6516 &connection_, &TestConnection::EnsureWritableAndSendStreamData5)));
6517 ProcessAckPacket(&ack);
6518
6519 // Check that ack is bundled with outgoing data and the delayed ack
6520 // alarm is reset.
6521 if (GetParam().no_stop_waiting) {
6522 // Do not ACK acks.
6523 EXPECT_EQ(1u, writer_->frame_count());
6524 } else {
6525 EXPECT_EQ(3u, writer_->frame_count());
6526 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6527 }
6528 if (GetParam().no_stop_waiting) {
6529 EXPECT_TRUE(writer_->ack_frames().empty());
6530 } else {
6531 EXPECT_FALSE(writer_->ack_frames().empty());
6532 EXPECT_EQ(QuicPacketNumber(3u),
6533 LargestAcked(writer_->ack_frames().front()));
6534 }
6535 EXPECT_EQ(1u, writer_->stream_frames().size());
6536 EXPECT_FALSE(connection_.HasPendingAcks());
6537}
6538
6539TEST_P(QuicConnectionTest, NoAckSentForClose) {
6540 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6541 ProcessPacket(1);
6542 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6543 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6544 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6545 ProcessClosePacket(2);
6546 EXPECT_EQ(1, connection_close_frame_count_);
6547 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6548 IsError(QUIC_PEER_GOING_AWAY));
6549}
6550
6551TEST_P(QuicConnectionTest, SendWhenDisconnected) {
6552 EXPECT_TRUE(connection_.connected());
6553 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6554 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6555 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6556 ConnectionCloseBehavior::SILENT_CLOSE);
6557 EXPECT_FALSE(connection_.connected());
6558 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6559 EXPECT_EQ(DISCARD, connection_.GetSerializedPacketFate(
6560 /*is_mtu_discovery=*/false, ENCRYPTION_INITIAL));
6561}
6562
6563TEST_P(QuicConnectionTest, SendConnectivityProbingWhenDisconnected) {
6564 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
6565 if (!IsDefaultTestConfiguration()) {
6566 return;
6567 }
6568
6569 EXPECT_TRUE(connection_.connected());
6570 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6571 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6572 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
6573 ConnectionCloseBehavior::SILENT_CLOSE);
6574 EXPECT_FALSE(connection_.connected());
6575 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
6576
6577 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6578 .Times(0);
6579
6580 EXPECT_QUIC_BUG(connection_.SendConnectivityProbingPacket(
6581 writer_.get(), connection_.peer_address()),
6582 "Not sending connectivity probing packet as connection is "
6583 "disconnected.");
6584 EXPECT_EQ(1, connection_close_frame_count_);
6585 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6586 IsError(QUIC_PEER_GOING_AWAY));
6587}
6588
6589TEST_P(QuicConnectionTest, WriteBlockedAfterClientSendsConnectivityProbe) {
6590 PathProbeTestInit(Perspective::IS_CLIENT);
6591 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6592 // Block next write so that sending connectivity probe will encounter a
6593 // blocked write when send a connectivity probe to the peer.
6594 probing_writer.BlockOnNextWrite();
6595 // Connection will not be marked as write blocked as connectivity probe only
6596 // affects the probing_writer which is not the default.
6597 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
6598
6599 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6600 .Times(1);
6601 connection_.SendConnectivityProbingPacket(&probing_writer,
6602 connection_.peer_address());
6603}
6604
6605TEST_P(QuicConnectionTest, WriterBlockedAfterServerSendsConnectivityProbe) {
6606 PathProbeTestInit(Perspective::IS_SERVER);
6607 if (version().SupportsAntiAmplificationLimit()) {
6608 QuicConnectionPeer::SetAddressValidated(&connection_);
6609 }
6610
6611 // Block next write so that sending connectivity probe will encounter a
6612 // blocked write when send a connectivity probe to the peer.
6613 writer_->BlockOnNextWrite();
6614 // Connection will be marked as write blocked as server uses the default
6615 // writer to send connectivity probes.
6616 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
6617
6618 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6619 .Times(1);
6620 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6621 QuicPathFrameBuffer payload{
6622 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
6623 QuicConnection::ScopedPacketFlusher flusher(&connection_);
6624 connection_.SendPathChallenge(
6625 payload, connection_.self_address(), connection_.peer_address(),
6626 connection_.effective_peer_address(), writer_.get());
6627 } else {
6628 connection_.SendConnectivityProbingPacket(writer_.get(),
6629 connection_.peer_address());
6630 }
6631}
6632
6633TEST_P(QuicConnectionTest, WriterErrorWhenClientSendsConnectivityProbe) {
6634 PathProbeTestInit(Perspective::IS_CLIENT);
6635 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
6636 probing_writer.SetShouldWriteFail();
6637
6638 // Connection should not be closed if a connectivity probe is failed to be
6639 // sent.
6640 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6641
6642 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6643 .Times(0);
6644 connection_.SendConnectivityProbingPacket(&probing_writer,
6645 connection_.peer_address());
6646}
6647
6648TEST_P(QuicConnectionTest, WriterErrorWhenServerSendsConnectivityProbe) {
6649 PathProbeTestInit(Perspective::IS_SERVER);
6650
6651 writer_->SetShouldWriteFail();
6652 // Connection should not be closed if a connectivity probe is failed to be
6653 // sent.
6654 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6655
6656 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(1), _, _))
6657 .Times(0);
6658 connection_.SendConnectivityProbingPacket(writer_.get(),
6659 connection_.peer_address());
6660}
6661
6662TEST_P(QuicConnectionTest, PublicReset) {
6663 if (GetParam().version.HasIetfInvariantHeader()) {
6664 return;
6665 }
6666 QuicPublicResetPacket header;
6667 // Public reset packet in only built by server.
6668 header.connection_id = connection_id_;
6669 std::unique_ptr<QuicEncryptedPacket> packet(
6670 framer_.BuildPublicResetPacket(header));
6671 std::unique_ptr<QuicReceivedPacket> received(
6672 ConstructReceivedPacket(*packet, QuicTime::Zero()));
6673 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6674 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6675 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6676 EXPECT_EQ(1, connection_close_frame_count_);
6677 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6678 IsError(QUIC_PUBLIC_RESET));
6679}
6680
6681TEST_P(QuicConnectionTest, IetfStatelessReset) {
6682 if (!GetParam().version.HasIetfInvariantHeader()) {
6683 return;
6684 }
6685 QuicConfig config;
6686 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
6687 kTestStatelessResetToken);
6688 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6689 connection_.SetFromConfig(config);
6690 std::unique_ptr<QuicEncryptedPacket> packet(
6691 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
6692 /*received_packet_length=*/100,
6693 kTestStatelessResetToken));
6694 std::unique_ptr<QuicReceivedPacket> received(
6695 ConstructReceivedPacket(*packet, QuicTime::Zero()));
Bence Békybac04052022-04-07 15:44:29 -04006696 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6697 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6698 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6699 EXPECT_EQ(1, connection_close_frame_count_);
6700 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6701 IsError(QUIC_PUBLIC_RESET));
6702}
6703
6704TEST_P(QuicConnectionTest, GoAway) {
6705 if (VersionHasIetfQuicFrames(GetParam().version.transport_version)) {
6706 // GoAway is not available in version 99.
6707 return;
6708 }
6709
6710 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6711
6712 QuicGoAwayFrame* goaway = new QuicGoAwayFrame();
6713 goaway->last_good_stream_id = 1;
6714 goaway->error_code = QUIC_PEER_GOING_AWAY;
6715 goaway->reason_phrase = "Going away.";
6716 EXPECT_CALL(visitor_, OnGoAway(_));
6717 ProcessGoAwayPacket(goaway);
6718}
6719
6720TEST_P(QuicConnectionTest, WindowUpdate) {
6721 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6722
6723 QuicWindowUpdateFrame window_update;
6724 window_update.stream_id = 3;
6725 window_update.max_data = 1234;
6726 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6727 ProcessFramePacket(QuicFrame(window_update));
6728}
6729
6730TEST_P(QuicConnectionTest, Blocked) {
6731 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6732
6733 QuicBlockedFrame blocked;
6734 blocked.stream_id = 3;
6735 EXPECT_CALL(visitor_, OnBlockedFrame(_));
6736 ProcessFramePacket(QuicFrame(blocked));
6737 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_received);
6738 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
6739}
6740
6741TEST_P(QuicConnectionTest, ZeroBytePacket) {
6742 // Don't close the connection for zero byte packets.
6743 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
6744 QuicReceivedPacket encrypted(nullptr, 0, QuicTime::Zero());
6745 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, encrypted);
6746}
6747
6748TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
6749 if (GetParam().version.HasIetfInvariantHeader()) {
6750 return;
6751 }
6752 // Set the packet number of the ack packet to be least unacked (4).
6753 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 3);
6754 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6755 ProcessStopWaitingPacket(InitStopWaitingFrame(4));
6756 EXPECT_FALSE(connection_.ack_frame().packets.Empty());
6757}
6758
6759TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
6760 // All supported versions except the one the connection supports.
6761 ParsedQuicVersionVector versions;
6762 for (auto version : AllSupportedVersions()) {
6763 if (version != connection_.version()) {
6764 versions.push_back(version);
6765 }
6766 }
6767
6768 // Send a version negotiation packet.
6769 std::unique_ptr<QuicEncryptedPacket> encrypted(
6770 QuicFramer::BuildVersionNegotiationPacket(
6771 connection_id_, EmptyQuicConnectionId(),
6772 connection_.version().HasIetfInvariantHeader(),
6773 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6774 std::unique_ptr<QuicReceivedPacket> received(
6775 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6776 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6777 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6778 // Verify no connection close packet gets sent.
6779 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6780 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6781 EXPECT_FALSE(connection_.connected());
6782 EXPECT_EQ(1, connection_close_frame_count_);
6783 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6784 IsError(QUIC_INVALID_VERSION));
6785}
6786
6787TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiationWithConnectionClose) {
6788 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6789 QuicConfig config;
6790 QuicTagVector connection_options;
6791 connection_options.push_back(kINVC);
6792 config.SetClientConnectionOptions(connection_options);
6793 connection_.SetFromConfig(config);
6794
6795 // All supported versions except the one the connection supports.
6796 ParsedQuicVersionVector versions;
6797 for (auto version : AllSupportedVersions()) {
6798 if (version != connection_.version()) {
6799 versions.push_back(version);
6800 }
6801 }
6802
6803 // Send a version negotiation packet.
6804 std::unique_ptr<QuicEncryptedPacket> encrypted(
6805 QuicFramer::BuildVersionNegotiationPacket(
6806 connection_id_, EmptyQuicConnectionId(),
6807 connection_.version().HasIetfInvariantHeader(),
6808 connection_.version().HasLengthPrefixedConnectionIds(), versions));
6809 std::unique_ptr<QuicReceivedPacket> received(
6810 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6811 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6812 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6813 // Verify connection close packet gets sent.
6814 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1u));
6815 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6816 EXPECT_FALSE(connection_.connected());
6817 EXPECT_EQ(1, connection_close_frame_count_);
6818 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6819 IsError(QUIC_INVALID_VERSION));
6820}
6821
6822TEST_P(QuicConnectionTest, BadVersionNegotiation) {
6823 // Send a version negotiation packet with the version the client started with.
6824 // It should be rejected.
6825 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
6826 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6827 std::unique_ptr<QuicEncryptedPacket> encrypted(
6828 QuicFramer::BuildVersionNegotiationPacket(
6829 connection_id_, EmptyQuicConnectionId(),
6830 connection_.version().HasIetfInvariantHeader(),
6831 connection_.version().HasLengthPrefixedConnectionIds(),
6832 AllSupportedVersions()));
6833 std::unique_ptr<QuicReceivedPacket> received(
6834 ConstructReceivedPacket(*encrypted, QuicTime::Zero()));
6835 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *received);
6836 EXPECT_EQ(1, connection_close_frame_count_);
6837 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6838 IsError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET));
6839}
6840
Bence Békybac04052022-04-07 15:44:29 -04006841TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
6842 // Construct a packet with stream frame and connection close frame.
6843 QuicPacketHeader header;
6844 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
6845 header.source_connection_id = connection_id_;
6846 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
6847 if (!peer_framer_.version().HasIetfInvariantHeader()) {
6848 header.source_connection_id_included = CONNECTION_ID_PRESENT;
6849 }
6850 } else {
6851 header.destination_connection_id = connection_id_;
6852 if (peer_framer_.version().HasIetfInvariantHeader()) {
6853 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
6854 }
6855 }
6856 header.packet_number = QuicPacketNumber(1);
6857 header.version_flag = false;
6858
6859 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
6860 // This QuicConnectionCloseFrame will default to being for a Google QUIC
6861 // close. If doing IETF QUIC then set fields appropriately for CC/T or CC/A,
6862 // depending on the mapping.
6863 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
6864 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
6865 /*transport_close_frame_type=*/0);
6866 QuicFrames frames;
6867 frames.push_back(QuicFrame(frame1_));
6868 frames.push_back(QuicFrame(&qccf));
6869 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
6870 EXPECT_TRUE(nullptr != packet);
6871 char buffer[kMaxOutgoingPacketSize];
6872 size_t encrypted_length = peer_framer_.EncryptPayload(
6873 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
6874 kMaxOutgoingPacketSize);
6875
6876 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_PEER))
6877 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
6878 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6879 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6880
6881 connection_.ProcessUdpPacket(
6882 kSelfAddress, kPeerAddress,
6883 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
6884 EXPECT_EQ(1, connection_close_frame_count_);
6885 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
6886 IsError(QUIC_PEER_GOING_AWAY));
6887}
6888
6889TEST_P(QuicConnectionTest, SelectMutualVersion) {
6890 connection_.SetSupportedVersions(AllSupportedVersions());
6891 // Set the connection to speak the lowest quic version.
6892 connection_.set_version(QuicVersionMin());
6893 EXPECT_EQ(QuicVersionMin(), connection_.version());
6894
6895 // Pass in available versions which includes a higher mutually supported
6896 // version. The higher mutually supported version should be selected.
6897 ParsedQuicVersionVector supported_versions = AllSupportedVersions();
6898 EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
6899 EXPECT_EQ(QuicVersionMax(), connection_.version());
6900
6901 // Expect that the lowest version is selected.
6902 // Ensure the lowest supported version is less than the max, unless they're
6903 // the same.
6904 ParsedQuicVersionVector lowest_version_vector;
6905 lowest_version_vector.push_back(QuicVersionMin());
6906 EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
6907 EXPECT_EQ(QuicVersionMin(), connection_.version());
6908
6909 // Shouldn't be able to find a mutually supported version.
6910 ParsedQuicVersionVector unsupported_version;
6911 unsupported_version.push_back(UnsupportedQuicVersion());
6912 EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
6913}
6914
6915TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
6916 EXPECT_FALSE(writer_->IsWriteBlocked());
6917
6918 // Send a packet.
6919 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6920 EXPECT_EQ(0u, connection_.NumQueuedPackets());
6921 EXPECT_EQ(1u, writer_->packets_write_attempts());
6922
6923 TriggerConnectionClose();
6924 EXPECT_LE(2u, writer_->packets_write_attempts());
6925}
6926
6927TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
6928 BlockOnNextWrite();
6929 TriggerConnectionClose();
6930 EXPECT_EQ(1u, writer_->packets_write_attempts());
6931 EXPECT_TRUE(writer_->IsWriteBlocked());
6932}
6933
6934TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
6935 BlockOnNextWrite();
6936 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6937 EXPECT_EQ(1u, connection_.NumQueuedPackets());
6938 EXPECT_EQ(1u, writer_->packets_write_attempts());
6939 EXPECT_TRUE(writer_->IsWriteBlocked());
6940 TriggerConnectionClose();
6941 EXPECT_EQ(1u, writer_->packets_write_attempts());
6942}
6943
6944TEST_P(QuicConnectionTest, OnPacketSentDebugVisitor) {
6945 PathProbeTestInit(Perspective::IS_CLIENT);
6946 MockQuicConnectionDebugVisitor debug_visitor;
6947 connection_.set_debug_visitor(&debug_visitor);
6948
6949 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
6950 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
6951
6952 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
6953 connection_.SendConnectivityProbingPacket(writer_.get(),
6954 connection_.peer_address());
6955}
6956
6957TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
6958 QuicPacketHeader header;
6959 header.packet_number = QuicPacketNumber(1);
6960 if (GetParam().version.HasIetfInvariantHeader()) {
6961 header.form = IETF_QUIC_LONG_HEADER_PACKET;
6962 }
6963
6964 MockQuicConnectionDebugVisitor debug_visitor;
6965 connection_.set_debug_visitor(&debug_visitor);
6966 EXPECT_CALL(debug_visitor, OnPacketHeader(Ref(header), _, _)).Times(1);
6967 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(1);
6968 EXPECT_CALL(debug_visitor, OnSuccessfulVersionNegotiation(_)).Times(1);
6969 connection_.OnPacketHeader(header);
6970}
6971
6972TEST_P(QuicConnectionTest, Pacing) {
6973 TestConnection server(connection_id_, kPeerAddress, kSelfAddress,
6974 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07006975 Perspective::IS_SERVER, version(),
6976 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04006977 TestConnection client(connection_id_, kSelfAddress, kPeerAddress,
6978 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07006979 Perspective::IS_CLIENT, version(),
6980 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04006981 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
6982 static_cast<const QuicSentPacketManager*>(
6983 &client.sent_packet_manager())));
6984 EXPECT_FALSE(QuicSentPacketManagerPeer::UsingPacing(
6985 static_cast<const QuicSentPacketManager*>(
6986 &server.sent_packet_manager())));
6987}
6988
6989TEST_P(QuicConnectionTest, WindowUpdateInstigateAcks) {
6990 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6991
6992 // Send a WINDOW_UPDATE frame.
6993 QuicWindowUpdateFrame window_update;
6994 window_update.stream_id = 3;
6995 window_update.max_data = 1234;
6996 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
6997 ProcessFramePacket(QuicFrame(window_update));
6998
6999 // Ensure that this has caused the ACK alarm to be set.
7000 EXPECT_TRUE(connection_.HasPendingAcks());
7001}
7002
7003TEST_P(QuicConnectionTest, BlockedFrameInstigateAcks) {
7004 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7005
7006 // Send a BLOCKED frame.
7007 QuicBlockedFrame blocked;
7008 blocked.stream_id = 3;
7009 EXPECT_CALL(visitor_, OnBlockedFrame(_));
7010 ProcessFramePacket(QuicFrame(blocked));
7011
7012 // Ensure that this has caused the ACK alarm to be set.
7013 EXPECT_TRUE(connection_.HasPendingAcks());
7014}
7015
7016TEST_P(QuicConnectionTest, ReevaluateTimeUntilSendOnAck) {
7017 // Enable pacing.
7018 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7019 QuicConfig config;
7020 connection_.SetFromConfig(config);
7021
7022 // Send two packets. One packet is not sufficient because if it gets acked,
7023 // there will be no packets in flight after that and the pacer will always
7024 // allow the next packet in that situation.
7025 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7026 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7027 connection_.SendStreamDataWithString(
7028 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
7029 0, NO_FIN);
7030 connection_.SendStreamDataWithString(
7031 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "bar",
7032 3, NO_FIN);
7033 connection_.OnCanWrite();
7034
7035 // Schedule the next packet for a few milliseconds in future.
7036 QuicSentPacketManagerPeer::DisablePacerBursts(manager_);
7037 QuicTime scheduled_pacing_time =
7038 clock_.Now() + QuicTime::Delta::FromMilliseconds(5);
7039 QuicSentPacketManagerPeer::SetNextPacedPacketTime(manager_,
7040 scheduled_pacing_time);
7041
7042 // Send a packet and have it be blocked by congestion control.
7043 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
7044 connection_.SendStreamDataWithString(
7045 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "baz",
7046 6, NO_FIN);
7047 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
7048
7049 // Process an ack and the send alarm will be set to the new 5ms delay.
7050 QuicAckFrame ack = InitAckFrame(1);
7051 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
7052 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7053 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
7054 ProcessAckPacket(&ack);
7055 size_t padding_frame_count = writer_->padding_frames().size();
7056 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
7057 EXPECT_EQ(1u, writer_->stream_frames().size());
7058 EXPECT_TRUE(connection_.GetSendAlarm()->IsSet());
7059 EXPECT_EQ(scheduled_pacing_time, connection_.GetSendAlarm()->deadline());
7060 writer_->Reset();
7061}
7062
7063TEST_P(QuicConnectionTest, SendAcksImmediately) {
7064 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7065 return;
7066 }
7067 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7068 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7069 ProcessDataPacket(1);
7070 CongestionBlockWrites();
7071 SendAckPacketToPeer();
7072}
7073
7074TEST_P(QuicConnectionTest, SendPingImmediately) {
7075 MockQuicConnectionDebugVisitor debug_visitor;
7076 connection_.set_debug_visitor(&debug_visitor);
7077
7078 CongestionBlockWrites();
7079 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7080 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7081 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
7082 EXPECT_CALL(debug_visitor, OnPingSent()).Times(1);
7083 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
7084 EXPECT_FALSE(connection_.HasQueuedData());
7085}
7086
7087TEST_P(QuicConnectionTest, SendBlockedImmediately) {
7088 MockQuicConnectionDebugVisitor debug_visitor;
7089 connection_.set_debug_visitor(&debug_visitor);
7090
7091 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
7092 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7093 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(1);
7094 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
QUICHE team1a271082022-05-18 10:22:22 -07007095 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04007096 EXPECT_EQ(1u, connection_.GetStats().blocked_frames_sent);
7097 EXPECT_FALSE(connection_.HasQueuedData());
7098}
7099
7100TEST_P(QuicConnectionTest, FailedToSendBlockedFrames) {
7101 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7102 return;
7103 }
7104 MockQuicConnectionDebugVisitor debug_visitor;
7105 connection_.set_debug_visitor(&debug_visitor);
QUICHE team1a271082022-05-18 10:22:22 -07007106 QuicBlockedFrame blocked(1, 3, 0);
Bence Békybac04052022-04-07 15:44:29 -04007107
7108 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7109 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(0);
7110 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7111 connection_.SendControlFrame(QuicFrame(blocked));
7112 EXPECT_EQ(0u, connection_.GetStats().blocked_frames_sent);
7113 EXPECT_FALSE(connection_.HasQueuedData());
7114}
7115
7116TEST_P(QuicConnectionTest, SendingUnencryptedStreamDataFails) {
7117 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
7118 if (!IsDefaultTestConfiguration()) {
7119 return;
7120 }
7121
vasilvvac2e30d2022-06-02 14:26:59 -07007122 EXPECT_QUIC_BUG(
7123 {
7124 EXPECT_CALL(visitor_,
7125 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7126 .WillOnce(
7127 Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
7128 connection_.SaveAndSendStreamData(3, {}, 0, FIN);
7129 EXPECT_FALSE(connection_.connected());
7130 EXPECT_EQ(1, connection_close_frame_count_);
7131 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
7132 IsError(QUIC_ATTEMPT_TO_SEND_UNENCRYPTED_STREAM_DATA));
7133 },
7134 "Cannot send stream data with level: ENCRYPTION_INITIAL");
Bence Békybac04052022-04-07 15:44:29 -04007135}
7136
7137TEST_P(QuicConnectionTest, SetRetransmissionAlarmForCryptoPacket) {
7138 EXPECT_TRUE(connection_.connected());
7139 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
7140
7141 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7142 connection_.SendCryptoStreamData();
7143
7144 // Verify retransmission timer is correctly set after crypto packet has been
7145 // sent.
7146 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
7147 QuicTime retransmission_time =
7148 QuicConnectionPeer::GetSentPacketManager(&connection_)
7149 ->GetRetransmissionTime();
7150 EXPECT_NE(retransmission_time, clock_.ApproximateNow());
7151 EXPECT_EQ(retransmission_time,
7152 connection_.GetRetransmissionAlarm()->deadline());
7153
7154 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7155 connection_.GetRetransmissionAlarm()->Fire();
7156}
7157
7158// Includes regression test for b/69979024.
7159TEST_P(QuicConnectionTest, PathDegradingDetectionForNonCryptoPackets) {
7160 EXPECT_TRUE(connection_.connected());
7161 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7162 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007163 EXPECT_CALL(visitor_, GetHandshakeState())
7164 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7165 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007166
7167 const char data[] = "data";
7168 size_t data_size = strlen(data);
7169 QuicStreamOffset offset = 0;
7170
7171 for (int i = 0; i < 2; ++i) {
7172 // Send a packet. Now there's a retransmittable packet on the wire, so the
7173 // path degrading detection should be set.
7174 connection_.SendStreamDataWithString(
7175 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7176 offset, NO_FIN);
7177 offset += data_size;
7178 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7179 // Check the deadline of the path degrading detection.
7180 QuicTime::Delta delay =
7181 QuicConnectionPeer::GetSentPacketManager(&connection_)
7182 ->GetPathDegradingDelay();
7183 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7184 clock_.ApproximateNow());
7185
7186 // Send a second packet. The path degrading detection's deadline should
7187 // remain the same.
7188 // Regression test for b/69979024.
7189 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7190 QuicTime prev_deadline =
7191 connection_.GetBlackholeDetectorAlarm()->deadline();
7192 connection_.SendStreamDataWithString(
7193 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7194 offset, NO_FIN);
7195 offset += data_size;
7196 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7197 EXPECT_EQ(prev_deadline,
7198 connection_.GetBlackholeDetectorAlarm()->deadline());
7199
7200 // Now receive an ACK of the first packet. This should advance the path
7201 // degrading detection's deadline since forward progress has been made.
7202 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7203 if (i == 0) {
7204 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7205 }
7206 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7207 QuicAckFrame frame = InitAckFrame(
7208 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7209 ProcessAckPacket(&frame);
7210 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7211 // Check the deadline of the path degrading detection.
7212 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7213 ->GetPathDegradingDelay();
7214 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7215 clock_.ApproximateNow());
7216
7217 if (i == 0) {
7218 // Now receive an ACK of the second packet. Since there are no more
7219 // retransmittable packets on the wire, this should cancel the path
7220 // degrading detection.
7221 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7222 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7223 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7224 ProcessAckPacket(&frame);
7225 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7226 } else {
7227 // Advance time to the path degrading alarm's deadline and simulate
7228 // firing the alarm.
7229 clock_.AdvanceTime(delay);
7230 EXPECT_CALL(visitor_, OnPathDegrading());
7231 connection_.PathDegradingTimeout();
7232 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7233 }
7234 }
7235 EXPECT_TRUE(connection_.IsPathDegrading());
7236}
7237
7238TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7239 const QuicTime::Delta retransmittable_on_wire_timeout =
7240 QuicTime::Delta::FromMilliseconds(50);
7241 connection_.set_initial_retransmittable_on_wire_timeout(
7242 retransmittable_on_wire_timeout);
7243
7244 EXPECT_TRUE(connection_.connected());
7245 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7246 .WillRepeatedly(Return(true));
7247
7248 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7249 EXPECT_FALSE(connection_.IsPathDegrading());
7250 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
fayang59e518a2022-11-29 11:16:45 -08007251 EXPECT_CALL(visitor_, GetHandshakeState())
7252 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7253 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007254
7255 const char data[] = "data";
7256 size_t data_size = strlen(data);
7257 QuicStreamOffset offset = 0;
7258
7259 // Send a packet.
7260 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7261 offset += data_size;
7262 // Now there's a retransmittable packet on the wire, so the path degrading
7263 // alarm should be set.
7264 // The retransmittable-on-wire alarm should not be set.
7265 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7266 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7267 ->GetPathDegradingDelay();
7268 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7269 clock_.ApproximateNow());
7270 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7271 // The ping alarm is set for the ping timeout, not the shorter
7272 // retransmittable_on_wire_timeout.
7273 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7274 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7275 EXPECT_EQ(ping_delay,
7276 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7277
7278 // Now receive an ACK of the packet.
7279 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7280 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7281 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7282 QuicAckFrame frame =
7283 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7284 ProcessAckPacket(&frame);
7285 // No more retransmittable packets on the wire, so the path degrading alarm
7286 // should be cancelled, and the ping alarm should be set to the
7287 // retransmittable_on_wire_timeout.
7288 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7289 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7290 EXPECT_EQ(retransmittable_on_wire_timeout,
7291 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7292
7293 // Simulate firing the ping alarm and sending a PING.
7294 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7295 connection_.GetPingAlarm()->Fire();
7296
7297 // Now there's a retransmittable packet (PING) on the wire, so the path
7298 // degrading alarm should be set.
fayang59e518a2022-11-29 11:16:45 -08007299 ASSERT_TRUE(connection_.PathDegradingDetectionInProgress());
Bence Békybac04052022-04-07 15:44:29 -04007300 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7301 ->GetPathDegradingDelay();
7302 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7303 clock_.ApproximateNow());
7304}
7305
7306TEST_P(QuicConnectionTest, ServerRetransmittableOnWire) {
7307 set_perspective(Perspective::IS_SERVER);
7308 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7309 SetQuicReloadableFlag(quic_enable_server_on_wire_ping, true);
7310
7311 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7312 QuicConfig config;
7313 QuicTagVector connection_options;
7314 connection_options.push_back(kSRWP);
7315 config.SetInitialReceivedConnectionOptions(connection_options);
7316 connection_.SetFromConfig(config);
7317
7318 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7319 .WillRepeatedly(Return(true));
7320
7321 ProcessPacket(1);
7322
7323 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7324 QuicTime::Delta ping_delay = QuicTime::Delta::FromMilliseconds(200);
7325 EXPECT_EQ(ping_delay,
7326 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7327
7328 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
7329 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
7330 // Verify PING alarm gets cancelled.
7331 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7332
7333 // Now receive an ACK of the packet.
7334 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
7335 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7336 QuicAckFrame frame =
7337 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7338 ProcessAckPacket(2, &frame);
7339 // Verify PING alarm gets scheduled.
7340 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7341 EXPECT_EQ(ping_delay,
7342 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7343}
7344
fayangf6607db2022-04-21 18:10:41 -07007345TEST_P(QuicConnectionTest, RetransmittableOnWireSendFirstPacket) {
fayang9b455102022-11-29 18:19:20 -08007346 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007347 return;
7348 }
7349 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7350 .WillRepeatedly(Return(true));
7351 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7352
7353 const QuicTime::Delta kRetransmittableOnWireTimeout =
7354 QuicTime::Delta::FromMilliseconds(200);
7355 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7356
7357 connection_.set_initial_retransmittable_on_wire_timeout(
7358 kRetransmittableOnWireTimeout);
7359
7360 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7361 QuicConfig config;
7362 QuicTagVector connection_options;
7363 connection_options.push_back(kROWF);
7364 config.SetClientConnectionOptions(connection_options);
7365 connection_.SetFromConfig(config);
7366
7367 // Send a request.
7368 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7369 // Receive an ACK after 1-RTT.
7370 clock_.AdvanceTime(kTestRtt);
7371 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7372 QuicAckFrame frame =
7373 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7374 ProcessAckPacket(&frame);
7375 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7376 EXPECT_EQ(kRetransmittableOnWireTimeout,
7377 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7378 EXPECT_EQ(1u, writer_->packets_write_attempts());
7379
7380 // Fire retransmittable-on-wire alarm.
7381 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7382 connection_.GetPingAlarm()->Fire();
7383 EXPECT_EQ(2u, writer_->packets_write_attempts());
7384 // Verify alarm is set in keep-alive mode.
7385 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7386 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7387 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7388}
7389
7390TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytes) {
fayang9b455102022-11-29 18:19:20 -08007391 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007392 return;
7393 }
7394 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7395 .WillRepeatedly(Return(true));
7396 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7397
7398 const QuicTime::Delta kRetransmittableOnWireTimeout =
7399 QuicTime::Delta::FromMilliseconds(200);
7400 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7401
7402 connection_.set_initial_retransmittable_on_wire_timeout(
7403 kRetransmittableOnWireTimeout);
7404
7405 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7406 QuicConfig config;
7407 QuicTagVector connection_options;
7408 connection_options.push_back(kROWR);
7409 config.SetClientConnectionOptions(connection_options);
7410 connection_.SetFromConfig(config);
7411
7412 // Send a request.
7413 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7414 // Receive an ACK after 1-RTT.
7415 clock_.AdvanceTime(kTestRtt);
7416 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7417 QuicAckFrame frame =
7418 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7419 ProcessAckPacket(&frame);
7420 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7421 EXPECT_EQ(kRetransmittableOnWireTimeout,
7422 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7423 EXPECT_EQ(1u, writer_->packets_write_attempts());
7424
7425 // Fire retransmittable-on-wire alarm.
7426 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7427 // Next packet is not processable by the framer in the test writer.
7428 ExpectNextPacketUnprocessable();
7429 connection_.GetPingAlarm()->Fire();
7430 EXPECT_EQ(2u, writer_->packets_write_attempts());
7431 // Verify alarm is set in keep-alive mode.
7432 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7433 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7434 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7435}
7436
7437TEST_P(QuicConnectionTest,
7438 RetransmittableOnWireSendRandomBytesWithWriterBlocked) {
fayang9b455102022-11-29 18:19:20 -08007439 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
fayangf6607db2022-04-21 18:10:41 -07007440 return;
7441 }
7442 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7443 .WillRepeatedly(Return(true));
7444 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7445 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7446
7447 const QuicTime::Delta kRetransmittableOnWireTimeout =
7448 QuicTime::Delta::FromMilliseconds(200);
7449 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7450
7451 connection_.set_initial_retransmittable_on_wire_timeout(
7452 kRetransmittableOnWireTimeout);
7453
7454 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7455 QuicConfig config;
7456 QuicTagVector connection_options;
7457 connection_options.push_back(kROWR);
7458 config.SetClientConnectionOptions(connection_options);
7459 connection_.SetFromConfig(config);
7460
7461 // Send a request.
7462 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7463 // Receive an ACK after 1-RTT.
7464 clock_.AdvanceTime(kTestRtt);
7465 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7466 QuicAckFrame frame =
7467 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7468 ProcessAckPacket(&frame);
7469 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7470 EXPECT_EQ(kRetransmittableOnWireTimeout,
7471 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7472 EXPECT_EQ(1u, writer_->packets_write_attempts());
7473 // Receive an out of order data packet and block the ACK packet.
7474 BlockOnNextWrite();
7475 ProcessDataPacket(3);
7476 EXPECT_EQ(2u, writer_->packets_write_attempts());
7477 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7478
7479 // Fire retransmittable-on-wire alarm.
7480 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7481 connection_.GetPingAlarm()->Fire();
7482 // Verify the random bytes packet gets queued.
7483 EXPECT_EQ(2u, connection_.NumQueuedPackets());
7484}
7485
Bence Békybac04052022-04-07 15:44:29 -04007486// This test verifies that the connection marks path as degrading and does not
7487// spin timer to detect path degrading when a new packet is sent on the
7488// degraded path.
7489TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
7490 EXPECT_TRUE(connection_.connected());
7491 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7492 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007493 EXPECT_CALL(visitor_, GetHandshakeState())
7494 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7495 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007496
7497 const char data[] = "data";
7498 size_t data_size = strlen(data);
7499 QuicStreamOffset offset = 0;
7500
7501 // Send the first packet. Now there's a retransmittable packet on the wire, so
7502 // the path degrading alarm should be set.
7503 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7504 offset += data_size;
7505 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7506 // Check the deadline of the path degrading detection.
7507 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7508 ->GetPathDegradingDelay();
7509 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7510 clock_.ApproximateNow());
7511
7512 // Send a second packet. The path degrading detection's deadline should remain
7513 // the same.
7514 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7515 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7516 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7517 offset += data_size;
7518 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7519 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7520
7521 // Now receive an ACK of the first packet. This should advance the path
7522 // degrading detection's deadline since forward progress has been made.
7523 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7524 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7525 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7526 QuicAckFrame frame =
7527 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7528 ProcessAckPacket(&frame);
7529 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7530 // Check the deadline of the path degrading alarm.
7531 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7532 ->GetPathDegradingDelay();
7533 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7534 clock_.ApproximateNow());
7535
7536 // Advance time to the path degrading detection's deadline and simulate
7537 // firing the path degrading detection. This path will be considered as
7538 // degrading.
7539 clock_.AdvanceTime(delay);
7540 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7541 connection_.PathDegradingTimeout();
7542 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7543 EXPECT_TRUE(connection_.IsPathDegrading());
7544
7545 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7546 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7547 // Send a third packet. The path degrading detection is no longer set but path
7548 // should still be marked as degrading.
7549 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7550 offset += data_size;
7551 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7552 EXPECT_TRUE(connection_.IsPathDegrading());
7553}
7554
fayang59e518a2022-11-29 11:16:45 -08007555TEST_P(QuicConnectionTest, NoPathDegradingDetectionBeforeHandshakeConfirmed) {
7556 EXPECT_TRUE(connection_.connected());
7557 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7558 EXPECT_FALSE(connection_.IsPathDegrading());
7559 EXPECT_CALL(visitor_, GetHandshakeState())
7560 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
7561
7562 connection_.SendStreamDataWithString(1, "data", 0, NO_FIN);
7563 if (GetQuicReloadableFlag(
7564 quic_no_path_degrading_before_handshake_confirmed) &&
7565 connection_.SupportsMultiplePacketNumberSpaces()) {
7566 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7567 } else {
7568 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7569 }
7570}
7571
Bence Békybac04052022-04-07 15:44:29 -04007572// This test verifies that the connection unmarks path as degrarding and spins
7573// the timer to detect future path degrading when forward progress is made
7574// after path has been marked degrading.
7575TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7576 EXPECT_TRUE(connection_.connected());
7577 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7578 EXPECT_FALSE(connection_.IsPathDegrading());
fayang59e518a2022-11-29 11:16:45 -08007579 EXPECT_CALL(visitor_, GetHandshakeState())
7580 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
7581 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -04007582
7583 const char data[] = "data";
7584 size_t data_size = strlen(data);
7585 QuicStreamOffset offset = 0;
7586
7587 // Send the first packet. Now there's a retransmittable packet on the wire, so
7588 // the path degrading alarm should be set.
7589 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7590 offset += data_size;
7591 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7592 // Check the deadline of the path degrading alarm.
7593 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7594 ->GetPathDegradingDelay();
7595 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7596 clock_.ApproximateNow());
7597
7598 // Send a second packet. The path degrading alarm's deadline should remain
7599 // the same.
7600 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7601 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7602 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7603 offset += data_size;
7604 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7605 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7606
7607 // Now receive an ACK of the first packet. This should advance the path
7608 // degrading alarm's deadline since forward progress has been made.
7609 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7610 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7611 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7612 QuicAckFrame frame =
7613 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7614 ProcessAckPacket(&frame);
7615 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7616 // Check the deadline of the path degrading alarm.
7617 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7618 ->GetPathDegradingDelay();
7619 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7620 clock_.ApproximateNow());
7621
7622 // Advance time to the path degrading alarm's deadline and simulate
7623 // firing the alarm.
7624 clock_.AdvanceTime(delay);
7625 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7626 connection_.PathDegradingTimeout();
7627 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7628 EXPECT_TRUE(connection_.IsPathDegrading());
7629
7630 // Send a third packet. The path degrading alarm is no longer set but path
7631 // should still be marked as degrading.
7632 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7633 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7634 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7635 offset += data_size;
7636 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7637 EXPECT_TRUE(connection_.IsPathDegrading());
7638
7639 // Now receive an ACK of the second packet. This should unmark the path as
7640 // degrading. And will set a timer to detect new path degrading.
7641 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7642 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7643 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
7644 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7645 ProcessAckPacket(&frame);
7646 EXPECT_FALSE(connection_.IsPathDegrading());
7647 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7648}
7649
7650TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
7651 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7652 return;
7653 }
7654 set_perspective(Perspective::IS_SERVER);
7655 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7656
7657 EXPECT_FALSE(connection_.IsPathDegrading());
7658 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7659
7660 // Send data.
7661 const char data[] = "data";
7662 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7663 EXPECT_FALSE(connection_.IsPathDegrading());
7664 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7665
7666 // Ack data.
7667 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7668 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7669 QuicAckFrame frame =
7670 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7671 ProcessAckPacket(&frame);
7672 EXPECT_FALSE(connection_.IsPathDegrading());
7673 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7674}
7675
7676TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
7677 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7678 return;
7679 }
7680 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7681 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7682 ProcessDataPacket(1);
7683 SendAckPacketToPeer();
7684 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7685 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7686 EXPECT_FALSE(connection_.IsPathDegrading());
7687 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7688}
7689
7690TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7691 // Verifies that multiple calls to CloseConnection do not
7692 // result in multiple attempts to close the connection - it will be marked as
7693 // disconnected after the first call.
7694 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
7695 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7696 ConnectionCloseBehavior::SILENT_CLOSE);
7697 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7698 ConnectionCloseBehavior::SILENT_CLOSE);
7699}
7700
7701TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7702 set_perspective(Perspective::IS_SERVER);
7703 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang161ce6e2022-07-01 18:02:11 -07007704 QuicConnectionPeer::SetAddressValidated(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04007705
7706 CryptoHandshakeMessage message;
7707 CryptoFramer framer;
7708 message.set_tag(kCHLO);
7709 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7710 frame1_.stream_id = 10;
7711 frame1_.data_buffer = data->data();
7712 frame1_.data_length = data->length();
7713
7714 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7715 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7716 }
7717 EXPECT_CALL(visitor_,
7718 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7719 ForceProcessFramePacket(QuicFrame(frame1_));
7720 if (VersionHasIetfQuicFrames(version().transport_version)) {
7721 // INITIAL packet should not contain STREAM frame.
7722 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7723 } else {
7724 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7725 }
7726}
7727
7728TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7729 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7730
7731 CryptoHandshakeMessage message;
7732 CryptoFramer framer;
7733 message.set_tag(kREJ);
7734 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7735 frame1_.stream_id = 10;
7736 frame1_.data_buffer = data->data();
7737 frame1_.data_length = data->length();
7738
7739 EXPECT_CALL(visitor_,
7740 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7741 ForceProcessFramePacket(QuicFrame(frame1_));
7742 if (VersionHasIetfQuicFrames(version().transport_version)) {
7743 // INITIAL packet should not contain STREAM frame.
7744 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7745 } else {
7746 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7747 }
7748}
7749
7750TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7751 SimulateNextPacketTooLarge();
7752 // A connection close packet is sent
7753 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7754 .Times(1);
7755 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7756 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7757}
7758
7759TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7760 // Test even we always get packet too large, we do not infinitely try to send
7761 // close packet.
7762 AlwaysGetPacketTooLarge();
7763 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7764 .Times(1);
7765 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7766 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7767}
7768
7769TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
7770 // Regression test for crbug.com/979507.
7771 //
7772 // If we get a write error when writing queued packets, we should attempt to
7773 // send a connection close packet, but if sending that fails, it shouldn't get
7774 // queued.
7775
7776 // Queue a packet to write.
7777 BlockOnNextWrite();
7778 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7779 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7780
7781 // Configure writer to always fail.
7782 AlwaysGetPacketTooLarge();
7783
7784 // Expect that we attempt to close the connection exactly once.
7785 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7786 .Times(1);
7787
7788 // Unblock the writes and actually send.
7789 writer_->SetWritable();
7790 connection_.OnCanWrite();
7791 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7792
7793 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7794}
7795
7796// Verify that if connection has no outstanding data, it notifies the send
7797// algorithm after the write.
7798TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7799 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7800 {
7801 InSequence seq;
7802 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7803 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7804 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7805 .WillRepeatedly(Return(false));
7806 }
7807
7808 connection_.SendStreamData3();
7809}
7810
7811// Verify that the connection does not become app-limited if there is
7812// outstanding data to send after the write.
7813TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7814 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7815 {
7816 InSequence seq;
7817 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7818 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7819 }
7820
7821 connection_.SendStreamData3();
7822}
7823
7824// Verify that the connection does not become app-limited after blocked write
7825// even if there is outstanding data to send after the write.
7826TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7827 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7828 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7829 BlockOnNextWrite();
7830
7831 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7832 connection_.SendStreamData3();
7833
7834 // Now unblock the writer, become congestion control blocked,
7835 // and ensure we become app-limited after writing.
7836 writer_->SetWritable();
7837 CongestionBlockWrites();
7838 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7839 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7840 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7841 connection_.OnCanWrite();
7842}
7843
Bence Békybac04052022-04-07 15:44:29 -04007844TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
7845 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7846 // Send an ack by simulating delayed ack alarm firing.
7847 ProcessPacket(1);
7848 EXPECT_TRUE(connection_.HasPendingAcks());
7849 connection_.GetAckAlarm()->Fire();
7850 // Simulate data packet causes write error.
7851 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7852 SimulateNextPacketTooLarge();
7853 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7854 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7855 // Ack frame is not bundled in connection close packet.
7856 EXPECT_TRUE(writer_->ack_frames().empty());
7857 if (writer_->padding_frames().empty()) {
7858 EXPECT_EQ(1u, writer_->frame_count());
7859 } else {
7860 EXPECT_EQ(2u, writer_->frame_count());
7861 }
7862
7863 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7864}
7865
7866TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
7867 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7868 return;
7869 }
7870
7871 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7872 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7873 connection_.CloseConnection(
7874 kQuicErrorCode, "Some random error message",
7875 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7876
7877 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7878
7879 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7880 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7881
7882 if (!connection_.version().CanSendCoalescedPackets()) {
7883 // Each connection close packet should be sent in distinct UDP packets.
7884 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7885 writer_->connection_close_packets());
7886 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7887 writer_->packets_write_attempts());
7888 return;
7889 }
7890
7891 // A single UDP packet should be sent with multiple connection close packets
7892 // coalesced together.
7893 EXPECT_EQ(1u, writer_->packets_write_attempts());
7894
7895 // Only the first packet has been processed yet.
7896 EXPECT_EQ(1u, writer_->connection_close_packets());
7897
7898 // ProcessPacket resets the visitor and frees the coalesced packet.
7899 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
7900 auto packet = writer_->coalesced_packet()->Clone();
7901 writer_->framer()->ProcessPacket(*packet);
7902 EXPECT_EQ(1u, writer_->connection_close_packets());
7903 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7904}
7905
7906TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
7907 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7908 return;
7909 }
7910
7911 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7912 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7913 connection_.CloseConnection(
7914 kQuicErrorCode, "Some random error message",
7915 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7916
7917 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7918
7919 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7920 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7921 EXPECT_EQ(1u, writer_->connection_close_packets());
7922 EXPECT_EQ(1u, writer_->packets_write_attempts());
7923 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7924}
7925
7926TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
7927 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7928 return;
7929 }
7930 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07007931 // Receives packet 1000 in initial data.
7932 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7933 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -04007934
7935 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7936 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7937 }
7938 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7939 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7940 connection_.CloseConnection(
7941 kQuicErrorCode, "Some random error message",
7942 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7943
7944 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7945
7946 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7947 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7948 EXPECT_TRUE(writer_->padding_frames().empty());
7949 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
7950}
7951
7952// Regression test for b/63620844.
7953TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
7954 SimulateNextPacketTooLarge();
7955 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7956 .Times(1);
7957
7958 connection_.SendCryptoStreamData();
7959 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7960}
7961
7962TEST_P(QuicConnectionTest, MaxPacingRate) {
7963 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
7964 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
7965 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
7966}
7967
7968TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
7969 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7970 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7971 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7972 EXPECT_EQ(CONNECTION_ID_PRESENT,
7973 writer_->last_packet_header().destination_connection_id_included);
7974
7975 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7976 QuicConfig config;
7977 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
7978 connection_.SetFromConfig(config);
7979
7980 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7981 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
7982 // Verify connection id is still sent in the packet.
7983 EXPECT_EQ(CONNECTION_ID_PRESENT,
7984 writer_->last_packet_header().destination_connection_id_included);
7985}
7986
Bence Békybac04052022-04-07 15:44:29 -04007987TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
7988 const QuicTime::Delta retransmittable_on_wire_timeout =
7989 QuicTime::Delta::FromMilliseconds(50);
7990 connection_.set_initial_retransmittable_on_wire_timeout(
7991 retransmittable_on_wire_timeout);
7992
7993 EXPECT_TRUE(connection_.connected());
7994 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7995 .WillRepeatedly(Return(true));
7996
7997 const char data[] = "data";
7998 size_t data_size = strlen(data);
7999 QuicStreamOffset offset = 0;
8000
8001 // Advance 5ms, send a retransmittable packet to the peer.
8002 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8003 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8004 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8005 offset += data_size;
8006 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8007 // The ping alarm is set for the ping timeout, not the shorter
8008 // retransmittable_on_wire_timeout.
8009 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8010 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8011 EXPECT_EQ(ping_delay,
8012 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8013
8014 // Advance 5ms, send a second retransmittable packet to the peer.
8015 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8016 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8017 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8018 offset += data_size;
8019 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8020
8021 // Now receive an ACK of the first packet. This should not set the
8022 // retransmittable-on-wire alarm since packet 2 is still on the wire.
8023 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8024 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8025 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8026 QuicAckFrame frame =
8027 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8028 ProcessAckPacket(&frame);
8029 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8030 // The ping alarm is set for the ping timeout, not the shorter
8031 // retransmittable_on_wire_timeout.
8032 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8033 // The ping alarm has a 1 second granularity, and the clock has been advanced
8034 // 10ms since it was originally set.
8035 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8036 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8037
8038 // Now receive an ACK of the second packet. This should set the
8039 // retransmittable-on-wire alarm now that no retransmittable packets are on
8040 // the wire.
8041 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8042 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8043 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8044 ProcessAckPacket(&frame);
8045 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8046 EXPECT_EQ(retransmittable_on_wire_timeout,
8047 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8048
8049 // Now receive a duplicate ACK of the second packet. This should not update
8050 // the ping alarm.
8051 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8052 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8053 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8054 ProcessAckPacket(&frame);
8055 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8056 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8057
8058 // Now receive a non-ACK packet. This should not update the ping alarm.
8059 prev_deadline = connection_.GetPingAlarm()->deadline();
8060 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8061 ProcessPacket(4);
8062 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8063 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8064
8065 // Simulate the alarm firing and check that a PING is sent.
8066 connection_.GetPingAlarm()->Fire();
8067 size_t padding_frame_count = writer_->padding_frames().size();
8068 if (GetParam().no_stop_waiting) {
8069 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
8070 } else {
8071 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
8072 }
8073 ASSERT_EQ(1u, writer_->ping_frames().size());
8074}
8075
8076TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8077 const QuicTime::Delta retransmittable_on_wire_timeout =
8078 QuicTime::Delta::FromMilliseconds(50);
8079 connection_.set_initial_retransmittable_on_wire_timeout(
8080 retransmittable_on_wire_timeout);
8081
8082 EXPECT_TRUE(connection_.connected());
8083 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8084 .WillRepeatedly(Return(true));
8085
8086 const char data[] = "data";
8087 size_t data_size = strlen(data);
8088 QuicStreamOffset offset = 0;
8089
8090 // Advance 5ms, send a retransmittable packet to the peer.
8091 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8092 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8093 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8094 offset += data_size;
8095 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8096 // The ping alarm is set for the ping timeout, not the shorter
8097 // retransmittable_on_wire_timeout.
8098 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8099 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8100 EXPECT_EQ(ping_delay,
8101 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8102
8103 // Now receive an ACK of the first packet. This should set the
8104 // retransmittable-on-wire alarm now that no retransmittable packets are on
8105 // the wire.
8106 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8107 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8108 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8109 QuicAckFrame frame =
8110 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8111 ProcessAckPacket(&frame);
8112 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8113 EXPECT_EQ(retransmittable_on_wire_timeout,
8114 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8115
8116 // Before the alarm fires, send another retransmittable packet. This should
8117 // cancel the retransmittable-on-wire alarm since now there's a
8118 // retransmittable packet on the wire.
8119 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8120 offset += data_size;
8121 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8122
8123 // Now receive an ACK of the second packet. This should set the
8124 // retransmittable-on-wire alarm now that no retransmittable packets are on
8125 // the wire.
8126 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8127 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8128 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8129 ProcessAckPacket(&frame);
8130 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8131 EXPECT_EQ(retransmittable_on_wire_timeout,
8132 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8133
8134 // Simulate the alarm firing and check that a PING is sent.
8135 writer_->Reset();
8136 connection_.GetPingAlarm()->Fire();
8137 size_t padding_frame_count = writer_->padding_frames().size();
8138 if (GetParam().no_stop_waiting) {
8139 // Do not ACK acks.
8140 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
8141 } else {
8142 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
8143 }
8144 ASSERT_EQ(1u, writer_->ping_frames().size());
8145}
8146
8147// When there is no stream data received but are open streams, send the
8148// first few consecutive pings with aggressive retransmittable-on-wire
8149// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8150// afterwards until it exceeds the default ping timeout.
8151TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8152 int max_aggressive_retransmittable_on_wire_ping_count = 5;
birenroyef686222022-09-12 11:34:34 -07008153 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008154 max_aggressive_retransmittable_on_wire_ping_count);
8155 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8156 QuicTime::Delta::FromMilliseconds(200);
8157 connection_.set_initial_retransmittable_on_wire_timeout(
8158 initial_retransmittable_on_wire_timeout);
8159
8160 EXPECT_TRUE(connection_.connected());
8161 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8162 .WillRepeatedly(Return(true));
8163
8164 const char data[] = "data";
8165 // Advance 5ms, send a retransmittable data packet to the peer.
8166 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8167 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8168 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8169 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8170 // The ping alarm is set for the ping timeout, not the shorter
8171 // retransmittable_on_wire_timeout.
8172 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008173 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008174 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8175
8176 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8177 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8178 .Times(AnyNumber());
8179
8180 // Verify that the first few consecutive retransmittable on wire pings are
8181 // sent with aggressive timeout.
8182 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8183 // Receive an ACK of the previous packet. This should set the ping alarm
8184 // with the initial retransmittable-on-wire timeout.
8185 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8186 QuicPacketNumber ack_num = creator_->packet_number();
8187 QuicAckFrame frame = InitAckFrame(
8188 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8189 ProcessAckPacket(&frame);
8190 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8191 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8192 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8193 // Simulate the alarm firing and check that a PING is sent.
8194 writer_->Reset();
8195 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8196 connection_.GetPingAlarm()->Fire();
8197 }
8198
8199 QuicTime::Delta retransmittable_on_wire_timeout =
8200 initial_retransmittable_on_wire_timeout;
8201
8202 // Verify subsequent pings are sent with timeout that is exponentially backed
8203 // off.
fayang5d393332022-04-18 13:34:54 -07008204 while (retransmittable_on_wire_timeout * 2 <
8205 QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) {
Bence Békybac04052022-04-07 15:44:29 -04008206 // Receive an ACK for the previous PING. This should set the
8207 // ping alarm with backed off retransmittable-on-wire timeout.
8208 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8209 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8210 QuicPacketNumber ack_num = creator_->packet_number();
8211 QuicAckFrame frame = InitAckFrame(
8212 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8213 ProcessAckPacket(&frame);
8214 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8215 EXPECT_EQ(retransmittable_on_wire_timeout,
8216 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8217
8218 // Simulate the alarm firing and check that a PING is sent.
8219 writer_->Reset();
8220 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8221 connection_.GetPingAlarm()->Fire();
8222 }
8223
8224 // The ping alarm is set with default ping timeout.
8225 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008226 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008227 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8228
8229 // Receive an ACK for the previous PING. The ping alarm is set with an
8230 // earlier deadline.
8231 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8232 QuicPacketNumber ack_num = creator_->packet_number();
8233 QuicAckFrame frame = InitAckFrame(
8234 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8235 ProcessAckPacket(&frame);
8236 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008237 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) -
8238 QuicTime::Delta::FromMilliseconds(5),
Bence Békybac04052022-04-07 15:44:29 -04008239 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8240}
8241
8242// This test verify that the count of consecutive aggressive pings is reset
8243// when new data is received. And it also verifies the connection resets
8244// the exponential back-off of the retransmittable-on-wire ping timeout
8245// after receiving new stream data.
8246TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8247 int max_aggressive_retransmittable_on_wire_ping_count = 3;
birenroyef686222022-09-12 11:34:34 -07008248 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
Bence Békybac04052022-04-07 15:44:29 -04008249 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8250 QuicTime::Delta::FromMilliseconds(200);
8251 connection_.set_initial_retransmittable_on_wire_timeout(
8252 initial_retransmittable_on_wire_timeout);
8253
8254 EXPECT_TRUE(connection_.connected());
8255 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8256 .WillRepeatedly(Return(true));
8257 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8258 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8259 .Times(AnyNumber());
8260
8261 const char data[] = "data";
8262 // Advance 5ms, send a retransmittable data packet to the peer.
8263 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8264 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8265 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8266 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8267 // The ping alarm is set for the ping timeout, not the shorter
8268 // retransmittable_on_wire_timeout.
8269 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008270 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008271 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8272
8273 // Receive an ACK of the first packet. This should set the ping alarm with
8274 // initial retransmittable-on-wire timeout since there is no retransmittable
8275 // packet on the wire.
8276 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8277 QuicAckFrame frame =
8278 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8279 ProcessAckPacket(&frame);
8280 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8281 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8282 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8283
8284 // Simulate the alarm firing and check that a PING is sent.
8285 writer_->Reset();
8286 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8287 connection_.GetPingAlarm()->Fire();
8288
8289 // Receive an ACK for the previous PING. Ping alarm will be set with
8290 // aggressive timeout.
8291 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8292 QuicPacketNumber ack_num = creator_->packet_number();
8293 frame = InitAckFrame(
8294 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8295 ProcessAckPacket(&frame);
8296 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8297 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8298 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8299
8300 // Process a data packet.
8301 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8302 ProcessDataPacket(peer_creator_.packet_number() + 1);
8303 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8304 peer_creator_.packet_number() + 1);
8305 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8306 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
fayang327663d2022-05-10 18:25:36 -07008307 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8308 connection_.GetPingAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -04008309
8310 // Verify the count of consecutive aggressive pings is reset.
8311 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8312 // Receive an ACK of the previous packet. This should set the ping alarm
8313 // with the initial retransmittable-on-wire timeout.
8314 QuicPacketNumber ack_num = creator_->packet_number();
8315 QuicAckFrame frame = InitAckFrame(
8316 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8317 ProcessAckPacket(&frame);
8318 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8319 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8320 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8321 // Simulate the alarm firing and check that a PING is sent.
8322 writer_->Reset();
8323 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8324 connection_.GetPingAlarm()->Fire();
8325 // Advance 5ms to receive next packet.
8326 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8327 }
8328
8329 // Receive another ACK for the previous PING. This should set the
8330 // ping alarm with backed off retransmittable-on-wire timeout.
8331 ack_num = creator_->packet_number();
8332 frame = InitAckFrame(
8333 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8334 ProcessAckPacket(&frame);
8335 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8336 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8337 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8338
8339 writer_->Reset();
8340 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8341 connection_.GetPingAlarm()->Fire();
8342
8343 // Process another data packet and a new ACK packet. The ping alarm is set
8344 // with aggressive ping timeout again.
8345 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8346 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8347 ProcessDataPacket(peer_creator_.packet_number() + 1);
8348 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8349 peer_creator_.packet_number() + 1);
8350 ack_num = creator_->packet_number();
8351 frame = InitAckFrame(
8352 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8353 ProcessAckPacket(&frame);
8354 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8355 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8356 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8357}
8358
8359// Make sure that we never send more retransmissible on the wire pings than
8360// the limit in FLAGS_quic_max_retransmittable_on_wire_ping_count.
8361TEST_P(QuicConnectionTest, RetransmittableOnWirePingLimit) {
8362 static constexpr int kMaxRetransmittableOnWirePingCount = 3;
birenroyef686222022-09-12 11:34:34 -07008363 SetQuicFlag(quic_max_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008364 kMaxRetransmittableOnWirePingCount);
8365 static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout =
8366 QuicTime::Delta::FromMilliseconds(200);
8367 static constexpr QuicTime::Delta short_delay =
8368 QuicTime::Delta::FromMilliseconds(5);
8369 ASSERT_LT(short_delay * 10, initial_retransmittable_on_wire_timeout);
8370 connection_.set_initial_retransmittable_on_wire_timeout(
8371 initial_retransmittable_on_wire_timeout);
8372
8373 EXPECT_TRUE(connection_.connected());
8374 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8375 .WillRepeatedly(Return(true));
8376
8377 const char data[] = "data";
8378 // Advance 5ms, send a retransmittable data packet to the peer.
8379 clock_.AdvanceTime(short_delay);
8380 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8381 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8382 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8383 // The ping alarm is set for the ping timeout, not the shorter
8384 // retransmittable_on_wire_timeout.
8385 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008386 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008387 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8388
8389 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8390 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8391 .Times(AnyNumber());
8392
8393 // Verify that the first few consecutive retransmittable on wire pings are
8394 // sent with aggressive timeout.
8395 for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) {
8396 // Receive an ACK of the previous packet. This should set the ping alarm
8397 // with the initial retransmittable-on-wire timeout.
8398 clock_.AdvanceTime(short_delay);
8399 QuicPacketNumber ack_num = creator_->packet_number();
8400 QuicAckFrame frame = InitAckFrame(
8401 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8402 ProcessAckPacket(&frame);
8403 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8404 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8405 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8406 // Simulate the alarm firing and check that a PING is sent.
8407 writer_->Reset();
8408 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8409 connection_.GetPingAlarm()->Fire();
8410 }
8411
8412 // Receive an ACK of the previous packet. This should set the ping alarm
8413 // but this time with the default ping timeout.
8414 QuicPacketNumber ack_num = creator_->packet_number();
8415 QuicAckFrame frame = InitAckFrame(
8416 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8417 ProcessAckPacket(&frame);
8418 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008419 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008420 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8421}
8422
8423TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8424 const StatelessResetToken kTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8425 0, 1, 0, 1, 0, 1, 0, 1};
8426 const StatelessResetToken kWrongTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8427 0, 1, 0, 1, 0, 1, 0, 2};
8428 QuicConfig config;
8429 // No token has been received.
8430 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8431
8432 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8433 // Token is different from received token.
8434 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8435 connection_.SetFromConfig(config);
8436 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8437
8438 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8439 connection_.SetFromConfig(config);
8440 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8441}
8442
8443TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8444 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8445 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8446 BlockOnNextWrite();
8447 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8448 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8449 // This causes connection to be closed because packet 1 has not been sent yet.
8450 QuicAckFrame frame = InitAckFrame(1);
8451 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
8452 ProcessAckPacket(1, &frame);
8453 EXPECT_EQ(0, connection_close_frame_count_);
8454}
8455
8456TEST_P(QuicConnectionTest, SendMessage) {
8457 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
8458 return;
8459 }
8460 if (connection_.version().UsesTls()) {
8461 QuicConfig config;
8462 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8463 &config, kMaxAcceptedDatagramFrameSize);
8464 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8465 connection_.SetFromConfig(config);
8466 }
8467 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
8468 quiche::QuicheMemSlice slice;
8469 {
8470 QuicConnection::ScopedPacketFlusher flusher(&connection_);
8471 connection_.SendStreamData3();
8472 // Send a message which cannot fit into current open packet, and 2 packets
8473 // get sent, one contains stream frame, and the other only contains the
8474 // message frame.
8475 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8476 slice = MemSliceFromString(absl::string_view(
8477 message.data(), connection_.GetCurrentLargestMessagePayload()));
8478 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8479 connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false));
8480 }
8481 // Fail to send a message if connection is congestion control blocked.
8482 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8483 slice = MemSliceFromString("message");
8484 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8485 connection_.SendMessage(2, absl::MakeSpan(&slice, 1), false));
8486
8487 // Always fail to send a message which cannot fit into one packet.
8488 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8489 slice = MemSliceFromString(absl::string_view(
8490 message.data(), connection_.GetCurrentLargestMessagePayload() + 1));
8491 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8492 connection_.SendMessage(3, absl::MakeSpan(&slice, 1), false));
8493}
8494
8495TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
8496 if (!connection_.version().SupportsMessageFrames()) {
8497 return;
8498 }
martinduke225e91a2022-11-28 17:18:13 -08008499 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008500 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
8501 expected_largest_payload += 3;
8502 }
8503 if (connection_.version().HasLongHeaderLengths()) {
8504 expected_largest_payload -= 2;
8505 }
8506 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8507 expected_largest_payload -= 1;
8508 }
8509 if (connection_.version().UsesTls()) {
8510 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8511 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8512 QuicConfig config;
8513 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8514 &config, kMaxAcceptedDatagramFrameSize);
8515 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8516 connection_.SetFromConfig(config);
8517 // Verify the value post-handshake.
8518 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8519 expected_largest_payload);
8520 } else {
8521 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8522 expected_largest_payload);
8523 }
8524}
8525
8526TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
8527 if (!connection_.version().SupportsMessageFrames()) {
8528 return;
8529 }
martinduke225e91a2022-11-28 17:18:13 -08008530 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008531 if (connection_.version().HasLongHeaderLengths()) {
8532 expected_largest_payload -= 2;
8533 }
8534 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8535 expected_largest_payload -= 1;
8536 }
8537 if (connection_.version().UsesTls()) {
8538 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8539 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8540 QuicConfig config;
8541 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8542 &config, kMaxAcceptedDatagramFrameSize);
8543 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8544 connection_.SetFromConfig(config);
8545 // Verify the value post-handshake.
8546 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8547 expected_largest_payload);
8548 } else {
8549 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8550 expected_largest_payload);
8551 }
8552}
8553
8554TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
8555 if (!connection_.version().SupportsMessageFrames() ||
8556 !connection_.version().UsesTls()) {
8557 return;
8558 }
8559 constexpr QuicPacketLength kFrameSizeLimit = 1000;
8560 constexpr QuicPacketLength kPayloadSizeLimit =
8561 kFrameSizeLimit - kQuicFrameTypeSize;
8562 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8563 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8564 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8565 QuicConfig config;
8566 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
8567 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8568 connection_.SetFromConfig(config);
8569 // Verify the value post-handshake.
8570 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
8571 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8572 kPayloadSizeLimit);
8573}
8574
8575// Test to check that the path challenge/path response logic works
8576// correctly. This test is only for version-99
8577TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) {
8578 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8579 return;
8580 }
8581 PathProbeTestInit(Perspective::IS_SERVER);
8582 QuicConnectionPeer::SetAddressValidated(&connection_);
8583 // First check if the server can send probing packet.
8584 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8585
8586 // Create and send the probe request (PATH_CHALLENGE frame).
8587 // SendConnectivityProbingPacket ends up calling
8588 // TestPacketWriter::WritePacket() which in turns receives and parses the
8589 // packet by calling framer_.ProcessPacket() -- which in turn calls
8590 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8591 // the packet in writer_->path_challenge_frames()
8592 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8593 connection_.SendConnectivityProbingPacket(writer_.get(),
8594 connection_.peer_address());
8595 // Save the random contents of the challenge for later comparison to the
8596 // response.
8597 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8598 QuicPathFrameBuffer challenge_data =
8599 writer_->path_challenge_frames().front().data_buffer;
8600
8601 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8602 // called and it will perform actions to ensure that the rest of the protocol
8603 // is performed.
8604 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8605 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8606 writer_->path_challenge_frames().front()));
8607 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8608 creator_->FlushCurrentPacket();
8609
8610 // The final check is to ensure that the random data in the response matches
8611 // the random data from the challenge.
8612 EXPECT_EQ(1u, writer_->path_response_frames().size());
8613 EXPECT_EQ(0, memcmp(&challenge_data,
8614 &(writer_->path_response_frames().front().data_buffer),
8615 sizeof(challenge_data)));
8616}
8617
8618TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnDefaulSocket) {
8619 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8620 return;
8621 }
8622 PathProbeTestInit(Perspective::IS_CLIENT);
8623 // First check if the client can send probing packet.
8624 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8625
8626 // Create and send the probe request (PATH_CHALLENGE frame).
8627 // SendConnectivityProbingPacket ends up calling
8628 // TestPacketWriter::WritePacket() which in turns receives and parses the
8629 // packet by calling framer_.ProcessPacket() -- which in turn calls
8630 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8631 // the packet in writer_->path_challenge_frames()
8632 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8633 connection_.SendConnectivityProbingPacket(writer_.get(),
8634 connection_.peer_address());
8635 // Save the random contents of the challenge for later validation against the
8636 // response.
8637 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8638 QuicPathFrameBuffer challenge_data =
8639 writer_->path_challenge_frames().front().data_buffer;
8640
8641 // Normally, QuicConnection::OnPathChallengeFrame would be
8642 // called and it will perform actions to ensure that the rest of the protocol
8643 // is performed.
8644 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8645 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8646 writer_->path_challenge_frames().front()));
8647 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8648 creator_->FlushCurrentPacket();
8649
8650 // The final check is to ensure that the random data in the response matches
8651 // the random data from the challenge.
8652 EXPECT_EQ(1u, writer_->path_response_frames().size());
8653 EXPECT_EQ(0, memcmp(&challenge_data,
8654 &(writer_->path_response_frames().front().data_buffer),
8655 sizeof(challenge_data)));
8656}
8657
8658TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnAlternativeSocket) {
danzh87605712022-04-11 14:36:39 -07008659 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -04008660 return;
8661 }
8662 PathProbeTestInit(Perspective::IS_CLIENT);
8663 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8664
8665 QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8666 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8667 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8668 .Times(AtLeast(1u))
8669 .WillOnce(Invoke([&]() {
8670 EXPECT_EQ(1u, new_writer.packets_write_attempts());
8671 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
8672 EXPECT_EQ(1u, new_writer.padding_frames().size());
8673 EXPECT_EQ(kNewSelfAddress.host(),
8674 new_writer.last_write_source_address());
8675 }));
8676 bool success = false;
8677 connection_.ValidatePath(
8678 std::make_unique<TestQuicPathValidationContext>(
8679 kNewSelfAddress, connection_.peer_address(), &new_writer),
8680 std::make_unique<TestValidationResultDelegate>(
8681 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
8682
8683 // Receiving a PATH_CHALLENGE on the alternative path. Response to this
8684 // PATH_CHALLENGE should be sent via the alternative writer.
8685 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8686 .Times(AtLeast(1u))
8687 .WillOnce(Invoke([&]() {
8688 EXPECT_EQ(2u, new_writer.packets_write_attempts());
8689 EXPECT_EQ(1u, new_writer.path_response_frames().size());
8690 EXPECT_EQ(1u, new_writer.padding_frames().size());
8691 EXPECT_EQ(kNewSelfAddress.host(),
8692 new_writer.last_write_source_address());
8693 }));
8694 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8695 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8696 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8697 probing_packet->encrypted_length),
8698 clock_.Now()));
8699 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8700
8701 QuicSocketAddress kNewerSelfAddress(QuicIpAddress::Loopback6(),
8702 /*port=*/34567);
8703 // Receiving a PATH_CHALLENGE on an unknown socket should be ignored.
8704 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
8705 ProcessReceivedPacket(kNewerSelfAddress, kPeerAddress, *received);
8706}
8707
8708TEST_P(QuicConnectionTest,
8709 RestartPathDegradingDetectionAfterMigrationWithProbe) {
8710 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8711 PathProbeTestInit(Perspective::IS_CLIENT);
8712
8713 // Send data and verify the path degrading detection is set.
8714 const char data[] = "data";
8715 size_t data_size = strlen(data);
8716 QuicStreamOffset offset = 0;
8717 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8718 offset += data_size;
8719
8720 // Verify the path degrading detection is in progress.
8721 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8722 EXPECT_FALSE(connection_.IsPathDegrading());
8723 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
8724
8725 // Simulate the firing of path degrading.
8726 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
8727 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
8728 connection_.PathDegradingTimeout();
8729 EXPECT_TRUE(connection_.IsPathDegrading());
8730 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8731
8732 if (!GetParam().version.HasIetfQuicFrames()) {
8733 // Simulate path degrading handling by sending a probe on an alternet path.
8734 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8735 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
8736 connection_.SendConnectivityProbingPacket(&probing_writer,
8737 connection_.peer_address());
8738 // Verify that path degrading detection is not reset.
8739 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8740
8741 // Simulate successful path degrading handling by receiving probe response.
8742 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
8743
8744 EXPECT_CALL(visitor_,
8745 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
8746 .Times(1);
8747 const QuicSocketAddress kNewSelfAddress =
8748 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8749
8750 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8751 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8752 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8753 probing_packet->encrypted_length),
8754 clock_.Now()));
8755 uint64_t num_probing_received =
8756 connection_.GetStats().num_connectivity_probing_received;
8757 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8758
8759 EXPECT_EQ(num_probing_received + 1,
8760 connection_.GetStats().num_connectivity_probing_received);
8761 EXPECT_EQ(kPeerAddress, connection_.peer_address());
8762 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8763 EXPECT_TRUE(connection_.IsPathDegrading());
8764 }
8765
8766 // Verify new path degrading detection is activated.
8767 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
8768 connection_.OnSuccessfulMigration(/*is_port_change*/ true);
8769 EXPECT_FALSE(connection_.IsPathDegrading());
8770 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8771}
8772
8773TEST_P(QuicConnectionTest, ClientsResetCwndAfterConnectionMigration) {
8774 if (!GetParam().version.HasIetfQuicFrames()) {
8775 return;
8776 }
8777 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8778 PathProbeTestInit(Perspective::IS_CLIENT);
8779 EXPECT_EQ(kSelfAddress, connection_.self_address());
8780
8781 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
8782 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
8783 rtt_stats->set_initial_rtt(default_init_rtt * 2);
8784 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
8785
fayang339f0c82022-04-30 14:20:02 -07008786 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
8787 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008788 const SendAlgorithmInterface* send_algorithm = manager_->GetSendAlgorithm();
8789
8790 // Migrate to a new address with different IP.
8791 const QuicSocketAddress kNewSelfAddress =
8792 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
8793 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8794 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
8795 &new_writer, false);
8796 EXPECT_EQ(default_init_rtt, manager_->GetRttStats()->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07008797 EXPECT_EQ(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008798 EXPECT_NE(send_algorithm, manager_->GetSendAlgorithm());
8799}
8800
8801// Regression test for b/110259444
8802TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8803 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8804 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8805 writer_->SetWriteBlocked();
8806
8807 ProcessPacket(1);
8808 // Verify ack alarm is set.
8809 EXPECT_TRUE(connection_.HasPendingAcks());
8810 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8811 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8812 connection_.GetAckAlarm()->Fire();
8813
8814 writer_->SetWritable();
8815 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8816 ProcessPacket(2);
8817 // Verify ack alarm is not set.
8818 EXPECT_FALSE(connection_.HasPendingAcks());
8819}
8820
8821TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8822 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8823 writer_->set_supports_release_time(true);
8824 QuicConfig config;
8825 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8826 connection_.SetFromConfig(config);
8827 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8828
8829 QuicTagVector connection_options;
8830 connection_options.push_back(kNPCO);
8831 config.SetConnectionOptionsToSend(connection_options);
8832 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8833 connection_.SetFromConfig(config);
8834 // Verify pacing offload is disabled.
8835 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8836}
8837
8838// Regression test for b/110259444
8839// Get a path response without having issued a path challenge...
8840TEST_P(QuicConnectionTest, OrphanPathResponse) {
8841 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8842
8843 QuicPathResponseFrame frame(99, data);
8844 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8845 // If PATH_RESPONSE was accepted (payload matches the payload saved
8846 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8847 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8848 // Since this PATH_RESPONSE does not match, current_packet_content_
8849 // must not be FIRST_FRAME_IS_PING.
8850 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8851 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8852}
8853
8854// Regression test for b/120791670
8855TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
8856 // This test mimics a problematic scenario where a QUIC connection using a
8857 // modern version received a Q043 packet and processed it incorrectly.
8858 // We can remove this test once Q043 is deprecated.
8859 if (!version().HasIetfInvariantHeader()) {
8860 return;
8861 }
8862 set_perspective(Perspective::IS_SERVER);
8863 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8864 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8865 } else {
8866 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8867 }
8868 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
8869 ENCRYPTION_INITIAL);
8870
8871 // Let connection process a Google QUIC packet.
8872 peer_framer_.set_version_for_tests(ParsedQuicVersion::Q043());
8873 std::unique_ptr<QuicPacket> packet(
8874 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
8875 char buffer[kMaxOutgoingPacketSize];
8876 size_t encrypted_length =
8877 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8878 *packet, buffer, kMaxOutgoingPacketSize);
8879 // Make sure no stream frame is processed.
8880 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8881 connection_.ProcessUdpPacket(
8882 kSelfAddress, kPeerAddress,
8883 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8884
8885 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8886 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8887}
8888
8889TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
8890 if (!VersionHasIetfQuicFrames(version().transport_version)) {
8891 return;
8892 }
8893 // Set first_sending_packet_number to be 0 to allow successfully processing
8894 // acks which ack packet number 0.
8895 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8896 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8897
8898 ProcessPacket(0);
8899 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8900 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8901
8902 ProcessPacket(1);
8903 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8904 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8905
8906 ProcessPacket(2);
8907 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8908 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8909}
8910
8911TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8912 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8913 return;
8914 }
Bence Békybac04052022-04-07 15:44:29 -04008915 connection_.SendCryptoStreamData();
8916 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8917 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8918 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8919 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8920 QuicAckFrame frame1 = InitAckFrame(1);
8921 // Received ACK for packet 1.
8922 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8923
8924 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8925 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8926 NO_FIN);
8927 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8928 NO_FIN);
8929 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8930 8, NO_FIN);
8931 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8932 12, FIN);
8933 // Received ACK for packets 2, 4, 5.
8934 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8935 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8936 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8937 QuicAckFrame frame2 =
8938 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8939 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8940 // Make sure although the same packet number is used, but they are in
8941 // different packet number spaces.
8942 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8943}
8944
8945TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8946 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8947 return;
8948 }
Bence Békybac04052022-04-07 15:44:29 -04008949 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8950 std::make_unique<TaggingEncrypter>(0x01));
8951
8952 connection_.SendCryptoStreamData();
8953 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8954 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8955 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8956 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8957 QuicAckFrame frame1 = InitAckFrame(1);
8958 // Received ACK for packet 1.
8959 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8960
8961 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8962 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8963 NO_FIN);
8964 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8965 NO_FIN);
8966
8967 // Received ACK for packets 2 and 3 in wrong packet number space.
8968 QuicAckFrame invalid_ack =
8969 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
8970 EXPECT_CALL(visitor_,
8971 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
8972 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
8973 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
8974 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
8975}
8976
8977TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8978 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8979 return;
8980 }
8981 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8982 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8983 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8984 }
8985 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04008986 // Receives packet 1000 in initial data.
8987 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
8988 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08008989 peer_framer_.SetEncrypter(
8990 ENCRYPTION_FORWARD_SECURE,
8991 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
8992 SetDecrypter(
8993 ENCRYPTION_FORWARD_SECURE,
8994 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04008995 // Receives packet 1000 in application data.
8996 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
8997 EXPECT_TRUE(connection_.HasPendingAcks());
8998 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8999 0, NO_FIN);
9000 // Verify application data ACK gets bundled with outgoing data.
9001 EXPECT_EQ(2u, writer_->frame_count());
9002 // Make sure ACK alarm is still set because initial data is not ACKed.
9003 EXPECT_TRUE(connection_.HasPendingAcks());
9004 // Receive packet 1001 in application data.
9005 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_FORWARD_SECURE);
9006 clock_.AdvanceTime(DefaultRetransmissionTime());
9007 // Simulates ACK alarm fires and verify two ACKs are flushed.
9008 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
martinduke9e0811c2022-12-08 20:35:57 -08009009 connection_.SetEncrypter(
9010 ENCRYPTION_FORWARD_SECURE,
9011 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -04009012 connection_.GetAckAlarm()->Fire();
9013 EXPECT_FALSE(connection_.HasPendingAcks());
9014 // Receives more packets in application data.
9015 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_FORWARD_SECURE);
9016 EXPECT_TRUE(connection_.HasPendingAcks());
9017
9018 // Verify zero rtt and forward secure packets get acked in the same packet.
9019 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9020 ProcessDataPacket(1003);
9021 EXPECT_FALSE(connection_.HasPendingAcks());
9022}
9023
9024TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9025 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9026 return;
9027 }
9028 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9029 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9030 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9031 }
9032 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -04009033 // Receives packet 1000 in initial data.
9034 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9035 EXPECT_TRUE(connection_.HasPendingAcks());
martinduke9e0811c2022-12-08 20:35:57 -08009036 peer_framer_.SetEncrypter(
9037 ENCRYPTION_ZERO_RTT,
9038 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009039 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -08009040 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -04009041 // Receives packet 1000 in application data.
9042 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9043 EXPECT_TRUE(connection_.HasPendingAcks());
9044
9045 writer_->SetWriteBlocked();
9046 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9047 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9048 // blocked.
9049 clock_.AdvanceTime(DefaultDelayedAckTime());
9050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9051 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9052 std::make_unique<TaggingEncrypter>(0x02));
9053 connection_.GetAckAlarm()->Fire();
9054 // Verify ACK alarm is not set.
9055 EXPECT_FALSE(connection_.HasPendingAcks());
9056
9057 writer_->SetWritable();
9058 // Verify 2 ACKs are sent when connection gets unblocked.
9059 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9060 connection_.OnCanWrite();
9061 EXPECT_FALSE(connection_.HasPendingAcks());
9062}
9063
9064// Make sure a packet received with the right client connection ID is processed.
9065TEST_P(QuicConnectionTest, ValidClientConnectionId) {
9066 if (!framer_.version().SupportsClientConnectionIds()) {
9067 return;
9068 }
9069 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9070 SetClientConnectionId(TestConnectionId(0x33));
9071 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9072 header.destination_connection_id = TestConnectionId(0x33);
9073 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9074 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9075 QuicFrames frames;
9076 QuicPingFrame ping_frame;
9077 QuicPaddingFrame padding_frame;
9078 frames.push_back(QuicFrame(ping_frame));
9079 frames.push_back(QuicFrame(padding_frame));
9080 std::unique_ptr<QuicPacket> packet =
9081 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9082 char buffer[kMaxOutgoingPacketSize];
9083 size_t encrypted_length = peer_framer_.EncryptPayload(
9084 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9085 kMaxOutgoingPacketSize);
9086 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9087 false);
9088 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9089 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9090 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9091}
9092
9093// Make sure a packet received with a different client connection ID is dropped.
9094TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
9095 if (!framer_.version().SupportsClientConnectionIds()) {
9096 return;
9097 }
9098 SetClientConnectionId(TestConnectionId(0x33));
9099 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9100 header.destination_connection_id = TestConnectionId(0xbad);
9101 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9102 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9103 QuicFrames frames;
9104 QuicPingFrame ping_frame;
9105 QuicPaddingFrame padding_frame;
9106 frames.push_back(QuicFrame(ping_frame));
9107 frames.push_back(QuicFrame(padding_frame));
9108 std::unique_ptr<QuicPacket> packet =
9109 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9110 char buffer[kMaxOutgoingPacketSize];
9111 size_t encrypted_length = peer_framer_.EncryptPayload(
9112 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9113 kMaxOutgoingPacketSize);
9114 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9115 false);
9116 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9117 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9118 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9119}
9120
9121// Make sure the first packet received with a different client connection ID on
9122// the server is processed and it changes the client connection ID.
9123TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
9124 if (!framer_.version().SupportsClientConnectionIds()) {
9125 return;
9126 }
9127 set_perspective(Perspective::IS_SERVER);
9128 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9129 header.source_connection_id = TestConnectionId(0x33);
9130 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9131 QuicFrames frames;
9132 QuicPingFrame ping_frame;
9133 QuicPaddingFrame padding_frame;
9134 frames.push_back(QuicFrame(ping_frame));
9135 frames.push_back(QuicFrame(padding_frame));
9136 std::unique_ptr<QuicPacket> packet =
9137 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9138 char buffer[kMaxOutgoingPacketSize];
9139 size_t encrypted_length =
9140 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9141 *packet, buffer, kMaxOutgoingPacketSize);
9142 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9143 false);
9144 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9145 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9146 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9147 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9148}
9149void QuicConnectionTest::TestReplaceConnectionIdFromInitial() {
9150 if (!framer_.version().AllowsVariableLengthConnectionIds()) {
9151 return;
9152 }
9153 // We start with a known connection ID.
9154 EXPECT_TRUE(connection_.connected());
9155 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9156 EXPECT_NE(TestConnectionId(0x33), connection_.connection_id());
9157 // Receiving an initial can replace the connection ID once.
9158 {
9159 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9160 header.source_connection_id = TestConnectionId(0x33);
9161 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9162 QuicFrames frames;
9163 QuicPingFrame ping_frame;
9164 QuicPaddingFrame padding_frame;
9165 frames.push_back(QuicFrame(ping_frame));
9166 frames.push_back(QuicFrame(padding_frame));
9167 std::unique_ptr<QuicPacket> packet =
9168 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9169 char buffer[kMaxOutgoingPacketSize];
9170 size_t encrypted_length =
9171 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9172 *packet, buffer, kMaxOutgoingPacketSize);
9173 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9174 false);
9175 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9176 }
9177 EXPECT_TRUE(connection_.connected());
9178 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9179 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9180 // Trying to replace the connection ID a second time drops the packet.
9181 {
9182 QuicPacketHeader header = ConstructPacketHeader(2, ENCRYPTION_INITIAL);
9183 header.source_connection_id = TestConnectionId(0x66);
9184 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9185 QuicFrames frames;
9186 QuicPingFrame ping_frame;
9187 QuicPaddingFrame padding_frame;
9188 frames.push_back(QuicFrame(ping_frame));
9189 frames.push_back(QuicFrame(padding_frame));
9190 std::unique_ptr<QuicPacket> packet =
9191 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9192 char buffer[kMaxOutgoingPacketSize];
9193 size_t encrypted_length =
9194 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9195 *packet, buffer, kMaxOutgoingPacketSize);
9196 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9197 false);
9198 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9199 }
9200 EXPECT_TRUE(connection_.connected());
9201 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9202 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9203}
9204
9205TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromInitial) {
9206 TestReplaceConnectionIdFromInitial();
9207}
9208
9209TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromRetryAndInitial) {
9210 // First make the connection process a RETRY and replace the server connection
9211 // ID a first time.
9212 TestClientRetryHandling(/*invalid_retry_tag=*/false,
9213 /*missing_original_id_in_config=*/false,
9214 /*wrong_original_id_in_config=*/false,
9215 /*missing_retry_id_in_config=*/false,
9216 /*wrong_retry_id_in_config=*/false);
9217 // Reset the test framer to use the right connection ID.
9218 peer_framer_.SetInitialObfuscators(connection_.connection_id());
9219 // Now process an INITIAL and replace the server connection ID a second time.
9220 TestReplaceConnectionIdFromInitial();
9221}
9222
9223// Regression test for b/134416344.
9224TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9225 // This test mimics a scenario where a connection processes 2 packets and the
9226 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9227 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9228 // because connection is disconnected.
9229 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9230 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9231 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
9232 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
9233 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
9234 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9235 NO_IETF_QUIC_ERROR, "",
9236 /*transport_close_frame_type=*/0));
9237
9238 // Received 2 packets.
9239 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9240 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9241 } else {
9242 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9243 }
9244 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
9245 ENCRYPTION_INITIAL);
9246 EXPECT_TRUE(connection_.HasPendingAcks());
9247 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
9248 kSelfAddress, kPeerAddress,
9249 ENCRYPTION_INITIAL);
9250 // Verify ack alarm is not set.
9251 EXPECT_FALSE(connection_.HasPendingAcks());
9252}
9253
9254// Verify that a packet containing three coalesced packets is parsed correctly.
9255TEST_P(QuicConnectionTest, CoalescedPacket) {
9256 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9257 // Coalesced packets can only be encoded using long header lengths.
9258 return;
9259 }
9260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9261 EXPECT_TRUE(connection_.connected());
9262 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9263 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9264 } else {
9265 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9266 }
9267
9268 uint64_t packet_numbers[3] = {1, 2, 3};
9269 EncryptionLevel encryption_levels[3] = {
9270 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9271 char buffer[kMaxOutgoingPacketSize] = {};
9272 size_t total_encrypted_length = 0;
9273 for (int i = 0; i < 3; i++) {
9274 QuicPacketHeader header =
9275 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9276 QuicFrames frames;
9277 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9278 frames.push_back(QuicFrame(&crypto_frame_));
9279 } else {
9280 frames.push_back(QuicFrame(frame1_));
9281 }
9282 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9283 peer_creator_.set_encryption_level(encryption_levels[i]);
9284 size_t encrypted_length = peer_framer_.EncryptPayload(
9285 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9286 buffer + total_encrypted_length,
9287 sizeof(buffer) - total_encrypted_length);
9288 EXPECT_GT(encrypted_length, 0u);
9289 total_encrypted_length += encrypted_length;
9290 }
9291 connection_.ProcessUdpPacket(
9292 kSelfAddress, kPeerAddress,
9293 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9294 if (connection_.GetSendAlarm()->IsSet()) {
9295 connection_.GetSendAlarm()->Fire();
9296 }
9297
9298 EXPECT_TRUE(connection_.connected());
9299}
9300
9301// Regression test for crbug.com/992831.
9302TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9303 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9304 // Coalesced packets can only be encoded using long header lengths.
9305 return;
9306 }
9307 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9308 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9309 return;
9310 }
9311 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9312 EXPECT_TRUE(connection_.connected());
9313 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9314 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9315 .Times(3)
9316 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9317 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009318 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009319 });
9320 } else {
9321 EXPECT_CALL(visitor_, OnStreamFrame(_))
9322 .Times(3)
9323 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9324 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009325 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009326 });
9327 }
9328
9329 uint64_t packet_numbers[3] = {1, 2, 3};
9330 EncryptionLevel encryption_levels[3] = {
9331 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9332 char buffer[kMaxOutgoingPacketSize] = {};
9333 size_t total_encrypted_length = 0;
9334 for (int i = 0; i < 3; i++) {
9335 QuicPacketHeader header =
9336 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9337 QuicFrames frames;
9338 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9339 frames.push_back(QuicFrame(&crypto_frame_));
9340 } else {
9341 frames.push_back(QuicFrame(frame1_));
9342 }
9343 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9344 peer_creator_.set_encryption_level(encryption_levels[i]);
9345 size_t encrypted_length = peer_framer_.EncryptPayload(
9346 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9347 buffer + total_encrypted_length,
9348 sizeof(buffer) - total_encrypted_length);
9349 EXPECT_GT(encrypted_length, 0u);
9350 total_encrypted_length += encrypted_length;
9351 }
9352 connection_.ProcessUdpPacket(
9353 kSelfAddress, kPeerAddress,
9354 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9355 if (connection_.GetSendAlarm()->IsSet()) {
9356 connection_.GetSendAlarm()->Fire();
9357 }
9358
9359 EXPECT_TRUE(connection_.connected());
9360
9361 SendAckPacketToPeer();
9362}
9363
9364// Regresstion test for b/138962304.
9365TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
9366 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9367
9368 QuicStreamId stream_id = 2;
9369 QuicPacketNumber last_data_packet;
9370 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9371 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9372
9373 // Writer gets blocked.
9374 writer_->SetWriteBlocked();
9375
9376 // Cancel the stream.
9377 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9378 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9379 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9380 .WillRepeatedly(
9381 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
9382 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9383
9384 // Retransmission timer fires in RTO mode.
9385 connection_.GetRetransmissionAlarm()->Fire();
9386 // Verify no packets get flushed when writer is blocked.
9387 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9388}
9389
9390// Regresstion test for b/138962304.
fayang339f0c82022-04-30 14:20:02 -07009391TEST_P(QuicConnectionTest, PtoAndWriteBlocked) {
Bence Békybac04052022-04-07 15:44:29 -04009392 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
Bence Békybac04052022-04-07 15:44:29 -04009393
9394 QuicStreamId stream_id = 2;
9395 QuicPacketNumber last_data_packet;
9396 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9397 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9398 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9399
9400 // Writer gets blocked.
9401 writer_->SetWriteBlocked();
9402
9403 // Cancel stream 2.
9404 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9405 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9406 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9407
9408 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9409 // Retransmission timer fires in TLP mode.
9410 connection_.GetRetransmissionAlarm()->Fire();
9411 // Verify one packets is forced flushed when writer is blocked.
9412 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9413}
9414
Bence Békybac04052022-04-07 15:44:29 -04009415TEST_P(QuicConnectionTest, ProbeTimeout) {
9416 QuicConfig config;
9417 QuicTagVector connection_options;
9418 connection_options.push_back(k2PTO);
9419 config.SetConnectionOptionsToSend(connection_options);
9420 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9421 connection_.SetFromConfig(config);
9422 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9423
9424 QuicStreamId stream_id = 2;
9425 QuicPacketNumber last_packet;
9426 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9427 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9428 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9429
9430 // Reset stream.
9431 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9432 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9433
9434 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9435 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9436 connection_.GetRetransmissionAlarm()->Fire();
9437 EXPECT_EQ(0u, writer_->stream_frames().size());
9438 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9439 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9440}
9441
9442TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
9443 QuicConfig config;
9444 QuicTagVector connection_options;
9445 connection_options.push_back(k1PTO);
9446 connection_options.push_back(k6PTO);
9447 config.SetConnectionOptionsToSend(connection_options);
9448 QuicConfigPeer::SetNegotiated(&config, true);
9449 if (connection_.version().UsesTls()) {
9450 QuicConfigPeer::SetReceivedOriginalConnectionId(
9451 &config, connection_.connection_id());
9452 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9453 &config, connection_.connection_id());
9454 }
9455 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9456 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009457 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9458 GetQuicReloadableFlag(
9459 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009460 EXPECT_CALL(visitor_, GetHandshakeState())
9461 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9462 }
9463 connection_.OnHandshakeComplete();
9464 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9465
9466 // Send stream data.
9467 SendStreamDataToPeer(
9468 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9469 0, FIN, nullptr);
9470
9471 // Fire the retransmission alarm 5 times.
9472 for (int i = 0; i < 5; ++i) {
9473 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9474 connection_.GetRetransmissionAlarm()->Fire();
9475 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9476 EXPECT_TRUE(connection_.connected());
9477 }
9478 EXPECT_CALL(visitor_, OnPathDegrading());
9479 connection_.PathDegradingTimeout();
9480
Bence Békybac04052022-04-07 15:44:29 -04009481 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9482 // Closes connection on 6th PTO.
9483 // May send multiple connecction close packets with multiple PN spaces.
9484 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9485 EXPECT_CALL(visitor_,
9486 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9487 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9488 connection_.GetBlackholeDetectorAlarm()->Fire();
9489 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9490 EXPECT_FALSE(connection_.connected());
9491 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9492}
9493
9494TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
9495 QuicConfig config;
9496 QuicTagVector connection_options;
9497 connection_options.push_back(k2PTO);
9498 connection_options.push_back(k7PTO);
9499 config.SetConnectionOptionsToSend(connection_options);
9500 QuicConfigPeer::SetNegotiated(&config, true);
9501 if (connection_.version().UsesTls()) {
9502 QuicConfigPeer::SetReceivedOriginalConnectionId(
9503 &config, connection_.connection_id());
9504 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9505 &config, connection_.connection_id());
9506 }
9507 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9508 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009509 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9510 GetQuicReloadableFlag(
9511 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009512 EXPECT_CALL(visitor_, GetHandshakeState())
9513 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9514 }
9515 connection_.OnHandshakeComplete();
9516 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9517
9518 // Send stream data.
9519 SendStreamDataToPeer(
9520 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9521 0, FIN, nullptr);
9522
9523 // Fire the retransmission alarm 6 times.
9524 for (int i = 0; i < 6; ++i) {
9525 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9526 connection_.GetRetransmissionAlarm()->Fire();
9527 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9528 EXPECT_TRUE(connection_.connected());
9529 }
9530 EXPECT_CALL(visitor_, OnPathDegrading());
9531 connection_.PathDegradingTimeout();
9532
Bence Békybac04052022-04-07 15:44:29 -04009533 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9534 // Closes connection on 7th PTO.
9535 EXPECT_CALL(visitor_,
9536 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9538 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9539 connection_.GetBlackholeDetectorAlarm()->Fire();
9540 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9541 EXPECT_FALSE(connection_.connected());
9542 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9543}
9544
9545TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
9546 QuicConfig config;
9547 QuicTagVector connection_options;
9548 connection_options.push_back(k2PTO);
9549 connection_options.push_back(k8PTO);
9550 QuicConfigPeer::SetNegotiated(&config, true);
9551 if (connection_.version().UsesTls()) {
9552 QuicConfigPeer::SetReceivedOriginalConnectionId(
9553 &config, connection_.connection_id());
9554 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9555 &config, connection_.connection_id());
9556 }
9557 config.SetConnectionOptionsToSend(connection_options);
9558 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9559 connection_.SetFromConfig(config);
fayang59e518a2022-11-29 11:16:45 -08009560 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
9561 GetQuicReloadableFlag(
9562 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -04009563 EXPECT_CALL(visitor_, GetHandshakeState())
9564 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9565 }
9566 connection_.OnHandshakeComplete();
9567 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9568
9569 // Send stream data.
9570 SendStreamDataToPeer(
9571 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9572 0, FIN, nullptr);
9573
9574 // Fire the retransmission alarm 7 times.
9575 for (int i = 0; i < 7; ++i) {
9576 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9577 connection_.GetRetransmissionAlarm()->Fire();
9578 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9579 EXPECT_TRUE(connection_.connected());
9580 }
9581 EXPECT_CALL(visitor_, OnPathDegrading());
9582 connection_.PathDegradingTimeout();
9583
Bence Békybac04052022-04-07 15:44:29 -04009584 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9585 // Closes connection on 8th PTO.
9586 EXPECT_CALL(visitor_,
9587 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9588 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9589 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9590 connection_.GetBlackholeDetectorAlarm()->Fire();
9591 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9592 EXPECT_FALSE(connection_.connected());
9593 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9594}
9595
9596TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9597 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9598 return;
9599 }
9600 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9601 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9602
9603 // Send CHLO.
9604 connection_.SendCryptoStreamData();
9605 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9606
9607 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9608 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9609 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9610 QuicAckFrame frame1 = InitAckFrame(1);
9611 // Received ACK for packet 1.
9612 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9613
9614 // Verify retransmission alarm is still set because handshake is not
9615 // confirmed although there is nothing in flight.
9616 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9617 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9618 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9619
9620 // PTO fires, verify a PING packet gets sent because there is no data to send.
9621 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9622 connection_.GetRetransmissionAlarm()->Fire();
9623 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9624 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
9625 EXPECT_EQ(1u, writer_->ping_frames().size());
9626}
9627
9628TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009629 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009630 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009631 return;
9632 }
9633 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9634
9635 set_perspective(Perspective::IS_SERVER);
9636 // Verify no data can be sent at the beginning because bytes received is 0.
9637 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9638 connection_.SendCryptoDataWithString("foo", 0);
9639 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9640 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9641 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9642
9643 // Receives packet 1.
9644 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9645 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9646
9647 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -07009648 GetQuicFlag(quic_anti_amplification_factor);
Bence Békybac04052022-04-07 15:44:29 -04009649 // Verify now packets can be sent.
9650 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9651 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9652 connection_.SendCryptoDataWithString("foo", i * 3);
9653 // Verify retransmission alarm is not set if throttled by anti-amplification
9654 // limit.
9655 EXPECT_EQ(i != anti_amplification_factor - 1,
9656 connection_.GetRetransmissionAlarm()->IsSet());
9657 }
9658 // Verify server is throttled by anti-amplification limit.
9659 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9660 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9661
9662 // Receives packet 2.
9663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9664 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9665 // Verify more packets can be sent.
9666 for (size_t i = anti_amplification_factor + 1;
9667 i < anti_amplification_factor * 2; ++i) {
9668 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9669 connection_.SendCryptoDataWithString("foo", i * 3);
9670 }
9671 // Verify server is throttled by anti-amplification limit.
9672 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9673 connection_.SendCryptoDataWithString("foo",
9674 2 * anti_amplification_factor * 3);
9675
9676 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9677 ProcessPacket(3);
9678 // Verify anti-amplification limit is gone after address validation.
9679 for (size_t i = 0; i < 100; ++i) {
9680 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9681 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9682 }
9683}
9684
9685TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009686 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009687 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009688 return;
9689 }
9690 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9691
9692 set_perspective(Perspective::IS_SERVER);
9693 QuicConfig config;
9694 QuicTagVector connection_options;
9695 connection_options.push_back(k3AFF);
9696 config.SetInitialReceivedConnectionOptions(connection_options);
9697 if (connection_.version().UsesTls()) {
9698 QuicConfigPeer::SetReceivedOriginalConnectionId(
9699 &config, connection_.connection_id());
9700 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9701 QuicConnectionId());
9702 }
9703 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9704 connection_.SetFromConfig(config);
9705
9706 // Verify no data can be sent at the beginning because bytes received is 0.
9707 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9708 connection_.SendCryptoDataWithString("foo", 0);
9709 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9710 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9711 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9712
9713 // Receives packet 1.
9714 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9715 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9716
9717 const size_t anti_amplification_factor = 3;
9718 // Verify now packets can be sent.
9719 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9720 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9721 connection_.SendCryptoDataWithString("foo", i * 3);
9722 // Verify retransmission alarm is not set if throttled by anti-amplification
9723 // limit.
9724 EXPECT_EQ(i != anti_amplification_factor - 1,
9725 connection_.GetRetransmissionAlarm()->IsSet());
9726 }
9727 // Verify server is throttled by anti-amplification limit.
9728 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9729 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9730
9731 // Receives packet 2.
9732 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9733 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9734 // Verify more packets can be sent.
9735 for (size_t i = anti_amplification_factor + 1;
9736 i < anti_amplification_factor * 2; ++i) {
9737 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9738 connection_.SendCryptoDataWithString("foo", i * 3);
9739 }
9740 // Verify server is throttled by anti-amplification limit.
9741 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9742 connection_.SendCryptoDataWithString("foo",
9743 2 * anti_amplification_factor * 3);
9744
9745 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9746 ProcessPacket(3);
9747 // Verify anti-amplification limit is gone after address validation.
9748 for (size_t i = 0; i < 100; ++i) {
9749 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9750 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9751 }
9752}
9753
9754TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009755 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009756 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009757 return;
9758 }
9759 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9760
9761 set_perspective(Perspective::IS_SERVER);
9762 QuicConfig config;
9763 QuicTagVector connection_options;
9764 connection_options.push_back(k10AF);
9765 config.SetInitialReceivedConnectionOptions(connection_options);
9766 if (connection_.version().UsesTls()) {
9767 QuicConfigPeer::SetReceivedOriginalConnectionId(
9768 &config, connection_.connection_id());
9769 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9770 QuicConnectionId());
9771 }
9772 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9773 connection_.SetFromConfig(config);
9774
9775 // Verify no data can be sent at the beginning because bytes received is 0.
9776 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9777 connection_.SendCryptoDataWithString("foo", 0);
9778 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9779 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9780 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9781
9782 // Receives packet 1.
9783 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9784 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9785
9786 const size_t anti_amplification_factor = 10;
9787 // Verify now packets can be sent.
9788 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9789 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9790 connection_.SendCryptoDataWithString("foo", i * 3);
9791 // Verify retransmission alarm is not set if throttled by anti-amplification
9792 // limit.
9793 EXPECT_EQ(i != anti_amplification_factor - 1,
9794 connection_.GetRetransmissionAlarm()->IsSet());
9795 }
9796 // Verify server is throttled by anti-amplification limit.
9797 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9798 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9799
9800 // Receives packet 2.
9801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9802 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9803 // Verify more packets can be sent.
9804 for (size_t i = anti_amplification_factor + 1;
9805 i < anti_amplification_factor * 2; ++i) {
9806 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9807 connection_.SendCryptoDataWithString("foo", i * 3);
9808 }
9809 // Verify server is throttled by anti-amplification limit.
9810 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9811 connection_.SendCryptoDataWithString("foo",
9812 2 * anti_amplification_factor * 3);
9813
9814 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9815 ProcessPacket(3);
9816 // Verify anti-amplification limit is gone after address validation.
9817 for (size_t i = 0; i < 100; ++i) {
9818 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9819 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9820 }
9821}
9822
9823TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
9824 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9825 return;
9826 }
9827 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9828 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
9829 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -04009830 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9831 // Receives packet 1.
9832 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -08009833 connection_.SetEncrypter(
9834 ENCRYPTION_HANDSHAKE,
9835 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -04009836 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9837 EXPECT_TRUE(connection_.HasPendingAcks());
9838 // Send response in different encryption level and cause amplification factor
9839 // throttled.
9840 size_t i = 0;
9841 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
9842 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
9843 ENCRYPTION_HANDSHAKE);
9844 ++i;
9845 }
9846 // Verify ACK is still pending.
9847 EXPECT_TRUE(connection_.HasPendingAcks());
9848
9849 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
9850 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
9851 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9852 connection_.GetAckAlarm()->Fire();
9853 // Verify ACK alarm is cancelled.
9854 EXPECT_FALSE(connection_.HasPendingAcks());
9855
9856 // Receives packet 2 and verify ACK gets flushed.
9857 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9858 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9859 EXPECT_FALSE(writer_->ack_frames().empty());
9860}
9861
9862TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9863 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9864 // Test relevent only for IETF QUIC.
9865 return;
9866 }
9867 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9868 // Use the (unknown) frame type of 9999 to avoid triggering any logic
9869 // which might be associated with the processing of a known frame type.
9870 const uint64_t kTransportCloseFrameType = 9999u;
9871 QuicFramerPeer::set_current_received_frame_type(
9872 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9873 // Do a transport connection close
9874 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9875 connection_.CloseConnection(
9876 kQuicErrorCode, "Some random error message",
9877 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9878 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9879 writer_->connection_close_frames();
9880 ASSERT_EQ(1u, connection_close_frames.size());
9881 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9882 connection_close_frames[0].close_type);
9883 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
9884 EXPECT_EQ(kTransportCloseFrameType,
9885 connection_close_frames[0].transport_close_frame_type);
9886}
9887
Bence Békybac04052022-04-07 15:44:29 -04009888TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
9889 QuicConfig config;
9890 QuicTagVector connection_options;
9891 connection_options.push_back(k1PTO);
9892 connection_options.push_back(kPTOS);
9893 config.SetConnectionOptionsToSend(connection_options);
9894 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9895 connection_.SetFromConfig(config);
9896 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9897
9898 QuicStreamId stream_id = 2;
9899 QuicPacketNumber last_packet;
9900 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9901 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9902 EXPECT_EQ(QuicPacketNumber(2), last_packet);
9903 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9904
9905 // Fire PTO and verify the PTO retransmission skips one packet number.
9906 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9907 connection_.GetRetransmissionAlarm()->Fire();
9908 EXPECT_EQ(1u, writer_->stream_frames().size());
9909 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9910 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9911}
9912
9913TEST_P(QuicConnectionTest, SendCoalescedPackets) {
9914 if (!connection_.version().CanSendCoalescedPackets()) {
9915 return;
9916 }
9917 MockQuicConnectionDebugVisitor debug_visitor;
9918 connection_.set_debug_visitor(&debug_visitor);
9919 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(3);
9920 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
9921 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
9922 {
9923 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04009924 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9925 connection_.SendCryptoDataWithString("foo", 0);
9926 // Verify this packet is on hold.
9927 EXPECT_EQ(0u, writer_->packets_write_attempts());
9928
9929 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9930 std::make_unique<TaggingEncrypter>(0x02));
9931 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9932 connection_.SendCryptoDataWithString("bar", 3);
9933 EXPECT_EQ(0u, writer_->packets_write_attempts());
9934
9935 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9936 std::make_unique<TaggingEncrypter>(0x03));
9937 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9938 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
9939 }
9940 // Verify all 3 packets are coalesced in the same UDP datagram.
9941 EXPECT_EQ(1u, writer_->packets_write_attempts());
9942 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
9943 // Verify the packet is padded to full.
9944 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
9945
9946 // Verify packet process.
9947 EXPECT_EQ(1u, writer_->crypto_frames().size());
9948 EXPECT_EQ(0u, writer_->stream_frames().size());
9949 // Verify there is coalesced packet.
9950 EXPECT_NE(nullptr, writer_->coalesced_packet());
9951}
9952
9953TEST_P(QuicConnectionTest, FailToCoalescePacket) {
9954 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
9955 if (!IsDefaultTestConfiguration() ||
fayang161ce6e2022-07-01 18:02:11 -07009956 !connection_.version().CanSendCoalescedPackets() ||
birenroyef686222022-09-12 11:34:34 -07009957 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009958 return;
9959 }
9960
9961 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -04009962
Bence Békybac04052022-04-07 15:44:29 -04009963 auto test_body = [&] {
vasilvvac2e30d2022-06-02 14:26:59 -07009964 EXPECT_CALL(visitor_,
9965 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
9966 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
Bence Békybac04052022-04-07 15:44:29 -04009967
vasilvvac2e30d2022-06-02 14:26:59 -07009968 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -04009969
vasilvvac2e30d2022-06-02 14:26:59 -07009970 {
9971 QuicConnection::ScopedPacketFlusher flusher(&connection_);
vasilvvac2e30d2022-06-02 14:26:59 -07009972 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9973 connection_.SendCryptoDataWithString("foo", 0);
9974 // Verify this packet is on hold.
9975 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -04009976
vasilvvac2e30d2022-06-02 14:26:59 -07009977 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9978 std::make_unique<TaggingEncrypter>(0x02));
9979 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9980 connection_.SendCryptoDataWithString("bar", 3);
9981 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -04009982
vasilvvac2e30d2022-06-02 14:26:59 -07009983 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9984 std::make_unique<TaggingEncrypter>(0x03));
9985 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9986 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
Bence Békybac04052022-04-07 15:44:29 -04009987
vasilvvac2e30d2022-06-02 14:26:59 -07009988 creator_->Flush();
9989
9990 auto& coalesced_packet =
9991 QuicConnectionPeer::GetCoalescedPacket(&connection_);
9992 QuicPacketLength coalesced_packet_max_length =
9993 coalesced_packet.max_packet_length();
9994 QuicCoalescedPacketPeer::SetMaxPacketLength(coalesced_packet,
9995 coalesced_packet.length());
9996
9997 // Make the coalescer's FORWARD_SECURE packet longer.
9998 *QuicCoalescedPacketPeer::GetMutableEncryptedBuffer(
9999 coalesced_packet, ENCRYPTION_FORWARD_SECURE) += "!!! TEST !!!";
10000
10001 QUIC_LOG(INFO) << "Reduced coalesced_packet_max_length from "
10002 << coalesced_packet_max_length << " to "
10003 << coalesced_packet.max_packet_length()
10004 << ", coalesced_packet.length:"
10005 << coalesced_packet.length()
10006 << ", coalesced_packet.packet_lengths:"
10007 << absl::StrJoin(coalesced_packet.packet_lengths(), ":");
10008 }
10009
10010 EXPECT_FALSE(connection_.connected());
10011 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10012 IsError(QUIC_FAILED_TO_SERIALIZE_PACKET));
10013 EXPECT_EQ(saved_connection_close_frame_.error_details,
10014 "Failed to serialize coalesced packet.");
Bence Békybac04052022-04-07 15:44:29 -040010015 };
10016
10017 EXPECT_QUIC_BUG(test_body(), "SerializeCoalescedPacket failed.");
Bence Békybac04052022-04-07 15:44:29 -040010018}
10019
Bence Békybac04052022-04-07 15:44:29 -040010020TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10021 if (!connection_.version().UsesTls()) {
10022 return;
10023 }
10024 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10025 QuicFrames frames;
10026 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10027 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10028 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10029}
10030
10031TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10032 if (!connection_.version().UsesTls()) {
10033 return;
10034 }
10035 set_perspective(Perspective::IS_SERVER);
10036 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10037 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
10038 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
10039 }
10040 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10041 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10042 QuicFrames frames;
10043 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10044 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10045 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10046 EXPECT_EQ(1, connection_close_frame_count_);
10047 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10048 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10049}
10050
10051TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10052 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10053 return;
10054 }
Bence Békybac04052022-04-07 15:44:29 -040010055 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010056 connection_.SetEncrypter(
10057 ENCRYPTION_HANDSHAKE,
10058 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010059 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10060 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10061 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080010062 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010063
10064 // Send application data.
10065 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10066 0, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010067 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010068 QuicTime retransmission_time =
10069 connection_.GetRetransmissionAlarm()->deadline();
10070 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10071
10072 // Retransmit handshake data.
10073 clock_.AdvanceTime(retransmission_time - clock_.Now());
10074 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _));
10075 connection_.GetRetransmissionAlarm()->Fire();
10076 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010077 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010078
10079 // Send application data.
10080 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10081 4, NO_FIN);
martinduke9e0811c2022-12-08 20:35:57 -080010082 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010083 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10084 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10085
10086 // Retransmit handshake data again.
10087 clock_.AdvanceTime(retransmission_time - clock_.Now());
10088 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _));
10089 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(8), _, _));
10090 connection_.GetRetransmissionAlarm()->Fire();
10091 // Verify 1-RTT packet gets coalesced with handshake retransmission.
martinduke9e0811c2022-12-08 20:35:57 -080010092 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010093
10094 // Discard handshake key.
10095 connection_.OnHandshakeComplete();
10096 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10097 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10098
10099 // Retransmit application data.
10100 clock_.AdvanceTime(retransmission_time - clock_.Now());
10101 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(11), _, _));
10102 connection_.GetRetransmissionAlarm()->Fire();
martinduke9e0811c2022-12-08 20:35:57 -080010103 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040010104}
10105
10106void QuicConnectionTest::TestClientRetryHandling(
10107 bool invalid_retry_tag, bool missing_original_id_in_config,
10108 bool wrong_original_id_in_config, bool missing_retry_id_in_config,
10109 bool wrong_retry_id_in_config) {
10110 if (invalid_retry_tag) {
10111 ASSERT_FALSE(missing_original_id_in_config);
10112 ASSERT_FALSE(wrong_original_id_in_config);
10113 ASSERT_FALSE(missing_retry_id_in_config);
10114 ASSERT_FALSE(wrong_retry_id_in_config);
10115 } else {
10116 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10117 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
10118 }
10119 if (!version().UsesTls()) {
10120 return;
10121 }
10122
10123 // These values come from draft-ietf-quic-v2 Appendix A.4.
10124 uint8_t retry_packet_rfcv2[] = {
martindukea2cb68a2022-12-12 17:24:39 -080010125 0xcf, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10126 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xc8, 0x64, 0x6c, 0xe8,
10127 0xbf, 0xe3, 0x39, 0x52, 0xd9, 0x55, 0x54, 0x36, 0x65, 0xdc, 0xc7, 0xb6};
Bence Békybac04052022-04-07 15:44:29 -040010128 // These values come from RFC9001 Appendix A.4.
10129 uint8_t retry_packet_rfcv1[] = {
10130 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10131 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba,
10132 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba};
10133 uint8_t retry_packet29[] = {
10134 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10135 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10136 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
10137
10138 uint8_t* retry_packet;
10139 size_t retry_packet_length;
martindukea2cb68a2022-12-12 17:24:39 -080010140 if (version() == ParsedQuicVersion::V2Draft08()) {
Bence Békybac04052022-04-07 15:44:29 -040010141 retry_packet = retry_packet_rfcv2;
10142 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv2);
10143 } else if (version() == ParsedQuicVersion::RFCv1()) {
10144 retry_packet = retry_packet_rfcv1;
10145 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv1);
10146 } else if (version() == ParsedQuicVersion::Draft29()) {
10147 retry_packet = retry_packet29;
10148 retry_packet_length = ABSL_ARRAYSIZE(retry_packet29);
10149 } else {
10150 // TODO(dschinazi) generate retry packets for all versions once we have
10151 // server-side support for generating these programmatically.
10152 return;
10153 }
10154
10155 uint8_t original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10156 0x3e, 0x51, 0x57, 0x08};
10157 uint8_t new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10158 0x2a, 0x42, 0x62, 0xb5};
10159 uint8_t retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10160
10161 QuicConnectionId original_connection_id(
10162 reinterpret_cast<char*>(original_connection_id_bytes),
10163 ABSL_ARRAYSIZE(original_connection_id_bytes));
10164 QuicConnectionId new_connection_id(
10165 reinterpret_cast<char*>(new_connection_id_bytes),
10166 ABSL_ARRAYSIZE(new_connection_id_bytes));
10167
10168 std::string retry_token(reinterpret_cast<char*>(retry_token_bytes),
10169 ABSL_ARRAYSIZE(retry_token_bytes));
10170
10171 if (invalid_retry_tag) {
10172 // Flip the last bit of the retry packet to prevent the integrity tag
10173 // from validating correctly.
10174 retry_packet[retry_packet_length - 1] ^= 1;
10175 }
10176
10177 QuicConnectionId config_original_connection_id = original_connection_id;
10178 if (wrong_original_id_in_config) {
10179 // Flip the first bit of the connection ID.
10180 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10181 config_original_connection_id.mutable_data()[0] ^= 0x80;
10182 }
10183 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10184 if (wrong_retry_id_in_config) {
10185 // Flip the first bit of the connection ID.
10186 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10187 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10188 }
10189
10190 // Make sure the connection uses the connection ID from the test vectors,
10191 QuicConnectionPeer::SetServerConnectionId(&connection_,
10192 original_connection_id);
10193 // Make sure our fake framer has the new post-retry INITIAL keys so that any
10194 // retransmission triggered by retry can be decrypted.
10195 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10196
10197 // Process the RETRY packet.
10198 connection_.ProcessUdpPacket(
10199 kSelfAddress, kPeerAddress,
10200 QuicReceivedPacket(reinterpret_cast<char*>(retry_packet),
10201 retry_packet_length, clock_.Now()));
10202
10203 if (invalid_retry_tag) {
10204 // Make sure we refuse to process a RETRY with invalid tag.
10205 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10206 EXPECT_EQ(connection_.connection_id(), original_connection_id);
10207 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
10208 QuicConnectionPeer::GetPacketCreator(&connection_))
10209 .empty());
10210 return;
10211 }
10212
10213 // Make sure we correctly parsed the RETRY.
10214 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10215 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10216 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10217 QuicConnectionPeer::GetPacketCreator(&connection_)),
10218 retry_token);
10219
10220 // Test validating the original_connection_id from the config.
10221 QuicConfig received_config;
10222 QuicConfigPeer::SetNegotiated(&received_config, true);
10223 if (connection_.version().UsesTls()) {
10224 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10225 &received_config, connection_.connection_id());
10226 if (!missing_retry_id_in_config) {
10227 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10228 &received_config, config_retry_source_connection_id);
10229 }
10230 }
10231 if (!missing_original_id_in_config) {
10232 QuicConfigPeer::SetReceivedOriginalConnectionId(
10233 &received_config, config_original_connection_id);
10234 }
10235
10236 if (missing_original_id_in_config || wrong_original_id_in_config ||
10237 missing_retry_id_in_config || wrong_retry_id_in_config) {
10238 EXPECT_CALL(visitor_,
10239 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10240 .Times(1);
10241 } else {
10242 EXPECT_CALL(visitor_,
10243 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10244 .Times(0);
10245 }
10246 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10247 connection_.SetFromConfig(received_config);
10248 if (missing_original_id_in_config || wrong_original_id_in_config ||
10249 missing_retry_id_in_config || wrong_retry_id_in_config) {
10250 ASSERT_FALSE(connection_.connected());
10251 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10252 } else {
10253 EXPECT_TRUE(connection_.connected());
10254 }
10255}
10256
10257TEST_P(QuicConnectionTest, ClientParsesRetry) {
10258 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10259 /*missing_original_id_in_config=*/false,
10260 /*wrong_original_id_in_config=*/false,
10261 /*missing_retry_id_in_config=*/false,
10262 /*wrong_retry_id_in_config=*/false);
10263}
10264
10265TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
10266 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10267 /*missing_original_id_in_config=*/false,
10268 /*wrong_original_id_in_config=*/false,
10269 /*missing_retry_id_in_config=*/false,
10270 /*wrong_retry_id_in_config=*/false);
10271}
10272
10273TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
10274 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10275 /*missing_original_id_in_config=*/true,
10276 /*wrong_original_id_in_config=*/false,
10277 /*missing_retry_id_in_config=*/false,
10278 /*wrong_retry_id_in_config=*/false);
10279}
10280
10281TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
10282 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10283 /*missing_original_id_in_config=*/false,
10284 /*wrong_original_id_in_config=*/true,
10285 /*missing_retry_id_in_config=*/false,
10286 /*wrong_retry_id_in_config=*/false);
10287}
10288
10289TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10290 if (!connection_.version().UsesTls()) {
10291 // Versions that do not authenticate connection IDs never send the
10292 // retry_source_connection_id transport parameter.
10293 return;
10294 }
10295 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10296 /*missing_original_id_in_config=*/false,
10297 /*wrong_original_id_in_config=*/false,
10298 /*missing_retry_id_in_config=*/true,
10299 /*wrong_retry_id_in_config=*/false);
10300}
10301
10302TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10303 if (!connection_.version().UsesTls()) {
10304 // Versions that do not authenticate connection IDs never send the
10305 // retry_source_connection_id transport parameter.
10306 return;
10307 }
10308 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10309 /*missing_original_id_in_config=*/false,
10310 /*wrong_original_id_in_config=*/false,
10311 /*missing_retry_id_in_config=*/false,
10312 /*wrong_retry_id_in_config=*/true);
10313}
10314
10315TEST_P(QuicConnectionTest, ClientRetransmitsInitialPacketsOnRetry) {
10316 if (!connection_.version().HasIetfQuicFrames()) {
10317 // TestClientRetryHandling() currently only supports IETF draft versions.
10318 return;
10319 }
10320 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10321
10322 connection_.SendCryptoStreamData();
10323
10324 EXPECT_EQ(1u, writer_->packets_write_attempts());
10325 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10326 /*missing_original_id_in_config=*/false,
10327 /*wrong_original_id_in_config=*/false,
10328 /*missing_retry_id_in_config=*/false,
10329 /*wrong_retry_id_in_config=*/false);
10330
10331 // Verify that initial data is retransmitted immediately after receiving
10332 // RETRY.
10333 if (GetParam().ack_response == AckResponse::kImmediate) {
10334 EXPECT_EQ(2u, writer_->packets_write_attempts());
10335 EXPECT_EQ(1u, writer_->framer()->crypto_frames().size());
10336 }
10337}
10338
10339TEST_P(QuicConnectionTest, NoInitialPacketsRetransmissionOnInvalidRetry) {
10340 if (!connection_.version().HasIetfQuicFrames()) {
10341 return;
10342 }
10343 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10344
10345 connection_.SendCryptoStreamData();
10346
10347 EXPECT_EQ(1u, writer_->packets_write_attempts());
10348 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10349 /*missing_original_id_in_config=*/false,
10350 /*wrong_original_id_in_config=*/false,
10351 /*missing_retry_id_in_config=*/false,
10352 /*wrong_retry_id_in_config=*/false);
10353
10354 EXPECT_EQ(1u, writer_->packets_write_attempts());
10355}
10356
10357TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
10358 if (!connection_.version().UsesTls()) {
10359 // QUIC+TLS is required to transmit connection ID transport parameters.
10360 return;
10361 }
10362 if (connection_.version().UsesTls()) {
10363 // Versions that authenticate connection IDs always send the
10364 // original_destination_connection_id transport parameter.
10365 return;
10366 }
10367 // Make sure that receiving the original_destination_connection_id transport
10368 // parameter fails the handshake when no RETRY packet was received before it.
10369 QuicConfig received_config;
10370 QuicConfigPeer::SetNegotiated(&received_config, true);
10371 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10372 TestConnectionId(0x12345));
10373 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10374 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10375 .Times(1);
10376 connection_.SetFromConfig(received_config);
10377 EXPECT_FALSE(connection_.connected());
10378 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10379}
10380
10381TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10382 if (!connection_.version().UsesTls()) {
10383 // Versions that do not authenticate connection IDs never send the
10384 // retry_source_connection_id transport parameter.
10385 return;
10386 }
10387 // Make sure that receiving the retry_source_connection_id transport parameter
10388 // fails the handshake when no RETRY packet was received before it.
10389 QuicConfig received_config;
10390 QuicConfigPeer::SetNegotiated(&received_config, true);
10391 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10392 TestConnectionId(0x12345));
10393 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10394 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10395 .Times(1);
10396 connection_.SetFromConfig(received_config);
10397 EXPECT_FALSE(connection_.connected());
10398 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10399}
10400
10401// Regression test for http://crbug/1047977
10402TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10403 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10404 return;
10405 }
10406 // Received frame causes connection close.
10407 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10408 .WillOnce(InvokeWithoutArgs([this]() {
10409 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10410 connection_.CloseConnection(
10411 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10412 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10413 return true;
10414 }));
10415 QuicFrames frames;
10416 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10417 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10418 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10419}
10420
10421TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10422 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10423 return;
10424 }
10425 // Received frame causes connection close.
10426 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10427 .WillOnce(InvokeWithoutArgs([this]() {
10428 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10429 connection_.CloseConnection(
10430 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10431 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10432 return true;
10433 }));
10434 QuicFrames frames;
10435 frames.push_back(
10436 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10437 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10438 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10439}
10440
10441TEST_P(QuicConnectionTest,
10442 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10443 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10444 return;
10445 }
10446 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10447 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10448 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10449 // Receives packet 1000 in initial data.
10450 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10451 // Receives packet 2000 in application data.
10452 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10453 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10454 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10455 connection_.CloseConnection(
10456 kQuicErrorCode, "Some random error message",
10457 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10458
10459 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10460
10461 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10462 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10463 // Verify ack is bundled.
10464 EXPECT_EQ(1u, writer_->ack_frames().size());
10465
10466 if (!connection_.version().CanSendCoalescedPackets()) {
10467 // Each connection close packet should be sent in distinct UDP packets.
10468 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10469 writer_->connection_close_packets());
10470 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10471 writer_->packets_write_attempts());
10472 return;
10473 }
10474
10475 // A single UDP packet should be sent with multiple connection close packets
10476 // coalesced together.
10477 EXPECT_EQ(1u, writer_->packets_write_attempts());
10478
10479 // Only the first packet has been processed yet.
10480 EXPECT_EQ(1u, writer_->connection_close_packets());
10481
10482 // ProcessPacket resets the visitor and frees the coalesced packet.
10483 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10484 auto packet = writer_->coalesced_packet()->Clone();
10485 writer_->framer()->ProcessPacket(*packet);
10486 EXPECT_EQ(1u, writer_->connection_close_packets());
10487 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10488 // Verify ack is bundled.
10489 EXPECT_EQ(1u, writer_->ack_frames().size());
10490 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10491}
10492
10493// Regression test for b/151220135.
10494TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10495 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10496 return;
10497 }
10498 QuicConfig config;
10499 QuicTagVector connection_options;
10500 connection_options.push_back(kPTOS);
10501 connection_options.push_back(k1PTO);
10502 config.SetConnectionOptionsToSend(connection_options);
10503 if (connection_.version().UsesTls()) {
10504 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10505 &config, kMaxAcceptedDatagramFrameSize);
10506 }
10507 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10508 connection_.SetFromConfig(config);
10509 connection_.OnHandshakeComplete();
10510 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10511
10512 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10513 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10514
10515 // PTO fires, verify a PING packet gets sent because there is no data to
10516 // send.
10517 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10518 connection_.GetRetransmissionAlarm()->Fire();
10519 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10520 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10521 EXPECT_EQ(1u, writer_->ping_frames().size());
10522}
10523
10524// Regression test for b/155757133
10525TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10526 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10527 return;
10528 }
10529 const size_t kMinRttMs = 40;
10530 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10531 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10532 QuicTime::Delta::Zero(), QuicTime::Zero());
10533 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10534 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10535 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10536 // Discard INITIAL key.
10537 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10538 connection_.NeuterUnencryptedPackets();
10539 EXPECT_CALL(visitor_, GetHandshakeState())
10540 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10541
10542 ProcessPacket(2);
10543 ProcessPacket(3);
10544 ProcessPacket(4);
10545 // Process a packet containing stream frame followed by ACK of packets 1.
10546 QuicFrames frames;
10547 frames.push_back(QuicFrame(QuicStreamFrame(
10548 QuicUtils::GetFirstBidirectionalStreamId(
10549 connection_.version().transport_version, Perspective::IS_CLIENT),
10550 false, 0u, absl::string_view())));
10551 QuicAckFrame ack_frame = InitAckFrame(1);
10552 frames.push_back(QuicFrame(&ack_frame));
10553 // Receiving stream frame causes something to send.
10554 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10555 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
10556 // Verify now the queued ACK contains packet number 2.
10557 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10558 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10559 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10560 }));
10561 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10562 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10563}
10564
martinduke9e0811c2022-12-08 20:35:57 -080010565TEST_P(QuicConnectionTest, DoNotExtendIdleTimeOnUndecryptablePackets) {
Bence Békybac04052022-04-07 15:44:29 -040010566 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10567 QuicConfig config;
10568 connection_.SetFromConfig(config);
10569 // Subtract a second from the idle timeout on the client side.
10570 QuicTime initial_deadline =
10571 clock_.ApproximateNow() +
10572 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10573 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10574
10575 // Received an undecryptable packet.
10576 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080010577 peer_framer_.SetEncrypter(
10578 ENCRYPTION_FORWARD_SECURE,
10579 std::make_unique<quic::NullEncrypter>(Perspective::IS_CLIENT));
Bence Békybac04052022-04-07 15:44:29 -040010580 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10581 // Verify deadline does not get extended.
10582 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10583 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10584 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10585 clock_.AdvanceTime(delay);
10586 connection_.GetTimeoutAlarm()->Fire();
10587 // Verify connection gets closed.
10588 EXPECT_FALSE(connection_.connected());
10589}
10590
10591TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10592 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10593 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10594
10595 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10596 notifier_.WriteOrBufferWindowUpate(0, 0);
10597 }));
10598 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10599 ProcessDataPacket(1);
10600 // Verify ACK is bundled with WINDOW_UPDATE.
10601 EXPECT_FALSE(writer_->ack_frames().empty());
10602 EXPECT_FALSE(connection_.HasPendingAcks());
10603}
10604
10605TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10606 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10607 return;
10608 }
10609 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10610 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10611 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10612 }
10613 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010614 // Receives packet 1000 in initial data.
10615 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10616 EXPECT_TRUE(connection_.HasPendingAcks());
10617
martinduke9e0811c2022-12-08 20:35:57 -080010618 peer_framer_.SetEncrypter(
10619 ENCRYPTION_ZERO_RTT,
10620 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040010621 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080010622 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040010623 // Receives packet 1000 in application data.
10624 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
10625 EXPECT_TRUE(connection_.HasPendingAcks());
10626 // Verify ACK deadline does not change.
10627 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10628 connection_.GetAckAlarm()->deadline());
10629
10630 // Ack alarm fires early.
10631 // Verify the earliest ACK is flushed.
10632 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10633 connection_.GetAckAlarm()->Fire();
10634 EXPECT_TRUE(connection_.HasPendingAcks());
10635 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10636 connection_.GetAckAlarm()->deadline());
10637}
10638
10639TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
10640 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10641 return;
10642 }
10643 QuicConfig config;
10644 QuicTagVector connection_options;
10645 connection_options.push_back(kCBHD);
10646 config.SetConnectionOptionsToSend(connection_options);
10647 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10648 connection_.SetFromConfig(config);
10649 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080010650 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
10651 connection_.OnHandshakeComplete();
Bence Békybac04052022-04-07 15:44:29 -040010652 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10653 // Send stream data.
10654 SendStreamDataToPeer(
10655 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10656 0, FIN, nullptr);
10657 // Verify blackhole detection is in progress.
10658 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10659}
10660
10661TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
10662 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10663 return;
10664 }
10665 set_perspective(Perspective::IS_SERVER);
10666 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10667 if (version().SupportsAntiAmplificationLimit()) {
10668 QuicConnectionPeer::SetAddressValidated(&connection_);
10669 }
10670 QuicConfig config;
10671 QuicTagVector connection_options;
10672 connection_options.push_back(kCBHD);
10673 config.SetInitialReceivedConnectionOptions(connection_options);
10674 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10675 connection_.SetFromConfig(config);
10676 EXPECT_CALL(visitor_, GetHandshakeState())
10677 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10678 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10679 // Send stream data.
10680 SendStreamDataToPeer(
10681 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10682 0, FIN, nullptr);
10683 // Verify blackhole detection is disabled.
10684 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10685}
10686
Bence Békybac04052022-04-07 15:44:29 -040010687// Regresstion test for b/158491591.
10688TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
10689 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10690 return;
10691 }
Bence Békybac04052022-04-07 15:44:29 -040010692 // Send handshake packet.
martinduke9e0811c2022-12-08 20:35:57 -080010693 connection_.SetEncrypter(
10694 ENCRYPTION_HANDSHAKE,
10695 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010696 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10697 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10698 QuicConfig config;
10699 QuicTagVector connection_options;
10700 connection_options.push_back(k5RTO);
10701 config.SetConnectionOptionsToSend(connection_options);
10702 QuicConfigPeer::SetNegotiated(&config, true);
fayang59e518a2022-11-29 11:16:45 -080010703 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10704 GetQuicReloadableFlag(
10705 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040010706 EXPECT_CALL(visitor_, GetHandshakeState())
10707 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10708 }
10709 if (connection_.version().UsesTls()) {
10710 QuicConfigPeer::SetReceivedOriginalConnectionId(
10711 &config, connection_.connection_id());
10712 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10713 &config, connection_.connection_id());
10714 }
10715 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10716 connection_.SetFromConfig(config);
10717
10718 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
fayang59e518a2022-11-29 11:16:45 -080010719 if (GetQuicReloadableFlag(
10720 quic_no_path_degrading_before_handshake_confirmed)) {
10721 // No blackhole detection before handshake confirmed.
10722 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10723 } else {
10724 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10725 }
Bence Békybac04052022-04-07 15:44:29 -040010726 // Discard handshake keys.
fayang59e518a2022-11-29 11:16:45 -080010727 EXPECT_CALL(visitor_, GetHandshakeState())
10728 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040010729 connection_.OnHandshakeComplete();
fayang59e518a2022-11-29 11:16:45 -080010730 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2) ||
10731 GetQuicReloadableFlag(
10732 quic_no_path_degrading_before_handshake_confirmed)) {
Bence Békybac04052022-04-07 15:44:29 -040010733 // Verify blackhole detection stops.
10734 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10735 } else {
10736 // Problematic: although there is nothing in flight, blackhole detection is
10737 // still in progress.
10738 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10739 }
10740}
10741
10742TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
10743 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10744 return;
10745 }
10746 // SetFromConfig is always called after construction from InitializeSession.
10747 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10748 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10749 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10750 QuicConfig config;
10751 connection_.SetFromConfig(config);
10752 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10753 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -040010754
martinduke9e0811c2022-12-08 20:35:57 -080010755 peer_framer_.SetEncrypter(
10756 ENCRYPTION_HANDSHAKE,
10757 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10758 peer_framer_.SetEncrypter(
10759 ENCRYPTION_FORWARD_SECURE,
10760 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010761
10762 for (uint64_t i = 1; i <= 3; ++i) {
10763 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10764 }
10765 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10766 for (uint64_t j = 5; j <= 7; ++j) {
10767 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10768 }
10769 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10770 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10771 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080010772 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010773 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080010774 connection_.SetEncrypter(
10775 ENCRYPTION_HANDSHAKE,
10776 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010777 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10778 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
10779 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10780 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
10781 }
10782 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10783 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10784
martinduke9e0811c2022-12-08 20:35:57 -080010785 SetDecrypter(
10786 ENCRYPTION_FORWARD_SECURE,
10787 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010788 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10789 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080010790 connection_.SetEncrypter(
10791 ENCRYPTION_FORWARD_SECURE,
10792 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010793 // Verify the 1-RTT packet gets processed.
10794 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
10795 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10796 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10797}
10798
10799TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
10800 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10801 return;
10802 }
10803 set_perspective(Perspective::IS_SERVER);
10804 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10805 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10806 }
10807 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010808 // Receives packet 1000 in initial data.
10809 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10810 EXPECT_TRUE(connection_.HasPendingAcks());
10811
Bence Békybac04052022-04-07 15:44:29 -040010812 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10813 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10814 QuicTime expected_pto_time =
10815 connection_.sent_packet_manager().GetRetransmissionTime();
10816
10817 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10818 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10819 std::make_unique<TaggingEncrypter>(0x02));
10820 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10821 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10822 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10823 // Verify PTO time does not change.
10824 EXPECT_EQ(expected_pto_time,
10825 connection_.sent_packet_manager().GetRetransmissionTime());
10826
10827 // Receives packet 1001 in initial data.
10828 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
10829 EXPECT_TRUE(connection_.HasPendingAcks());
10830 // Receives packet 1002 in initial data.
10831 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
10832 EXPECT_FALSE(writer_->ack_frames().empty());
10833 // Verify CRYPTO frame is bundled with INITIAL ACK.
10834 EXPECT_FALSE(writer_->crypto_frames().empty());
10835 // Verify PTO time changes.
10836 EXPECT_NE(expected_pto_time,
10837 connection_.sent_packet_manager().GetRetransmissionTime());
10838}
10839
10840TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
10841 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10842 return;
10843 }
10844 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
10845 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10846 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10847 }
10848 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
martinduke9e0811c2022-12-08 20:35:57 -080010849 connection_.SetEncrypter(
10850 ENCRYPTION_HANDSHAKE,
10851 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010852 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10853 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080010854 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
10855 peer_framer_.SetEncrypter(
10856 ENCRYPTION_HANDSHAKE,
10857 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010858 // Receives packet 1000 in handshake data.
10859 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
10860 EXPECT_TRUE(connection_.HasPendingAcks());
10861 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10862 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10863
10864 // Receives packet 1001 in handshake data.
10865 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
10866 EXPECT_TRUE(connection_.HasPendingAcks());
10867 // Receives packet 1002 in handshake data.
10868 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
10869 EXPECT_FALSE(writer_->ack_frames().empty());
10870 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
10871 EXPECT_FALSE(writer_->crypto_frames().empty());
10872}
10873
10874// Regresstion test for b/156232673.
10875TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
10876 if (!connection_.version().CanSendCoalescedPackets()) {
10877 return;
10878 }
10879 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10880 {
10881 QuicConnection::ScopedPacketFlusher flusher(&connection_);
martinduke9e0811c2022-12-08 20:35:57 -080010882 connection_.SetEncrypter(
10883 ENCRYPTION_HANDSHAKE,
10884 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
10885 connection_.SetEncrypter(
10886 ENCRYPTION_FORWARD_SECURE,
10887 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040010888 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10889 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
10890 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10891 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
10892 // Verify soft max packet length gets resumed and handshake packet gets
10893 // successfully sent.
10894 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
10895 }
10896}
10897
10898// Regression test for b/160790422.
10899TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
10900 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10901 return;
10902 }
10903 set_perspective(Perspective::IS_SERVER);
10904 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10905 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10906 }
10907 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040010908 // Receives packet 1000 in initial data.
10909 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10910 EXPECT_TRUE(connection_.HasPendingAcks());
10911
Bence Békybac04052022-04-07 15:44:29 -040010912 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10913 // Send INITIAL 1.
10914 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10915 QuicTime expected_pto_time =
10916 connection_.sent_packet_manager().GetRetransmissionTime();
10917
10918 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
martinduke9e0811c2022-12-08 20:35:57 -080010919 connection_.SetEncrypter(
10920 ENCRYPTION_HANDSHAKE,
10921 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010922 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10923 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10924 // Send HANDSHAKE 2 and 3.
10925 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10926 connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
10927 // Verify PTO time does not change.
10928 EXPECT_EQ(expected_pto_time,
10929 connection_.sent_packet_manager().GetRetransmissionTime());
10930
10931 // Receives ACK for HANDSHAKE 2.
10932 QuicFrames frames;
10933 auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
10934 frames.push_back(QuicFrame(&ack_frame));
10935 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10936 ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
10937 // Discard INITIAL key.
10938 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10939 connection_.NeuterUnencryptedPackets();
10940 // Receives PING from peer.
10941 frames.clear();
10942 frames.push_back(QuicFrame(QuicPingFrame()));
10943 frames.push_back(QuicFrame(QuicPaddingFrame(3)));
10944 ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
10945 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
10946 connection_.GetAckAlarm()->deadline());
10947 // Fire ACK alarm.
10948 clock_.AdvanceTime(kAlarmGranularity);
10949 connection_.GetAckAlarm()->Fire();
10950 EXPECT_FALSE(writer_->ack_frames().empty());
10951 // Verify handshake data gets retransmitted early.
10952 EXPECT_FALSE(writer_->crypto_frames().empty());
10953}
10954
10955// Regression test for b/161228202
10956TEST_P(QuicConnectionTest, InflatedRttSample) {
10957 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10958 return;
10959 }
10960 // 30ms RTT.
10961 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
10962 set_perspective(Perspective::IS_SERVER);
10963 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
Bence Békybac04052022-04-07 15:44:29 -040010964 // Receives packet 1000 in initial data.
10965 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10966 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10967 }
10968 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10969 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10970 EXPECT_TRUE(connection_.HasPendingAcks());
10971
Bence Békybac04052022-04-07 15:44:29 -040010972 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10973 // Send INITIAL 1.
10974 std::string initial_crypto_data(512, 'a');
10975 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
10976 ENCRYPTION_INITIAL);
10977 ASSERT_TRUE(connection_.sent_packet_manager()
10978 .GetRetransmissionTime()
10979 .IsInitialized());
10980 QuicTime::Delta pto_timeout =
10981 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
10982 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080010983 connection_.SetEncrypter(
10984 ENCRYPTION_HANDSHAKE,
10985 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040010986 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10987 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10988 std::string handshake_crypto_data(1024, 'a');
10989 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
10990 ENCRYPTION_HANDSHAKE);
10991
10992 // INITIAL 1 gets lost and PTO fires.
10993 clock_.AdvanceTime(pto_timeout);
10994 connection_.GetRetransmissionAlarm()->Fire();
10995
10996 clock_.AdvanceTime(kTestRTT);
10997 // Assume retransmitted INITIAL gets received.
10998 QuicFrames frames;
10999 auto ack_frame = InitAckFrame({{QuicPacketNumber(4), QuicPacketNumber(5)}});
11000 frames.push_back(QuicFrame(&ack_frame));
11001 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
11002 .Times(AnyNumber());
11003 ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
11004 EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
11005 // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
11006 frames.clear();
11007 // HANDSHAKE 5 is also processed.
11008 QuicAckFrame ack_frame2 =
11009 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
11010 {QuicPacketNumber(5), QuicPacketNumber(6)}});
11011 ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
11012 frames.push_back(QuicFrame(&ack_frame2));
11013 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
11014 // Verify RTT inflation gets mitigated.
11015 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
11016}
11017
11018// Regression test for b/161228202
martinduke9e0811c2022-12-08 20:35:57 -080011019TEST_P(QuicConnectionTest, CoalescingPacketCausesInfiniteLoop) {
Bence Békybac04052022-04-07 15:44:29 -040011020 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11021 return;
11022 }
11023 set_perspective(Perspective::IS_SERVER);
Bence Békybac04052022-04-07 15:44:29 -040011024 // Receives packet 1000 in initial data.
11025 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11026 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11027 }
11028 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11029
11030 // Set anti amplification factor to 2, such that RetransmitDataOfSpaceIfAny
11031 // makes no forward progress and causes infinite loop.
birenroyef686222022-09-12 11:34:34 -070011032 SetQuicFlag(quic_anti_amplification_factor, 2);
Bence Békybac04052022-04-07 15:44:29 -040011033
11034 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11035 EXPECT_TRUE(connection_.HasPendingAcks());
11036
Bence Békybac04052022-04-07 15:44:29 -040011037 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11038 // Send INITIAL 1.
11039 std::string initial_crypto_data(512, 'a');
11040 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11041 ENCRYPTION_INITIAL);
11042 ASSERT_TRUE(connection_.sent_packet_manager()
11043 .GetRetransmissionTime()
11044 .IsInitialized());
11045 QuicTime::Delta pto_timeout =
11046 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11047 // Send Handshake 2.
martinduke9e0811c2022-12-08 20:35:57 -080011048 connection_.SetEncrypter(
11049 ENCRYPTION_HANDSHAKE,
11050 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011051 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11052 // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
11053 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11054 std::string handshake_crypto_data(1024, 'a');
11055 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11056 ENCRYPTION_HANDSHAKE);
11057
11058 // INITIAL 1 gets lost and PTO fires.
11059 clock_.AdvanceTime(pto_timeout);
11060 connection_.GetRetransmissionAlarm()->Fire();
11061}
11062
11063TEST_P(QuicConnectionTest, ClientAckDelayForAsyncPacketProcessing) {
11064 if (!version().HasIetfQuicFrames()) {
11065 return;
11066 }
11067 // SetFromConfig is always called after construction from InitializeSession.
11068 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11069 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11070 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11071 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11072 connection_.NeuterUnencryptedPackets();
11073 }));
11074 QuicConfig config;
11075 connection_.SetFromConfig(config);
11076 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080011077 peer_framer_.SetEncrypter(
11078 ENCRYPTION_HANDSHAKE,
11079 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011080 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11081
11082 // Received undecryptable HANDSHAKE 2.
11083 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11084 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11085 // Received INITIAL 4 (which is retransmission of INITIAL 1) after 100ms.
11086 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
11087 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL);
11088 // Generate HANDSHAKE key.
11089 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080011090 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011091 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080011092 connection_.SetEncrypter(
11093 ENCRYPTION_HANDSHAKE,
11094 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040011095 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11096 // Verify HANDSHAKE packet gets processed.
fayangfea655c2022-05-17 08:19:12 -070011097 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -040011098 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
fayangfea655c2022-05-17 08:19:12 -070011099 // Verify immediate ACK has been sent out when flush went out of scope.
11100 ASSERT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -040011101 ASSERT_FALSE(writer_->ack_frames().empty());
fayangfea655c2022-05-17 08:19:12 -070011102 // Verify the ack_delay_time in the sent HANDSHAKE ACK frame is 100ms.
11103 EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
Bence Békybac04052022-04-07 15:44:29 -040011104 writer_->ack_frames()[0].ack_delay_time);
11105 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
11106}
11107
11108TEST_P(QuicConnectionTest, TestingLiveness) {
11109 const size_t kMinRttMs = 40;
11110 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11111 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11112 QuicTime::Delta::Zero(), QuicTime::Zero());
11113 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11114 QuicConfig config;
11115
11116 CryptoHandshakeMessage msg;
11117 std::string error_details;
11118 QuicConfig client_config;
11119 client_config.SetInitialStreamFlowControlWindowToSend(
11120 kInitialStreamFlowControlWindowForTest);
11121 client_config.SetInitialSessionFlowControlWindowToSend(
11122 kInitialSessionFlowControlWindowForTest);
11123 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11124 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11125 const QuicErrorCode error =
11126 config.ProcessPeerHello(msg, CLIENT, &error_details);
11127 EXPECT_THAT(error, IsQuicNoError());
11128
11129 if (connection_.version().UsesTls()) {
11130 QuicConfigPeer::SetReceivedOriginalConnectionId(
11131 &config, connection_.connection_id());
11132 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11133 &config, connection_.connection_id());
11134 }
11135
11136 connection_.SetFromConfig(config);
11137 connection_.OnHandshakeComplete();
11138 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11139 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11140 EXPECT_FALSE(connection_.MaybeTestLiveness());
11141
haoyuewang7b43efb2022-04-20 16:26:03 -070011142 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040011143 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11144 // Advance time to near the idle timeout.
11145 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11146 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11147 EXPECT_TRUE(connection_.MaybeTestLiveness());
11148 // Verify idle deadline does not change.
haoyuewang7b43efb2022-04-20 16:26:03 -070011149 EXPECT_EQ(deadline, QuicConnectionPeer::GetIdleNetworkDeadline(&connection_));
Bence Békybac04052022-04-07 15:44:29 -040011150}
11151
fayang5783c332022-12-14 09:30:25 -080011152TEST_P(QuicConnectionTest, DisableLivenessTesting) {
11153 const size_t kMinRttMs = 40;
11154 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11155 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11156 QuicTime::Delta::Zero(), QuicTime::Zero());
11157 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11158 QuicConfig config;
11159
11160 CryptoHandshakeMessage msg;
11161 std::string error_details;
11162 QuicConfig client_config;
11163 client_config.SetInitialStreamFlowControlWindowToSend(
11164 kInitialStreamFlowControlWindowForTest);
11165 client_config.SetInitialSessionFlowControlWindowToSend(
11166 kInitialSessionFlowControlWindowForTest);
11167 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11168 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11169 const QuicErrorCode error =
11170 config.ProcessPeerHello(msg, CLIENT, &error_details);
11171 EXPECT_THAT(error, IsQuicNoError());
11172
11173 if (connection_.version().UsesTls()) {
11174 QuicConfigPeer::SetReceivedOriginalConnectionId(
11175 &config, connection_.connection_id());
11176 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11177 &config, connection_.connection_id());
11178 }
11179
11180 connection_.SetFromConfig(config);
11181 connection_.OnHandshakeComplete();
11182 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11183 connection_.DisableLivenessTesting();
11184 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11185 EXPECT_FALSE(connection_.MaybeTestLiveness());
11186
11187 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
11188 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11189 // Advance time to near the idle timeout.
11190 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11191 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11192 EXPECT_FALSE(connection_.MaybeTestLiveness());
11193}
11194
Bence Békybac04052022-04-07 15:44:29 -040011195TEST_P(QuicConnectionTest, SilentIdleTimeout) {
11196 set_perspective(Perspective::IS_SERVER);
11197 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11198 if (version().SupportsAntiAmplificationLimit()) {
11199 QuicConnectionPeer::SetAddressValidated(&connection_);
11200 }
11201
11202 QuicConfig config;
11203 QuicConfigPeer::SetNegotiated(&config, true);
11204 if (connection_.version().UsesTls()) {
11205 QuicConfigPeer::SetReceivedOriginalConnectionId(
11206 &config, connection_.connection_id());
11207 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
11208 QuicConnectionId());
11209 }
11210 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11211 connection_.SetFromConfig(config);
11212
11213 EXPECT_TRUE(connection_.connected());
11214 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11215
11216 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
11217 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
11218 }
11219 EXPECT_CALL(visitor_,
11220 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11221 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
haoyuewang7b43efb2022-04-20 16:26:03 -070011222 if (!QuicConnectionPeer::GetBandwidthUpdateTimeout(&connection_)
11223 .IsInfinite()) {
11224 // Fires the bandwidth update.
11225 connection_.GetTimeoutAlarm()->Fire();
11226 }
Bence Békybac04052022-04-07 15:44:29 -040011227 connection_.GetTimeoutAlarm()->Fire();
11228 // Verify the connection close packets get serialized and added to
11229 // termination packets list.
11230 EXPECT_NE(nullptr,
11231 QuicConnectionPeer::GetConnectionClosePacket(&connection_));
11232}
11233
martinduke9e0811c2022-12-08 20:35:57 -080011234TEST_P(QuicConnectionTest, DoNotSendPing) {
Bence Békybac04052022-04-07 15:44:29 -040011235 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11236 connection_.OnHandshakeComplete();
11237 EXPECT_TRUE(connection_.connected());
11238 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11239 .WillRepeatedly(Return(true));
11240 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
11241 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11242
11243 SendStreamDataToPeer(
11244 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
11245 "GET /", 0, FIN, nullptr);
11246 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11247 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11248 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
11249 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11250
11251 // Now recevie an ACK and response of the previous packet, which will move the
11252 // ping alarm forward.
11253 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11254 QuicFrames frames;
11255 QuicAckFrame ack_frame = InitAckFrame(1);
11256 frames.push_back(QuicFrame(&ack_frame));
11257 frames.push_back(QuicFrame(QuicStreamFrame(
11258 GetNthClientInitiatedStreamId(0, connection_.transport_version()), true,
11259 0u, absl::string_view())));
11260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11261 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
11262 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11263 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
11264 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11265 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11266 // The ping timer is set slightly less than 15 seconds in the future, because
11267 // of the 1s ping timer alarm granularity.
11268 EXPECT_EQ(
11269 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
11270 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11271
11272 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
11273 // Suppose now ShouldKeepConnectionAlive returns false.
11274 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11275 .WillRepeatedly(Return(false));
11276 // Verify PING does not get sent.
11277 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11278 connection_.GetPingAlarm()->Fire();
11279}
11280
11281// Regression test for b/159698337
11282TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) {
11283 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11284 return;
11285 }
11286 // Finish handshake.
11287 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11288 notifier_.NeuterUnencryptedData();
11289 connection_.NeuterUnencryptedPackets();
11290 connection_.OnHandshakeComplete();
11291 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080011292 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040011293
11294 std::string data(1200, 'a');
11295 // Send data packets 1 - 5.
11296 for (size_t i = 0; i < 5; ++i) {
11297 SendStreamDataToPeer(
11298 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
11299 i * 1200, i == 4 ? FIN : NO_FIN, nullptr);
11300 }
11301 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
11302
11303 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _)).Times(3);
11304
11305 // ACK packet 5 and 1 and 2 are detected lost.
11306 QuicAckFrame frame =
11307 InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}});
11308 LostPacketVector lost_packets;
11309 lost_packets.push_back(
11310 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
11311 lost_packets.push_back(
11312 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
11313 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11314 .Times(AnyNumber())
11315 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11316 Return(LossDetectionInterface::DetectionStats())));
11317 ProcessAckPacket(1, &frame);
11318 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11319 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
11320 EXPECT_TRUE(retransmission_alarm->IsSet());
11321
11322 // ACK packet 1 - 5 and 7.
11323 QuicAckFrame frame2 =
11324 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)},
11325 {QuicPacketNumber(7), QuicPacketNumber(8)}});
11326 ProcessAckPacket(2, &frame2);
11327 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11328
11329 // ACK packet 7 again and assume packet 6 is detected lost.
11330 QuicAckFrame frame3 =
11331 InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}});
11332 lost_packets.clear();
11333 lost_packets.push_back(
11334 LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize));
11335 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11336 .Times(AnyNumber())
11337 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11338 Return(LossDetectionInterface::DetectionStats())));
11339 ProcessAckPacket(3, &frame3);
11340 // Make sure loss detection is cancelled even there is no new acked packets.
11341 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11342}
11343
11344TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) {
11345 EXPECT_TRUE(connection_.connected());
11346 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11347 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
11348 QuicTime::Delta::Zero(), QuicTime::Zero());
11349
11350 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11351 QuicConfig config;
11352 config.SetClientConnectionOptions(QuicTagVector{kFIDT});
11353 QuicConfigPeer::SetNegotiated(&config, true);
11354 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11355 EXPECT_CALL(visitor_, GetHandshakeState())
11356 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11357 }
11358 if (connection_.version().UsesTls()) {
11359 QuicConfigPeer::SetReceivedOriginalConnectionId(
11360 &config, connection_.connection_id());
11361 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11362 &config, connection_.connection_id());
11363 }
11364 connection_.SetFromConfig(config);
11365
11366 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11367 // Send a packet close to timeout.
11368 QuicTime::Delta timeout =
11369 connection_.GetTimeoutAlarm()->deadline() - clock_.Now();
11370 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1));
11371 // Send stream data.
11372 SendStreamDataToPeer(
11373 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11374 0, FIN, nullptr);
11375 // Verify this sent packet does not extend idle timeout since 1s is > PTO
11376 // delay.
11377 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11378 EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
11379 connection_.GetTimeoutAlarm()->deadline() - clock_.Now());
11380
11381 // Received an ACK 100ms later.
11382 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100));
11383 QuicAckFrame ack = InitAckFrame(1);
11384 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
11385 ProcessAckPacket(1, &ack);
11386 // Verify idle timeout gets extended.
11387 EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline());
11388}
11389
11390// Regression test for b/166255274
11391TEST_P(QuicConnectionTest,
11392 ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) {
11393 if (!connection_.version().CanSendCoalescedPackets()) {
11394 return;
11395 }
Bence Békybac04052022-04-07 15:44:29 -040011396 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11397 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11398 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11399 EXPECT_TRUE(connection_.HasPendingAcks());
11400 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11401 std::make_unique<TaggingEncrypter>(0x02));
11402 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11403 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11404 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11405 connection_.NeuterUnencryptedPackets();
11406 }));
11407 {
11408 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11409 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11410 // Verify the packet is on hold.
11411 EXPECT_EQ(0u, writer_->packets_write_attempts());
11412 // Flush pending ACKs.
11413 connection_.GetAckAlarm()->Fire();
11414 }
11415 EXPECT_FALSE(connection_.packet_creator().HasPendingFrames());
11416 // The ACK frame is deleted along with initial_packet_ in coalescer. Sending
11417 // connection close would cause this (released) ACK frame be serialized (and
11418 // crashes).
11419 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11420 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
11421 EXPECT_TRUE(connection_.connected());
11422}
11423
11424TEST_P(QuicConnectionTest, PathValidationOnNewSocketSuccess) {
danzh87605712022-04-11 14:36:39 -070011425 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011426 return;
11427 }
11428 PathProbeTestInit(Perspective::IS_CLIENT);
11429 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11430 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11431 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11432 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11433 .Times(AtLeast(1u))
11434 .WillOnce(Invoke([&]() {
11435 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11436 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11437 EXPECT_EQ(1u, new_writer.padding_frames().size());
11438 EXPECT_EQ(kNewSelfAddress.host(),
11439 new_writer.last_write_source_address());
11440 }));
11441 bool success = false;
11442 connection_.ValidatePath(
11443 std::make_unique<TestQuicPathValidationContext>(
11444 kNewSelfAddress, connection_.peer_address(), &new_writer),
11445 std::make_unique<TestValidationResultDelegate>(
11446 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11447 EXPECT_EQ(0u, writer_->packets_write_attempts());
11448
11449 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011450 frames.push_back(QuicFrame(QuicPathResponseFrame(
Bence Békybac04052022-04-07 15:44:29 -040011451 99, new_writer.path_challenge_frames().front().data_buffer)));
11452 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
11453 ENCRYPTION_FORWARD_SECURE);
11454 EXPECT_TRUE(success);
11455}
11456
11457TEST_P(QuicConnectionTest, NewPathValidationCancelsPreviousOne) {
danzh87605712022-04-11 14:36:39 -070011458 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011459 return;
11460 }
11461 PathProbeTestInit(Perspective::IS_CLIENT);
11462 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11463 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11464 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11465 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11466 .Times(AtLeast(1u))
11467 .WillOnce(Invoke([&]() {
11468 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11469 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11470 EXPECT_EQ(1u, new_writer.padding_frames().size());
11471 EXPECT_EQ(kNewSelfAddress.host(),
11472 new_writer.last_write_source_address());
11473 }));
11474 bool success = true;
11475 connection_.ValidatePath(
11476 std::make_unique<TestQuicPathValidationContext>(
11477 kNewSelfAddress, connection_.peer_address(), &new_writer),
11478 std::make_unique<TestValidationResultDelegate>(
11479 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11480 EXPECT_EQ(0u, writer_->packets_write_attempts());
11481
11482 // Start another path validation request.
11483 const QuicSocketAddress kNewSelfAddress2(QuicIpAddress::Any4(), 12346);
11484 EXPECT_NE(kNewSelfAddress2, connection_.self_address());
11485 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
11486 if (!connection_.connection_migration_use_new_cid()) {
11487 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11488 .Times(AtLeast(1u))
11489 .WillOnce(Invoke([&]() {
11490 EXPECT_EQ(1u, new_writer2.packets_write_attempts());
11491 EXPECT_EQ(1u, new_writer2.path_challenge_frames().size());
11492 EXPECT_EQ(1u, new_writer2.padding_frames().size());
11493 EXPECT_EQ(kNewSelfAddress2.host(),
11494 new_writer2.last_write_source_address());
11495 }));
11496 }
11497 bool success2 = false;
11498 connection_.ValidatePath(
11499 std::make_unique<TestQuicPathValidationContext>(
11500 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
11501 std::make_unique<TestValidationResultDelegate>(
11502 &connection_, kNewSelfAddress2, connection_.peer_address(),
11503 &success2));
11504 EXPECT_FALSE(success);
11505 if (connection_.connection_migration_use_new_cid()) {
11506 // There is no pening path validation as there is no available connection
11507 // ID.
11508 EXPECT_FALSE(connection_.HasPendingPathValidation());
11509 } else {
11510 EXPECT_TRUE(connection_.HasPendingPathValidation());
11511 }
11512}
11513
11514// Regression test for b/182571515.
11515TEST_P(QuicConnectionTest, PathValidationRetry) {
danzh87605712022-04-11 14:36:39 -070011516 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011517 return;
11518 }
11519 PathProbeTestInit(Perspective::IS_CLIENT);
11520
11521 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11522 .Times(2u)
11523 .WillRepeatedly(Invoke([&]() {
11524 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11525 EXPECT_EQ(1u, writer_->padding_frames().size());
11526 }));
11527 bool success = true;
11528 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11529 connection_.self_address(),
11530 connection_.peer_address(), writer_.get()),
11531 std::make_unique<TestValidationResultDelegate>(
11532 &connection_, connection_.self_address(),
11533 connection_.peer_address(), &success));
11534 EXPECT_EQ(1u, writer_->packets_write_attempts());
11535 EXPECT_TRUE(connection_.HasPendingPathValidation());
11536
11537 // Retry after time out.
11538 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11539 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11540 static_cast<TestAlarmFactory::TestAlarm*>(
11541 QuicPathValidatorPeer::retry_timer(
11542 QuicConnectionPeer::path_validator(&connection_)))
11543 ->Fire();
11544 EXPECT_EQ(2u, writer_->packets_write_attempts());
11545}
11546
11547TEST_P(QuicConnectionTest, PathValidationReceivesStatelessReset) {
danzh87605712022-04-11 14:36:39 -070011548 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011549 return;
11550 }
11551 PathProbeTestInit(Perspective::IS_CLIENT);
11552 QuicConfig config;
11553 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
11554 kTestStatelessResetToken);
11555 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11556 connection_.SetFromConfig(config);
11557 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11558 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11559 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11560 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11561 .Times(AtLeast(1u))
11562 .WillOnce(Invoke([&]() {
11563 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11564 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11565 EXPECT_EQ(1u, new_writer.padding_frames().size());
11566 EXPECT_EQ(kNewSelfAddress.host(),
11567 new_writer.last_write_source_address());
11568 }));
11569 bool success = true;
11570 connection_.ValidatePath(
11571 std::make_unique<TestQuicPathValidationContext>(
11572 kNewSelfAddress, connection_.peer_address(), &new_writer),
11573 std::make_unique<TestValidationResultDelegate>(
11574 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11575 EXPECT_EQ(0u, writer_->packets_write_attempts());
11576 EXPECT_TRUE(connection_.HasPendingPathValidation());
11577
11578 std::unique_ptr<QuicEncryptedPacket> packet(
11579 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
11580 /*received_packet_length=*/100,
11581 kTestStatelessResetToken));
11582 std::unique_ptr<QuicReceivedPacket> received(
11583 ConstructReceivedPacket(*packet, QuicTime::Zero()));
11584 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
11585 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
11586 EXPECT_FALSE(connection_.HasPendingPathValidation());
11587 EXPECT_FALSE(success);
11588}
11589
11590// Tests that PATH_CHALLENGE is dropped if it is sent via a blocked alternative
11591// writer.
11592TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedNewSocket) {
11593 if (!VersionHasIetfQuicFrames(connection_.version().transport_version) ||
11594 !connection_.connection_migration_use_new_cid()) {
11595 return;
11596 }
11597 PathProbeTestInit(Perspective::IS_CLIENT);
11598 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11599 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11600 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11601 new_writer.BlockOnNextWrite();
11602 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
11603 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11604 .Times(AtLeast(1))
11605 .WillOnce(Invoke([&]() {
11606 // Even though the socket is blocked, the PATH_CHALLENGE should still be
11607 // treated as sent.
11608 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11609 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11610 EXPECT_EQ(1u, new_writer.padding_frames().size());
11611 EXPECT_EQ(kNewSelfAddress.host(),
11612 new_writer.last_write_source_address());
11613 }));
11614 bool success = false;
11615 connection_.ValidatePath(
11616 std::make_unique<TestQuicPathValidationContext>(
11617 kNewSelfAddress, connection_.peer_address(), &new_writer),
11618 std::make_unique<TestValidationResultDelegate>(
11619 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11620 EXPECT_EQ(0u, writer_->packets_write_attempts());
11621
11622 new_writer.SetWritable();
11623 // Write event on the default socket shouldn't make any difference.
11624 connection_.OnCanWrite();
11625 // A NEW_CONNECTION_ID frame is received in PathProbeTestInit and OnCanWrite
11626 // will write a acking packet.
11627 EXPECT_EQ(1u, writer_->packets_write_attempts());
11628 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11629}
11630
11631// Tests that PATH_CHALLENGE is dropped if it is sent via the default writer
11632// and the writer is blocked.
11633TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedDefaultSocket) {
danzh87605712022-04-11 14:36:39 -070011634 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011635 return;
11636 }
11637 PathProbeTestInit(Perspective::IS_SERVER);
11638 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11639 writer_->BlockOnNextWrite();
11640 // 1st time is after writer returns WRITE_STATUS_BLOCKED. 2nd time is in
11641 // ShouldGeneratePacket().
11642 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(2));
11643 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
11644 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11645 .Times(AtLeast(1u))
11646 .WillOnce(Invoke([&]() {
11647 // This packet isn't sent actually, instead it is buffered in the
11648 // connection.
11649 EXPECT_EQ(1u, writer_->packets_write_attempts());
11650 if (connection_.validate_client_address()) {
11651 EXPECT_EQ(1u, writer_->path_response_frames().size());
11652 EXPECT_EQ(0,
11653 memcmp(&path_challenge_payload,
11654 &writer_->path_response_frames().front().data_buffer,
11655 sizeof(path_challenge_payload)));
11656 }
11657 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11658 EXPECT_EQ(1u, writer_->padding_frames().size());
11659 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11660 }))
11661 .WillRepeatedly(Invoke([&]() {
11662 // Only one PATH_CHALLENGE should be sent out.
11663 EXPECT_EQ(0u, writer_->path_challenge_frames().size());
11664 }));
11665 bool success = false;
11666 if (connection_.validate_client_address()) {
11667 // Receiving a PATH_CHALLENGE from the new peer address should trigger
11668 // address validation.
11669 QuicFrames frames;
11670 frames.push_back(
wubd0152ca2022-04-08 08:26:44 -070011671 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040011672 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11673 ENCRYPTION_FORWARD_SECURE);
11674 } else {
11675 // Manually start to validate the new peer address.
11676 connection_.ValidatePath(
11677 std::make_unique<TestQuicPathValidationContext>(
11678 connection_.self_address(), kNewPeerAddress, writer_.get()),
11679 std::make_unique<TestValidationResultDelegate>(
11680 &connection_, connection_.self_address(), kNewPeerAddress,
11681 &success));
11682 }
11683 EXPECT_EQ(1u, writer_->packets_write_attempts());
11684
11685 // Try again with the new socket blocked from the beginning. The 2nd
11686 // PATH_CHALLENGE shouldn't be serialized, but be dropped.
11687 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11688 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11689 static_cast<TestAlarmFactory::TestAlarm*>(
11690 QuicPathValidatorPeer::retry_timer(
11691 QuicConnectionPeer::path_validator(&connection_)))
11692 ->Fire();
11693
11694 // No more write attempt should be made.
11695 EXPECT_EQ(1u, writer_->packets_write_attempts());
11696
11697 writer_->SetWritable();
11698 // OnCanWrite() should actually write out the 1st PATH_CHALLENGE packet
11699 // buffered earlier, thus incrementing the write counter. It may also send
11700 // ACKs to previously received packets.
11701 connection_.OnCanWrite();
11702 EXPECT_LE(2u, writer_->packets_write_attempts());
11703}
11704
11705// Tests that write error on the alternate socket should be ignored.
11706TEST_P(QuicConnectionTest, SendPathChallengeFailOnNewSocket) {
danzh87605712022-04-11 14:36:39 -070011707 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011708 return;
11709 }
11710 PathProbeTestInit(Perspective::IS_CLIENT);
11711 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11712 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11713 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11714 new_writer.SetShouldWriteFail();
11715 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11716 .Times(0);
11717 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11718
11719 bool success = false;
11720 connection_.ValidatePath(
11721 std::make_unique<TestQuicPathValidationContext>(
11722 kNewSelfAddress, connection_.peer_address(), &new_writer),
11723 std::make_unique<TestValidationResultDelegate>(
11724 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11725 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11726 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11727 EXPECT_EQ(1u, new_writer.padding_frames().size());
11728 EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address());
11729
11730 EXPECT_EQ(0u, writer_->packets_write_attempts());
11731 // Regardless of the write error, the connection should still be connected.
11732 EXPECT_TRUE(connection_.connected());
11733}
11734
11735// Tests that write error while sending PATH_CHALLANGE from the default socket
11736// should close the connection.
11737TEST_P(QuicConnectionTest, SendPathChallengeFailOnDefaultPath) {
danzh87605712022-04-11 14:36:39 -070011738 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011739 return;
11740 }
11741 PathProbeTestInit(Perspective::IS_CLIENT);
11742
11743 writer_->SetShouldWriteFail();
11744 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11745 .WillOnce(
11746 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11747 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11748 }));
11749 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11750 {
11751 // Add a flusher to force flush, otherwise the frames will remain in the
11752 // packet creator.
11753 bool success = false;
11754 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11755 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11756 connection_.self_address(),
11757 connection_.peer_address(), writer_.get()),
11758 std::make_unique<TestValidationResultDelegate>(
11759 &connection_, connection_.self_address(),
11760 connection_.peer_address(), &success));
11761 }
11762 EXPECT_EQ(1u, writer_->packets_write_attempts());
11763 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11764 EXPECT_EQ(1u, writer_->padding_frames().size());
11765 EXPECT_EQ(connection_.peer_address(), writer_->last_write_peer_address());
11766 EXPECT_FALSE(connection_.connected());
11767 // Closing connection should abandon ongoing path validation.
11768 EXPECT_FALSE(connection_.HasPendingPathValidation());
11769}
11770
11771TEST_P(QuicConnectionTest, SendPathChallengeFailOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011772 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011773 return;
11774 }
11775 PathProbeTestInit(Perspective::IS_CLIENT);
11776
11777 writer_->SetShouldWriteFail();
11778 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11779 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11780 .WillOnce(
11781 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11782 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11783 }));
11784 // Sending PATH_CHALLENGE to trigger a flush write which will fail and close
11785 // the connection.
11786 bool success = false;
11787 connection_.ValidatePath(
11788 std::make_unique<TestQuicPathValidationContext>(
11789 connection_.self_address(), kNewPeerAddress, writer_.get()),
11790 std::make_unique<TestValidationResultDelegate>(
11791 &connection_, connection_.self_address(), kNewPeerAddress, &success));
11792
11793 EXPECT_EQ(1u, writer_->packets_write_attempts());
11794 EXPECT_FALSE(connection_.HasPendingPathValidation());
11795 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11796 EXPECT_EQ(1u, writer_->padding_frames().size());
11797 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11798 EXPECT_FALSE(connection_.connected());
11799}
11800
11801TEST_P(QuicConnectionTest,
11802 SendPathChallengeFailPacketTooBigOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011803 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011804 return;
11805 }
11806 PathProbeTestInit(Perspective::IS_CLIENT);
11807 // Make sure there is no outstanding ACK_FRAME to write.
11808 connection_.OnCanWrite();
11809 uint32_t num_packets_write_attempts = writer_->packets_write_attempts();
11810
11811 writer_->SetShouldWriteFail();
11812 writer_->SetWriteError(*writer_->MessageTooBigErrorCode());
11813 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11814 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11815 .Times(0u);
11816 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11817 // Sending PATH_CHALLENGE to trigger a flush write which will fail with
11818 // MSG_TOO_BIG.
11819 bool success = false;
11820 connection_.ValidatePath(
11821 std::make_unique<TestQuicPathValidationContext>(
11822 connection_.self_address(), kNewPeerAddress, writer_.get()),
11823 std::make_unique<TestValidationResultDelegate>(
11824 &connection_, connection_.self_address(), kNewPeerAddress, &success));
11825 EXPECT_TRUE(connection_.HasPendingPathValidation());
11826 // Connection shouldn't be closed.
11827 EXPECT_TRUE(connection_.connected());
11828 EXPECT_EQ(++num_packets_write_attempts, writer_->packets_write_attempts());
11829 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11830 EXPECT_EQ(1u, writer_->padding_frames().size());
11831 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11832}
11833
11834// Check that if there are two PATH_CHALLENGE frames in the packet, the latter
11835// one is ignored.
11836TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) {
11837 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11838 return;
11839 }
11840 PathProbeTestInit(Perspective::IS_SERVER);
11841
11842 QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7};
11843 QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15};
11844 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011845 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer1)));
11846 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer2)));
Bence Békybac04052022-04-07 15:44:29 -040011847 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11848 /*port=*/23456);
11849
11850 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
11851
11852 // Expect 2 packets to be sent: the first are padded PATH_RESPONSE(s) to the
11853 // alternative peer address. The 2nd is a ACK-only packet to the original
11854 // peer address.
11855 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11856 .Times(2)
11857 .WillOnce(Invoke([=]() {
11858 EXPECT_EQ(1u, writer_->path_response_frames().size());
11859 // The final check is to ensure that the random data in the response
11860 // matches the random data from the challenge.
11861 EXPECT_EQ(0,
11862 memcmp(path_frame_buffer1.data(),
11863 &(writer_->path_response_frames().front().data_buffer),
11864 sizeof(path_frame_buffer1)));
11865 EXPECT_EQ(1u, writer_->padding_frames().size());
11866 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11867 }))
11868 .WillOnce(Invoke([=]() {
11869 // The last write of ACK-only packet should still use the old peer
11870 // address.
11871 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11872 }));
11873 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11874 ENCRYPTION_FORWARD_SECURE);
11875}
11876
11877TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) {
11878 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11879 return;
11880 }
11881 PathProbeTestInit(Perspective::IS_SERVER);
11882
11883 QuicFrames frames;
11884 frames.push_back(QuicFrame(frame1_));
11885 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070011886 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
fayang161ce6e2022-07-01 18:02:11 -070011887 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
Bence Békybac04052022-04-07 15:44:29 -040011888 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
11889 /*port=*/23456);
11890
11891 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
11892 EXPECT_CALL(*send_algorithm_, OnConnectionMigration())
11893 .Times(connection_.validate_client_address() ? 0u : 1u);
11894 EXPECT_CALL(visitor_, OnStreamFrame(_))
11895 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
11896 // Send some data on the stream. The STREAM_FRAME should be built into
11897 // one packet together with the latter PATH_RESPONSE and PATH_CHALLENGE.
11898 const std::string data{"response body"};
11899 connection_.producer()->SaveStreamData(frame.stream_id, data);
11900 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11901 NO_FIN);
11902 }));
11903 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11904 .Times(connection_.validate_client_address() ? 0u : 1u);
11905 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11906 ENCRYPTION_FORWARD_SECURE);
11907
11908 // Verify that this packet contains a STREAM_FRAME and a
11909 // PATH_RESPONSE_FRAME.
11910 EXPECT_EQ(1u, writer_->stream_frames().size());
11911 EXPECT_EQ(1u, writer_->path_response_frames().size());
11912 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
11913 writer_->path_challenge_frames().size());
11914 // The final check is to ensure that the random data in the response
11915 // matches the random data from the challenge.
11916 EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
11917 &(writer_->path_response_frames().front().data_buffer),
11918 sizeof(path_frame_buffer)));
11919 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
11920 writer_->path_challenge_frames().size());
11921 EXPECT_EQ(1u, writer_->padding_frames().size());
11922 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11923 if (connection_.validate_client_address()) {
11924 EXPECT_TRUE(connection_.HasPendingPathValidation());
11925 }
11926}
11927
11928TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) {
11929 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11930 return;
11931 }
11932 PathProbeTestInit(Perspective::IS_SERVER);
11933
11934 QuicFrames frames;
11935 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070011936 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040011937 // PATH_RESPONSE should be flushed out before the rest packet is parsed.
11938 frames.push_back(QuicFrame(frame1_));
11939 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
11940 /*port=*/23456);
11941 QuicByteCount received_packet_size;
11942 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11943 .Times(AtLeast(1u))
11944 .WillOnce(Invoke([=, &received_packet_size]() {
11945 // Verify that this packet contains a PATH_RESPONSE_FRAME.
11946 EXPECT_EQ(0u, writer_->stream_frames().size());
11947 EXPECT_EQ(1u, writer_->path_response_frames().size());
11948 // The final check is to ensure that the random data in the response
11949 // matches the random data from the challenge.
11950 EXPECT_EQ(0,
11951 memcmp(path_frame_buffer.data(),
11952 &(writer_->path_response_frames().front().data_buffer),
11953 sizeof(path_frame_buffer)));
11954 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
11955 writer_->path_challenge_frames().size());
11956 EXPECT_EQ(1u, writer_->padding_frames().size());
11957 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11958 received_packet_size =
11959 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_);
11960 }));
11961 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
11962 EXPECT_CALL(*send_algorithm_, OnConnectionMigration())
11963 .Times(connection_.validate_client_address() ? 0u : 1u);
11964 EXPECT_CALL(visitor_, OnStreamFrame(_))
11965 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
11966 // Send some data on the stream. The STREAM_FRAME should be built into a
11967 // new packet but throttled by anti-amplifciation limit.
11968 const std::string data{"response body"};
11969 connection_.producer()->SaveStreamData(frame.stream_id, data);
11970 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11971 NO_FIN);
11972 }));
11973
11974 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11975 ENCRYPTION_FORWARD_SECURE);
11976 if (!connection_.validate_client_address()) {
11977 return;
11978 }
11979 EXPECT_TRUE(connection_.HasPendingPathValidation());
11980 EXPECT_EQ(0u,
11981 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
11982 EXPECT_EQ(
11983 received_packet_size,
11984 QuicConnectionPeer::BytesReceivedBeforeAddressValidation(&connection_));
11985}
11986
11987// Tests that a PATH_CHALLENGE is received in between other frames in an out of
11988// order packet.
11989TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) {
11990 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11991 return;
11992 }
11993 PathProbeTestInit(Perspective::IS_SERVER);
11994
11995 QuicFrames frames;
11996 frames.push_back(QuicFrame(frame1_));
11997 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070011998 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040011999 frames.push_back(QuicFrame(frame2_));
12000 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12001 /*port=*/23456);
12002
12003 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12004 EXPECT_CALL(visitor_, OnStreamFrame(_))
12005 .Times(2)
12006 .WillRepeatedly(Invoke([=](const QuicStreamFrame& frame) {
12007 // Send some data on the stream. The STREAM_FRAME should be built into
12008 // one packet together with the latter PATH_RESPONSE.
12009 const std::string data{"response body"};
12010 connection_.producer()->SaveStreamData(frame.stream_id, data);
12011 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
12012 NO_FIN);
12013 }));
12014 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
12015 .WillOnce(Invoke([=]() {
12016 // Verify that this packet contains a STREAM_FRAME and is sent to the
12017 // original peer address.
12018 EXPECT_EQ(1u, writer_->stream_frames().size());
12019 // No connection migration should happen because the packet is received
12020 // out of order.
12021 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12022 }))
12023 .WillOnce(Invoke([=]() {
12024 EXPECT_EQ(1u, writer_->path_response_frames().size());
12025 // The final check is to ensure that the random data in the response
12026 // matches the random data from the challenge.
12027 EXPECT_EQ(0,
12028 memcmp(path_frame_buffer.data(),
12029 &(writer_->path_response_frames().front().data_buffer),
12030 sizeof(path_frame_buffer)));
12031 EXPECT_EQ(1u, writer_->padding_frames().size());
12032 // PATH_RESPONSE should be sent in another packet to a different peer
12033 // address.
12034 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
12035 }))
12036 .WillOnce(Invoke([=]() {
12037 // Verify that this packet contains a STREAM_FRAME and is sent to the
12038 // original peer address.
12039 EXPECT_EQ(1u, writer_->stream_frames().size());
12040 // No connection migration should happen because the packet is received
12041 // out of order.
12042 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
12043 }));
12044 // Lower the packet number so that receiving this packet shouldn't trigger
12045 // peer migration.
12046 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12047 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12048 ENCRYPTION_FORWARD_SECURE);
12049}
12050
12051// Tests that a PATH_CHALLENGE is cached if its PATH_RESPONSE can't be sent.
12052TEST_P(QuicConnectionTest, FailToWritePathResponse) {
12053 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12054 return;
12055 }
12056 PathProbeTestInit(Perspective::IS_SERVER);
12057
12058 QuicFrames frames;
12059 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012060 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012061 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12062 /*port=*/23456);
12063
12064 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12065 // Lower the packet number so that receiving this packet shouldn't trigger
12066 // peer migration.
12067 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12068 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
12069 writer_->SetWriteBlocked();
12070 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12071 ENCRYPTION_FORWARD_SECURE);
12072}
12073
12074// Regression test for b/168101557.
12075TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) {
12076 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12077 return;
12078 }
12079 set_perspective(Perspective::IS_SERVER);
12080 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
12081 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12082 }
12083 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040012084 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12085 EXPECT_TRUE(connection_.HasPendingAcks());
12086
Bence Békybac04052022-04-07 15:44:29 -040012087 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12088 // Send INITIAL 1.
12089 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12090
martinduke9e0811c2022-12-08 20:35:57 -080012091 connection_.SetEncrypter(
12092 ENCRYPTION_HANDSHAKE,
12093 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012094 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12095 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080012096 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012097 // Send HANDSHAKE packets.
12098 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
12099 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12100
martinduke9e0811c2022-12-08 20:35:57 -080012101 connection_.SetEncrypter(
12102 ENCRYPTION_FORWARD_SECURE,
12103 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012104 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12105 // Send half RTT packet.
12106 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12107
12108 // Receives HANDSHAKE 1.
martinduke9e0811c2022-12-08 20:35:57 -080012109 peer_framer_.SetEncrypter(
12110 ENCRYPTION_HANDSHAKE,
12111 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012112 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
12113 // Discard INITIAL key.
12114 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12115 connection_.NeuterUnencryptedPackets();
12116 // Verify there is pending ACK.
12117 ASSERT_TRUE(connection_.HasPendingAcks());
12118 // Set the send alarm.
12119 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
12120
12121 // Fire ACK alarm.
12122 connection_.GetAckAlarm()->Fire();
12123 // Verify 1-RTT packet is coalesced with handshake packet.
12124 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12125 connection_.GetSendAlarm()->Fire();
12126
12127 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12128 connection_.GetRetransmissionAlarm()->Fire();
12129 // Verify a handshake packet gets PTOed and 1-RTT packet gets coalesced.
12130 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12131}
12132
12133// Regression test for b/168294218.
12134TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) {
12135 if (!connection_.version().CanSendCoalescedPackets()) {
12136 return;
12137 }
12138 SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true);
12139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
12140 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12141 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12142 connection_.NeuterUnencryptedPackets();
12143 }));
12144 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12145
12146 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
12147 {
12148 QuicConnection::ScopedPacketFlusher flusher(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040012149 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
12150 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
martinduke9e0811c2022-12-08 20:35:57 -080012151 connection_.SetEncrypter(
12152 ENCRYPTION_HANDSHAKE,
12153 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012154 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12155 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
12156 // Verify this packet is on hold.
12157 EXPECT_EQ(0u, writer_->packets_write_attempts());
12158 }
12159 EXPECT_TRUE(connection_.connected());
12160}
12161
12162// Regresstion test for b/168294218
12163TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) {
12164 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12165 return;
12166 }
12167 // Not defer send in response to packet.
12168 connection_.set_defer_send_in_response_to_packets(false);
12169 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12170 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12171 connection_.NeuterUnencryptedPackets();
12172 }));
12173 EXPECT_CALL(visitor_, OnCryptoFrame(_))
12174 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
12175 if (frame.level == ENCRYPTION_HANDSHAKE) {
12176 // 0-RTT gets rejected.
12177 connection_.MarkZeroRttPacketsForRetransmission(0);
12178 // Send Crypto data.
martinduke9e0811c2022-12-08 20:35:57 -080012179 connection_.SetEncrypter(
12180 ENCRYPTION_HANDSHAKE,
12181 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012182 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12183 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
martinduke9e0811c2022-12-08 20:35:57 -080012184 connection_.SetEncrypter(
12185 ENCRYPTION_FORWARD_SECURE,
12186 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012187 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12188 // Advance INITIAL ack delay to trigger initial ACK to be sent AFTER
12189 // the retransmission of rejected 0-RTT packets while the HANDSHAKE
12190 // packet is still in the coalescer, such that the INITIAL key gets
12191 // dropped between SendAllPendingAcks and actually send the ack frame,
12192 // bummer.
12193 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12194 }
12195 }));
Bence Békybac04052022-04-07 15:44:29 -040012196 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12197 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080012198 connection_.SetEncrypter(
12199 ENCRYPTION_ZERO_RTT,
12200 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040012201 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12202 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12203
12204 QuicAckFrame frame1 = InitAckFrame(1);
12205 // Received ACK for packet 1.
12206 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
12207 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
12208 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12209
12210 // Fire retransmission alarm.
12211 connection_.GetRetransmissionAlarm()->Fire();
12212
12213 QuicFrames frames1;
12214 frames1.push_back(QuicFrame(&crypto_frame_));
12215 QuicFrames frames2;
12216 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12217 absl::string_view(data1));
12218 frames2.push_back(QuicFrame(&crypto_frame));
12219 ProcessCoalescedPacket(
12220 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
12221}
12222
12223TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) {
12224 if (!connection_.version().UsesTls()) {
12225 return;
12226 }
12227 MockQuicConnectionDebugVisitor debug_visitor;
12228 connection_.set_debug_visitor(&debug_visitor);
Bence Békybac04052022-04-07 15:44:29 -040012229 connection_.SendCryptoStreamData();
12230 // Send 0-RTT packet.
12231 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
12232 std::make_unique<TaggingEncrypter>(0x02));
12233 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12234 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12235 connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN);
12236 // Received ACK for packet 1, HANDSHAKE packet and 1-RTT ACK.
12237 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
12238 .Times(AnyNumber());
12239 QuicFrames frames1;
12240 QuicAckFrame ack_frame1 = InitAckFrame(1);
12241 frames1.push_back(QuicFrame(&ack_frame1));
12242
12243 QuicFrames frames2;
12244 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12245 absl::string_view(data1));
12246 frames2.push_back(QuicFrame(&crypto_frame));
12247 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12248 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
12249 ProcessCoalescedPacket(
12250 {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}});
12251
12252 QuicFrames frames3;
12253 QuicAckFrame ack_frame2 =
12254 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
12255 frames3.push_back(QuicFrame(&ack_frame2));
12256 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1);
12257 ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}});
12258
12259 QuicFrames frames4;
12260 QuicAckFrame ack_frame3 =
12261 InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}});
12262 frames4.push_back(QuicFrame(&ack_frame3));
12263 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12264 ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}});
12265}
12266
12267TEST_P(QuicConnectionTest, InitiateKeyUpdate) {
12268 if (!connection_.version().UsesTls()) {
12269 return;
12270 }
12271
12272 TransportParameters params;
12273 QuicConfig config;
12274 std::string error_details;
12275 EXPECT_THAT(config.ProcessTransportParameters(
12276 params, /* is_resumption = */ false, &error_details),
12277 IsQuicNoError());
12278 QuicConfigPeer::SetNegotiated(&config, true);
12279 if (connection_.version().UsesTls()) {
12280 QuicConfigPeer::SetReceivedOriginalConnectionId(
12281 &config, connection_.connection_id());
12282 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12283 &config, connection_.connection_id());
12284 }
12285 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12286 connection_.SetFromConfig(config);
12287
12288 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12289
12290 MockFramerVisitor peer_framer_visitor_;
12291 peer_framer_.set_visitor(&peer_framer_visitor_);
12292
martinduke9e0811c2022-12-08 20:35:57 -080012293 uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012294 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12295 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012296 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012297 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012298 std::make_unique<StrictTaggingDecrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012299 EXPECT_CALL(visitor_, GetHandshakeState())
12300 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12301 connection_.OnHandshakeComplete();
12302
12303 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012304 std::make_unique<TaggingEncrypter>(correct_tag));
Bence Békybac04052022-04-07 15:44:29 -040012305
12306 // Key update should still not be allowed, since no packet has been acked
12307 // from the current key phase.
12308 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12309 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12310
12311 // Send packet 1.
12312 QuicPacketNumber last_packet;
12313 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12314 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12315
12316 // Key update should still not be allowed, even though a packet was sent in
12317 // the current key phase it hasn't been acked yet.
12318 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12319 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12320
12321 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12322 // Receive ack for packet 1.
12323 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12324 QuicAckFrame frame1 = InitAckFrame(1);
12325 ProcessAckPacket(&frame1);
12326
12327 // OnDecryptedFirstPacketInKeyPhase is called even on the first key phase,
12328 // so discard_previous_keys_alarm_ should be set now.
12329 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12330 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12331
martinduke9e0811c2022-12-08 20:35:57 -080012332 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012333 // Key update should now be allowed.
12334 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012335 .WillOnce([&correct_tag]() {
12336 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12337 });
12338 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12339 .WillOnce([&correct_tag]() {
12340 return std::make_unique<TaggingEncrypter>(correct_tag);
12341 });
Bence Békybac04052022-04-07 15:44:29 -040012342 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12343 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12344 // discard_previous_keys_alarm_ should not be set until a packet from the new
12345 // key phase has been received. (The alarm that was set above should be
12346 // cleared if it hasn't fired before the next key update happened.)
12347 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12348 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12349
12350 // Pretend that peer accepts the key update.
12351 EXPECT_CALL(peer_framer_visitor_,
12352 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012353 .WillOnce([&correct_tag]() {
12354 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12355 });
Bence Békybac04052022-04-07 15:44:29 -040012356 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012357 .WillOnce([&correct_tag]() {
12358 return std::make_unique<TaggingEncrypter>(correct_tag);
12359 });
Bence Békybac04052022-04-07 15:44:29 -040012360 peer_framer_.SetKeyUpdateSupportForConnection(true);
12361 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12362
12363 // Another key update should not be allowed yet.
12364 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12365
12366 // Send packet 2.
12367 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12368 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12369 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12370 // Receive ack for packet 2.
12371 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12372 QuicAckFrame frame2 = InitAckFrame(2);
12373 ProcessAckPacket(&frame2);
12374 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12375 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12376
martinduke9e0811c2022-12-08 20:35:57 -080012377 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012378 // Key update should be allowed again now that a packet has been acked from
12379 // the current key phase.
12380 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012381 .WillOnce([&correct_tag]() {
12382 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12383 });
12384 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12385 .WillOnce([&correct_tag]() {
12386 return std::make_unique<TaggingEncrypter>(correct_tag);
12387 });
Bence Békybac04052022-04-07 15:44:29 -040012388 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12389 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12390
12391 // Pretend that peer accepts the key update.
12392 EXPECT_CALL(peer_framer_visitor_,
12393 AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012394 .WillOnce([&correct_tag]() {
12395 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12396 });
Bence Békybac04052022-04-07 15:44:29 -040012397 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012398 .WillOnce([&correct_tag]() {
12399 return std::make_unique<TaggingEncrypter>(correct_tag);
12400 });
Bence Békybac04052022-04-07 15:44:29 -040012401 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12402
12403 // Another key update should not be allowed yet.
12404 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12405
12406 // Send packet 3.
12407 SendStreamDataToPeer(3, "baz", 0, NO_FIN, &last_packet);
12408 EXPECT_EQ(QuicPacketNumber(3u), last_packet);
12409
12410 // Another key update should not be allowed yet.
12411 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12412 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12413
12414 // Receive ack for packet 3.
12415 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12416 QuicAckFrame frame3 = InitAckFrame(3);
12417 ProcessAckPacket(&frame3);
12418 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12419 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12420
martinduke9e0811c2022-12-08 20:35:57 -080012421 correct_tag++;
Bence Békybac04052022-04-07 15:44:29 -040012422 // Key update should be allowed now.
12423 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
martinduke9e0811c2022-12-08 20:35:57 -080012424 .WillOnce([&correct_tag]() {
12425 return std::make_unique<StrictTaggingDecrypter>(correct_tag);
12426 });
12427 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12428 .WillOnce([&correct_tag]() {
12429 return std::make_unique<TaggingEncrypter>(correct_tag);
12430 });
Bence Békybac04052022-04-07 15:44:29 -040012431 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12432 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12433 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12434 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12435}
12436
12437TEST_P(QuicConnectionTest, InitiateKeyUpdateApproachingConfidentialityLimit) {
12438 if (!connection_.version().UsesTls()) {
12439 return;
12440 }
12441
birenroyef686222022-09-12 11:34:34 -070012442 SetQuicFlag(quic_key_update_confidentiality_limit, 3U);
Bence Békybac04052022-04-07 15:44:29 -040012443
12444 std::string error_details;
12445 TransportParameters params;
12446 // Key update is enabled.
12447 QuicConfig config;
12448 EXPECT_THAT(config.ProcessTransportParameters(
12449 params, /* is_resumption = */ false, &error_details),
12450 IsQuicNoError());
12451 QuicConfigPeer::SetNegotiated(&config, true);
12452 if (connection_.version().UsesTls()) {
12453 QuicConfigPeer::SetReceivedOriginalConnectionId(
12454 &config, connection_.connection_id());
12455 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12456 &config, connection_.connection_id());
12457 }
12458 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12459 connection_.SetFromConfig(config);
12460
12461 MockFramerVisitor peer_framer_visitor_;
12462 peer_framer_.set_visitor(&peer_framer_visitor_);
12463
martinduke9e0811c2022-12-08 20:35:57 -080012464 uint8_t current_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012465
12466 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12467 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12468 std::make_unique<TaggingEncrypter>(current_tag));
12469 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12470 std::make_unique<StrictTaggingDecrypter>(current_tag));
12471 EXPECT_CALL(visitor_, GetHandshakeState())
12472 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12473 connection_.OnHandshakeComplete();
12474
12475 peer_framer_.SetKeyUpdateSupportForConnection(true);
12476 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12477 std::make_unique<TaggingEncrypter>(current_tag));
12478
12479 const QuicConnectionStats& stats = connection_.GetStats();
12480
12481 for (int packet_num = 1; packet_num <= 8; ++packet_num) {
12482 if (packet_num == 3 || packet_num == 6) {
12483 current_tag++;
12484 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12485 .WillOnce([current_tag]() {
12486 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12487 });
12488 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12489 .WillOnce([current_tag]() {
12490 return std::make_unique<TaggingEncrypter>(current_tag);
12491 });
12492 EXPECT_CALL(visitor_,
12493 OnKeyUpdate(KeyUpdateReason::kLocalKeyUpdateLimitOverride));
12494 }
12495 // Send packet.
12496 QuicPacketNumber last_packet;
12497 SendStreamDataToPeer(packet_num, "foo", 0, NO_FIN, &last_packet);
12498 EXPECT_EQ(QuicPacketNumber(packet_num), last_packet);
12499 if (packet_num >= 6) {
12500 EXPECT_EQ(2U, stats.key_update_count);
12501 } else if (packet_num >= 3) {
12502 EXPECT_EQ(1U, stats.key_update_count);
12503 } else {
12504 EXPECT_EQ(0U, stats.key_update_count);
12505 }
12506
12507 if (packet_num == 4 || packet_num == 7) {
12508 // Pretend that peer accepts the key update.
12509 EXPECT_CALL(peer_framer_visitor_,
12510 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12511 .WillOnce([current_tag]() {
12512 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12513 });
12514 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12515 .WillOnce([current_tag]() {
12516 return std::make_unique<TaggingEncrypter>(current_tag);
12517 });
12518 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12519 }
12520 // Receive ack for packet.
12521 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12522 QuicAckFrame frame1 = InitAckFrame(packet_num);
12523 ProcessAckPacket(&frame1);
12524 }
12525}
12526
12527TEST_P(QuicConnectionTest,
12528 CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed) {
12529 if (!connection_.version().UsesTls()) {
12530 return;
12531 }
12532
12533 // Set key update confidentiality limit to 1 packet.
birenroyef686222022-09-12 11:34:34 -070012534 SetQuicFlag(quic_key_update_confidentiality_limit, 1U);
Bence Békybac04052022-04-07 15:44:29 -040012535 // Use confidentiality limit for connection close of 3 packets.
12536 constexpr size_t kConfidentialityLimit = 3U;
12537
12538 std::string error_details;
12539 TransportParameters params;
12540 // Key update is enabled.
12541 QuicConfig config;
12542 EXPECT_THAT(config.ProcessTransportParameters(
12543 params, /* is_resumption = */ false, &error_details),
12544 IsQuicNoError());
12545 QuicConfigPeer::SetNegotiated(&config, true);
12546 if (connection_.version().UsesTls()) {
12547 QuicConfigPeer::SetReceivedOriginalConnectionId(
12548 &config, connection_.connection_id());
12549 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12550 &config, connection_.connection_id());
12551 }
12552 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12553 connection_.SetFromConfig(config);
12554
12555 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12556 connection_.SetEncrypter(
12557 ENCRYPTION_FORWARD_SECURE,
martinduke9e0811c2022-12-08 20:35:57 -080012558 std::make_unique<TaggingEncrypterWithConfidentialityLimit>(
12559 ENCRYPTION_FORWARD_SECURE, kConfidentialityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012560 EXPECT_CALL(visitor_, GetHandshakeState())
12561 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12562 connection_.OnHandshakeComplete();
12563
12564 QuicPacketNumber last_packet;
12565 // Send 3 packets without receiving acks for any of them. Key update will not
12566 // be allowed, so the confidentiality limit should be reached, forcing the
12567 // connection to be closed.
12568 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12569 EXPECT_TRUE(connection_.connected());
12570 SendStreamDataToPeer(2, "foo", 0, NO_FIN, &last_packet);
12571 EXPECT_TRUE(connection_.connected());
12572 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12573 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
12574 EXPECT_FALSE(connection_.connected());
12575 const QuicConnectionStats& stats = connection_.GetStats();
12576 EXPECT_EQ(0U, stats.key_update_count);
12577 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12578}
12579
12580TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitDuringHandshake) {
12581 if (!connection_.version().UsesTls()) {
12582 return;
12583 }
12584
martinduke9e0811c2022-12-08 20:35:57 -080012585 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012586 constexpr uint8_t wrong_tag = 0xFE;
12587 constexpr QuicPacketCount kIntegrityLimit = 3;
12588
12589 SetDecrypter(ENCRYPTION_HANDSHAKE,
12590 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12591 correct_tag, kIntegrityLimit));
12592 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12593 std::make_unique<TaggingEncrypter>(correct_tag));
12594 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12595 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12596 std::make_unique<TaggingEncrypter>(wrong_tag));
12597 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12598 EXPECT_TRUE(connection_.connected());
12599 if (i == kIntegrityLimit) {
12600 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12601 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
12602 }
12603 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12604 EXPECT_EQ(
12605 i, connection_.GetStats().num_failed_authentication_packets_received);
12606 }
12607 EXPECT_FALSE(connection_.connected());
12608 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12609}
12610
12611TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAfterHandshake) {
12612 if (!connection_.version().UsesTls()) {
12613 return;
12614 }
12615
martinduke9e0811c2022-12-08 20:35:57 -080012616 constexpr uint8_t correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012617 constexpr uint8_t wrong_tag = 0xFE;
12618 constexpr QuicPacketCount kIntegrityLimit = 3;
12619
Bence Békybac04052022-04-07 15:44:29 -040012620 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12621 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12622 correct_tag, kIntegrityLimit));
12623 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12624 std::make_unique<TaggingEncrypter>(correct_tag));
12625 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12626 EXPECT_CALL(visitor_, GetHandshakeState())
12627 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12628 connection_.OnHandshakeComplete();
12629 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12630 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12631 std::make_unique<TaggingEncrypter>(wrong_tag));
12632 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12633 EXPECT_TRUE(connection_.connected());
12634 if (i == kIntegrityLimit) {
12635 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12636 }
12637 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12638 EXPECT_EQ(
12639 i, connection_.GetStats().num_failed_authentication_packets_received);
12640 }
12641 EXPECT_FALSE(connection_.connected());
12642 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12643}
12644
12645TEST_P(QuicConnectionTest,
12646 CloseConnectionOnIntegrityLimitAcrossEncryptionLevels) {
12647 if (!connection_.version().UsesTls()) {
12648 return;
12649 }
12650
martinduke9e0811c2022-12-08 20:35:57 -080012651 uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012652 constexpr uint8_t wrong_tag = 0xFE;
12653 constexpr QuicPacketCount kIntegrityLimit = 4;
12654
Bence Békybac04052022-04-07 15:44:29 -040012655 SetDecrypter(ENCRYPTION_HANDSHAKE,
12656 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12657 correct_tag, kIntegrityLimit));
12658 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12659 std::make_unique<TaggingEncrypter>(correct_tag));
12660 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12661 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12662 std::make_unique<TaggingEncrypter>(wrong_tag));
12663 for (uint64_t i = 1; i <= 2; ++i) {
12664 EXPECT_TRUE(connection_.connected());
12665 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12666 EXPECT_EQ(
12667 i, connection_.GetStats().num_failed_authentication_packets_received);
12668 }
12669
martinduke9e0811c2022-12-08 20:35:57 -080012670 correct_tag = ENCRYPTION_FORWARD_SECURE;
Bence Békybac04052022-04-07 15:44:29 -040012671 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12672 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12673 correct_tag, kIntegrityLimit));
12674 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12675 std::make_unique<TaggingEncrypter>(correct_tag));
12676 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12677 EXPECT_CALL(visitor_, GetHandshakeState())
12678 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12679 connection_.OnHandshakeComplete();
12680 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12681 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
12682 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12683 std::make_unique<TaggingEncrypter>(wrong_tag));
12684 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12685 EXPECT_TRUE(connection_.connected());
12686 if (i == kIntegrityLimit) {
12687 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12688 }
12689 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12690 EXPECT_EQ(
12691 i, connection_.GetStats().num_failed_authentication_packets_received);
12692 }
12693 EXPECT_FALSE(connection_.connected());
12694 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12695}
12696
12697TEST_P(QuicConnectionTest, IntegrityLimitDoesNotApplyWithoutDecryptionKey) {
12698 if (!connection_.version().UsesTls()) {
12699 return;
12700 }
12701
martinduke9e0811c2022-12-08 20:35:57 -080012702 constexpr uint8_t correct_tag = ENCRYPTION_HANDSHAKE;
Bence Békybac04052022-04-07 15:44:29 -040012703 constexpr uint8_t wrong_tag = 0xFE;
12704 constexpr QuicPacketCount kIntegrityLimit = 3;
12705
Bence Békybac04052022-04-07 15:44:29 -040012706 SetDecrypter(ENCRYPTION_HANDSHAKE,
12707 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12708 correct_tag, kIntegrityLimit));
12709 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12710 std::make_unique<TaggingEncrypter>(correct_tag));
12711 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12712 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
12713
12714 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12715 std::make_unique<TaggingEncrypter>(wrong_tag));
12716 for (uint64_t i = 1; i <= kIntegrityLimit * 2; ++i) {
12717 EXPECT_TRUE(connection_.connected());
12718 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12719 EXPECT_EQ(
12720 0u, connection_.GetStats().num_failed_authentication_packets_received);
12721 }
12722 EXPECT_TRUE(connection_.connected());
12723}
12724
12725TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossKeyPhases) {
12726 if (!connection_.version().UsesTls()) {
12727 return;
12728 }
12729
12730 constexpr QuicPacketCount kIntegrityLimit = 4;
12731
12732 TransportParameters params;
12733 QuicConfig config;
12734 std::string error_details;
12735 EXPECT_THAT(config.ProcessTransportParameters(
12736 params, /* is_resumption = */ false, &error_details),
12737 IsQuicNoError());
12738 QuicConfigPeer::SetNegotiated(&config, true);
12739 if (connection_.version().UsesTls()) {
12740 QuicConfigPeer::SetReceivedOriginalConnectionId(
12741 &config, connection_.connection_id());
12742 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12743 &config, connection_.connection_id());
12744 }
12745 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12746 connection_.SetFromConfig(config);
12747
12748 MockFramerVisitor peer_framer_visitor_;
12749 peer_framer_.set_visitor(&peer_framer_visitor_);
12750
Bence Békybac04052022-04-07 15:44:29 -040012751 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12752 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12753 std::make_unique<TaggingEncrypter>(0x01));
12754 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12755 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
martinduke9e0811c2022-12-08 20:35:57 -080012756 ENCRYPTION_FORWARD_SECURE, kIntegrityLimit));
Bence Békybac04052022-04-07 15:44:29 -040012757 EXPECT_CALL(visitor_, GetHandshakeState())
12758 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12759 connection_.OnHandshakeComplete();
12760 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12761
12762 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12763 std::make_unique<TaggingEncrypter>(0xFF));
12764 for (uint64_t i = 1; i <= 2; ++i) {
12765 EXPECT_TRUE(connection_.connected());
12766 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12767 EXPECT_EQ(
12768 i, connection_.GetStats().num_failed_authentication_packets_received);
12769 }
12770
martinduke9e0811c2022-12-08 20:35:57 -080012771 peer_framer_.SetEncrypter(
12772 ENCRYPTION_FORWARD_SECURE,
12773 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040012774 // Send packet 1.
12775 QuicPacketNumber last_packet;
12776 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12777 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12778 // Receive ack for packet 1.
12779 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12780 QuicAckFrame frame1 = InitAckFrame(1);
12781 ProcessAckPacket(&frame1);
12782 // Key update should now be allowed, initiate it.
12783 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12784 .WillOnce([kIntegrityLimit]() {
12785 return std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12786 0x02, kIntegrityLimit);
12787 });
12788 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12789 return std::make_unique<TaggingEncrypter>(0x02);
12790 });
12791 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12792 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12793
12794 // Pretend that peer accepts the key update.
12795 EXPECT_CALL(peer_framer_visitor_,
12796 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12797 .WillOnce(
12798 []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
12799 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12800 .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); });
12801 peer_framer_.SetKeyUpdateSupportForConnection(true);
12802 peer_framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests);
12803
12804 // Send packet 2.
12805 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12806 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12807 // Receive ack for packet 2.
12808 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12809 QuicAckFrame frame2 = InitAckFrame(2);
12810 ProcessAckPacket(&frame2);
12811
12812 EXPECT_EQ(2u,
12813 connection_.GetStats().num_failed_authentication_packets_received);
12814
12815 // Do two more undecryptable packets. Integrity limit should be reached.
12816 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12817 std::make_unique<TaggingEncrypter>(0xFF));
12818 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12819 EXPECT_TRUE(connection_.connected());
12820 if (i == kIntegrityLimit) {
12821 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12822 }
12823 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12824 EXPECT_EQ(
12825 i, connection_.GetStats().num_failed_authentication_packets_received);
12826 }
12827 EXPECT_FALSE(connection_.connected());
12828 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12829}
12830
12831TEST_P(QuicConnectionTest, SendAckFrequencyFrame) {
12832 if (!version().HasIetfQuicFrames()) {
12833 return;
12834 }
12835 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12836 set_perspective(Perspective::IS_SERVER);
12837 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
12838 .Times(AnyNumber());
12839 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12840
12841 QuicConfig config;
12842 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
12843 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12844 connection_.SetFromConfig(config);
12845 QuicConnectionPeer::SetAddressValidated(&connection_);
12846 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12847 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
12848
12849 connection_.OnHandshakeComplete();
12850
12851 writer_->SetWritable();
12852 QuicPacketCreatorPeer::SetPacketNumber(creator_, 99);
12853 // Send packet 100
12854 SendStreamDataToPeer(/*id=*/1, "foo", /*offset=*/0, NO_FIN, nullptr);
12855
12856 QuicAckFrequencyFrame captured_frame;
12857 EXPECT_CALL(visitor_, SendAckFrequency(_))
12858 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
12859 captured_frame = frame;
12860 }));
12861 // Send packet 101.
12862 SendStreamDataToPeer(/*id=*/1, "bar", /*offset=*/3, NO_FIN, nullptr);
12863
12864 EXPECT_EQ(captured_frame.packet_tolerance, 10u);
12865 EXPECT_EQ(captured_frame.max_ack_delay,
12866 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
12867
12868 // Sending packet 102 does not trigger sending another AckFrequencyFrame.
12869 SendStreamDataToPeer(/*id=*/1, "baz", /*offset=*/6, NO_FIN, nullptr);
12870}
12871
12872TEST_P(QuicConnectionTest, SendAckFrequencyFrameUponHandshakeCompletion) {
12873 if (!version().HasIetfQuicFrames()) {
12874 return;
12875 }
12876 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12877 set_perspective(Perspective::IS_SERVER);
12878 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
12879 .Times(AnyNumber());
12880 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12881
12882 QuicConfig config;
12883 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
12884 QuicTagVector quic_tag_vector;
12885 // Enable sending AckFrequency upon handshake completion.
12886 quic_tag_vector.push_back(kAFF2);
12887 QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector);
12888 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12889 connection_.SetFromConfig(config);
12890 QuicConnectionPeer::SetAddressValidated(&connection_);
12891 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12892 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
12893
12894 QuicAckFrequencyFrame captured_frame;
12895 EXPECT_CALL(visitor_, SendAckFrequency(_))
12896 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
12897 captured_frame = frame;
12898 }));
12899
12900 connection_.OnHandshakeComplete();
12901
12902 EXPECT_EQ(captured_frame.packet_tolerance, 2u);
12903 EXPECT_EQ(captured_frame.max_ack_delay,
12904 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
12905}
12906
12907TEST_P(QuicConnectionTest, FastRecoveryOfLostServerHello) {
12908 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12909 return;
12910 }
12911 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12912 QuicConfig config;
12913 connection_.SetFromConfig(config);
12914
Bence Békybac04052022-04-07 15:44:29 -040012915 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12916 connection_.SendCryptoStreamData();
12917 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
12918
12919 // Assume ServerHello gets lost.
12920 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12921 std::make_unique<TaggingEncrypter>(0x02));
12922 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
12923 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12924 // Shorten PTO for fast recovery from lost ServerHello.
12925 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
12926 connection_.GetRetransmissionAlarm()->deadline());
12927}
12928
12929TEST_P(QuicConnectionTest, ServerHelloGetsReordered) {
12930 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12931 return;
12932 }
12933 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12934 QuicConfig config;
12935 connection_.SetFromConfig(config);
12936 EXPECT_CALL(visitor_, OnCryptoFrame(_))
12937 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
12938 if (frame.level == ENCRYPTION_INITIAL) {
12939 // Install handshake read keys.
martinduke9e0811c2022-12-08 20:35:57 -080012940 SetDecrypter(
12941 ENCRYPTION_HANDSHAKE,
12942 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
12943 connection_.SetEncrypter(
12944 ENCRYPTION_HANDSHAKE,
12945 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040012946 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12947 }
12948 }));
12949
Bence Békybac04052022-04-07 15:44:29 -040012950 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12951 connection_.SendCryptoStreamData();
12952 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
12953
12954 // Assume ServerHello gets reordered.
12955 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12956 std::make_unique<TaggingEncrypter>(0x02));
12957 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
12958 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12959 // Verify fast recovery is not enabled.
12960 EXPECT_EQ(connection_.sent_packet_manager().GetRetransmissionTime(),
12961 connection_.GetRetransmissionAlarm()->deadline());
12962}
12963
12964TEST_P(QuicConnectionTest, MigratePath) {
12965 EXPECT_CALL(visitor_, GetHandshakeState())
12966 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12967 EXPECT_CALL(visitor_, OnPathDegrading());
12968 connection_.OnPathDegradingDetected();
12969 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
12970 EXPECT_NE(kNewSelfAddress, connection_.self_address());
12971
12972 // Buffer a packet.
12973 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
12974 writer_->SetWriteBlocked();
12975 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
12976 EXPECT_EQ(1u, connection_.NumQueuedPackets());
12977
12978 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
12979 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
12980 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
12981 &new_writer, /*owns_writer=*/false);
12982
12983 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
12984 EXPECT_EQ(&new_writer, QuicConnectionPeer::GetWriter(&connection_));
12985 EXPECT_FALSE(connection_.IsPathDegrading());
12986 // Buffered packet on the old path should be discarded.
12987 if (connection_.connection_migration_use_new_cid()) {
12988 EXPECT_EQ(0u, connection_.NumQueuedPackets());
12989 } else {
12990 EXPECT_EQ(1u, connection_.NumQueuedPackets());
12991 }
12992}
12993
12994TEST_P(QuicConnectionTest, MigrateToNewPathDuringProbing) {
danzh87605712022-04-11 14:36:39 -070012995 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040012996 return;
12997 }
12998 PathProbeTestInit(Perspective::IS_CLIENT);
12999 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
13000 EXPECT_NE(kNewSelfAddress, connection_.self_address());
13001 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13002 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13003 bool success = false;
13004 connection_.ValidatePath(
13005 std::make_unique<TestQuicPathValidationContext>(
13006 kNewSelfAddress, connection_.peer_address(), &new_writer),
13007 std::make_unique<TestValidationResultDelegate>(
13008 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
13009 EXPECT_TRUE(connection_.HasPendingPathValidation());
13010 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13011 &connection_, kNewSelfAddress, connection_.peer_address()));
13012
13013 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
13014 &new_writer, /*owns_writer=*/false);
13015 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
13016 EXPECT_TRUE(connection_.HasPendingPathValidation());
13017 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13018 &connection_, kNewSelfAddress, connection_.peer_address()));
13019}
13020
renjietang89540a62022-12-01 14:46:26 -080013021TEST_P(QuicConnectionTest, MultiPortConnection) {
renjietangfca5c772022-08-25 13:48:21 -070013022 set_perspective(Perspective::IS_CLIENT);
13023 QuicConfig config;
renjietang89540a62022-12-01 14:46:26 -080013024 config.SetConnectionOptionsToSend(QuicTagVector{kRVCM});
13025 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
renjietangfca5c772022-08-25 13:48:21 -070013026 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13027 connection_.SetFromConfig(config);
13028 if (!connection_.connection_migration_use_new_cid()) {
13029 return;
13030 }
13031 connection_.CreateConnectionIdManager();
13032 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13033 connection_.OnHandshakeComplete();
13034
renjietang864fbda2022-09-08 10:50:07 -070013035 EXPECT_CALL(visitor_, OnPathDegrading());
13036 connection_.OnPathDegradingDetected();
13037
renjietangfca5c772022-08-25 13:48:21 -070013038 auto self_address = connection_.self_address();
13039 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13040 self_address.port() + 1);
13041 EXPECT_NE(kNewSelfAddress, self_address);
13042 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13043
renjietang89540a62022-12-01 14:46:26 -080013044 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
renjietangfca5c772022-08-25 13:48:21 -070013045 QuicNewConnectionIdFrame frame;
13046 frame.connection_id = TestConnectionId(1234);
13047 ASSERT_NE(frame.connection_id, connection_.connection_id());
13048 frame.stateless_reset_token =
13049 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13050 frame.retire_prior_to = 0u;
13051 frame.sequence_number = 1u;
13052 EXPECT_CALL(visitor_, CreateContextForMultiPortPath())
13053 .WillRepeatedly(Return(
13054 testing::ByMove(std::make_unique<TestQuicPathValidationContext>(
13055 kNewSelfAddress, connection_.peer_address(), &new_writer))));
13056 connection_.OnNewConnectionIdFrame(frame);
13057 EXPECT_TRUE(connection_.HasPendingPathValidation());
13058 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13059 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013060 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13061 EXPECT_FALSE(alt_path->validated);
renjietangfca5c772022-08-25 13:48:21 -070013062
renjietang864fbda2022-09-08 10:50:07 -070013063 // 30ms RTT.
13064 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13065 // Fake a response delay.
13066 clock_.AdvanceTime(kTestRTT);
13067
renjietangfca5c772022-08-25 13:48:21 -070013068 QuicFrames frames;
13069 frames.push_back(QuicFrame(QuicPathResponseFrame(
renjietang89540a62022-12-01 14:46:26 -080013070 99, new_writer.path_challenge_frames().back().data_buffer)));
renjietangfca5c772022-08-25 13:48:21 -070013071 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13072 ENCRYPTION_FORWARD_SECURE);
13073 // No migration should happen and the alternative path should still be alive.
13074 EXPECT_FALSE(connection_.HasPendingPathValidation());
13075 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13076 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013077 EXPECT_TRUE(alt_path->validated);
renjietangfca5c772022-08-25 13:48:21 -070013078
renjietang864fbda2022-09-08 10:50:07 -070013079 auto stats = connection_.multi_port_stats();
13080 EXPECT_EQ(1, stats->num_path_degrading);
13081 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13082 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13083 EXPECT_EQ(kTestRTT,
13084 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13085
renjietang89540a62022-12-01 14:46:26 -080013086 // When there's no active request, the probing shouldn't happen. But the
13087 // probing context should be saved.
13088 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive()).WillOnce(Return(false));
13089 connection_.GetMultiPortProbingAlarm()->Fire();
13090 EXPECT_FALSE(connection_.HasPendingPathValidation());
13091 EXPECT_FALSE(connection_.GetMultiPortProbingAlarm()->IsSet());
13092
13093 // Simulate the situation where a new request stream is created.
13094 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13095 .WillRepeatedly(Return(true));
13096 random_generator_.ChangeValue();
13097 connection_.MaybeProbeMultiPortPath();
13098 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13099 &connection_, kNewSelfAddress, connection_.peer_address()));
13100 EXPECT_TRUE(alt_path->validated);
13101 // Fake a response delay.
13102 clock_.AdvanceTime(kTestRTT);
13103 QuicFrames frames2;
13104 frames2.push_back(QuicFrame(QuicPathResponseFrame(
13105 99, new_writer.path_challenge_frames().back().data_buffer)));
13106 ProcessFramesPacketWithAddresses(frames2, kNewSelfAddress, kPeerAddress,
13107 ENCRYPTION_FORWARD_SECURE);
13108 // No migration should happen and the alternative path should still be alive.
13109 EXPECT_FALSE(connection_.HasPendingPathValidation());
13110 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13111 &connection_, kNewSelfAddress, connection_.peer_address()));
13112 EXPECT_TRUE(alt_path->validated);
13113 EXPECT_EQ(1, stats->num_path_degrading);
13114 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13115 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13116 EXPECT_EQ(kTestRTT,
13117 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13118
13119 EXPECT_TRUE(connection_.GetMultiPortProbingAlarm()->IsSet());
13120 // Since there's already a scheduled probing alarm, manual calls won't have
13121 // any effect.
13122 connection_.MaybeProbeMultiPortPath();
13123 EXPECT_FALSE(connection_.HasPendingPathValidation());
13124
13125 // Simulate the case where the path validation fails after retries.
renjietangfca5c772022-08-25 13:48:21 -070013126 connection_.GetMultiPortProbingAlarm()->Fire();
13127 EXPECT_TRUE(connection_.HasPendingPathValidation());
13128 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13129 &connection_, kNewSelfAddress, connection_.peer_address()));
13130 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13131 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13132 static_cast<TestAlarmFactory::TestAlarm*>(
13133 QuicPathValidatorPeer::retry_timer(
13134 QuicConnectionPeer::path_validator(&connection_)))
13135 ->Fire();
13136 }
13137
13138 EXPECT_FALSE(connection_.HasPendingPathValidation());
13139 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13140 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang864fbda2022-09-08 10:50:07 -070013141 EXPECT_EQ(1, stats->num_path_degrading);
13142 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13143 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_not_degrading);
renjietangfca5c772022-08-25 13:48:21 -070013144}
13145
renjietang89540a62022-12-01 14:46:26 -080013146TEST_P(QuicConnectionTest, TooManyMultiPortPathCreations) {
13147 set_perspective(Perspective::IS_CLIENT);
13148 QuicConfig config;
13149 config.SetConnectionOptionsToSend(QuicTagVector{kRVCM});
13150 config.SetClientConnectionOptions(QuicTagVector{kMPQC});
13151 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13152 connection_.SetFromConfig(config);
13153 if (!connection_.connection_migration_use_new_cid()) {
13154 return;
13155 }
13156 connection_.CreateConnectionIdManager();
13157 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13158 connection_.OnHandshakeComplete();
13159
13160 EXPECT_CALL(visitor_, OnPathDegrading());
13161 connection_.OnPathDegradingDetected();
13162
13163 auto self_address = connection_.self_address();
13164 const QuicSocketAddress kNewSelfAddress(self_address.host(),
13165 self_address.port() + 1);
13166 EXPECT_NE(kNewSelfAddress, self_address);
13167 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13168
13169 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
13170 .WillRepeatedly(Return(true));
13171
13172 QuicNewConnectionIdFrame frame;
13173 frame.connection_id = TestConnectionId(1234);
13174 ASSERT_NE(frame.connection_id, connection_.connection_id());
13175 frame.stateless_reset_token =
13176 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13177 frame.retire_prior_to = 0u;
13178 frame.sequence_number = 1u;
13179 EXPECT_CALL(visitor_, CreateContextForMultiPortPath())
13180 .WillRepeatedly(Return(
13181 testing::ByMove(std::make_unique<TestQuicPathValidationContext>(
13182 kNewSelfAddress, connection_.peer_address(), &new_writer))));
13183 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13184 EXPECT_TRUE(connection_.HasPendingPathValidation());
13185 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13186 &connection_, kNewSelfAddress, connection_.peer_address()));
13187 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13188 EXPECT_FALSE(alt_path->validated);
13189
13190 EXPECT_TRUE(connection_.HasPendingPathValidation());
13191 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13192 &connection_, kNewSelfAddress, connection_.peer_address()));
13193 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13194 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13195 static_cast<TestAlarmFactory::TestAlarm*>(
13196 QuicPathValidatorPeer::retry_timer(
13197 QuicConnectionPeer::path_validator(&connection_)))
13198 ->Fire();
13199 }
13200
13201 auto stats = connection_.multi_port_stats();
13202 EXPECT_FALSE(connection_.HasPendingPathValidation());
13203 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13204 &connection_, kNewSelfAddress, connection_.peer_address()));
13205 EXPECT_EQ(1, stats->num_path_degrading);
13206 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13207
13208 uint64_t connection_id = 1235;
13209 for (size_t i = 0; i < kMaxNumMultiPortPaths - 1; ++i) {
13210 QuicNewConnectionIdFrame frame;
13211 frame.connection_id = TestConnectionId(connection_id + i);
13212 ASSERT_NE(frame.connection_id, connection_.connection_id());
13213 frame.stateless_reset_token =
13214 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13215 frame.retire_prior_to = 0u;
13216 frame.sequence_number = i + 2;
13217 EXPECT_CALL(visitor_, CreateContextForMultiPortPath())
13218 .WillRepeatedly(Return(
13219 testing::ByMove(std::make_unique<TestQuicPathValidationContext>(
13220 kNewSelfAddress, connection_.peer_address(), &new_writer))));
13221 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
13222 EXPECT_TRUE(connection_.HasPendingPathValidation());
13223 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13224 &connection_, kNewSelfAddress, connection_.peer_address()));
13225 EXPECT_FALSE(alt_path->validated);
13226
13227 for (size_t j = 0; j < QuicPathValidator::kMaxRetryTimes + 1; ++j) {
13228 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13229 static_cast<TestAlarmFactory::TestAlarm*>(
13230 QuicPathValidatorPeer::retry_timer(
13231 QuicConnectionPeer::path_validator(&connection_)))
13232 ->Fire();
13233 }
13234
13235 EXPECT_FALSE(connection_.HasPendingPathValidation());
13236 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13237 &connection_, kNewSelfAddress, connection_.peer_address()));
13238 EXPECT_EQ(1, stats->num_path_degrading);
13239 EXPECT_EQ(i + 2, stats->num_multi_port_probe_failures_when_path_degrading);
13240 }
13241
13242 // The 6th attemp should fail.
13243 QuicNewConnectionIdFrame frame2;
13244 frame2.connection_id = TestConnectionId(1239);
13245 ASSERT_NE(frame2.connection_id, connection_.connection_id());
13246 frame2.stateless_reset_token =
13247 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
13248 frame2.retire_prior_to = 0u;
13249 frame2.sequence_number = 6u;
13250 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame2));
13251 EXPECT_FALSE(connection_.HasPendingPathValidation());
13252 EXPECT_EQ(kMaxNumMultiPortPaths,
13253 stats->num_multi_port_probe_failures_when_path_degrading);
13254}
13255
Bence Békybac04052022-04-07 15:44:29 -040013256TEST_P(QuicConnectionTest, SingleAckInPacket) {
13257 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13258 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13259 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13260 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13261 connection_.NeuterUnencryptedPackets();
13262 connection_.OnHandshakeComplete();
13263 EXPECT_CALL(visitor_, GetHandshakeState())
13264 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13265
13266 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13267 connection_.SendStreamData3();
13268 connection_.CloseConnection(
13269 QUIC_INTERNAL_ERROR, "error",
13270 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
13271 }));
13272 QuicFrames frames;
13273 frames.push_back(QuicFrame(frame1_));
13274 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
13275 ENCRYPTION_FORWARD_SECURE);
13276 ASSERT_FALSE(writer_->ack_frames().empty());
13277 EXPECT_EQ(1u, writer_->ack_frames().size());
13278}
13279
13280TEST_P(QuicConnectionTest,
13281 ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey) {
13282 if (!connection_.version().UsesTls()) {
13283 return;
13284 }
13285
13286 set_perspective(Perspective::IS_SERVER);
13287 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080013288 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040013289
13290 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13291 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13292
13293 // Finish handshake.
13294 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13295 notifier_.NeuterUnencryptedData();
13296 connection_.NeuterUnencryptedPackets();
13297 connection_.OnHandshakeComplete();
13298 EXPECT_CALL(visitor_, GetHandshakeState())
13299 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13300
13301 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13302 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13303 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13304
13305 // 0-RTT packet received out of order should be decoded since the decrypter
13306 // is temporarily retained.
13307 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13308 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13309 EXPECT_EQ(
13310 0u,
13311 connection_.GetStats()
13312 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13313
13314 // Simulate the timeout for discarding 0-RTT keys passing.
13315 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
13316
13317 // Another 0-RTT packet received now should not be decoded.
13318 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13319 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
13320 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13321 EXPECT_EQ(
13322 1u,
13323 connection_.GetStats()
13324 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13325
13326 // The |discard_zero_rtt_decryption_keys_alarm_| should only be set on the
13327 // first 1-RTT packet received.
13328 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13329 ProcessDataPacketAtLevel(5, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13330 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13331}
13332
13333TEST_P(QuicConnectionTest, NewTokenFrameInstigateAcks) {
13334 if (!version().HasIetfQuicFrames()) {
13335 return;
13336 }
13337 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13338
13339 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13340 EXPECT_CALL(visitor_, OnNewTokenReceived(_));
13341 ProcessFramePacket(QuicFrame(new_token));
13342
13343 // Ensure that this has caused the ACK alarm to be set.
13344 EXPECT_TRUE(connection_.HasPendingAcks());
13345}
13346
13347TEST_P(QuicConnectionTest, ServerClosesConnectionOnNewTokenFrame) {
13348 if (!version().HasIetfQuicFrames()) {
13349 return;
13350 }
13351 set_perspective(Perspective::IS_SERVER);
13352 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13353 EXPECT_CALL(visitor_, OnNewTokenReceived(_)).Times(0);
13354 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13355 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13356 ProcessFramePacket(QuicFrame(new_token));
13357 EXPECT_FALSE(connection_.connected());
13358}
13359
13360TEST_P(QuicConnectionTest, OverrideRetryTokenWithRetryPacket) {
13361 if (!version().HasIetfQuicFrames()) {
13362 return;
13363 }
13364 std::string address_token = "TestAddressToken";
13365 connection_.SetSourceAddressTokenToSend(address_token);
13366 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13367 QuicConnectionPeer::GetPacketCreator(&connection_)),
13368 address_token);
13369 // Passes valid retry and verify token gets overridden.
13370 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13371 /*missing_original_id_in_config=*/false,
13372 /*wrong_original_id_in_config=*/false,
13373 /*missing_retry_id_in_config=*/false,
13374 /*wrong_retry_id_in_config=*/false);
13375}
13376
13377TEST_P(QuicConnectionTest, DonotOverrideRetryTokenWithAddressToken) {
13378 if (!version().HasIetfQuicFrames()) {
13379 return;
13380 }
13381 // Passes valid retry and verify token gets overridden.
13382 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13383 /*missing_original_id_in_config=*/false,
13384 /*wrong_original_id_in_config=*/false,
13385 /*missing_retry_id_in_config=*/false,
13386 /*wrong_retry_id_in_config=*/false);
13387 std::string retry_token = QuicPacketCreatorPeer::GetRetryToken(
13388 QuicConnectionPeer::GetPacketCreator(&connection_));
13389
13390 std::string address_token = "TestAddressToken";
13391 connection_.SetSourceAddressTokenToSend(address_token);
13392 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13393 QuicConnectionPeer::GetPacketCreator(&connection_)),
13394 retry_token);
13395}
13396
13397TEST_P(QuicConnectionTest,
13398 ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt) {
13399 if (!connection_.version().UsesTls()) {
13400 return;
13401 }
13402
13403 // The code that checks for this error piggybacks on some book-keeping state
13404 // kept for key update, so enable key update for the test.
13405 std::string error_details;
13406 TransportParameters params;
13407 QuicConfig config;
13408 EXPECT_THAT(config.ProcessTransportParameters(
13409 params, /* is_resumption = */ false, &error_details),
13410 IsQuicNoError());
13411 QuicConfigPeer::SetNegotiated(&config, true);
13412 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
13413 connection_.connection_id());
13414 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
13415 &config, connection_.connection_id());
13416 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13417 connection_.SetFromConfig(config);
13418
13419 set_perspective(Perspective::IS_SERVER);
13420 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080013421 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040013422
13423 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13424 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13425
13426 // Finish handshake.
13427 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13428 notifier_.NeuterUnencryptedData();
13429 connection_.NeuterUnencryptedPackets();
13430 connection_.OnHandshakeComplete();
13431 EXPECT_CALL(visitor_, GetHandshakeState())
13432 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13433
13434 // Decrypt a 1-RTT packet.
13435 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13436 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13437 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13438
13439 // 0-RTT packet with higher packet number than a 1-RTT packet is invalid and
13440 // should cause the connection to be closed.
13441 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13442 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13443 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13444 EXPECT_FALSE(connection_.connected());
13445 TestConnectionCloseQuicErrorCode(
13446 QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
13447}
13448
13449// Regression test for b/177312785
13450TEST_P(QuicConnectionTest, PeerMigrateBeforeHandshakeConfirm) {
13451 if (!VersionHasIetfQuicFrames(version().transport_version)) {
13452 return;
13453 }
13454 set_perspective(Perspective::IS_SERVER);
13455 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
13456 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
13457 EXPECT_CALL(visitor_, GetHandshakeState())
13458 .WillRepeatedly(Return(HANDSHAKE_START));
13459
13460 // Clear direct_peer_address.
13461 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
13462 // Clear effective_peer_address, it is the same as direct_peer_address for
13463 // this test.
13464 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
13465 QuicSocketAddress());
13466 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
13467
13468 const QuicSocketAddress kNewPeerAddress =
13469 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
13470 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
13471 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
13472 ENCRYPTION_INITIAL);
13473 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13474 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13475
13476 // Process another packet with a different peer address on server side will
13477 // close connection.
13478 QuicAckFrame frame = InitAckFrame(1);
13479 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13480 EXPECT_CALL(visitor_,
13481 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
13482 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
13483
13484 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _)).Times(0);
13485 ProcessFramePacketWithAddresses(QuicFrame(&frame), kSelfAddress,
13486 kNewPeerAddress, ENCRYPTION_INITIAL);
13487 EXPECT_FALSE(connection_.connected());
13488}
13489
13490// Regresstion test for b/175685916
13491TEST_P(QuicConnectionTest, TryToFlushAckWithAckQueued) {
13492 if (!version().HasIetfQuicFrames()) {
13493 return;
13494 }
13495 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13496 set_perspective(Perspective::IS_SERVER);
13497
13498 QuicConfig config;
13499 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13500 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13501 connection_.SetFromConfig(config);
13502 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13503 connection_.OnHandshakeComplete();
13504 QuicPacketCreatorPeer::SetPacketNumber(creator_, 200);
13505
13506 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13507 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13508 // Sending ACK_FREQUENCY bundles ACK. QuicConnectionPeer::SendPing
13509 // will try to bundle ACK but there is no pending ACK.
13510 EXPECT_CALL(visitor_, SendAckFrequency(_))
13511 .WillOnce(Invoke(&notifier_,
13512 &SimpleSessionNotifier::WriteOrBufferAckFrequency));
13513 QuicConnectionPeer::SendPing(&connection_);
13514}
13515
13516TEST_P(QuicConnectionTest, PathChallengeBeforePeerIpAddressChangeAtServer) {
13517 set_perspective(Perspective::IS_SERVER);
13518 if (!connection_.connection_migration_use_new_cid()) {
13519 return;
13520 }
13521 PathProbeTestInit(Perspective::IS_SERVER);
13522 SetClientConnectionId(TestConnectionId(1));
13523 connection_.CreateConnectionIdManager();
13524
13525 QuicConnectionId server_cid0 = connection_.connection_id();
13526 QuicConnectionId client_cid0 = connection_.client_connection_id();
13527 QuicConnectionId client_cid1 = TestConnectionId(2);
13528 QuicConnectionId server_cid1;
13529 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013530 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013531 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13532 .WillOnce(Return(TestConnectionId(456)));
13533 }
haoyuewangada6b822022-06-23 13:41:18 -070013534 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13535 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13536 server_cid1 = cid;
13537 return true;
13538 }));
Bence Békybac04052022-04-07 15:44:29 -040013539 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13540 connection_.MaybeSendConnectionIdToClient();
13541 // Receives new client CID from client.
13542 QuicNewConnectionIdFrame new_cid_frame;
13543 new_cid_frame.connection_id = client_cid1;
13544 new_cid_frame.sequence_number = 1u;
13545 new_cid_frame.retire_prior_to = 0u;
13546 connection_.OnNewConnectionIdFrame(new_cid_frame);
13547 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13548 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13549 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13550
13551 peer_creator_.SetServerConnectionId(server_cid1);
13552 const QuicSocketAddress kNewPeerAddress =
13553 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
13554 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13555 QuicFrames frames1;
13556 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070013557 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040013558 QuicPathFrameBuffer payload;
13559 EXPECT_CALL(*send_algorithm_,
13560 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13561 .Times(AtLeast(1))
13562 .WillOnce(Invoke([&]() {
13563 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13564 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13565 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13566 EXPECT_FALSE(writer_->path_response_frames().empty());
13567 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13568 payload = writer_->path_challenge_frames().front().data_buffer;
13569 }));
13570 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
13571 ENCRYPTION_FORWARD_SECURE);
13572 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13573 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13574 EXPECT_TRUE(connection_.HasPendingPathValidation());
13575 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13576 const auto* alternative_path =
13577 QuicConnectionPeer::GetAlternativePath(&connection_);
13578 EXPECT_EQ(default_path->client_connection_id, client_cid0);
13579 EXPECT_EQ(default_path->server_connection_id, server_cid0);
13580 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
13581 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
13582 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13583 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13584
13585 // Process another packet with a different peer address on server side will
13586 // start connection migration.
13587 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
13588 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13589 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13590 }));
13591 // IETF QUIC send algorithm should be changed to a different object, so no
13592 // OnPacketSent() called on the old send algorithm.
13593 EXPECT_CALL(*send_algorithm_,
13594 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13595 .Times(0);
13596 QuicFrames frames2;
13597 frames2.push_back(QuicFrame(frame2_));
13598 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
13599 ENCRYPTION_FORWARD_SECURE);
13600 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13601 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
13602 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
13603 connection_.active_effective_peer_migration_type());
13604 EXPECT_TRUE(writer_->path_challenge_frames().empty());
13605 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
13606 send_algorithm_);
13607 // Switch to use the mock send algorithm.
13608 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
13609 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
13610 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
13611 .WillRepeatedly(Return(kDefaultTCPMSS));
13612 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
13613 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
13614 .Times(AnyNumber())
13615 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13616 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
13617 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
13618 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
13619 connection_.SetSendAlgorithm(send_algorithm_);
13620 EXPECT_EQ(default_path->client_connection_id, client_cid1);
13621 EXPECT_EQ(default_path->server_connection_id, server_cid1);
13622 // The previous default path is kept as alternative path before reverse path
13623 // validation finishes.
13624 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
13625 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
13626 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
13627 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
13628
13629 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13630 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
13631 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
13632 connection_.active_effective_peer_migration_type());
13633 EXPECT_EQ(1u, connection_.GetStats()
13634 .num_peer_migration_to_proactively_validated_address);
13635
13636 // The PATH_CHALLENGE and PATH_RESPONSE is expanded upto the max packet size
13637 // which may exceeds the anti-amplification limit. Verify server is throttled
13638 // by anti-amplification limit.
13639 connection_.SendCryptoDataWithString("foo", 0);
13640 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
13641
13642 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
13643 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070013644 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040013645 EXPECT_CALL(visitor_, MaybeSendAddressToken());
13646 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
13647 .Times(testing::AtLeast(1u));
13648 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
13649 ENCRYPTION_FORWARD_SECURE);
13650 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
13651 // Verify that alternative_path_ is cleared and the peer CID is retired.
13652 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
13653 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
13654 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
13655 auto* retire_peer_issued_cid_alarm =
13656 connection_.GetRetirePeerIssuedConnectionIdAlarm();
13657 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
13658 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
13659 retire_peer_issued_cid_alarm->Fire();
13660
13661 // Verify the anti-amplification limit is lifted by sending a packet larger
13662 // than the anti-amplification limit.
13663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
13664 EXPECT_CALL(*send_algorithm_, PacingRate(_))
13665 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13666 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
13667 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -070013668 EXPECT_EQ(1u, connection_.num_unlinkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -040013669}
13670
13671TEST_P(QuicConnectionTest,
13672 PathValidationSucceedsBeforePeerIpAddressChangeAtServer) {
13673 set_perspective(Perspective::IS_SERVER);
13674 if (!connection_.connection_migration_use_new_cid()) {
13675 return;
13676 }
13677 PathProbeTestInit(Perspective::IS_SERVER);
13678 connection_.CreateConnectionIdManager();
13679
13680 QuicConnectionId server_cid0 = connection_.connection_id();
13681 QuicConnectionId server_cid1;
13682 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013683 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013684 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13685 .WillOnce(Return(TestConnectionId(456)));
13686 }
haoyuewangada6b822022-06-23 13:41:18 -070013687 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13688 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13689 server_cid1 = cid;
13690 return true;
13691 }));
Bence Békybac04052022-04-07 15:44:29 -040013692 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13693 connection_.MaybeSendConnectionIdToClient();
13694 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13695 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13696
13697 // Receive probing packet with new peer address.
13698 peer_creator_.SetServerConnectionId(server_cid1);
13699 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
13700 /*port=*/23456);
13701 QuicPathFrameBuffer payload;
13702 EXPECT_CALL(*send_algorithm_,
13703 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13704 .WillOnce(Invoke([&]() {
13705 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13706 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13707 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13708 EXPECT_FALSE(writer_->path_response_frames().empty());
13709 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13710 payload = writer_->path_challenge_frames().front().data_buffer;
13711 }))
13712 .WillRepeatedly(Invoke([&]() {
13713 // Only start reverse path validation once.
13714 EXPECT_TRUE(writer_->path_challenge_frames().empty());
13715 }));
13716 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13717 QuicFrames frames1;
13718 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070013719 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040013720 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
13721 ENCRYPTION_FORWARD_SECURE);
13722 EXPECT_TRUE(connection_.HasPendingPathValidation());
13723 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13724 const auto* alternative_path =
13725 QuicConnectionPeer::GetAlternativePath(&connection_);
13726 EXPECT_EQ(default_path->server_connection_id, server_cid0);
13727 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
13728 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13729
13730 // Receive PATH_RESPONSE should mark the new peer address validated.
13731 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070013732 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040013733 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
13734 ENCRYPTION_FORWARD_SECURE);
13735
13736 // Process another packet with a newer peer address with the same port will
13737 // start connection migration.
13738 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
13739 // IETF QUIC send algorithm should be changed to a different object, so no
13740 // OnPacketSent() called on the old send algorithm.
13741 EXPECT_CALL(*send_algorithm_,
13742 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13743 .Times(0);
13744 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
13745 /*port=*/34567);
13746 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13747 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
13748 }));
13749 EXPECT_CALL(visitor_, MaybeSendAddressToken());
13750 QuicFrames frames2;
13751 frames2.push_back(QuicFrame(frame2_));
13752 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewerPeerAddress,
13753 ENCRYPTION_FORWARD_SECURE);
13754 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
13755 EXPECT_EQ(kNewerPeerAddress, connection_.effective_peer_address());
13756 // Since the newer address has the same IP as the previously validated probing
13757 // address. The peer migration becomes validated immediately.
13758 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
13759 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
13760 EXPECT_EQ(1u, connection_.GetStats()
13761 .num_peer_migration_to_proactively_validated_address);
13762 EXPECT_FALSE(connection_.HasPendingPathValidation());
13763 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
13764 send_algorithm_);
13765
13766 EXPECT_EQ(default_path->server_connection_id, server_cid1);
13767 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
13768 // Verify that alternative_path_ is cleared.
13769 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
13770 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
13771
13772 // Switch to use the mock send algorithm.
13773 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
13774 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
13775 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
13776 .WillRepeatedly(Return(kDefaultTCPMSS));
13777 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
13778 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
13779 .Times(AnyNumber())
13780 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13781 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
13782 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
13783 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
13784 connection_.SetSendAlgorithm(send_algorithm_);
13785
13786 // Verify the server is not throttled by the anti-amplification limit by
13787 // sending a packet larger than the anti-amplification limit.
13788 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13789 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
13790 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
13791}
13792
danzhb37451f2022-04-19 08:18:54 -070013793// Regression test of b/228645208.
13794TEST_P(QuicConnectionTest, NoNonProbingFrameOnAlternativePath) {
13795 if (!connection_.connection_migration_use_new_cid()) {
13796 return;
13797 }
13798
13799 PathProbeTestInit(Perspective::IS_SERVER);
13800 SetClientConnectionId(TestConnectionId(1));
13801 connection_.CreateConnectionIdManager();
13802
13803 QuicConnectionId server_cid0 = connection_.connection_id();
13804 QuicConnectionId client_cid0 = connection_.client_connection_id();
13805 QuicConnectionId client_cid1 = TestConnectionId(2);
13806 QuicConnectionId server_cid1;
13807 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013808 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013809 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13810 .WillOnce(Return(TestConnectionId(456)));
13811 }
haoyuewangada6b822022-06-23 13:41:18 -070013812 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13813 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13814 server_cid1 = cid;
13815 return true;
13816 }));
danzhb37451f2022-04-19 08:18:54 -070013817 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13818 connection_.MaybeSendConnectionIdToClient();
13819 // Receives new client CID from client.
13820 QuicNewConnectionIdFrame new_cid_frame;
13821 new_cid_frame.connection_id = client_cid1;
13822 new_cid_frame.sequence_number = 1u;
13823 new_cid_frame.retire_prior_to = 0u;
13824 connection_.OnNewConnectionIdFrame(new_cid_frame);
13825 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13826 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13827 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13828
13829 peer_creator_.SetServerConnectionId(server_cid1);
13830 const QuicSocketAddress kNewPeerAddress =
13831 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
13832 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13833 QuicFrames frames1;
13834 frames1.push_back(
13835 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
13836 QuicPathFrameBuffer payload;
13837 EXPECT_CALL(*send_algorithm_,
13838 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13839 .Times(AtLeast(1))
13840 .WillOnce(Invoke([&]() {
13841 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13842 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13843 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13844 EXPECT_FALSE(writer_->path_response_frames().empty());
13845 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13846 payload = writer_->path_challenge_frames().front().data_buffer;
13847 }));
13848 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
13849 ENCRYPTION_FORWARD_SECURE);
13850 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13851 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13852 EXPECT_TRUE(connection_.HasPendingPathValidation());
13853 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13854 const auto* alternative_path =
13855 QuicConnectionPeer::GetAlternativePath(&connection_);
13856 EXPECT_EQ(default_path->client_connection_id, client_cid0);
13857 EXPECT_EQ(default_path->server_connection_id, server_cid0);
13858 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
13859 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
13860 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13861 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13862
13863 // Process non-probing packets on the default path.
13864 peer_creator_.SetServerConnectionId(server_cid0);
13865 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillRepeatedly(Invoke([=]() {
13866 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13867 }));
13868 // Receives packets 3 - 39 to send 19 ACK-only packets, which will force the
13869 // connection to reach |kMaxConsecutiveNonRetransmittablePackets| while
13870 // sending the next ACK.
13871 for (size_t i = 3; i <= 39; ++i) {
13872 ProcessDataPacket(i);
13873 }
13874 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13875 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13876
13877 EXPECT_TRUE(connection_.HasPendingAcks());
13878 QuicTime ack_time = connection_.GetAckAlarm()->deadline();
13879 QuicTime path_validation_retry_time =
13880 connection_.GetRetryTimeout(kNewPeerAddress, writer_.get());
13881 // Advance time to simultaneously fire path validation retry and ACK alarms.
13882 clock_.AdvanceTime(std::max(ack_time, path_validation_retry_time) -
13883 clock_.ApproximateNow());
13884
13885 // The 20th ACK should bundle with a WINDOW_UPDATE frame.
13886 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
13887 .WillOnce(Invoke([this]() {
13888 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
13889 }));
martindukee6444ef2022-09-23 12:32:23 -070013890 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
13891 .WillOnce(Invoke([&]() {
13892 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13893 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13894 // Retry path validation shouldn't bundle ACK.
13895 EXPECT_TRUE(writer_->ack_frames().empty());
13896 }))
13897 .WillOnce(Invoke([&]() {
13898 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
13899 EXPECT_FALSE(writer_->ack_frames().empty());
13900 EXPECT_FALSE(writer_->window_update_frames().empty());
13901 }));
13902 static_cast<TestAlarmFactory::TestAlarm*>(
13903 QuicPathValidatorPeer::retry_timer(
13904 QuicConnectionPeer::path_validator(&connection_)))
13905 ->Fire();
danzhb37451f2022-04-19 08:18:54 -070013906}
13907
haoyuewangada6b822022-06-23 13:41:18 -070013908TEST_P(QuicConnectionTest, DoNotIssueNewCidIfVisitorSaysNo) {
13909 set_perspective(Perspective::IS_SERVER);
13910 if (!connection_.connection_migration_use_new_cid()) {
13911 return;
13912 }
13913
13914 connection_.CreateConnectionIdManager();
13915
13916 QuicConnectionId server_cid0 = connection_.connection_id();
13917 QuicConnectionId client_cid1 = TestConnectionId(2);
13918 QuicConnectionId server_cid1;
13919 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013920 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013921 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13922 .WillOnce(Return(TestConnectionId(456)));
13923 }
haoyuewangada6b822022-06-23 13:41:18 -070013924 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(false));
13925 if (GetQuicReloadableFlag(quic_check_cid_collision_when_issue_new_cid)) {
13926 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(0);
13927 } else {
13928 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(1);
13929 }
13930 connection_.MaybeSendConnectionIdToClient();
13931}
13932
Bence Békybac04052022-04-07 15:44:29 -040013933TEST_P(QuicConnectionTest,
13934 ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer) {
13935 PathProbeTestInit(Perspective::IS_SERVER);
13936 if (!connection_.validate_client_address()) {
13937 return;
13938 }
13939
13940 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
13941 /*port=*/23456);
13942
13943 // Process a packet with a new peer address will start connection migration.
13944 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
13945 // IETF QUIC send algorithm should be changed to a different object, so no
13946 // OnPacketSent() called on the old send algorithm.
13947 EXPECT_CALL(*send_algorithm_,
13948 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13949 .Times(0);
13950 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13951 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13952 }));
13953 QuicFrames frames2;
13954 frames2.push_back(QuicFrame(frame2_));
13955 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
13956 ENCRYPTION_FORWARD_SECURE);
13957 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
13958 EXPECT_TRUE(connection_.HasPendingPathValidation());
13959
13960 // Switch to use the mock send algorithm.
13961 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
13962 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
13963 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
13964 .WillRepeatedly(Return(kDefaultTCPMSS));
13965 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
13966 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
13967 .Times(AnyNumber())
13968 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13969 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
13970 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
13971 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
13972 connection_.SetSendAlgorithm(send_algorithm_);
13973
13974 // Receive probing packet with a newer peer address shouldn't override the
13975 // on-going path validation.
13976 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
13977 /*port=*/34567);
13978 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
13979 .WillOnce(Invoke([&]() {
13980 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
13981 EXPECT_FALSE(writer_->path_response_frames().empty());
13982 EXPECT_TRUE(writer_->path_challenge_frames().empty());
13983 }));
13984 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13985 QuicFrames frames1;
13986 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070013987 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040013988 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewerPeerAddress,
13989 ENCRYPTION_FORWARD_SECURE);
13990 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
13991 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13992 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
13993 EXPECT_TRUE(connection_.HasPendingPathValidation());
13994}
13995
13996TEST_P(QuicConnectionTest,
13997 PathValidationFailedOnClientDueToLackOfServerConnectionId) {
13998 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070013999 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014000 QuicConfig config;
14001 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14002 connection_.SetFromConfig(config);
14003 config.SetConnectionOptionsToSend({kRVCM});
14004 }
14005 if (!connection_.connection_migration_use_new_cid()) {
14006 return;
14007 }
14008 PathProbeTestInit(Perspective::IS_CLIENT,
14009 /*receive_new_server_connection_id=*/false);
14010
14011 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14012 /*port=*/34567);
14013
14014 bool success;
14015 connection_.ValidatePath(
14016 std::make_unique<TestQuicPathValidationContext>(
14017 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14018 std::make_unique<TestValidationResultDelegate>(
14019 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
14020
14021 EXPECT_FALSE(success);
14022}
14023
14024TEST_P(QuicConnectionTest,
14025 PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime) {
14026 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014027 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014028 QuicConfig config;
14029 config.SetConnectionOptionsToSend({kRVCM});
14030 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14031 connection_.SetFromConfig(config);
14032 }
14033 if (!connection_.connection_migration_use_new_cid()) {
14034 return;
14035 }
14036 PathProbeTestInit(Perspective::IS_CLIENT,
14037 /*receive_new_server_connection_id=*/false);
14038 SetClientConnectionId(TestConnectionId(1));
14039
14040 // Make sure server connection ID is available for the 1st validation.
14041 QuicConnectionId server_cid0 = connection_.connection_id();
14042 QuicConnectionId server_cid1 = TestConnectionId(2);
14043 QuicConnectionId server_cid2 = TestConnectionId(4);
14044 QuicConnectionId client_cid1;
14045 QuicNewConnectionIdFrame frame1;
14046 frame1.connection_id = server_cid1;
14047 frame1.sequence_number = 1u;
14048 frame1.retire_prior_to = 0u;
14049 frame1.stateless_reset_token =
14050 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14051 connection_.OnNewConnectionIdFrame(frame1);
14052 const auto* packet_creator =
14053 QuicConnectionPeer::GetPacketCreator(&connection_);
14054 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid0);
14055
14056 // Client will issue a new client connection ID to server.
martinduke08e3ff82022-10-18 09:06:26 -070014057 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14058 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014059 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14060 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14061 client_cid1 = frame.connection_id;
14062 }));
14063
14064 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14065 ASSERT_NE(kSelfAddress1, connection_.self_address());
14066 bool success1;
14067 connection_.ValidatePath(
14068 std::make_unique<TestQuicPathValidationContext>(
14069 kSelfAddress1, connection_.peer_address(), writer_.get()),
14070 std::make_unique<TestValidationResultDelegate>(
14071 &connection_, kSelfAddress1, connection_.peer_address(), &success1));
14072
14073 // Migrate upon 1st validation success.
14074 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14075 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14076 &new_writer, /*owns_writer=*/false));
14077 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14078 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14079 EXPECT_EQ(default_path->client_connection_id, client_cid1);
14080 EXPECT_EQ(default_path->server_connection_id, server_cid1);
14081 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14082 const auto* alternative_path =
14083 QuicConnectionPeer::GetAlternativePath(&connection_);
14084 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14085 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14086 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14087 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid1);
14088
14089 // Client will retire server connection ID on old default_path.
14090 auto* retire_peer_issued_cid_alarm =
14091 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14092 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14093 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14094 retire_peer_issued_cid_alarm->Fire();
14095
14096 // Another server connection ID is available to client.
14097 QuicNewConnectionIdFrame frame2;
14098 frame2.connection_id = server_cid2;
14099 frame2.sequence_number = 2u;
14100 frame2.retire_prior_to = 1u;
14101 frame2.stateless_reset_token =
14102 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14103 connection_.OnNewConnectionIdFrame(frame2);
14104
14105 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14106 /*port=*/45678);
14107 bool success2;
14108 connection_.ValidatePath(
14109 std::make_unique<TestQuicPathValidationContext>(
14110 kSelfAddress2, connection_.peer_address(), writer_.get()),
14111 std::make_unique<TestValidationResultDelegate>(
14112 &connection_, kSelfAddress2, connection_.peer_address(), &success2));
14113 // Since server does not retire any client connection ID yet, 2nd validation
14114 // would fail due to lack of client connection ID.
14115 EXPECT_FALSE(success2);
14116}
14117
14118TEST_P(QuicConnectionTest, ServerConnectionIdRetiredUponPathValidationFailure) {
14119 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014120 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014121 QuicConfig config;
14122 config.SetConnectionOptionsToSend({kRVCM});
14123 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14124 connection_.SetFromConfig(config);
14125 }
14126 if (!connection_.connection_migration_use_new_cid()) {
14127 return;
14128 }
14129 PathProbeTestInit(Perspective::IS_CLIENT);
14130
14131 // Make sure server connection ID is available for validation.
14132 QuicNewConnectionIdFrame frame;
14133 frame.connection_id = TestConnectionId(2);
14134 frame.sequence_number = 1u;
14135 frame.retire_prior_to = 0u;
14136 frame.stateless_reset_token =
14137 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14138 connection_.OnNewConnectionIdFrame(frame);
14139
14140 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
14141 /*port=*/34567);
14142 bool success;
14143 connection_.ValidatePath(
14144 std::make_unique<TestQuicPathValidationContext>(
14145 kNewSelfAddress, connection_.peer_address(), writer_.get()),
14146 std::make_unique<TestValidationResultDelegate>(
14147 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
14148
14149 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
14150 path_validator->CancelPathValidation();
14151 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14152 EXPECT_FALSE(success);
14153 const auto* alternative_path =
14154 QuicConnectionPeer::GetAlternativePath(&connection_);
14155 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
14156 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
14157 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
14158
14159 // Client will retire server connection ID on alternative_path.
14160 auto* retire_peer_issued_cid_alarm =
14161 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14162 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14163 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
14164 retire_peer_issued_cid_alarm->Fire();
14165}
14166
14167TEST_P(QuicConnectionTest,
14168 MigratePathDirectlyFailedDueToLackOfServerConnectionId) {
14169 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014170 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014171 QuicConfig config;
14172 config.SetConnectionOptionsToSend({kRVCM});
14173 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14174 connection_.SetFromConfig(config);
14175 }
14176 if (!connection_.connection_migration_use_new_cid()) {
14177 return;
14178 }
14179 PathProbeTestInit(Perspective::IS_CLIENT,
14180 /*receive_new_server_connection_id=*/false);
14181 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14182 ASSERT_NE(kSelfAddress1, connection_.self_address());
14183
14184 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14185 ASSERT_FALSE(connection_.MigratePath(kSelfAddress1,
14186 connection_.peer_address(), &new_writer,
14187 /*owns_writer=*/false));
14188}
14189
14190TEST_P(QuicConnectionTest,
14191 MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime) {
14192 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014193 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014194 QuicConfig config;
14195 config.SetConnectionOptionsToSend({kRVCM});
14196 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14197 connection_.SetFromConfig(config);
14198 }
14199 if (!connection_.connection_migration_use_new_cid()) {
14200 return;
14201 }
14202 PathProbeTestInit(Perspective::IS_CLIENT,
14203 /*receive_new_server_connection_id=*/false);
14204 SetClientConnectionId(TestConnectionId(1));
14205
14206 // Make sure server connection ID is available for the 1st migration.
14207 QuicNewConnectionIdFrame frame1;
14208 frame1.connection_id = TestConnectionId(2);
14209 frame1.sequence_number = 1u;
14210 frame1.retire_prior_to = 0u;
14211 frame1.stateless_reset_token =
14212 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14213 connection_.OnNewConnectionIdFrame(frame1);
14214
14215 // Client will issue a new client connection ID to server.
14216 QuicConnectionId new_client_connection_id;
martinduke08e3ff82022-10-18 09:06:26 -070014217 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14218 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014219 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14220 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14221 new_client_connection_id = frame.connection_id;
14222 }));
14223
14224 // 1st migration is successful.
14225 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14226 ASSERT_NE(kSelfAddress1, connection_.self_address());
14227 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14228 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14229 &new_writer,
14230 /*owns_writer=*/false));
14231 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14232 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14233 EXPECT_EQ(default_path->client_connection_id, new_client_connection_id);
14234 EXPECT_EQ(default_path->server_connection_id, frame1.connection_id);
14235 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14236
14237 // Client will retire server connection ID on old default_path.
14238 auto* retire_peer_issued_cid_alarm =
14239 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14240 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14241 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14242 retire_peer_issued_cid_alarm->Fire();
14243
14244 // Another server connection ID is available to client.
14245 QuicNewConnectionIdFrame frame2;
14246 frame2.connection_id = TestConnectionId(4);
14247 frame2.sequence_number = 2u;
14248 frame2.retire_prior_to = 1u;
14249 frame2.stateless_reset_token =
14250 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14251 connection_.OnNewConnectionIdFrame(frame2);
14252
14253 // Since server does not retire any client connection ID yet, 2nd migration
14254 // would fail due to lack of client connection ID.
14255 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14256 /*port=*/45678);
14257 auto new_writer2 = std::make_unique<TestPacketWriter>(version(), &clock_,
14258 Perspective::IS_CLIENT);
14259 ASSERT_FALSE(connection_.MigratePath(
14260 kSelfAddress2, connection_.peer_address(), new_writer2.release(),
14261 /*owns_writer=*/true));
14262}
14263
14264TEST_P(QuicConnectionTest,
14265 CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID) {
14266 if (!version().HasIetfQuicFrames()) {
14267 return;
14268 }
14269 set_perspective(Perspective::IS_SERVER);
14270 ASSERT_TRUE(connection_.client_connection_id().IsEmpty());
14271
14272 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14273 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14274 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14275 QuicNewConnectionIdFrame frame;
14276 frame.sequence_number = 1u;
14277 frame.connection_id = TestConnectionId(1);
14278 frame.stateless_reset_token =
14279 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14280 frame.retire_prior_to = 0u;
14281
14282 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14283
14284 EXPECT_FALSE(connection_.connected());
14285 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14286 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14287}
14288
14289TEST_P(QuicConnectionTest, NewConnectionIdFrameResultsInError) {
14290 if (!version().HasIetfQuicFrames()) {
14291 return;
14292 }
14293 connection_.CreateConnectionIdManager();
14294 ASSERT_FALSE(connection_.connection_id().IsEmpty());
14295
14296 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14297 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14298 QuicNewConnectionIdFrame frame;
14299 frame.sequence_number = 1u;
14300 frame.connection_id = connection_id_; // Reuses connection ID casuing error.
14301 frame.stateless_reset_token =
14302 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14303 frame.retire_prior_to = 0u;
14304
14305 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14306
14307 EXPECT_FALSE(connection_.connected());
14308 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14309 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14310}
14311
14312TEST_P(QuicConnectionTest,
14313 ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14314 if (!version().HasIetfQuicFrames()) {
14315 return;
14316 }
14317 connection_.CreateConnectionIdManager();
14318
14319 QuicNewConnectionIdFrame frame;
14320 frame.sequence_number = 1u;
14321 frame.connection_id = TestConnectionId(1);
14322 frame.stateless_reset_token =
14323 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14324 frame.retire_prior_to = 0u;
14325
14326 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14327 auto* retire_peer_issued_cid_alarm =
14328 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14329 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14330
14331 frame.sequence_number = 2u;
14332 frame.connection_id = TestConnectionId(2);
14333 frame.stateless_reset_token =
14334 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14335 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14336
14337 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14338 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14339 EXPECT_EQ(connection_.connection_id(), connection_id_);
14340
14341 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14342 retire_peer_issued_cid_alarm->Fire();
14343 EXPECT_EQ(connection_.connection_id(), TestConnectionId(2));
14344 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14345 TestConnectionId(2));
14346}
14347
14348TEST_P(QuicConnectionTest,
14349 ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14350 if (!version().HasIetfQuicFrames()) {
14351 return;
14352 }
14353 set_perspective(Perspective::IS_SERVER);
14354 SetClientConnectionId(TestConnectionId(0));
14355
14356 QuicNewConnectionIdFrame frame;
14357 frame.sequence_number = 1u;
14358 frame.connection_id = TestConnectionId(1);
14359 frame.stateless_reset_token =
14360 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14361 frame.retire_prior_to = 0u;
14362
14363 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14364 auto* retire_peer_issued_cid_alarm =
14365 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14366 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14367
14368 frame.sequence_number = 2u;
14369 frame.connection_id = TestConnectionId(2);
14370 frame.stateless_reset_token =
14371 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14372 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14373
14374 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14375 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14376 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14377
14378 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14379 retire_peer_issued_cid_alarm->Fire();
14380 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14381 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14382 TestConnectionId(2));
14383}
14384
14385TEST_P(
14386 QuicConnectionTest,
14387 ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame) {
danzhaf2e52a2022-04-20 07:37:03 -070014388 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014389 return;
14390 }
14391 PathProbeTestInit(Perspective::IS_SERVER);
14392 SetClientConnectionId(TestConnectionId(0));
14393
14394 // Populate alternative_path_ with probing packet.
14395 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
14396
14397 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
14398 QuicEncryptedPacket(probing_packet->encrypted_buffer,
14399 probing_packet->encrypted_length),
14400 clock_.Now()));
14401 QuicIpAddress new_host;
14402 new_host.FromString("1.1.1.1");
14403 ProcessReceivedPacket(kSelfAddress,
14404 QuicSocketAddress(new_host, /*port=*/23456), *received);
14405
14406 EXPECT_EQ(
14407 TestConnectionId(0),
14408 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14409
14410 QuicNewConnectionIdFrame frame;
14411 frame.sequence_number = 1u;
14412 frame.connection_id = TestConnectionId(1);
14413 frame.stateless_reset_token =
14414 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14415 frame.retire_prior_to = 0u;
14416
14417 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14418 auto* retire_peer_issued_cid_alarm =
14419 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14420 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14421
14422 frame.sequence_number = 2u;
14423 frame.connection_id = TestConnectionId(2);
14424 frame.stateless_reset_token =
14425 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14426 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14427
14428 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14429 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14430 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14431
14432 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14433 retire_peer_issued_cid_alarm->Fire();
14434 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14435 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14436 TestConnectionId(2));
14437 // Clean up alternative path connection ID.
14438 EXPECT_EQ(
14439 TestConnectionId(2),
14440 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14441}
14442
14443TEST_P(QuicConnectionTest,
14444 CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued) {
14445 if (!version().HasIetfQuicFrames() ||
14446 !connection_.connection_migration_use_new_cid()) {
14447 return;
14448 }
14449 set_perspective(Perspective::IS_SERVER);
14450
14451 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14452 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14453 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14454 QuicRetireConnectionIdFrame frame;
14455 frame.sequence_number = 1u;
14456
14457 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14458
14459 EXPECT_FALSE(connection_.connected());
14460 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14461 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14462}
14463
14464TEST_P(QuicConnectionTest, RetireConnectionIdFrameResultsInError) {
14465 if (!version().HasIetfQuicFrames() ||
14466 !connection_.connection_migration_use_new_cid()) {
14467 return;
14468 }
14469 set_perspective(Perspective::IS_SERVER);
14470 connection_.CreateConnectionIdManager();
14471
martinduke08e3ff82022-10-18 09:06:26 -070014472 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014473 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14474 .WillOnce(Return(TestConnectionId(456)));
14475 }
haoyuewangada6b822022-06-23 13:41:18 -070014476 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_));
Bence Békybac04052022-04-07 15:44:29 -040014477 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14478 connection_.MaybeSendConnectionIdToClient();
14479
14480 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14481 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14482 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14483 QuicRetireConnectionIdFrame frame;
14484 frame.sequence_number = 2u; // The corresponding ID is never issued.
14485
14486 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14487
14488 EXPECT_FALSE(connection_.connected());
14489 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14490 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14491}
14492
14493TEST_P(QuicConnectionTest,
14494 ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore) {
14495 if (!version().HasIetfQuicFrames()) {
14496 return;
14497 }
14498 set_perspective(Perspective::IS_SERVER);
14499 connection_.CreateConnectionIdManager();
14500
14501 auto* retire_self_issued_cid_alarm =
14502 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14503 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14504
14505 QuicConnectionId cid0 = connection_id_;
14506 QuicRetireConnectionIdFrame frame;
14507 frame.sequence_number = 0u;
14508 if (connection_.connection_migration_use_new_cid()) {
martinduke08e3ff82022-10-18 09:06:26 -070014509 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014510 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(cid0))
14511 .WillOnce(Return(TestConnectionId(456)));
14512 EXPECT_CALL(connection_id_generator_,
14513 GenerateNextConnectionId(TestConnectionId(456)))
14514 .WillOnce(Return(TestConnectionId(789)));
14515 }
haoyuewangada6b822022-06-23 13:41:18 -070014516 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14517 .Times(2)
14518 .WillRepeatedly(Return(true));
Bence Békybac04052022-04-07 15:44:29 -040014519 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
14520 }
14521 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(frame));
14522}
14523
14524TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionId) {
14525 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014526 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014527 QuicConfig config;
14528 config.SetConnectionOptionsToSend({kRVCM});
14529 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14530 connection_.SetFromConfig(config);
14531 }
14532 if (!connection_.connection_migration_use_new_cid()) {
14533 return;
14534 }
14535 set_perspective(Perspective::IS_SERVER);
14536 connection_.CreateConnectionIdManager();
14537 QuicConnectionId recorded_cid;
haoyuewangada6b822022-06-23 13:41:18 -070014538 auto cid_recorder = [&recorded_cid](const QuicConnectionId& cid) -> bool {
Bence Békybac04052022-04-07 15:44:29 -040014539 recorded_cid = cid;
haoyuewangada6b822022-06-23 13:41:18 -070014540 return true;
Bence Békybac04052022-04-07 15:44:29 -040014541 };
14542 QuicConnectionId cid0 = connection_id_;
14543 QuicConnectionId cid1;
14544 QuicConnectionId cid2;
14545 EXPECT_EQ(connection_.connection_id(), cid0);
14546 EXPECT_EQ(connection_.GetOneActiveServerConnectionId(), cid0);
14547
14548 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke08e3ff82022-10-18 09:06:26 -070014549 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014550 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14551 .WillOnce(Return(TestConnectionId(456)));
14552 }
haoyuewangada6b822022-06-23 13:41:18 -070014553 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040014554 .WillOnce(Invoke(cid_recorder));
14555 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14556 connection_.MaybeSendConnectionIdToClient();
14557 cid1 = recorded_cid;
14558
14559 auto* retire_self_issued_cid_alarm =
14560 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14561 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14562
14563 // Generate three packets with different connection IDs that will arrive out
14564 // of order (2, 1, 3) later.
14565 char buffers[3][kMaxOutgoingPacketSize];
14566 // Destination connection ID of packet1 is cid0.
14567 auto packet1 =
14568 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14569 buffers[0], kMaxOutgoingPacketSize);
14570 peer_creator_.SetServerConnectionId(cid1);
14571 auto retire_cid_frame = std::make_unique<QuicRetireConnectionIdFrame>();
14572 retire_cid_frame->sequence_number = 0u;
14573 // Destination connection ID of packet2 is cid1.
14574 auto packet2 = ConstructPacket({QuicFrame(retire_cid_frame.release())},
14575 ENCRYPTION_FORWARD_SECURE, buffers[1],
14576 kMaxOutgoingPacketSize);
14577 // Destination connection ID of packet3 is cid1.
14578 auto packet3 =
14579 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14580 buffers[2], kMaxOutgoingPacketSize);
14581
14582 // Packet2 with RetireConnectionId frame trigers sending NewConnectionId
14583 // immediately.
martinduke08e3ff82022-10-18 09:06:26 -070014584 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014585 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14586 .WillOnce(Return(TestConnectionId(456)));
14587 }
haoyuewangada6b822022-06-23 13:41:18 -070014588 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040014589 .WillOnce(Invoke(cid_recorder));
14590 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14591 peer_creator_.SetServerConnectionId(cid1);
14592 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet2);
14593 cid2 = recorded_cid;
14594 // cid0 is not retired immediately.
14595 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
14596 ElementsAre(cid0, cid1, cid2));
14597 ASSERT_TRUE(retire_self_issued_cid_alarm->IsSet());
14598 EXPECT_EQ(connection_.connection_id(), cid1);
14599 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
14600 connection_.GetOneActiveServerConnectionId() == cid1 ||
14601 connection_.GetOneActiveServerConnectionId() == cid2);
14602
14603 // Packet1 updates the connection ID on the default path but not the active
14604 // connection ID.
14605 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet1);
14606 EXPECT_EQ(connection_.connection_id(), cid0);
14607 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
14608 connection_.GetOneActiveServerConnectionId() == cid1 ||
14609 connection_.GetOneActiveServerConnectionId() == cid2);
14610
14611 // cid0 is retired when the retire CID alarm fires.
14612 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(cid0));
14613 retire_self_issued_cid_alarm->Fire();
14614 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
14615 ElementsAre(cid1, cid2));
14616 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
14617 connection_.GetOneActiveServerConnectionId() == cid2);
14618
14619 // Packet3 updates the connection ID on the default path.
14620 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet3);
14621 EXPECT_EQ(connection_.connection_id(), cid1);
14622 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
14623 connection_.GetOneActiveServerConnectionId() == cid2);
14624}
14625
14626TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoAlternativePath) {
14627 if (!version().HasIetfQuicFrames()) {
14628 return;
14629 }
14630 set_perspective(Perspective::IS_SERVER);
14631 connection_.CreateConnectionIdManager();
14632 connection_.set_client_connection_id(TestConnectionId(1));
14633
14634 // Set up the state after path probing.
14635 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14636 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
14637 QuicIpAddress new_host;
14638 new_host.FromString("12.12.12.12");
14639 alternative_path->self_address = default_path->self_address;
14640 alternative_path->peer_address = QuicSocketAddress(new_host, 12345);
14641 alternative_path->server_connection_id = TestConnectionId(3);
14642 ASSERT_TRUE(alternative_path->client_connection_id.IsEmpty());
14643 ASSERT_FALSE(alternative_path->stateless_reset_token.has_value());
14644
14645 QuicNewConnectionIdFrame frame;
14646 frame.sequence_number = 1u;
14647 frame.connection_id = TestConnectionId(5);
14648 frame.stateless_reset_token =
14649 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14650 frame.retire_prior_to = 0u;
14651 // New ID is patched onto the alternative path when the needed
14652 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
14653 connection_.OnNewConnectionIdFrame(frame);
14654
14655 ASSERT_EQ(alternative_path->client_connection_id, frame.connection_id);
14656 ASSERT_EQ(alternative_path->stateless_reset_token,
14657 frame.stateless_reset_token);
14658}
14659
14660TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoDefaultPath) {
14661 if (!version().HasIetfQuicFrames()) {
14662 return;
14663 }
14664 set_perspective(Perspective::IS_SERVER);
14665 connection_.CreateConnectionIdManager();
14666 connection_.set_client_connection_id(TestConnectionId(1));
14667
14668 // Set up the state after peer migration without probing.
14669 auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14670 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
14671 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14672 *alternative_path = std::move(*default_path);
14673 QuicIpAddress new_host;
14674 new_host.FromString("12.12.12.12");
14675 default_path->self_address = default_path->self_address;
14676 default_path->peer_address = QuicSocketAddress(new_host, 12345);
14677 default_path->server_connection_id = TestConnectionId(3);
14678 packet_creator->SetDefaultPeerAddress(default_path->peer_address);
14679 packet_creator->SetServerConnectionId(default_path->server_connection_id);
14680 packet_creator->SetClientConnectionId(default_path->client_connection_id);
14681
14682 ASSERT_FALSE(default_path->validated);
14683 ASSERT_TRUE(default_path->client_connection_id.IsEmpty());
14684 ASSERT_FALSE(default_path->stateless_reset_token.has_value());
14685
14686 QuicNewConnectionIdFrame frame;
14687 frame.sequence_number = 1u;
14688 frame.connection_id = TestConnectionId(5);
14689 frame.stateless_reset_token =
14690 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14691 frame.retire_prior_to = 0u;
14692 // New ID is patched onto the default path when the needed
14693 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
14694 connection_.OnNewConnectionIdFrame(frame);
14695
14696 ASSERT_EQ(default_path->client_connection_id, frame.connection_id);
14697 ASSERT_EQ(default_path->stateless_reset_token, frame.stateless_reset_token);
14698 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), frame.connection_id);
14699}
14700
14701TEST_P(QuicConnectionTest, ShouldGeneratePacketBlockedByMissingConnectionId) {
14702 if (!version().HasIetfQuicFrames()) {
14703 return;
14704 }
14705 set_perspective(Perspective::IS_SERVER);
14706 connection_.set_client_connection_id(TestConnectionId(1));
14707 connection_.CreateConnectionIdManager();
14708 if (version().SupportsAntiAmplificationLimit()) {
14709 QuicConnectionPeer::SetAddressValidated(&connection_);
14710 }
14711
14712 ASSERT_TRUE(
14713 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
14714
14715 QuicPacketCreator* packet_creator =
14716 QuicConnectionPeer::GetPacketCreator(&connection_);
14717 QuicIpAddress peer_host1;
14718 peer_host1.FromString("12.12.12.12");
14719 QuicSocketAddress peer_address1(peer_host1, 1235);
14720
14721 {
14722 // No connection ID is available as context is created without any.
14723 QuicPacketCreator::ScopedPeerAddressContext context(
14724 packet_creator, peer_address1, EmptyQuicConnectionId(),
14725 EmptyQuicConnectionId(),
14726 /*update_connection_id=*/true);
14727 ASSERT_FALSE(connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
14728 NOT_HANDSHAKE));
14729 }
14730 ASSERT_TRUE(
14731 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
14732}
14733
14734// Regression test for b/182571515
14735TEST_P(QuicConnectionTest, LostDataThenGetAcknowledged) {
14736 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -070014737 if (!connection_.validate_client_address() ||
birenroyef686222022-09-12 11:34:34 -070014738 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040014739 return;
14740 }
14741
14742 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
14743 if (version().SupportsAntiAmplificationLimit()) {
14744 QuicConnectionPeer::SetAddressValidated(&connection_);
14745 }
14746 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14747 // Discard INITIAL key.
14748 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
14749 connection_.NeuterUnencryptedPackets();
14750 EXPECT_CALL(visitor_, GetHandshakeState())
14751 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
14752
14753 QuicPacketNumber last_packet;
14754 // Send packets 1 to 4.
14755 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
14756 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 2
14757 SendStreamDataToPeer(3, "foo", 6, NO_FIN, &last_packet); // Packet 3
14758 SendStreamDataToPeer(3, "foo", 9, NO_FIN, &last_packet); // Packet 4
14759
14760 // Process a PING packet to set peer address.
14761 ProcessFramePacket(QuicFrame(QuicPingFrame()));
14762
14763 // Process a packet containing a STREAM_FRAME and an ACK with changed peer
14764 // address.
14765 QuicFrames frames;
14766 frames.push_back(QuicFrame(frame1_));
14767 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}});
14768 frames.push_back(QuicFrame(&ack));
14769
Bence Békybac04052022-04-07 15:44:29 -040014770 // Invoke OnCanWrite.
Bence Békybac04052022-04-07 15:44:29 -040014771 QuicIpAddress ip_address;
14772 ASSERT_TRUE(ip_address.FromString("127.0.52.223"));
vasilvvac2e30d2022-06-02 14:26:59 -070014773 EXPECT_QUIC_BUG(
14774 {
14775 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(1);
14776 EXPECT_CALL(visitor_, OnStreamFrame(_))
14777 .WillOnce(InvokeWithoutArgs(&notifier_,
14778 &SimpleSessionNotifier::OnCanWrite));
14779 ProcessFramesPacketWithAddresses(frames, kSelfAddress,
14780 QuicSocketAddress(ip_address, 1000),
14781 ENCRYPTION_FORWARD_SECURE);
14782 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
14783
14784 // Verify stream frame will not be retransmitted.
14785 EXPECT_TRUE(writer_->stream_frames().empty());
14786 },
14787 "Try to write mid packet processing");
Bence Békybac04052022-04-07 15:44:29 -040014788}
14789
14790TEST_P(QuicConnectionTest, PtoSendStreamData) {
14791 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14792 return;
14793 }
14794 set_perspective(Perspective::IS_SERVER);
14795 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
14796 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
14797 }
14798 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040014799 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
14800 EXPECT_TRUE(connection_.HasPendingAcks());
14801
Bence Békybac04052022-04-07 15:44:29 -040014802 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14803 // Send INITIAL 1.
14804 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
14805
martinduke9e0811c2022-12-08 20:35:57 -080014806 connection_.SetEncrypter(
14807 ENCRYPTION_HANDSHAKE,
14808 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040014809 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
14810 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080014811 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040014812 // Send HANDSHAKE packets.
14813 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
14814 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
14815
martinduke9e0811c2022-12-08 20:35:57 -080014816 connection_.SetEncrypter(
14817 ENCRYPTION_FORWARD_SECURE,
14818 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040014819 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14820
14821 // Send half RTT packet with congestion control blocked.
14822 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
14823 connection_.SendStreamDataWithString(2, std::string(1500, 'a'), 0, NO_FIN);
14824
14825 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14826 connection_.GetRetransmissionAlarm()->Fire();
14827 // Verify INITIAL and HANDSHAKE get retransmitted.
martinduke9e0811c2022-12-08 20:35:57 -080014828 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040014829}
14830
14831TEST_P(QuicConnectionTest, SendingZeroRttPacketsDoesNotPostponePTO) {
14832 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14833 return;
14834 }
Bence Békybac04052022-04-07 15:44:29 -040014835 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14836 // Send CHLO.
14837 connection_.SendCryptoStreamData();
14838 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14839 // Install 0-RTT keys.
14840 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14841 std::make_unique<TaggingEncrypter>(0x02));
14842 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14843
14844 // CHLO gets acknowledged after 10ms.
14845 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
14846 QuicAckFrame frame1 = InitAckFrame(1);
14847 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
14848 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
14849 // Verify PTO is still armed since address validation is not finished yet.
14850 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14851 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14852
14853 // Send 0-RTT packet.
14854 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
14855 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14856 std::make_unique<TaggingEncrypter>(0x02));
14857 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14858 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
14859 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14860 // PTO deadline should be unchanged.
14861 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
14862}
14863
14864TEST_P(QuicConnectionTest, QueueingUndecryptablePacketsDoesntPostponePTO) {
14865 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14866 return;
14867 }
14868 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14869 QuicConfig config;
14870 config.set_max_undecryptable_packets(3);
14871 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040014872 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14873 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
14874 // Send CHLO.
14875 connection_.SendCryptoStreamData();
14876
14877 // Send 0-RTT packet.
14878 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14879 std::make_unique<TaggingEncrypter>(0x02));
14880 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14881 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
14882
14883 // CHLO gets acknowledged after 10ms.
14884 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
14885 QuicAckFrame frame1 = InitAckFrame(1);
14886 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
14887 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
14888 // Verify PTO is still armed since address validation is not finished yet.
14889 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14890 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14891
14892 // Receive an undecryptable packets.
14893 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
14894 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
14895 std::make_unique<TaggingEncrypter>(0xFF));
14896 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14897 // Verify PTO deadline is sooner.
14898 EXPECT_GT(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
14899 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14900
14901 // PTO fires.
14902 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
14903 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
14904 connection_.GetRetransmissionAlarm()->Fire();
14905 // Verify PTO is still armed since address validation is not finished yet.
14906 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14907 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14908
14909 // Verify PTO deadline does not change.
14910 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14911 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
14912}
14913
14914TEST_P(QuicConnectionTest, QueueUndecryptableHandshakePackets) {
14915 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14916 return;
14917 }
14918 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14919 QuicConfig config;
14920 config.set_max_undecryptable_packets(3);
14921 connection_.SetFromConfig(config);
Bence Békybac04052022-04-07 15:44:29 -040014922 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14923 connection_.RemoveDecrypter(ENCRYPTION_HANDSHAKE);
14924 // Send CHLO.
14925 connection_.SendCryptoStreamData();
14926
14927 // Send 0-RTT packet.
14928 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14929 std::make_unique<TaggingEncrypter>(0x02));
14930 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14931 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
14932 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
14933
14934 // Receive an undecryptable handshake packet.
14935 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
14936 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
14937 std::make_unique<TaggingEncrypter>(0xFF));
14938 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
14939 // Verify this handshake packet gets queued.
14940 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
14941}
14942
14943TEST_P(QuicConnectionTest, PingNotSentAt0RTTLevelWhenInitialAvailable) {
14944 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14945 return;
14946 }
Bence Békybac04052022-04-07 15:44:29 -040014947 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14948 // Send CHLO.
14949 connection_.SendCryptoStreamData();
14950 // Send 0-RTT packet.
martinduke9e0811c2022-12-08 20:35:57 -080014951 connection_.SetEncrypter(
14952 ENCRYPTION_ZERO_RTT,
14953 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040014954 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14955 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
14956
14957 // CHLO gets acknowledged after 10ms.
14958 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
14959 QuicAckFrame frame1 = InitAckFrame(1);
14960 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
14961 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
14962 // Verify PTO is still armed since address validation is not finished yet.
14963 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14964 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14965
14966 // PTO fires.
14967 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
14968 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
14969 connection_.GetRetransmissionAlarm()->Fire();
14970 // Verify the PING gets sent in ENCRYPTION_INITIAL.
martinduke9e0811c2022-12-08 20:35:57 -080014971 EXPECT_NE(0x02020202u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040014972}
14973
14974TEST_P(QuicConnectionTest, AckElicitingFrames) {
14975 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014976 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014977 QuicConfig config;
14978 config.SetConnectionOptionsToSend({kRVCM});
14979 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14980 connection_.SetFromConfig(config);
14981 }
14982 if (!version().HasIetfQuicFrames() ||
14983 !connection_.connection_migration_use_new_cid()) {
14984 return;
14985 }
martinduke08e3ff82022-10-18 09:06:26 -070014986 EXPECT_CALL(connection_id_generator_,
14987 GenerateNextConnectionId(TestConnectionId(12)))
14988 .WillOnce(Return(TestConnectionId(456)));
14989 EXPECT_CALL(connection_id_generator_,
14990 GenerateNextConnectionId(TestConnectionId(456)))
14991 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040014992 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
14993 EXPECT_CALL(visitor_, OnRstStream(_));
14994 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
14995 EXPECT_CALL(visitor_, OnBlockedFrame(_));
14996 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
14997 EXPECT_CALL(visitor_, OnStreamFrame(_));
14998 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
14999 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_));
15000 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_));
15001 EXPECT_CALL(visitor_, OnStopSendingFrame(_));
15002 EXPECT_CALL(visitor_, OnMessageReceived(""));
15003 EXPECT_CALL(visitor_, OnNewTokenReceived(""));
15004
15005 SetClientConnectionId(TestConnectionId(12));
15006 connection_.CreateConnectionIdManager();
15007 QuicConnectionPeer::GetSelfIssuedConnectionIdManager(&connection_)
15008 ->MaybeSendNewConnectionIds();
15009 connection_.set_can_receive_ack_frequency_frame();
15010
15011 QuicAckFrame ack_frame = InitAckFrame(1);
15012 QuicRstStreamFrame rst_stream_frame;
15013 QuicWindowUpdateFrame window_update_frame;
15014 QuicPathChallengeFrame path_challenge_frame;
15015 QuicNewConnectionIdFrame new_connection_id_frame;
15016 QuicRetireConnectionIdFrame retire_connection_id_frame;
15017 retire_connection_id_frame.sequence_number = 1u;
15018 QuicStopSendingFrame stop_sending_frame;
15019 QuicPathResponseFrame path_response_frame;
15020 QuicMessageFrame message_frame;
15021 QuicNewTokenFrame new_token_frame;
15022 QuicAckFrequencyFrame ack_frequency_frame;
15023 QuicBlockedFrame blocked_frame;
15024 size_t packet_number = 1;
15025
15026 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15027
15028 for (uint8_t i = 0; i < NUM_FRAME_TYPES; ++i) {
15029 QuicFrameType frame_type = static_cast<QuicFrameType>(i);
15030 bool skipped = false;
15031 QuicFrame frame;
15032 QuicFrames frames;
15033 // Add some padding to fullfill the min size requirement of header
15034 // protection.
15035 frames.push_back(QuicFrame(QuicPaddingFrame(10)));
15036 switch (frame_type) {
15037 case PADDING_FRAME:
15038 frame = QuicFrame(QuicPaddingFrame(10));
15039 break;
15040 case MTU_DISCOVERY_FRAME:
15041 frame = QuicFrame(QuicMtuDiscoveryFrame());
15042 break;
15043 case PING_FRAME:
15044 frame = QuicFrame(QuicPingFrame());
15045 break;
15046 case MAX_STREAMS_FRAME:
15047 frame = QuicFrame(QuicMaxStreamsFrame());
15048 break;
15049 case STOP_WAITING_FRAME:
15050 // Not supported.
15051 skipped = true;
15052 break;
15053 case STREAMS_BLOCKED_FRAME:
15054 frame = QuicFrame(QuicStreamsBlockedFrame());
15055 break;
15056 case STREAM_FRAME:
15057 frame = QuicFrame(QuicStreamFrame());
15058 break;
15059 case HANDSHAKE_DONE_FRAME:
15060 frame = QuicFrame(QuicHandshakeDoneFrame());
15061 break;
15062 case ACK_FRAME:
15063 frame = QuicFrame(&ack_frame);
15064 break;
15065 case RST_STREAM_FRAME:
15066 frame = QuicFrame(&rst_stream_frame);
15067 break;
15068 case CONNECTION_CLOSE_FRAME:
15069 // Do not test connection close.
15070 skipped = true;
15071 break;
15072 case GOAWAY_FRAME:
15073 // Does not exist in IETF QUIC.
15074 skipped = true;
15075 break;
15076 case BLOCKED_FRAME:
15077 frame = QuicFrame(blocked_frame);
15078 break;
15079 case WINDOW_UPDATE_FRAME:
15080 frame = QuicFrame(window_update_frame);
15081 break;
15082 case PATH_CHALLENGE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015083 frame = QuicFrame(path_challenge_frame);
Bence Békybac04052022-04-07 15:44:29 -040015084 break;
15085 case STOP_SENDING_FRAME:
15086 frame = QuicFrame(stop_sending_frame);
15087 break;
15088 case NEW_CONNECTION_ID_FRAME:
15089 frame = QuicFrame(&new_connection_id_frame);
15090 break;
15091 case RETIRE_CONNECTION_ID_FRAME:
15092 frame = QuicFrame(&retire_connection_id_frame);
15093 break;
15094 case PATH_RESPONSE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070015095 frame = QuicFrame(path_response_frame);
Bence Békybac04052022-04-07 15:44:29 -040015096 break;
15097 case MESSAGE_FRAME:
15098 frame = QuicFrame(&message_frame);
15099 break;
15100 case CRYPTO_FRAME:
15101 // CRYPTO_FRAME is ack eliciting is covered by other tests.
15102 skipped = true;
15103 break;
15104 case NEW_TOKEN_FRAME:
15105 frame = QuicFrame(&new_token_frame);
15106 break;
15107 case ACK_FREQUENCY_FRAME:
15108 frame = QuicFrame(&ack_frequency_frame);
15109 break;
15110 case NUM_FRAME_TYPES:
15111 skipped = true;
15112 break;
15113 }
15114 if (skipped) {
15115 continue;
15116 }
15117 ASSERT_EQ(frame_type, frame.type);
15118 frames.push_back(frame);
15119 EXPECT_FALSE(connection_.HasPendingAcks());
15120 // Process frame.
15121 ProcessFramesPacketAtLevel(packet_number++, frames,
15122 ENCRYPTION_FORWARD_SECURE);
15123 if (QuicUtils::IsAckElicitingFrame(frame_type)) {
15124 ASSERT_TRUE(connection_.HasPendingAcks()) << frame;
15125 // Flush ACK.
15126 clock_.AdvanceTime(DefaultDelayedAckTime());
15127 connection_.GetAckAlarm()->Fire();
15128 }
15129 EXPECT_FALSE(connection_.HasPendingAcks());
15130 ASSERT_TRUE(connection_.connected());
15131 }
15132}
15133
15134TEST_P(QuicConnectionTest, ReceivedChloAndAck) {
15135 if (!version().HasIetfQuicFrames()) {
15136 return;
15137 }
15138 set_perspective(Perspective::IS_SERVER);
15139 QuicFrames frames;
15140 QuicAckFrame ack_frame = InitAckFrame(1);
15141 frames.push_back(MakeCryptoFrame());
15142 frames.push_back(QuicFrame(&ack_frame));
15143
15144 EXPECT_CALL(visitor_, OnCryptoFrame(_))
15145 .WillOnce(IgnoreResult(InvokeWithoutArgs(
15146 &connection_, &TestConnection::SendCryptoStreamData)));
15147 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15148 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15149 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
15150 ENCRYPTION_INITIAL);
15151}
15152
15153// Regression test for b/201643321.
15154TEST_P(QuicConnectionTest, FailedToRetransmitShlo) {
fayang161ce6e2022-07-01 18:02:11 -070015155 if (!version().HasIetfQuicFrames() ||
birenroyef686222022-09-12 11:34:34 -070015156 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040015157 return;
15158 }
15159 set_perspective(Perspective::IS_SERVER);
15160 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15161 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015162 // Received INITIAL 1.
15163 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15164 EXPECT_TRUE(connection_.HasPendingAcks());
15165
martinduke9e0811c2022-12-08 20:35:57 -080015166 peer_framer_.SetEncrypter(
15167 ENCRYPTION_ZERO_RTT,
15168 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015169
martinduke9e0811c2022-12-08 20:35:57 -080015170 connection_.SetEncrypter(
15171 ENCRYPTION_HANDSHAKE,
15172 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015173 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015174 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015175 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015176 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15177 connection_.SetEncrypter(
15178 ENCRYPTION_FORWARD_SECURE,
15179 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015180 // Received ENCRYPTION_ZERO_RTT 1.
15181 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15182 {
15183 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15184 // Send INITIAL 1.
15185 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15186 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15187 // Send HANDSHAKE 2.
15188 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15189 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15190 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
15191 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15192 // Send half RTT data to exhaust amplification credit.
15193 connection_.SendStreamDataWithString(0, std::string(100 * 1024, 'a'), 0,
15194 NO_FIN);
15195 }
15196 // Received INITIAL 2.
15197 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
15198 ASSERT_TRUE(connection_.HasPendingAcks());
15199 // Verify ACK delay is 1ms.
15200 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
15201 connection_.GetAckAlarm()->deadline());
15202 // ACK is not throttled by amplification limit, and SHLO is bundled. Also
15203 // HANDSHAKE + 1RTT packets get coalesced.
fayange9753892022-05-17 03:57:11 -070015204 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -040015205 // ACK alarm fires.
15206 clock_.AdvanceTime(kAlarmGranularity);
15207 connection_.GetAckAlarm()->Fire();
fayange9753892022-05-17 03:57:11 -070015208 // Verify 1-RTT packet is coalesced.
martinduke9e0811c2022-12-08 20:35:57 -080015209 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015210 // Only the first packet in the coalesced packet has been processed,
15211 // verify SHLO is bundled with INITIAL ACK.
15212 EXPECT_EQ(1u, writer_->ack_frames().size());
15213 EXPECT_EQ(1u, writer_->crypto_frames().size());
15214 // Process the coalesced HANDSHAKE packet.
15215 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15216 auto packet = writer_->coalesced_packet()->Clone();
15217 writer_->framer()->ProcessPacket(*packet);
15218 EXPECT_EQ(0u, writer_->ack_frames().size());
15219 EXPECT_EQ(1u, writer_->crypto_frames().size());
fayange9753892022-05-17 03:57:11 -070015220 // Process the coalesced 1-RTT packet.
15221 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15222 packet = writer_->coalesced_packet()->Clone();
15223 writer_->framer()->ProcessPacket(*packet);
15224 EXPECT_EQ(0u, writer_->crypto_frames().size());
15225 EXPECT_EQ(1u, writer_->stream_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040015226
15227 // Received INITIAL 3.
15228 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
15229 ProcessCryptoPacketAtLevel(3, ENCRYPTION_INITIAL);
15230 EXPECT_TRUE(connection_.HasPendingAcks());
15231}
15232
15233// Regression test for b/216133388.
15234TEST_P(QuicConnectionTest, FailedToConsumeCryptoData) {
15235 if (!version().HasIetfQuicFrames()) {
15236 return;
15237 }
15238 set_perspective(Perspective::IS_SERVER);
15239 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15240 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015241 // Received INITIAL 1.
15242 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15243 EXPECT_TRUE(connection_.HasPendingAcks());
15244
martinduke9e0811c2022-12-08 20:35:57 -080015245 peer_framer_.SetEncrypter(
15246 ENCRYPTION_ZERO_RTT,
15247 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15248 connection_.SetEncrypter(
15249 ENCRYPTION_HANDSHAKE,
15250 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015251 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015252 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015253 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015254 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15255 connection_.SetEncrypter(
15256 ENCRYPTION_FORWARD_SECURE,
15257 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015258 // Received ENCRYPTION_ZERO_RTT 1.
15259 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15260 {
15261 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15262 // Send INITIAL 1.
15263 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15264 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15265 // Send HANDSHAKE 2.
15266 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15267 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15268 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15269 ENCRYPTION_HANDSHAKE);
15270 // Send 1-RTT 3.
15271 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15272 connection_.SendStreamDataWithString(0, std::string(40, 'a'), 0, NO_FIN);
15273 }
15274 // Received HANDSHAKE Ping, hence discard INITIAL keys.
15275 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15276 std::make_unique<TaggingEncrypter>(0x03));
15277 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15278 connection_.NeuterUnencryptedPackets();
15279 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
15280 clock_.AdvanceTime(kAlarmGranularity);
15281 {
15282 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15283 // Sending this 1-RTT data would leave the coalescer only have space to
15284 // accommodate the HANDSHAKE ACK. The crypto data cannot be bundled with the
15285 // ACK.
15286 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15287 connection_.SendStreamDataWithString(0, std::string(1395, 'a'), 40, NO_FIN);
15288 }
15289 // Verify retransmission alarm is armed.
15290 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15291 const QuicTime retransmission_time =
15292 connection_.GetRetransmissionAlarm()->deadline();
15293 clock_.AdvanceTime(retransmission_time - clock_.Now());
15294 connection_.GetRetransmissionAlarm()->Fire();
15295
fayang43294412022-04-21 09:22:12 -070015296 // Verify the retransmission is a coalesced packet with HANDSHAKE 2 and
15297 // 1-RTT 3.
martinduke9e0811c2022-12-08 20:35:57 -080015298 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
fayang43294412022-04-21 09:22:12 -070015299 // Only the first packet in the coalesced packet has been processed.
15300 EXPECT_EQ(1u, writer_->crypto_frames().size());
15301 // Process the coalesced 1-RTT packet.
15302 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15303 auto packet = writer_->coalesced_packet()->Clone();
15304 writer_->framer()->ProcessPacket(*packet);
15305 EXPECT_EQ(1u, writer_->stream_frames().size());
15306 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
Bence Békybac04052022-04-07 15:44:29 -040015307 // Verify retransmission alarm is still armed.
15308 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15309}
15310
15311TEST_P(QuicConnectionTest,
15312 RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing) {
15313 // An endpoint might postpone the processing of ACK when the corresponding
15314 // decryption key is not available. This test makes sure the RTT sample does
15315 // not include the queuing delay.
15316 if (!version().HasIetfQuicFrames()) {
15317 return;
15318 }
15319 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15320 QuicConfig config;
15321 config.set_max_undecryptable_packets(3);
15322 connection_.SetFromConfig(config);
15323
15324 // 30ms RTT.
15325 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
15326 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
15327 rtt_stats->UpdateRtt(kTestRTT, QuicTime::Delta::Zero(), QuicTime::Zero());
Bence Békybac04052022-04-07 15:44:29 -040015328
15329 // Send 0-RTT packet.
15330 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015331 connection_.SetEncrypter(
15332 ENCRYPTION_ZERO_RTT,
15333 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015334 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15335 connection_.SendStreamDataWithString(0, std::string(10, 'a'), 0, FIN);
15336
15337 // Receives 1-RTT ACK for 0-RTT packet after RTT + ack_delay.
15338 clock_.AdvanceTime(
15339 kTestRTT + QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
15340 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
martinduke9e0811c2022-12-08 20:35:57 -080015341 peer_framer_.SetEncrypter(
15342 ENCRYPTION_FORWARD_SECURE,
15343 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015344 QuicAckFrame ack_frame = InitAckFrame(1);
15345 // Peer reported ACK delay.
15346 ack_frame.ack_delay_time =
15347 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
15348 QuicFrames frames;
15349 frames.push_back(QuicFrame(&ack_frame));
15350 QuicPacketHeader header =
15351 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15352 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15353
15354 char buffer[kMaxOutgoingPacketSize];
15355 size_t encrypted_length = peer_framer_.EncryptPayload(
15356 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15357 kMaxOutgoingPacketSize);
15358 connection_.ProcessUdpPacket(
15359 kSelfAddress, kPeerAddress,
15360 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15361 if (connection_.GetSendAlarm()->IsSet()) {
15362 connection_.GetSendAlarm()->Fire();
15363 }
15364 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15365
15366 // Assume 1-RTT decrypter is available after 10ms.
15367 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15368 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
martinduke9e0811c2022-12-08 20:35:57 -080015369 SetDecrypter(
15370 ENCRYPTION_FORWARD_SECURE,
15371 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015372 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15373
15374 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
15375 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15376 // Verify RTT sample does not include queueing delay.
15377 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
15378}
15379
15380// Regression test for b/112480134.
15381TEST_P(QuicConnectionTest, NoExtraPaddingInReserializedInitial) {
15382 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
15383 if (!IsDefaultTestConfiguration() ||
15384 !connection_.version().CanSendCoalescedPackets()) {
15385 return;
15386 }
15387
15388 set_perspective(Perspective::IS_SERVER);
15389 MockQuicConnectionDebugVisitor debug_visitor;
15390 connection_.set_debug_visitor(&debug_visitor);
15391
15392 uint64_t debug_visitor_sent_count = 0;
15393 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _))
15394 .WillRepeatedly([&]() { debug_visitor_sent_count++; });
15395
15396 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15397 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015398
15399 // Received INITIAL 1.
15400 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15401
martinduke9e0811c2022-12-08 20:35:57 -080015402 peer_framer_.SetEncrypter(
15403 ENCRYPTION_ZERO_RTT,
15404 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
15405 connection_.SetEncrypter(
15406 ENCRYPTION_HANDSHAKE,
15407 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015408 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015409 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015410 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015411 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15412 connection_.SetEncrypter(
15413 ENCRYPTION_FORWARD_SECURE,
15414 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015415
15416 // Received ENCRYPTION_ZERO_RTT 2.
15417 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15418
15419 {
15420 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15421 // Send INITIAL 1.
15422 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15423 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15424 // Send HANDSHAKE 2.
15425 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15426 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15427 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15428 ENCRYPTION_HANDSHAKE);
15429 // Send 1-RTT 3.
15430 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15431 connection_.SendStreamDataWithString(0, std::string(400, 'b'), 0, NO_FIN);
15432 }
15433
15434 // Arrange the stream data to be sent in response to ENCRYPTION_INITIAL 3.
15435 const std::string data4(1000, '4'); // Data to send in stream id 4
15436 const std::string data8(3000, '8'); // Data to send in stream id 8
15437 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce([&]() {
15438 connection_.producer()->SaveStreamData(4, data4);
15439 connection_.producer()->SaveStreamData(8, data8);
15440
15441 notifier_.WriteOrBufferData(4, data4.size(), FIN_AND_PADDING);
15442
15443 // This should trigger FlushCoalescedPacket.
15444 notifier_.WriteOrBufferData(8, data8.size(), FIN);
15445 });
15446
15447 QuicByteCount pending_padding_after_serialize_2nd_1rtt_packet = 0;
15448 QuicPacketCount num_1rtt_packets_serialized = 0;
15449 EXPECT_CALL(connection_, OnSerializedPacket(_))
15450 .WillRepeatedly([&](SerializedPacket packet) {
15451 if (packet.encryption_level == ENCRYPTION_FORWARD_SECURE) {
15452 num_1rtt_packets_serialized++;
15453 if (num_1rtt_packets_serialized == 2) {
15454 pending_padding_after_serialize_2nd_1rtt_packet =
15455 connection_.packet_creator().pending_padding_bytes();
15456 }
15457 }
15458 connection_.QuicConnection::OnSerializedPacket(std::move(packet));
15459 });
15460
15461 // Server receives INITIAL 3, this will serialzie FS 7 (stream 4, stream 8),
15462 // which will trigger a flush of a coalesced packet consists of INITIAL 4,
15463 // HS 5 and FS 6 (stream 4).
wub08efde42022-05-09 12:25:02 -070015464
15465 // Expect no QUIC_BUG.
15466 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15467 EXPECT_EQ(
15468 debug_visitor_sent_count,
15469 connection_.sent_packet_manager().GetLargestSentPacket().ToUint64());
Bence Békybac04052022-04-07 15:44:29 -040015470
15471 // The error only happens if after serializing the second 1RTT packet(pkt #7),
15472 // the pending padding bytes is non zero.
15473 EXPECT_GT(pending_padding_after_serialize_2nd_1rtt_packet, 0u);
15474 EXPECT_TRUE(connection_.connected());
15475}
15476
15477TEST_P(QuicConnectionTest, ReportedAckDelayIncludesQueuingDelay) {
15478 if (!version().HasIetfQuicFrames()) {
15479 return;
15480 }
15481 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15482 QuicConfig config;
15483 config.set_max_undecryptable_packets(3);
15484 connection_.SetFromConfig(config);
15485
15486 // Receive 1-RTT ack-eliciting packet while keys are not available.
15487 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015488 peer_framer_.SetEncrypter(
15489 ENCRYPTION_FORWARD_SECURE,
15490 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015491 QuicFrames frames;
15492 frames.push_back(QuicFrame(QuicPingFrame()));
15493 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
15494 QuicPacketHeader header =
15495 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15496 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15497
15498 char buffer[kMaxOutgoingPacketSize];
15499 size_t encrypted_length = peer_framer_.EncryptPayload(
15500 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15501 kMaxOutgoingPacketSize);
15502 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15503 const QuicTime packet_receipt_time = clock_.Now();
15504 connection_.ProcessUdpPacket(
15505 kSelfAddress, kPeerAddress,
15506 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15507 if (connection_.GetSendAlarm()->IsSet()) {
15508 connection_.GetSendAlarm()->Fire();
15509 }
15510 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15511 // 1-RTT keys become available after 10ms.
15512 const QuicTime::Delta kQueuingDelay = QuicTime::Delta::FromMilliseconds(10);
15513 clock_.AdvanceTime(kQueuingDelay);
15514 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15515 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke9e0811c2022-12-08 20:35:57 -080015516 SetDecrypter(
15517 ENCRYPTION_FORWARD_SECURE,
15518 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015519 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15520
15521 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15522 ASSERT_TRUE(connection_.HasPendingAcks());
fayangfea655c2022-05-17 08:19:12 -070015523 EXPECT_EQ(packet_receipt_time + DefaultDelayedAckTime(),
15524 connection_.GetAckAlarm()->deadline());
15525 clock_.AdvanceTime(packet_receipt_time + DefaultDelayedAckTime() -
15526 clock_.Now());
Bence Békybac04052022-04-07 15:44:29 -040015527 // Fire ACK alarm.
15528 connection_.GetAckAlarm()->Fire();
15529 ASSERT_EQ(1u, writer_->ack_frames().size());
fayangfea655c2022-05-17 08:19:12 -070015530 // Verify ACK delay time does not include queuing delay.
15531 EXPECT_EQ(DefaultDelayedAckTime(), writer_->ack_frames()[0].ack_delay_time);
Bence Békybac04052022-04-07 15:44:29 -040015532}
15533
15534TEST_P(QuicConnectionTest, CoalesceOneRTTPacketWithInitialAndHandshakePackets) {
15535 if (!version().HasIetfQuicFrames()) {
15536 return;
15537 }
15538 set_perspective(Perspective::IS_SERVER);
15539 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15540 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015541
15542 // Received INITIAL 1.
15543 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15544
martinduke9e0811c2022-12-08 20:35:57 -080015545 peer_framer_.SetEncrypter(
15546 ENCRYPTION_ZERO_RTT,
15547 std::make_unique<TaggingEncrypter>(ENCRYPTION_ZERO_RTT));
Bence Békybac04052022-04-07 15:44:29 -040015548
martinduke9e0811c2022-12-08 20:35:57 -080015549 connection_.SetEncrypter(
15550 ENCRYPTION_HANDSHAKE,
15551 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015552 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015553 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015554 SetDecrypter(ENCRYPTION_ZERO_RTT,
martinduke9e0811c2022-12-08 20:35:57 -080015555 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_ZERO_RTT));
15556 connection_.SetEncrypter(
15557 ENCRYPTION_FORWARD_SECURE,
15558 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015559
15560 // Received ENCRYPTION_ZERO_RTT 2.
15561 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15562
15563 {
15564 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15565 // Send INITIAL 1.
15566 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15567 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15568 // Send HANDSHAKE 2.
15569 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15570 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15571 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15572 ENCRYPTION_HANDSHAKE);
15573 // Send 1-RTT data.
15574 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15575 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
15576 }
15577 // Verify coalesced packet [INITIAL 1 + HANDSHAKE 2 + part of 1-RTT data] +
15578 // rest of 1-RTT data get sent.
15579 EXPECT_EQ(2u, writer_->packets_write_attempts());
15580
15581 // Received ENCRYPTION_INITIAL 3.
15582 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15583
15584 // Verify a coalesced packet gets sent.
15585 EXPECT_EQ(3u, writer_->packets_write_attempts());
15586
15587 // Only the first INITIAL packet has been processed yet.
15588 EXPECT_EQ(1u, writer_->ack_frames().size());
15589 EXPECT_EQ(1u, writer_->crypto_frames().size());
15590
15591 // Process HANDSHAKE packet.
15592 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15593 auto packet = writer_->coalesced_packet()->Clone();
15594 writer_->framer()->ProcessPacket(*packet);
15595 EXPECT_EQ(1u, writer_->crypto_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040015596 // Process 1-RTT packet.
15597 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15598 packet = writer_->coalesced_packet()->Clone();
15599 writer_->framer()->ProcessPacket(*packet);
15600 EXPECT_EQ(1u, writer_->stream_frames().size());
15601}
15602
15603// Regression test for b/180103273
15604TEST_P(QuicConnectionTest, SendMultipleConnectionCloses) {
15605 if (!version().HasIetfQuicFrames() ||
15606 !GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
15607 return;
15608 }
15609 set_perspective(Perspective::IS_SERVER);
15610 // Finish handshake.
15611 QuicConnectionPeer::SetAddressValidated(&connection_);
15612 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15613 notifier_.NeuterUnencryptedData();
15614 connection_.NeuterUnencryptedPackets();
15615 connection_.OnHandshakeComplete();
15616 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15617 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
15618 EXPECT_CALL(visitor_, GetHandshakeState())
fayang59e518a2022-11-29 11:16:45 -080015619 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
Bence Békybac04052022-04-07 15:44:29 -040015620
15621 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
15622 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
bnc3000cba2022-04-18 12:19:14 -070015623 // Verify that BeforeConnectionCloseSent() gets called twice,
15624 // while OnConnectionClosed() is called only once.
Bence Békybac04052022-04-07 15:44:29 -040015625 EXPECT_CALL(visitor_, BeforeConnectionCloseSent()).Times(2);
15626 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15627 // Send connection close w/o closing connection.
15628 QuicConnectionPeer::SendConnectionClosePacket(
15629 &connection_, INTERNAL_ERROR, QUIC_INTERNAL_ERROR, "internal error");
bnc3000cba2022-04-18 12:19:14 -070015630 // Fire blackhole detection alarm. This will invoke
15631 // SendConnectionClosePacket() a second time.
15632 connection_.GetBlackholeDetectorAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -040015633}
15634
15635// Regression test for b/157895910.
15636TEST_P(QuicConnectionTest, EarliestSentTimeNotInitializedWhenPtoFires) {
15637 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15638 return;
15639 }
15640 set_perspective(Perspective::IS_SERVER);
15641 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15642 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
Bence Békybac04052022-04-07 15:44:29 -040015643
15644 // Received INITIAL 1.
15645 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
martinduke9e0811c2022-12-08 20:35:57 -080015646 connection_.SetEncrypter(
15647 ENCRYPTION_HANDSHAKE,
15648 std::make_unique<TaggingEncrypter>(ENCRYPTION_HANDSHAKE));
Bence Békybac04052022-04-07 15:44:29 -040015649 SetDecrypter(ENCRYPTION_HANDSHAKE,
martinduke9e0811c2022-12-08 20:35:57 -080015650 std::make_unique<StrictTaggingDecrypter>(ENCRYPTION_HANDSHAKE));
15651 connection_.SetEncrypter(
15652 ENCRYPTION_FORWARD_SECURE,
15653 std::make_unique<TaggingEncrypter>(ENCRYPTION_FORWARD_SECURE));
Bence Békybac04052022-04-07 15:44:29 -040015654 {
15655 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15656 // Send INITIAL 1.
15657 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15658 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15659 // Send HANDSHAKE 2.
15660 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15661 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15662 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15663 ENCRYPTION_HANDSHAKE);
15664 // Send half RTT data.
15665 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15666 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
15667 }
15668
15669 // Received ACKs for both INITIAL and HANDSHAKE packets.
15670 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
15671 .Times(AnyNumber());
15672 QuicFrames frames1;
15673 QuicAckFrame ack_frame1 = InitAckFrame(1);
15674 frames1.push_back(QuicFrame(&ack_frame1));
15675
15676 QuicFrames frames2;
15677 QuicAckFrame ack_frame2 =
15678 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
15679 frames2.push_back(QuicFrame(&ack_frame2));
15680 ProcessCoalescedPacket(
15681 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
15682 // Verify PTO is not armed given the only outstanding data is half RTT data.
15683 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15684}
15685
wub47bb7282022-06-14 09:40:33 -070015686TEST_P(QuicConnectionTest, CalculateNetworkBlackholeDelay) {
15687 if (!IsDefaultTestConfiguration()) {
15688 return;
15689 }
15690
15691 const QuicTime::Delta kOneSec = QuicTime::Delta::FromSeconds(1);
15692 const QuicTime::Delta kTwoSec = QuicTime::Delta::FromSeconds(2);
15693 const QuicTime::Delta kFourSec = QuicTime::Delta::FromSeconds(4);
15694
15695 // Normal case: blackhole_delay longer than path_degrading_delay +
15696 // 2*pto_delay.
15697 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
15698 kOneSec),
15699 kFourSec);
15700
15701 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
15702 kTwoSec),
15703 QuicTime::Delta::FromSeconds(5));
15704}
15705
fayangb225e172022-06-27 17:45:38 -070015706TEST_P(QuicConnectionTest, FixBytesAccountingForBufferedCoalescedPackets) {
15707 if (!connection_.version().CanSendCoalescedPackets()) {
15708 return;
15709 }
fayangb225e172022-06-27 17:45:38 -070015710 // Write is blocked.
15711 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
15712 writer_->SetWriteBlocked();
15713 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15714 QuicConnectionPeer::SendPing(&connection_);
15715 const QuicConnectionStats& stats = connection_.GetStats();
fayang4e283832022-09-01 12:47:07 -070015716 // Verify padding is accounted.
15717 EXPECT_EQ(stats.bytes_sent, connection_.max_packet_length());
fayangb225e172022-06-27 17:45:38 -070015718}
15719
fayang161ce6e2022-07-01 18:02:11 -070015720TEST_P(QuicConnectionTest, StrictAntiAmplificationLimit) {
15721 if (!connection_.version().SupportsAntiAmplificationLimit()) {
15722 return;
15723 }
15724 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
15725 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -070015726 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15727 // Verify no data can be sent at the beginning because bytes received is 0.
15728 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
15729 connection_.SendCryptoDataWithString("foo", 0);
15730 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
15731 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
15732 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15733
15734 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -070015735 GetQuicFlag(quic_anti_amplification_factor);
fayang161ce6e2022-07-01 18:02:11 -070015736 // Receives packet 1.
15737 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
15738 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
15739 .Times(anti_amplification_factor);
15740 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15741 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15742 std::make_unique<TaggingEncrypter>(0x02));
15743 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15744 std::make_unique<TaggingEncrypter>(0x03));
15745
15746 for (size_t i = 1; i < anti_amplification_factor - 1; ++i) {
15747 connection_.SendCryptoDataWithString("foo", i * 3);
15748 }
15749 // Send an addtion packet with max_packet_size - 1.
15750 connection_.SetMaxPacketLength(connection_.max_packet_length() - 1);
15751 connection_.SendCryptoDataWithString("bar",
15752 (anti_amplification_factor - 1) * 3);
15753 EXPECT_LT(writer_->total_bytes_written(),
15754 anti_amplification_factor *
15755 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
birenroyef686222022-09-12 11:34:34 -070015756 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070015757 // 3 connection closes which will be buffered.
15758 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
15759 // Verify retransmission alarm is not set.
15760 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15761 } else {
15762 // Crypto + 3 connection closes.
15763 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
15764 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15765 }
15766 // Try to send another packet with max_packet_size.
15767 connection_.SetMaxPacketLength(connection_.max_packet_length() + 1);
15768 connection_.SendCryptoDataWithString("bar", anti_amplification_factor * 3);
15769 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15770 // Close connection.
15771 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15772 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15773 connection_.CloseConnection(
15774 QUIC_INTERNAL_ERROR, "error",
15775 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
15776 EXPECT_EQ(0u, connection_.NumQueuedPackets());
birenroyef686222022-09-12 11:34:34 -070015777 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070015778 EXPECT_LT(writer_->total_bytes_written(),
15779 anti_amplification_factor *
15780 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15781 } else {
15782 EXPECT_LT(writer_->total_bytes_written(),
15783 (anti_amplification_factor + 2) *
15784 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15785 EXPECT_GT(writer_->total_bytes_written(),
15786 (anti_amplification_factor + 1) *
15787 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15788 }
15789}
15790
martinduke96840a02022-07-14 07:09:06 -070015791TEST_P(QuicConnectionTest, OriginalConnectionId) {
15792 set_perspective(Perspective::IS_SERVER);
15793 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
15794 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
15795 connection_.connection_id());
15796 QuicConnectionId original({0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
15797 connection_.SetOriginalDestinationConnectionId(original);
15798 EXPECT_EQ(original, connection_.GetOriginalDestinationConnectionId());
15799 // Send a 1-RTT packet to start the DiscardZeroRttDecryptionKeys timer.
15800 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
15801 ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE);
martindukee6444ef2022-09-23 12:32:23 -070015802 if (connection_.version().UsesTls()) {
martinduke96840a02022-07-14 07:09:06 -070015803 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
15804 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(original));
15805 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
15806 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
15807 connection_.connection_id());
15808 } else {
15809 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), original);
15810 }
15811}
15812
martindukebae24052022-10-06 15:27:46 -070015813ACTION_P2(InstallKeys, conn, level) {
15814 uint8_t crypto_input = (level == ENCRYPTION_FORWARD_SECURE) ? 0x03 : 0x02;
15815 conn->SetEncrypter(level, std::make_unique<TaggingEncrypter>(crypto_input));
15816 conn->InstallDecrypter(
15817 level, std::make_unique<StrictTaggingDecrypter>(crypto_input));
15818 conn->SetDefaultEncryptionLevel(level);
martindukec2a33062022-09-30 16:04:13 -070015819}
15820
martindukebae24052022-10-06 15:27:46 -070015821TEST_P(QuicConnectionTest, ServerConnectionIdChangeWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070015822 if (!connection_.version().HasIetfQuicFrames()) {
15823 return;
15824 }
15825 // Call SetFromConfig so that the undecrypted packet buffer size is
15826 // initialized above zero.
15827 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
15828 QuicConfig config;
15829 connection_.SetFromConfig(config);
martindukebae24052022-10-06 15:27:46 -070015830 connection_.RemoveEncrypter(ENCRYPTION_FORWARD_SECURE);
15831 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martindukec2a33062022-09-30 16:04:13 -070015832
15833 // Send Client Initial.
15834 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15835 connection_.SendCryptoStreamData();
15836
15837 EXPECT_EQ(1u, writer_->packets_write_attempts());
martindukebae24052022-10-06 15:27:46 -070015838 // Server Handshake packet with new connection ID is buffered.
martindukec2a33062022-09-30 16:04:13 -070015839 QuicConnectionId old_id = connection_id_;
15840 connection_id_ = TestConnectionId(2);
15841 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15842 std::make_unique<TaggingEncrypter>(0x02));
15843 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
martindukec2a33062022-09-30 16:04:13 -070015844 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
15845 EXPECT_EQ(connection_.connection_id(), old_id);
15846
martindukebae24052022-10-06 15:27:46 -070015847 // Server 1-RTT Packet is buffered.
15848 peer_creator_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15849 std::make_unique<TaggingEncrypter>(0x03));
15850 ProcessDataPacket(0);
15851 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 2u);
15852
martindukec2a33062022-09-30 16:04:13 -070015853 // Pretend the server Initial packet will yield the Handshake keys.
15854 EXPECT_CALL(visitor_, OnCryptoFrame(_))
15855 .Times(2)
martindukebae24052022-10-06 15:27:46 -070015856 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE))
15857 .WillOnce(InstallKeys(&connection_, ENCRYPTION_FORWARD_SECURE));
15858 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martindukec2a33062022-09-30 16:04:13 -070015859 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
15860 // Two packets processed, connection ID changed.
15861 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
15862 EXPECT_EQ(connection_.connection_id(), connection_id_);
15863}
15864
martindukebae24052022-10-06 15:27:46 -070015865TEST_P(QuicConnectionTest, ServerConnectionIdChangeTwiceWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070015866 if (!connection_.version().HasIetfQuicFrames()) {
15867 return;
15868 }
15869 // Call SetFromConfig so that the undecrypted packet buffer size is
15870 // initialized above zero.
15871 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
15872 QuicConfig config;
15873 connection_.SetFromConfig(config);
15874
15875 // Send Client Initial.
15876 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15877 connection_.SendCryptoStreamData();
15878
15879 EXPECT_EQ(1u, writer_->packets_write_attempts());
15880 // Server Handshake Packet Arrives with new connection ID.
15881 QuicConnectionId old_id = connection_id_;
15882 connection_id_ = TestConnectionId(2);
15883 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15884 std::make_unique<TaggingEncrypter>(0x02));
15885 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
15886 // Packet is buffered.
15887 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
15888 EXPECT_EQ(connection_.connection_id(), old_id);
15889
15890 // Pretend the server Initial packet will yield the Handshake keys.
15891 EXPECT_CALL(visitor_, OnCryptoFrame(_))
martindukebae24052022-10-06 15:27:46 -070015892 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE));
martindukec2a33062022-09-30 16:04:13 -070015893 connection_id_ = TestConnectionId(1);
15894 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
15895 // Handshake packet discarded because there's a different connection ID.
15896 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
15897 EXPECT_EQ(connection_.connection_id(), connection_id_);
15898}
15899
Bence Békybac04052022-04-07 15:44:29 -040015900} // namespace
15901} // namespace test
15902} // namespace quic