blob: 2152a6f9163c88e957899220c82d5c6253798fa7 [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>
12#include <utility>
13
14#include "absl/base/macros.h"
15#include "absl/strings/str_cat.h"
16#include "absl/strings/str_join.h"
17#include "absl/strings/string_view.h"
18#include "quiche/quic/core/congestion_control/loss_detection_interface.h"
19#include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
20#include "quiche/quic/core/crypto/null_decrypter.h"
21#include "quiche/quic/core/crypto/null_encrypter.h"
22#include "quiche/quic/core/crypto/quic_decrypter.h"
23#include "quiche/quic/core/crypto/quic_encrypter.h"
24#include "quiche/quic/core/frames/quic_connection_close_frame.h"
25#include "quiche/quic/core/frames/quic_new_connection_id_frame.h"
26#include "quiche/quic/core/frames/quic_path_response_frame.h"
27#include "quiche/quic/core/frames/quic_rst_stream_frame.h"
28#include "quiche/quic/core/quic_connection_id.h"
29#include "quiche/quic/core/quic_constants.h"
30#include "quiche/quic/core/quic_error_codes.h"
31#include "quiche/quic/core/quic_packet_creator.h"
32#include "quiche/quic/core/quic_packets.h"
33#include "quiche/quic/core/quic_path_validator.h"
34#include "quiche/quic/core/quic_types.h"
35#include "quiche/quic/core/quic_utils.h"
36#include "quiche/quic/core/quic_versions.h"
37#include "quiche/quic/platform/api/quic_expect_bug.h"
38#include "quiche/quic/platform/api/quic_flags.h"
39#include "quiche/quic/platform/api/quic_ip_address.h"
bnc96dc1782022-09-06 08:16:01 -070040#include "quiche/quic/platform/api/quic_ip_address_family.h"
Bence Békybac04052022-04-07 15:44:29 -040041#include "quiche/quic/platform/api/quic_logging.h"
42#include "quiche/quic/platform/api/quic_socket_address.h"
43#include "quiche/quic/platform/api/quic_test.h"
44#include "quiche/quic/test_tools/mock_clock.h"
martinduke605dca22022-09-01 10:40:19 -070045#include "quiche/quic/test_tools/mock_connection_id_generator.h"
Bence Békybac04052022-04-07 15:44:29 -040046#include "quiche/quic/test_tools/mock_random.h"
47#include "quiche/quic/test_tools/quic_coalesced_packet_peer.h"
48#include "quiche/quic/test_tools/quic_config_peer.h"
49#include "quiche/quic/test_tools/quic_connection_peer.h"
50#include "quiche/quic/test_tools/quic_framer_peer.h"
51#include "quiche/quic/test_tools/quic_packet_creator_peer.h"
52#include "quiche/quic/test_tools/quic_path_validator_peer.h"
53#include "quiche/quic/test_tools/quic_sent_packet_manager_peer.h"
54#include "quiche/quic/test_tools/quic_test_utils.h"
55#include "quiche/quic/test_tools/simple_data_producer.h"
56#include "quiche/quic/test_tools/simple_session_notifier.h"
57#include "quiche/common/platform/api/quiche_reference_counted.h"
58#include "quiche/common/simple_buffer_allocator.h"
59
60using testing::_;
61using testing::AnyNumber;
62using testing::AtLeast;
63using testing::DoAll;
64using testing::ElementsAre;
65using testing::Ge;
66using testing::IgnoreResult;
67using testing::InSequence;
68using testing::Invoke;
69using testing::InvokeWithoutArgs;
70using testing::Lt;
71using testing::Ref;
72using testing::Return;
73using testing::SaveArg;
74using testing::SetArgPointee;
75using testing::StrictMock;
76
77namespace quic {
78namespace test {
79namespace {
80
81const char data1[] = "foo data";
82const char data2[] = "bar data";
83
84const bool kHasStopWaiting = true;
85
86const int kDefaultRetransmissionTimeMs = 500;
87
88DiversificationNonce kTestDiversificationNonce = {
89 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a',
90 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
91 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b',
92};
93
94const StatelessResetToken kTestStatelessResetToken{
95 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
96 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f};
97
98const QuicSocketAddress kPeerAddress =
99 QuicSocketAddress(QuicIpAddress::Loopback6(),
100 /*port=*/12345);
101const QuicSocketAddress kSelfAddress =
102 QuicSocketAddress(QuicIpAddress::Loopback6(),
103 /*port=*/443);
104
105QuicStreamId GetNthClientInitiatedStreamId(int n,
106 QuicTransportVersion version) {
107 return QuicUtils::GetFirstBidirectionalStreamId(version,
108 Perspective::IS_CLIENT) +
109 n * 2;
110}
111
112QuicLongHeaderType EncryptionlevelToLongHeaderType(EncryptionLevel level) {
113 switch (level) {
114 case ENCRYPTION_INITIAL:
115 return INITIAL;
116 case ENCRYPTION_HANDSHAKE:
117 return HANDSHAKE;
118 case ENCRYPTION_ZERO_RTT:
119 return ZERO_RTT_PROTECTED;
120 case ENCRYPTION_FORWARD_SECURE:
121 QUICHE_DCHECK(false);
122 return INVALID_PACKET_TYPE;
123 default:
124 QUICHE_DCHECK(false);
125 return INVALID_PACKET_TYPE;
126 }
127}
128
129// A NullEncrypterWithConfidentialityLimit is a NullEncrypter that allows
130// specifying the confidentiality limit on the maximum number of packets that
131// may be encrypted per key phase in TLS+QUIC.
132class NullEncrypterWithConfidentialityLimit : public NullEncrypter {
133 public:
134 NullEncrypterWithConfidentialityLimit(Perspective perspective,
135 QuicPacketCount confidentiality_limit)
136 : NullEncrypter(perspective),
137 confidentiality_limit_(confidentiality_limit) {}
138
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,
201 std::make_unique<NullEncrypter>(perspective));
202 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);
305 SetEncrypter(encryption_level, std::make_unique<TaggingEncrypter>(0x01));
306 SetDefaultEncryptionLevel(encryption_level);
307 return SaveAndSendStreamData(id, data, offset, state);
308 }
309
310 QuicConsumedData SendStreamData3() {
311 return SendStreamDataWithString(
312 GetNthClientInitiatedStreamId(1, transport_version()), "food", 0,
313 NO_FIN);
314 }
315
316 QuicConsumedData SendStreamData5() {
317 return SendStreamDataWithString(
318 GetNthClientInitiatedStreamId(2, transport_version()), "food2", 0,
319 NO_FIN);
320 }
321
322 // Ensures the connection can write stream data before writing.
323 QuicConsumedData EnsureWritableAndSendStreamData5() {
324 EXPECT_TRUE(CanWrite(HAS_RETRANSMITTABLE_DATA));
325 return SendStreamData5();
326 }
327
328 // The crypto stream has special semantics so that it is not blocked by a
329 // congestion window limitation, and also so that it gets put into a separate
330 // packet (so that it is easier to reason about a crypto frame not being
331 // split needlessly across packet boundaries). As a result, we have separate
332 // tests for some cases for this stream.
333 QuicConsumedData SendCryptoStreamData() {
334 QuicStreamOffset offset = 0;
335 absl::string_view data("chlo");
336 if (!QuicVersionUsesCryptoFrames(transport_version())) {
337 return SendCryptoDataWithString(data, offset);
338 }
339 producer_.SaveCryptoData(ENCRYPTION_INITIAL, offset, data);
340 size_t bytes_written;
341 if (notifier_) {
342 bytes_written =
343 notifier_->WriteCryptoData(ENCRYPTION_INITIAL, data.length(), offset);
344 } else {
345 bytes_written = QuicConnection::SendCryptoData(ENCRYPTION_INITIAL,
346 data.length(), offset);
347 }
348 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
349 }
350
351 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
352 QuicStreamOffset offset) {
353 return SendCryptoDataWithString(data, offset, ENCRYPTION_INITIAL);
354 }
355
356 QuicConsumedData SendCryptoDataWithString(absl::string_view data,
357 QuicStreamOffset offset,
358 EncryptionLevel encryption_level) {
359 if (!QuicVersionUsesCryptoFrames(transport_version())) {
360 return SendStreamDataWithString(
361 QuicUtils::GetCryptoStreamId(transport_version()), data, offset,
362 NO_FIN);
363 }
364 producer_.SaveCryptoData(encryption_level, offset, data);
365 size_t bytes_written;
366 if (notifier_) {
367 bytes_written =
368 notifier_->WriteCryptoData(encryption_level, data.length(), offset);
369 } else {
370 bytes_written = QuicConnection::SendCryptoData(encryption_level,
371 data.length(), offset);
372 }
373 return QuicConsumedData(bytes_written, /*fin_consumed*/ false);
374 }
375
376 void set_version(ParsedQuicVersion version) {
377 QuicConnectionPeer::GetFramer(this)->set_version(version);
378 }
379
380 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
381 QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
382 writer()->SetSupportedVersions(versions);
383 }
384
385 // This should be called before setting customized encrypters/decrypters for
386 // connection and peer creator.
387 void set_perspective(Perspective perspective) {
388 writer()->set_perspective(perspective);
389 QuicConnectionPeer::ResetPeerIssuedConnectionIdManager(this);
390 QuicConnectionPeer::SetPerspective(this, perspective);
391 QuicSentPacketManagerPeer::SetPerspective(
392 QuicConnectionPeer::GetSentPacketManager(this), perspective);
393 QuicConnectionPeer::GetFramer(this)->SetInitialObfuscators(
394 TestConnectionId());
395 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
396 ENCRYPTION_FORWARD_SECURE}) {
397 if (QuicConnectionPeer::GetFramer(this)->HasEncrypterOfEncryptionLevel(
398 level)) {
399 SetEncrypter(level, std::make_unique<NullEncrypter>(perspective));
400 }
401 if (QuicConnectionPeer::GetFramer(this)->HasDecrypterOfEncryptionLevel(
402 level)) {
403 InstallDecrypter(level, std::make_unique<NullDecrypter>(perspective));
404 }
405 }
406 }
407
408 // Enable path MTU discovery. Assumes that the test is performed from the
409 // server perspective and the higher value of MTU target is used.
410 void EnablePathMtuDiscovery(MockSendAlgorithm* send_algorithm) {
411 ASSERT_EQ(Perspective::IS_SERVER, perspective());
412
413 if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) {
414 OnConfigNegotiated();
415 } else {
416 QuicConfig config;
417 QuicTagVector connection_options;
418 connection_options.push_back(kMTUH);
419 config.SetInitialReceivedConnectionOptions(connection_options);
420 EXPECT_CALL(*send_algorithm, SetFromConfig(_, _));
421 SetFromConfig(config);
422 }
423
424 // Normally, the pacing would be disabled in the test, but calling
425 // SetFromConfig enables it. Set nearly-infinite bandwidth to make the
426 // pacing algorithm work.
427 EXPECT_CALL(*send_algorithm, PacingRate(_))
428 .WillRepeatedly(Return(QuicBandwidth::Infinite()));
429 }
430
431 TestAlarmFactory::TestAlarm* GetAckAlarm() {
432 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
433 QuicConnectionPeer::GetAckAlarm(this));
434 }
435
436 TestAlarmFactory::TestAlarm* GetPingAlarm() {
437 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
438 QuicConnectionPeer::GetPingAlarm(this));
439 }
440
441 TestAlarmFactory::TestAlarm* GetRetransmissionAlarm() {
442 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
443 QuicConnectionPeer::GetRetransmissionAlarm(this));
444 }
445
446 TestAlarmFactory::TestAlarm* GetSendAlarm() {
447 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
448 QuicConnectionPeer::GetSendAlarm(this));
449 }
450
451 TestAlarmFactory::TestAlarm* GetTimeoutAlarm() {
452 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
453 QuicConnectionPeer::GetIdleNetworkDetectorAlarm(this));
454 }
455
456 TestAlarmFactory::TestAlarm* GetMtuDiscoveryAlarm() {
457 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
458 QuicConnectionPeer::GetMtuDiscoveryAlarm(this));
459 }
460
461 TestAlarmFactory::TestAlarm* GetProcessUndecryptablePacketsAlarm() {
462 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
463 QuicConnectionPeer::GetProcessUndecryptablePacketsAlarm(this));
464 }
465
466 TestAlarmFactory::TestAlarm* GetDiscardPreviousOneRttKeysAlarm() {
467 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
468 QuicConnectionPeer::GetDiscardPreviousOneRttKeysAlarm(this));
469 }
470
471 TestAlarmFactory::TestAlarm* GetDiscardZeroRttDecryptionKeysAlarm() {
472 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
473 QuicConnectionPeer::GetDiscardZeroRttDecryptionKeysAlarm(this));
474 }
475
476 TestAlarmFactory::TestAlarm* GetBlackholeDetectorAlarm() {
477 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
478 QuicConnectionPeer::GetBlackholeDetectorAlarm(this));
479 }
480
481 TestAlarmFactory::TestAlarm* GetRetirePeerIssuedConnectionIdAlarm() {
482 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
483 QuicConnectionPeer::GetRetirePeerIssuedConnectionIdAlarm(this));
484 }
485
486 TestAlarmFactory::TestAlarm* GetRetireSelfIssuedConnectionIdAlarm() {
487 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
488 QuicConnectionPeer::GetRetireSelfIssuedConnectionIdAlarm(this));
489 }
490
renjietangfca5c772022-08-25 13:48:21 -0700491 TestAlarmFactory::TestAlarm* GetMultiPortProbingAlarm() {
492 return reinterpret_cast<TestAlarmFactory::TestAlarm*>(
493 QuicConnectionPeer::GetMultiPortProbingAlarm(this));
494 }
495
Bence Békybac04052022-04-07 15:44:29 -0400496 void PathDegradingTimeout() {
497 QUICHE_DCHECK(PathDegradingDetectionInProgress());
498 GetBlackholeDetectorAlarm()->Fire();
499 }
500
501 bool PathDegradingDetectionInProgress() {
502 return QuicConnectionPeer::GetPathDegradingDeadline(this).IsInitialized();
503 }
504
505 bool BlackholeDetectionInProgress() {
506 return QuicConnectionPeer::GetBlackholeDetectionDeadline(this)
507 .IsInitialized();
508 }
509
510 bool PathMtuReductionDetectionInProgress() {
511 return QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(this)
512 .IsInitialized();
513 }
514
Bence Békybac04052022-04-07 15:44:29 -0400515 QuicByteCount GetBytesInFlight() {
516 return QuicConnectionPeer::GetSentPacketManager(this)->GetBytesInFlight();
517 }
518
519 void set_notifier(SimpleSessionNotifier* notifier) { notifier_ = notifier; }
520
521 void ReturnEffectivePeerAddressForNextPacket(const QuicSocketAddress& addr) {
522 next_effective_peer_addr_ = std::make_unique<QuicSocketAddress>(addr);
523 }
524
Bence Békybac04052022-04-07 15:44:29 -0400525 void SendOrQueuePacket(SerializedPacket packet) override {
526 QuicConnection::SendOrQueuePacket(std::move(packet));
527 self_address_on_default_path_while_sending_packet_ = self_address();
528 }
529
530 QuicSocketAddress self_address_on_default_path_while_sending_packet() {
531 return self_address_on_default_path_while_sending_packet_;
532 }
533
534 SimpleDataProducer* producer() { return &producer_; }
535
536 using QuicConnection::active_effective_peer_migration_type;
537 using QuicConnection::IsCurrentPacketConnectivityProbing;
538 using QuicConnection::SelectMutualVersion;
Bence Békybac04052022-04-07 15:44:29 -0400539 using QuicConnection::set_defer_send_in_response_to_packets;
540
541 protected:
542 QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const override {
543 if (next_effective_peer_addr_) {
544 return *std::move(next_effective_peer_addr_);
545 }
546 return QuicConnection::GetEffectivePeerAddressFromCurrentPacket();
547 }
548
549 private:
550 TestPacketWriter* writer() {
551 return static_cast<TestPacketWriter*>(QuicConnection::writer());
552 }
553
554 SimpleDataProducer producer_;
555
556 SimpleSessionNotifier* notifier_;
557
558 std::unique_ptr<QuicSocketAddress> next_effective_peer_addr_;
559
560 QuicSocketAddress self_address_on_default_path_while_sending_packet_;
renjietangff3e9602022-10-25 12:16:49 -0700561
562 uint32_t num_unlinkable_client_migration_ = 0;
563
564 uint32_t num_linkable_client_migration_ = 0;
Bence Békybac04052022-04-07 15:44:29 -0400565};
566
567enum class AckResponse { kDefer, kImmediate };
568
569// Run tests with combinations of {ParsedQuicVersion, AckResponse}.
570struct TestParams {
571 TestParams(ParsedQuicVersion version, AckResponse ack_response,
572 bool no_stop_waiting)
573 : version(version),
574 ack_response(ack_response),
575 no_stop_waiting(no_stop_waiting) {}
576
577 ParsedQuicVersion version;
578 AckResponse ack_response;
579 bool no_stop_waiting;
580};
581
582// Used by ::testing::PrintToStringParamName().
583std::string PrintToString(const TestParams& p) {
584 return absl::StrCat(
585 ParsedQuicVersionToString(p.version), "_",
586 (p.ack_response == AckResponse::kDefer ? "defer" : "immediate"), "_",
587 (p.no_stop_waiting ? "No" : ""), "StopWaiting");
588}
589
590// Constructs various test permutations.
591std::vector<TestParams> GetTestParams() {
592 QuicFlagSaver flags;
593 std::vector<TestParams> params;
594 ParsedQuicVersionVector all_supported_versions = AllSupportedVersions();
595 for (size_t i = 0; i < all_supported_versions.size(); ++i) {
596 for (AckResponse ack_response :
597 {AckResponse::kDefer, AckResponse::kImmediate}) {
598 params.push_back(
599 TestParams(all_supported_versions[i], ack_response, true));
600 if (!all_supported_versions[i].HasIetfInvariantHeader()) {
601 params.push_back(
602 TestParams(all_supported_versions[i], ack_response, false));
603 }
604 }
605 }
606 return params;
607}
608
609class QuicConnectionTest : public QuicTestWithParam<TestParams> {
610 public:
611 // For tests that do silent connection closes, no such packet is generated. In
612 // order to verify the contents of the OnConnectionClosed upcall, EXPECTs
613 // should invoke this method, saving the frame, and then the test can verify
614 // the contents.
615 void SaveConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
616 ConnectionCloseSource /*source*/) {
617 saved_connection_close_frame_ = frame;
618 connection_close_frame_count_++;
619 }
620
621 protected:
622 QuicConnectionTest()
623 : connection_id_(TestConnectionId()),
624 framer_(SupportedVersions(version()), QuicTime::Zero(),
625 Perspective::IS_CLIENT, connection_id_.length()),
626 send_algorithm_(new StrictMock<MockSendAlgorithm>),
627 loss_algorithm_(new MockLossAlgorithm()),
628 helper_(new TestConnectionHelper(&clock_, &random_generator_)),
629 alarm_factory_(new TestAlarmFactory()),
630 peer_framer_(SupportedVersions(version()), QuicTime::Zero(),
631 Perspective::IS_SERVER, connection_id_.length()),
632 peer_creator_(connection_id_, &peer_framer_,
633 /*delegate=*/nullptr),
634 writer_(
635 new TestPacketWriter(version(), &clock_, Perspective::IS_CLIENT)),
636 connection_(connection_id_, kSelfAddress, kPeerAddress, helper_.get(),
637 alarm_factory_.get(), writer_.get(), Perspective::IS_CLIENT,
martinduke605dca22022-09-01 10:40:19 -0700638 version(), connection_id_generator_),
Bence Békybac04052022-04-07 15:44:29 -0400639 creator_(QuicConnectionPeer::GetPacketCreator(&connection_)),
640 manager_(QuicConnectionPeer::GetSentPacketManager(&connection_)),
641 frame1_(0, false, 0, absl::string_view(data1)),
642 frame2_(0, false, 3, absl::string_view(data2)),
643 crypto_frame_(ENCRYPTION_INITIAL, 0, absl::string_view(data1)),
644 packet_number_length_(PACKET_4BYTE_PACKET_NUMBER),
645 connection_id_included_(CONNECTION_ID_PRESENT),
646 notifier_(&connection_),
647 connection_close_frame_count_(0) {
648 QUIC_DVLOG(2) << "QuicConnectionTest(" << PrintToString(GetParam()) << ")";
649 connection_.set_defer_send_in_response_to_packets(GetParam().ack_response ==
650 AckResponse::kDefer);
651 framer_.SetInitialObfuscators(TestConnectionId());
652 connection_.InstallInitialCrypters(TestConnectionId());
653 CrypterPair crypters;
654 CryptoUtils::CreateInitialObfuscators(Perspective::IS_SERVER, version(),
655 TestConnectionId(), &crypters);
656 peer_creator_.SetEncrypter(ENCRYPTION_INITIAL,
657 std::move(crypters.encrypter));
658 if (version().KnowsWhichDecrypterToUse()) {
659 peer_framer_.InstallDecrypter(ENCRYPTION_INITIAL,
660 std::move(crypters.decrypter));
661 } else {
662 peer_framer_.SetDecrypter(ENCRYPTION_INITIAL,
663 std::move(crypters.decrypter));
664 }
665 for (EncryptionLevel level :
666 {ENCRYPTION_ZERO_RTT, ENCRYPTION_FORWARD_SECURE}) {
667 peer_creator_.SetEncrypter(
668 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
669 }
670 QuicFramerPeer::SetLastSerializedServerConnectionId(
671 QuicConnectionPeer::GetFramer(&connection_), connection_id_);
672 QuicFramerPeer::SetLastWrittenPacketNumberLength(
673 QuicConnectionPeer::GetFramer(&connection_), packet_number_length_);
674 if (version().HasIetfInvariantHeader()) {
675 EXPECT_TRUE(QuicConnectionPeer::GetNoStopWaitingFrames(&connection_));
676 } else {
677 QuicConnectionPeer::SetNoStopWaitingFrames(&connection_,
678 GetParam().no_stop_waiting);
679 }
680 QuicStreamId stream_id;
681 if (QuicVersionUsesCryptoFrames(version().transport_version)) {
682 stream_id = QuicUtils::GetFirstBidirectionalStreamId(
683 version().transport_version, Perspective::IS_CLIENT);
684 } else {
685 stream_id = QuicUtils::GetCryptoStreamId(version().transport_version);
686 }
687 frame1_.stream_id = stream_id;
688 frame2_.stream_id = stream_id;
689 connection_.set_visitor(&visitor_);
690 connection_.SetSessionNotifier(&notifier_);
691 connection_.set_notifier(&notifier_);
692 connection_.SetSendAlgorithm(send_algorithm_);
693 connection_.SetLossAlgorithm(loss_algorithm_.get());
694 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
695 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
696 .Times(AnyNumber());
697 EXPECT_CALL(*send_algorithm_, OnPacketNeutered(_)).Times(AnyNumber());
698 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
699 .WillRepeatedly(Return(kDefaultTCPMSS));
700 EXPECT_CALL(*send_algorithm_, PacingRate(_))
701 .WillRepeatedly(Return(QuicBandwidth::Zero()));
702 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
703 .Times(AnyNumber())
704 .WillRepeatedly(Return(QuicBandwidth::Zero()));
705 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_))
706 .Times(AnyNumber());
707 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
708 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
709 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
710 .Times(AnyNumber());
711 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
712 EXPECT_CALL(*send_algorithm_, GetCongestionControlType())
713 .Times(AnyNumber());
714 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).Times(AnyNumber());
715 EXPECT_CALL(visitor_, OnPacketDecrypted(_)).Times(AnyNumber());
716 EXPECT_CALL(visitor_, OnCanWrite())
717 .WillRepeatedly(Invoke(&notifier_, &SimpleSessionNotifier::OnCanWrite));
718 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
719 .WillRepeatedly(Return(false));
720 EXPECT_CALL(visitor_, OnCongestionWindowChange(_)).Times(AnyNumber());
721 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(AnyNumber());
722 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
723 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged())
724 .Times(testing::AtMost(1));
725 EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
726 .WillRepeatedly(Return(QuicTime::Zero()));
727 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
728 .Times(AnyNumber());
729 EXPECT_CALL(visitor_, GetHandshakeState())
730 .WillRepeatedly(Return(HANDSHAKE_START));
731 if (connection_.version().KnowsWhichDecrypterToUse()) {
732 connection_.InstallDecrypter(
733 ENCRYPTION_FORWARD_SECURE,
734 std::make_unique<NullDecrypter>(Perspective::IS_CLIENT));
735 }
736 peer_creator_.SetDefaultPeerAddress(kSelfAddress);
737 }
738
739 QuicConnectionTest(const QuicConnectionTest&) = delete;
740 QuicConnectionTest& operator=(const QuicConnectionTest&) = delete;
741
742 ParsedQuicVersion version() { return GetParam().version; }
743
744 QuicStopWaitingFrame* stop_waiting() {
745 QuicConnectionPeer::PopulateStopWaitingFrame(&connection_, &stop_waiting_);
746 return &stop_waiting_;
747 }
748
749 QuicPacketNumber least_unacked() {
750 if (writer_->stop_waiting_frames().empty()) {
751 return QuicPacketNumber();
752 }
753 return writer_->stop_waiting_frames()[0].least_unacked;
754 }
755
756 void use_tagging_decrypter() { writer_->use_tagging_decrypter(); }
757
758 void SetClientConnectionId(const QuicConnectionId& client_connection_id) {
759 connection_.set_client_connection_id(client_connection_id);
760 writer_->framer()->framer()->SetExpectedClientConnectionIdLength(
761 client_connection_id.length());
762 }
763
764 void SetDecrypter(EncryptionLevel level,
765 std::unique_ptr<QuicDecrypter> decrypter) {
766 if (connection_.version().KnowsWhichDecrypterToUse()) {
767 connection_.InstallDecrypter(level, std::move(decrypter));
768 } else {
769 connection_.SetDecrypter(level, std::move(decrypter));
770 }
771 }
772
773 void ProcessPacket(uint64_t number) {
774 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
775 ProcessDataPacket(number);
776 if (connection_.GetSendAlarm()->IsSet()) {
777 connection_.GetSendAlarm()->Fire();
778 }
779 }
780
781 void ProcessReceivedPacket(const QuicSocketAddress& self_address,
782 const QuicSocketAddress& peer_address,
783 const QuicReceivedPacket& packet) {
784 connection_.ProcessUdpPacket(self_address, peer_address, packet);
785 if (connection_.GetSendAlarm()->IsSet()) {
786 connection_.GetSendAlarm()->Fire();
787 }
788 }
789
790 QuicFrame MakeCryptoFrame() const {
791 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
792 return QuicFrame(new QuicCryptoFrame(crypto_frame_));
793 }
794 return QuicFrame(QuicStreamFrame(
795 QuicUtils::GetCryptoStreamId(connection_.transport_version()), false,
796 0u, absl::string_view()));
797 }
798
799 void ProcessFramePacket(QuicFrame frame) {
800 ProcessFramePacketWithAddresses(frame, kSelfAddress, kPeerAddress,
801 ENCRYPTION_FORWARD_SECURE);
802 }
803
804 void ProcessFramePacketWithAddresses(QuicFrame frame,
805 QuicSocketAddress self_address,
806 QuicSocketAddress peer_address,
807 EncryptionLevel level) {
808 QuicFrames frames;
809 frames.push_back(QuicFrame(frame));
810 return ProcessFramesPacketWithAddresses(frames, self_address, peer_address,
811 level);
812 }
813
814 std::unique_ptr<QuicReceivedPacket> ConstructPacket(QuicFrames frames,
815 EncryptionLevel level,
816 char* buffer,
817 size_t buffer_len) {
818 QUICHE_DCHECK(peer_framer_.HasEncrypterOfEncryptionLevel(level));
819 peer_creator_.set_encryption_level(level);
820 QuicPacketCreatorPeer::SetSendVersionInPacket(
821 &peer_creator_,
822 level < ENCRYPTION_FORWARD_SECURE &&
823 connection_.perspective() == Perspective::IS_SERVER);
824
825 SerializedPacket serialized_packet =
826 QuicPacketCreatorPeer::SerializeAllFrames(&peer_creator_, frames,
827 buffer, buffer_len);
828 return std::make_unique<QuicReceivedPacket>(
829 serialized_packet.encrypted_buffer, serialized_packet.encrypted_length,
830 clock_.Now());
831 }
832
833 void ProcessFramesPacketWithAddresses(QuicFrames frames,
834 QuicSocketAddress self_address,
835 QuicSocketAddress peer_address,
836 EncryptionLevel level) {
837 char buffer[kMaxOutgoingPacketSize];
838 connection_.ProcessUdpPacket(
839 self_address, peer_address,
840 *ConstructPacket(std::move(frames), level, buffer,
841 kMaxOutgoingPacketSize));
842 if (connection_.GetSendAlarm()->IsSet()) {
843 connection_.GetSendAlarm()->Fire();
844 }
845 }
846
847 // Bypassing the packet creator is unrealistic, but allows us to process
848 // packets the QuicPacketCreator won't allow us to create.
849 void ForceProcessFramePacket(QuicFrame frame) {
850 QuicFrames frames;
851 frames.push_back(QuicFrame(frame));
852 bool send_version = connection_.perspective() == Perspective::IS_SERVER;
853 if (connection_.version().KnowsWhichDecrypterToUse()) {
854 send_version = true;
855 }
856 QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, send_version);
857 QuicPacketHeader header;
858 QuicPacketCreatorPeer::FillPacketHeader(&peer_creator_, &header);
859 char encrypted_buffer[kMaxOutgoingPacketSize];
860 size_t length = peer_framer_.BuildDataPacket(
861 header, frames, encrypted_buffer, kMaxOutgoingPacketSize,
862 ENCRYPTION_INITIAL);
863 QUICHE_DCHECK_GT(length, 0u);
864
865 const size_t encrypted_length = peer_framer_.EncryptInPlace(
866 ENCRYPTION_INITIAL, header.packet_number,
867 GetStartOfEncryptedData(peer_framer_.version().transport_version,
868 header),
869 length, kMaxOutgoingPacketSize, encrypted_buffer);
870 QUICHE_DCHECK_GT(encrypted_length, 0u);
871
872 connection_.ProcessUdpPacket(
873 kSelfAddress, kPeerAddress,
874 QuicReceivedPacket(encrypted_buffer, encrypted_length, clock_.Now()));
875 }
876
877 size_t ProcessFramePacketAtLevel(uint64_t number, QuicFrame frame,
878 EncryptionLevel level) {
879 QuicFrames frames;
880 frames.push_back(frame);
881 return ProcessFramesPacketAtLevel(number, frames, level);
882 }
883
884 size_t ProcessFramesPacketAtLevel(uint64_t number, const QuicFrames& frames,
885 EncryptionLevel level) {
886 QuicPacketHeader header = ConstructPacketHeader(number, level);
887 // Set the correct encryption level and encrypter on peer_creator and
888 // peer_framer, respectively.
889 peer_creator_.set_encryption_level(level);
890 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
891 ENCRYPTION_INITIAL) {
892 peer_framer_.SetEncrypter(
893 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
894 std::make_unique<TaggingEncrypter>(0x01));
895 // Set the corresponding decrypter.
896 if (connection_.version().KnowsWhichDecrypterToUse()) {
897 connection_.InstallDecrypter(
898 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
899 std::make_unique<StrictTaggingDecrypter>(0x01));
900 } else {
901 connection_.SetDecrypter(
902 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
903 std::make_unique<StrictTaggingDecrypter>(0x01));
904 }
905 }
906 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
907
908 char buffer[kMaxOutgoingPacketSize];
909 size_t encrypted_length =
910 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
911 buffer, kMaxOutgoingPacketSize);
912 connection_.ProcessUdpPacket(
913 kSelfAddress, kPeerAddress,
914 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
915 if (connection_.GetSendAlarm()->IsSet()) {
916 connection_.GetSendAlarm()->Fire();
917 }
918 return encrypted_length;
919 }
920
921 struct PacketInfo {
922 PacketInfo(uint64_t packet_number, QuicFrames frames, EncryptionLevel level)
923 : packet_number(packet_number), frames(frames), level(level) {}
924
925 uint64_t packet_number;
926 QuicFrames frames;
927 EncryptionLevel level;
928 };
929
930 size_t ProcessCoalescedPacket(std::vector<PacketInfo> packets) {
931 char coalesced_buffer[kMaxOutgoingPacketSize];
932 size_t coalesced_size = 0;
933 bool contains_initial = false;
934 for (const auto& packet : packets) {
935 QuicPacketHeader header =
936 ConstructPacketHeader(packet.packet_number, packet.level);
937 // Set the correct encryption level and encrypter on peer_creator and
938 // peer_framer, respectively.
939 peer_creator_.set_encryption_level(packet.level);
940 if (packet.level == ENCRYPTION_INITIAL) {
941 contains_initial = true;
942 }
943 if (QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_) >
944 ENCRYPTION_INITIAL) {
945 peer_framer_.SetEncrypter(
946 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
947 std::make_unique<TaggingEncrypter>(0x01));
948 // Set the corresponding decrypter.
949 if (connection_.version().KnowsWhichDecrypterToUse()) {
950 connection_.InstallDecrypter(
951 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
952 std::make_unique<StrictTaggingDecrypter>(0x01));
953 } else {
954 connection_.SetDecrypter(
955 QuicPacketCreatorPeer::GetEncryptionLevel(&peer_creator_),
956 std::make_unique<StrictTaggingDecrypter>(0x01));
957 }
958 }
959 std::unique_ptr<QuicPacket> constructed_packet(
960 ConstructPacket(header, packet.frames));
961
962 char buffer[kMaxOutgoingPacketSize];
963 size_t encrypted_length = peer_framer_.EncryptPayload(
964 packet.level, QuicPacketNumber(packet.packet_number),
965 *constructed_packet, buffer, kMaxOutgoingPacketSize);
966 QUICHE_DCHECK_LE(coalesced_size + encrypted_length,
967 kMaxOutgoingPacketSize);
968 memcpy(coalesced_buffer + coalesced_size, buffer, encrypted_length);
969 coalesced_size += encrypted_length;
970 }
971 if (contains_initial) {
972 // Padded coalesced packet to full if it contains initial packet.
973 memset(coalesced_buffer + coalesced_size, '0',
974 kMaxOutgoingPacketSize - coalesced_size);
975 }
976 connection_.ProcessUdpPacket(
977 kSelfAddress, kPeerAddress,
978 QuicReceivedPacket(coalesced_buffer, coalesced_size, clock_.Now(),
979 false));
980 if (connection_.GetSendAlarm()->IsSet()) {
981 connection_.GetSendAlarm()->Fire();
982 }
983 return coalesced_size;
984 }
985
986 size_t ProcessDataPacket(uint64_t number) {
987 return ProcessDataPacketAtLevel(number, false, ENCRYPTION_FORWARD_SECURE);
988 }
989
990 size_t ProcessDataPacket(QuicPacketNumber packet_number) {
991 return ProcessDataPacketAtLevel(packet_number, false,
992 ENCRYPTION_FORWARD_SECURE);
993 }
994
995 size_t ProcessDataPacketAtLevel(QuicPacketNumber packet_number,
996 bool has_stop_waiting,
997 EncryptionLevel level) {
998 return ProcessDataPacketAtLevel(packet_number.ToUint64(), has_stop_waiting,
999 level);
1000 }
1001
1002 size_t ProcessCryptoPacketAtLevel(uint64_t number, EncryptionLevel level) {
1003 QuicPacketHeader header = ConstructPacketHeader(number, level);
1004 QuicFrames frames;
1005 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1006 frames.push_back(QuicFrame(&crypto_frame_));
1007 } else {
1008 frames.push_back(QuicFrame(frame1_));
1009 }
1010 if (level == ENCRYPTION_INITIAL) {
1011 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
1012 }
1013 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
1014 char buffer[kMaxOutgoingPacketSize];
1015 peer_creator_.set_encryption_level(level);
1016 size_t encrypted_length =
1017 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1018 buffer, kMaxOutgoingPacketSize);
1019 connection_.ProcessUdpPacket(
1020 kSelfAddress, kPeerAddress,
1021 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1022 if (connection_.GetSendAlarm()->IsSet()) {
1023 connection_.GetSendAlarm()->Fire();
1024 }
1025 return encrypted_length;
1026 }
1027
1028 size_t ProcessDataPacketAtLevel(uint64_t number, bool has_stop_waiting,
1029 EncryptionLevel level) {
1030 std::unique_ptr<QuicPacket> packet(
1031 ConstructDataPacket(number, has_stop_waiting, level));
1032 char buffer[kMaxOutgoingPacketSize];
1033 peer_creator_.set_encryption_level(level);
1034 size_t encrypted_length =
1035 peer_framer_.EncryptPayload(level, QuicPacketNumber(number), *packet,
1036 buffer, kMaxOutgoingPacketSize);
1037 connection_.ProcessUdpPacket(
1038 kSelfAddress, kPeerAddress,
1039 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
1040 if (connection_.GetSendAlarm()->IsSet()) {
1041 connection_.GetSendAlarm()->Fire();
1042 }
1043 return encrypted_length;
1044 }
1045
1046 void ProcessClosePacket(uint64_t number) {
1047 std::unique_ptr<QuicPacket> packet(ConstructClosePacket(number));
1048 char buffer[kMaxOutgoingPacketSize];
1049 size_t encrypted_length = peer_framer_.EncryptPayload(
1050 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(number), *packet, buffer,
1051 kMaxOutgoingPacketSize);
1052 connection_.ProcessUdpPacket(
1053 kSelfAddress, kPeerAddress,
1054 QuicReceivedPacket(buffer, encrypted_length, QuicTime::Zero(), false));
1055 }
1056
1057 QuicByteCount SendStreamDataToPeer(QuicStreamId id, absl::string_view data,
1058 QuicStreamOffset offset,
1059 StreamSendingState state,
1060 QuicPacketNumber* last_packet) {
QUICHE team24a23852022-10-31 18:03:52 -07001061 QuicByteCount packet_size = 0;
Bence Békybac04052022-04-07 15:44:29 -04001062 // Save the last packet's size.
1063 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1064 .Times(AnyNumber())
1065 .WillRepeatedly(SaveArg<3>(&packet_size));
1066 connection_.SendStreamDataWithString(id, data, offset, state);
1067 if (last_packet != nullptr) {
1068 *last_packet = creator_->packet_number();
1069 }
1070 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1071 .Times(AnyNumber());
1072 return packet_size;
1073 }
1074
1075 void SendAckPacketToPeer() {
1076 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1077 {
1078 QuicConnection::ScopedPacketFlusher flusher(&connection_);
1079 connection_.SendAck();
1080 }
1081 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1082 .Times(AnyNumber());
1083 }
1084
1085 void SendRstStream(QuicStreamId id, QuicRstStreamErrorCode error,
1086 QuicStreamOffset bytes_written) {
1087 notifier_.WriteOrBufferRstStream(id, error, bytes_written);
1088 connection_.OnStreamReset(id, error);
1089 }
1090
1091 void SendPing() { notifier_.WriteOrBufferPing(); }
1092
1093 MessageStatus SendMessage(absl::string_view message) {
1094 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1095 quiche::QuicheMemSlice slice(quiche::QuicheBuffer::Copy(
1096 connection_.helper()->GetStreamSendBufferAllocator(), message));
1097 return connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false);
1098 }
1099
1100 void ProcessAckPacket(uint64_t packet_number, QuicAckFrame* frame) {
1101 if (packet_number > 1) {
1102 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, packet_number - 1);
1103 } else {
1104 QuicPacketCreatorPeer::ClearPacketNumber(&peer_creator_);
1105 }
1106 ProcessFramePacket(QuicFrame(frame));
1107 }
1108
1109 void ProcessAckPacket(QuicAckFrame* frame) {
1110 ProcessFramePacket(QuicFrame(frame));
1111 }
1112
1113 void ProcessStopWaitingPacket(QuicStopWaitingFrame frame) {
1114 ProcessFramePacket(QuicFrame(frame));
1115 }
1116
1117 size_t ProcessStopWaitingPacketAtLevel(uint64_t number,
1118 QuicStopWaitingFrame frame,
1119 EncryptionLevel /*level*/) {
1120 return ProcessFramePacketAtLevel(number, QuicFrame(frame),
1121 ENCRYPTION_ZERO_RTT);
1122 }
1123
1124 void ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
1125 ProcessFramePacket(QuicFrame(frame));
1126 }
1127
1128 bool IsMissing(uint64_t number) {
1129 return IsAwaitingPacket(connection_.ack_frame(), QuicPacketNumber(number),
1130 QuicPacketNumber());
1131 }
1132
1133 std::unique_ptr<QuicPacket> ConstructPacket(const QuicPacketHeader& header,
1134 const QuicFrames& frames) {
1135 auto packet = BuildUnsizedDataPacket(&peer_framer_, header, frames);
1136 EXPECT_NE(nullptr, packet.get());
1137 return packet;
1138 }
1139
1140 QuicPacketHeader ConstructPacketHeader(uint64_t number,
1141 EncryptionLevel level) {
1142 QuicPacketHeader header;
1143 if (peer_framer_.version().HasIetfInvariantHeader() &&
1144 level < ENCRYPTION_FORWARD_SECURE) {
1145 // Set long header type accordingly.
1146 header.version_flag = true;
1147 header.form = IETF_QUIC_LONG_HEADER_PACKET;
1148 header.long_packet_type = EncryptionlevelToLongHeaderType(level);
1149 if (QuicVersionHasLongHeaderLengths(
1150 peer_framer_.version().transport_version)) {
dschinazi35c0ff72022-08-16 12:10:06 -07001151 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04001152 if (header.long_packet_type == INITIAL) {
dschinazi35c0ff72022-08-16 12:10:06 -07001153 header.retry_token_length_length =
1154 quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
Bence Békybac04052022-04-07 15:44:29 -04001155 }
1156 }
1157 }
1158 // Set connection_id to peer's in memory representation as this data packet
1159 // is created by peer_framer.
1160 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1161 header.source_connection_id = connection_id_;
1162 header.source_connection_id_included = connection_id_included_;
1163 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1164 } else {
1165 header.destination_connection_id = connection_id_;
1166 header.destination_connection_id_included = connection_id_included_;
1167 }
1168 if (peer_framer_.version().HasIetfInvariantHeader() &&
1169 peer_framer_.perspective() == Perspective::IS_SERVER) {
1170 if (!connection_.client_connection_id().IsEmpty()) {
1171 header.destination_connection_id = connection_.client_connection_id();
1172 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
1173 } else {
1174 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1175 }
1176 if (header.version_flag) {
1177 header.source_connection_id = connection_id_;
1178 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1179 if (GetParam().version.handshake_protocol == PROTOCOL_QUIC_CRYPTO &&
1180 header.long_packet_type == ZERO_RTT_PROTECTED) {
1181 header.nonce = &kTestDiversificationNonce;
1182 }
1183 }
1184 }
1185 header.packet_number_length = packet_number_length_;
1186 header.packet_number = QuicPacketNumber(number);
1187 return header;
1188 }
1189
1190 std::unique_ptr<QuicPacket> ConstructDataPacket(uint64_t number,
1191 bool has_stop_waiting,
1192 EncryptionLevel level) {
1193 QuicPacketHeader header = ConstructPacketHeader(number, level);
1194 QuicFrames frames;
1195 if (VersionHasIetfQuicFrames(version().transport_version) &&
1196 (level == ENCRYPTION_INITIAL || level == ENCRYPTION_HANDSHAKE)) {
1197 frames.push_back(QuicFrame(QuicPingFrame()));
1198 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
1199 } else {
1200 frames.push_back(QuicFrame(frame1_));
1201 if (has_stop_waiting) {
1202 frames.push_back(QuicFrame(stop_waiting_));
1203 }
1204 }
1205 return ConstructPacket(header, frames);
1206 }
1207
1208 std::unique_ptr<SerializedPacket> ConstructProbingPacket() {
1209 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1210 if (VersionHasIetfQuicFrames(version().transport_version)) {
1211 QuicPathFrameBuffer payload = {
1212 {0xde, 0xad, 0xbe, 0xef, 0xba, 0xdc, 0x0f, 0xfe}};
1213 return QuicPacketCreatorPeer::
1214 SerializePathChallengeConnectivityProbingPacket(&peer_creator_,
1215 payload);
1216 }
1217 return QuicPacketCreatorPeer::SerializeConnectivityProbingPacket(
1218 &peer_creator_);
1219 }
1220
1221 std::unique_ptr<QuicPacket> ConstructClosePacket(uint64_t number) {
1222 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1223 QuicPacketHeader header;
1224 // Set connection_id to peer's in memory representation as this connection
1225 // close packet is created by peer_framer.
1226 if (peer_framer_.perspective() == Perspective::IS_SERVER) {
1227 header.source_connection_id = connection_id_;
1228 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1229 if (!peer_framer_.version().HasIetfInvariantHeader()) {
1230 header.source_connection_id_included = CONNECTION_ID_PRESENT;
1231 }
1232 } else {
1233 header.destination_connection_id = connection_id_;
1234 if (peer_framer_.version().HasIetfInvariantHeader()) {
1235 header.destination_connection_id_included = CONNECTION_ID_ABSENT;
1236 }
1237 }
1238
1239 header.packet_number = QuicPacketNumber(number);
1240
1241 QuicErrorCode kQuicErrorCode = QUIC_PEER_GOING_AWAY;
1242 QuicConnectionCloseFrame qccf(peer_framer_.transport_version(),
1243 kQuicErrorCode, NO_IETF_QUIC_ERROR, "",
1244 /*transport_close_frame_type=*/0);
1245 QuicFrames frames;
1246 frames.push_back(QuicFrame(&qccf));
1247 return ConstructPacket(header, frames);
1248 }
1249
1250 QuicTime::Delta DefaultRetransmissionTime() {
1251 return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
1252 }
1253
1254 QuicTime::Delta DefaultDelayedAckTime() {
1255 return QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
1256 }
1257
1258 const QuicStopWaitingFrame InitStopWaitingFrame(uint64_t least_unacked) {
1259 QuicStopWaitingFrame frame;
1260 frame.least_unacked = QuicPacketNumber(least_unacked);
1261 return frame;
1262 }
1263
1264 // Construct a ack_frame that acks all packet numbers between 1 and
1265 // |largest_acked|, except |missing|.
1266 // REQUIRES: 1 <= |missing| < |largest_acked|
1267 QuicAckFrame ConstructAckFrame(uint64_t largest_acked, uint64_t missing) {
1268 return ConstructAckFrame(QuicPacketNumber(largest_acked),
1269 QuicPacketNumber(missing));
1270 }
1271
1272 QuicAckFrame ConstructAckFrame(QuicPacketNumber largest_acked,
1273 QuicPacketNumber missing) {
1274 if (missing == QuicPacketNumber(1)) {
1275 return InitAckFrame({{missing + 1, largest_acked + 1}});
1276 }
1277 return InitAckFrame(
1278 {{QuicPacketNumber(1), missing}, {missing + 1, largest_acked + 1}});
1279 }
1280
1281 // Undo nacking a packet within the frame.
1282 void AckPacket(QuicPacketNumber arrived, QuicAckFrame* frame) {
1283 EXPECT_FALSE(frame->packets.Contains(arrived));
1284 frame->packets.Add(arrived);
1285 }
1286
1287 void TriggerConnectionClose() {
1288 // Send an erroneous packet to close the connection.
1289 EXPECT_CALL(visitor_,
1290 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
1291 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
1292
1293 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1294 // Triggers a connection by receiving ACK of unsent packet.
1295 QuicAckFrame frame = InitAckFrame(10000);
1296 ProcessAckPacket(1, &frame);
1297 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1298 nullptr);
1299 EXPECT_EQ(1, connection_close_frame_count_);
1300 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
1301 IsError(QUIC_INVALID_ACK_DATA));
1302 }
1303
1304 void BlockOnNextWrite() {
1305 writer_->BlockOnNextWrite();
1306 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
1307 }
1308
1309 void SimulateNextPacketTooLarge() { writer_->SimulateNextPacketTooLarge(); }
1310
fayangf6607db2022-04-21 18:10:41 -07001311 void ExpectNextPacketUnprocessable() {
1312 writer_->ExpectNextPacketUnprocessable();
1313 }
1314
Bence Békybac04052022-04-07 15:44:29 -04001315 void AlwaysGetPacketTooLarge() { writer_->AlwaysGetPacketTooLarge(); }
1316
1317 void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1318 writer_->SetWritePauseTimeDelta(delta);
1319 }
1320
1321 void CongestionBlockWrites() {
1322 EXPECT_CALL(*send_algorithm_, CanSend(_))
1323 .WillRepeatedly(testing::Return(false));
1324 }
1325
1326 void CongestionUnblockWrites() {
1327 EXPECT_CALL(*send_algorithm_, CanSend(_))
1328 .WillRepeatedly(testing::Return(true));
1329 }
1330
1331 void set_perspective(Perspective perspective) {
1332 connection_.set_perspective(perspective);
1333 if (perspective == Perspective::IS_SERVER) {
1334 QuicConfig config;
1335 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -07001336 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -04001337 QuicTagVector connection_options;
1338 connection_options.push_back(kRVCM);
1339 config.SetInitialReceivedConnectionOptions(connection_options);
1340 }
1341 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1342 connection_.SetFromConfig(config);
1343
1344 connection_.set_can_truncate_connection_ids(true);
1345 QuicConnectionPeer::SetNegotiatedVersion(&connection_);
1346 connection_.OnSuccessfulVersionNegotiation();
1347 }
1348 QuicFramerPeer::SetPerspective(&peer_framer_,
1349 QuicUtils::InvertPerspective(perspective));
1350 peer_framer_.SetInitialObfuscators(TestConnectionId());
1351 for (EncryptionLevel level : {ENCRYPTION_ZERO_RTT, ENCRYPTION_HANDSHAKE,
1352 ENCRYPTION_FORWARD_SECURE}) {
1353 if (peer_framer_.HasEncrypterOfEncryptionLevel(level)) {
1354 peer_creator_.SetEncrypter(
1355 level, std::make_unique<NullEncrypter>(peer_framer_.perspective()));
1356 }
1357 }
1358 }
1359
1360 void set_packets_between_probes_base(
1361 const QuicPacketCount packets_between_probes_base) {
1362 QuicConnectionPeer::ReInitializeMtuDiscoverer(
1363 &connection_, packets_between_probes_base,
1364 QuicPacketNumber(packets_between_probes_base));
1365 }
1366
1367 bool IsDefaultTestConfiguration() {
1368 TestParams p = GetParam();
1369 return p.ack_response == AckResponse::kImmediate &&
1370 p.version == AllSupportedVersions()[0] && p.no_stop_waiting;
1371 }
1372
1373 void TestConnectionCloseQuicErrorCode(QuicErrorCode expected_code) {
1374 // Not strictly needed for this test, but is commonly done.
1375 EXPECT_FALSE(QuicConnectionPeer::GetConnectionClosePacket(&connection_) ==
1376 nullptr);
1377 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
1378 writer_->connection_close_frames();
1379 ASSERT_EQ(1u, connection_close_frames.size());
1380
1381 EXPECT_THAT(connection_close_frames[0].quic_error_code,
1382 IsError(expected_code));
1383
1384 if (!VersionHasIetfQuicFrames(version().transport_version)) {
1385 EXPECT_THAT(connection_close_frames[0].wire_error_code,
1386 IsError(expected_code));
1387 EXPECT_EQ(GOOGLE_QUIC_CONNECTION_CLOSE,
1388 connection_close_frames[0].close_type);
1389 return;
1390 }
1391
1392 QuicErrorCodeToIetfMapping mapping =
1393 QuicErrorCodeToTransportErrorCode(expected_code);
1394
1395 if (mapping.is_transport_close) {
1396 // This Google QUIC Error Code maps to a transport close,
1397 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
1398 connection_close_frames[0].close_type);
1399 } else {
1400 // This maps to an application close.
1401 EXPECT_EQ(IETF_QUIC_APPLICATION_CONNECTION_CLOSE,
1402 connection_close_frames[0].close_type);
1403 }
1404 EXPECT_EQ(mapping.error_code, connection_close_frames[0].wire_error_code);
1405 }
1406
1407 void MtuDiscoveryTestInit() {
1408 set_perspective(Perspective::IS_SERVER);
1409 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1410 if (version().SupportsAntiAmplificationLimit()) {
1411 QuicConnectionPeer::SetAddressValidated(&connection_);
1412 }
1413 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1414 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1415 // QuicFramer::GetMaxPlaintextSize uses the smallest max plaintext size
1416 // across all encrypters. The initial encrypter used with IETF QUIC has a
1417 // 16-byte overhead, while the NullEncrypter used throughout this test has a
1418 // 12-byte overhead. This test tests behavior that relies on computing the
1419 // packet size correctly, so by unsetting the initial encrypter, we avoid
1420 // having a mismatch between the overheads for the encrypters used. In
1421 // non-test scenarios all encrypters used for a given connection have the
1422 // same overhead, either 12 bytes for ones using Google QUIC crypto, or 16
1423 // bytes for ones using TLS.
1424 connection_.SetEncrypter(ENCRYPTION_INITIAL, nullptr);
1425 // Prevent packets from being coalesced.
1426 EXPECT_CALL(visitor_, GetHandshakeState())
1427 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1428 EXPECT_TRUE(connection_.connected());
1429 }
1430
1431 void PathProbeTestInit(Perspective perspective,
1432 bool receive_new_server_connection_id = true) {
1433 set_perspective(perspective);
1434 connection_.CreateConnectionIdManager();
1435 EXPECT_EQ(connection_.perspective(), perspective);
1436 if (perspective == Perspective::IS_SERVER) {
1437 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1438 }
1439 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1440 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
1441 // Discard INITIAL key.
1442 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1443 connection_.NeuterUnencryptedPackets();
1444 // Prevent packets from being coalesced.
1445 EXPECT_CALL(visitor_, GetHandshakeState())
1446 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1447 if (version().SupportsAntiAmplificationLimit() &&
1448 perspective == Perspective::IS_SERVER) {
1449 QuicConnectionPeer::SetAddressValidated(&connection_);
1450 }
1451 // Clear direct_peer_address.
1452 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1453 // Clear effective_peer_address, it is the same as direct_peer_address for
1454 // this test.
1455 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1456 QuicSocketAddress());
1457 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1458
1459 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1460 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1461 } else {
1462 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1463 }
1464 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
1465 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1466 kPeerAddress, ENCRYPTION_FORWARD_SECURE);
1467 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1468 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1469 if (perspective == Perspective::IS_CLIENT &&
1470 receive_new_server_connection_id && version().HasIetfQuicFrames()) {
1471 QuicNewConnectionIdFrame frame;
1472 frame.connection_id = TestConnectionId(1234);
1473 ASSERT_NE(frame.connection_id, connection_.connection_id());
1474 frame.stateless_reset_token =
1475 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
1476 frame.retire_prior_to = 0u;
1477 frame.sequence_number = 1u;
1478 connection_.OnNewConnectionIdFrame(frame);
1479 }
1480 }
1481
1482 void TestClientRetryHandling(bool invalid_retry_tag,
1483 bool missing_original_id_in_config,
1484 bool wrong_original_id_in_config,
1485 bool missing_retry_id_in_config,
1486 bool wrong_retry_id_in_config);
1487
1488 void TestReplaceConnectionIdFromInitial();
1489
1490 QuicConnectionId connection_id_;
1491 QuicFramer framer_;
1492
1493 MockSendAlgorithm* send_algorithm_;
1494 std::unique_ptr<MockLossAlgorithm> loss_algorithm_;
1495 MockClock clock_;
1496 MockRandom random_generator_;
1497 quiche::SimpleBufferAllocator buffer_allocator_;
1498 std::unique_ptr<TestConnectionHelper> helper_;
1499 std::unique_ptr<TestAlarmFactory> alarm_factory_;
1500 QuicFramer peer_framer_;
1501 QuicPacketCreator peer_creator_;
1502 std::unique_ptr<TestPacketWriter> writer_;
1503 TestConnection connection_;
1504 QuicPacketCreator* creator_;
1505 QuicSentPacketManager* manager_;
1506 StrictMock<MockQuicConnectionVisitor> visitor_;
1507
1508 QuicStreamFrame frame1_;
1509 QuicStreamFrame frame2_;
1510 QuicCryptoFrame crypto_frame_;
1511 QuicAckFrame ack_;
1512 QuicStopWaitingFrame stop_waiting_;
1513 QuicPacketNumberLength packet_number_length_;
1514 QuicConnectionIdIncluded connection_id_included_;
1515
1516 SimpleSessionNotifier notifier_;
1517
1518 QuicConnectionCloseFrame saved_connection_close_frame_;
1519 int connection_close_frame_count_;
martinduke605dca22022-09-01 10:40:19 -07001520 MockConnectionIdGenerator connection_id_generator_;
Bence Békybac04052022-04-07 15:44:29 -04001521};
1522
1523// Run all end to end tests with all supported versions.
1524INSTANTIATE_TEST_SUITE_P(QuicConnectionTests, QuicConnectionTest,
1525 ::testing::ValuesIn(GetTestParams()),
1526 ::testing::PrintToStringParamName());
1527
1528// These two tests ensure that the QuicErrorCode mapping works correctly.
1529// Both tests expect to see a Google QUIC close if not running IETF QUIC.
1530// If running IETF QUIC, the first will generate a transport connection
1531// close, the second an application connection close.
1532// The connection close codes for the two tests are manually chosen;
1533// they are expected to always map to transport- and application-
1534// closes, respectively. If that changes, new codes should be chosen.
1535TEST_P(QuicConnectionTest, CloseErrorCodeTestTransport) {
1536 EXPECT_TRUE(connection_.connected());
1537 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1538 connection_.CloseConnection(
1539 IETF_QUIC_PROTOCOL_VIOLATION, "Should be transport close",
1540 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1541 EXPECT_FALSE(connection_.connected());
1542 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
1543}
1544
1545// Test that the IETF QUIC Error code mapping function works
1546// properly for application connection close codes.
1547TEST_P(QuicConnectionTest, CloseErrorCodeTestApplication) {
1548 EXPECT_TRUE(connection_.connected());
1549 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
1550 connection_.CloseConnection(
1551 QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE,
1552 "Should be application close",
1553 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1554 EXPECT_FALSE(connection_.connected());
1555 TestConnectionCloseQuicErrorCode(QUIC_HEADERS_STREAM_DATA_DECOMPRESS_FAILURE);
1556}
1557
1558TEST_P(QuicConnectionTest, SelfAddressChangeAtClient) {
1559 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1560
1561 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
1562 EXPECT_TRUE(connection_.connected());
1563
1564 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1565 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1566 } else {
1567 EXPECT_CALL(visitor_, OnStreamFrame(_));
1568 }
1569 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1570 ENCRYPTION_INITIAL);
1571 // Cause change in self_address.
1572 QuicIpAddress host;
1573 host.FromString("1.1.1.1");
1574 QuicSocketAddress self_address(host, 123);
1575 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1576 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1577 } else {
1578 EXPECT_CALL(visitor_, OnStreamFrame(_));
1579 }
1580 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1581 ENCRYPTION_INITIAL);
1582 EXPECT_TRUE(connection_.connected());
1583}
1584
1585TEST_P(QuicConnectionTest, SelfAddressChangeAtServer) {
1586 set_perspective(Perspective::IS_SERVER);
1587 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1588
1589 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1590 EXPECT_TRUE(connection_.connected());
1591
1592 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1593 EXPECT_CALL(visitor_, OnCryptoFrame(_));
1594 } else {
1595 EXPECT_CALL(visitor_, OnStreamFrame(_));
1596 }
1597 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1598 ENCRYPTION_INITIAL);
1599 // Cause change in self_address.
1600 QuicIpAddress host;
1601 host.FromString("1.1.1.1");
1602 QuicSocketAddress self_address(host, 123);
1603 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
1604 EXPECT_CALL(visitor_, AllowSelfAddressChange()).WillOnce(Return(false));
fayang19027942022-05-16 10:29:29 -07001605 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address, kPeerAddress,
1606 ENCRYPTION_INITIAL);
1607 EXPECT_TRUE(connection_.connected());
Bence Békybac04052022-04-07 15:44:29 -04001608 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
1609}
1610
1611TEST_P(QuicConnectionTest, AllowSelfAddressChangeToMappedIpv4AddressAtServer) {
1612 set_perspective(Perspective::IS_SERVER);
1613 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1614
1615 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1616 EXPECT_TRUE(connection_.connected());
1617
1618 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1619 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
1620 } else {
1621 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
1622 }
1623 QuicIpAddress host;
1624 host.FromString("1.1.1.1");
1625 QuicSocketAddress self_address1(host, 443);
1626 connection_.SetSelfAddress(self_address1);
1627 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1628 kPeerAddress, ENCRYPTION_INITIAL);
1629 // Cause self_address change to mapped Ipv4 address.
1630 QuicIpAddress host2;
1631 host2.FromString(
1632 absl::StrCat("::ffff:", connection_.self_address().host().ToString()));
1633 QuicSocketAddress self_address2(host2, connection_.self_address().port());
1634 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address2,
1635 kPeerAddress, ENCRYPTION_INITIAL);
1636 EXPECT_TRUE(connection_.connected());
1637 // self_address change back to Ipv4 address.
1638 ProcessFramePacketWithAddresses(MakeCryptoFrame(), self_address1,
1639 kPeerAddress, ENCRYPTION_INITIAL);
1640 EXPECT_TRUE(connection_.connected());
1641}
1642
1643TEST_P(QuicConnectionTest, ClientAddressChangeAndPacketReordered) {
1644 set_perspective(Perspective::IS_SERVER);
1645 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1646 EXPECT_CALL(visitor_, GetHandshakeState())
1647 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1648
1649 // Clear direct_peer_address.
1650 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1651 // Clear effective_peer_address, it is the same as direct_peer_address for
1652 // this test.
1653 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1654 QuicSocketAddress());
1655
1656 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1657 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1658 } else {
1659 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
1660 }
1661 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
1662 const QuicSocketAddress kNewPeerAddress =
1663 QuicSocketAddress(QuicIpAddress::Loopback6(),
1664 /*port=*/23456);
1665 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
1666 kNewPeerAddress, ENCRYPTION_INITIAL);
1667 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1668 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1669
1670 // Decrease packet number to simulate out-of-order packets.
1671 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
1672 // This is an old packet, do not migrate.
1673 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
1674 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
1675 ENCRYPTION_INITIAL);
1676 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1677 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1678}
1679
1680TEST_P(QuicConnectionTest, PeerPortChangeAtServer) {
1681 set_perspective(Perspective::IS_SERVER);
1682 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1683 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1684 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1685 // Prevent packets from being coalesced.
1686 EXPECT_CALL(visitor_, GetHandshakeState())
1687 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1688 if (version().SupportsAntiAmplificationLimit()) {
1689 QuicConnectionPeer::SetAddressValidated(&connection_);
1690 }
1691
1692 // Clear direct_peer_address.
1693 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1694 // Clear effective_peer_address, it is the same as direct_peer_address for
1695 // this test.
1696 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1697 QuicSocketAddress());
1698 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1699
1700 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
1701 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
1702 rtt_stats->set_initial_rtt(default_init_rtt * 2);
1703 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
1704
fayang339f0c82022-04-30 14:20:02 -07001705 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
1706 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001707
1708 const QuicSocketAddress kNewPeerAddress =
1709 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
1710 EXPECT_CALL(visitor_, OnStreamFrame(_))
1711 .WillOnce(Invoke(
1712 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1713 .WillOnce(Invoke(
1714 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1715 QuicFrames frames;
1716 frames.push_back(QuicFrame(frame1_));
1717 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1718 ENCRYPTION_FORWARD_SECURE);
1719 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1720 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1721
1722 // Process another packet with a different peer address on server side will
1723 // start connection migration.
1724 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
1725 QuicFrames frames2;
1726 frames2.push_back(QuicFrame(frame2_));
1727 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1728 ENCRYPTION_FORWARD_SECURE);
1729 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1730 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1731 // PORT_CHANGE shouldn't state change in sent packet manager.
1732 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07001733 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04001734 EXPECT_EQ(manager_->GetSendAlgorithm(), send_algorithm_);
1735 if (connection_.validate_client_address()) {
1736 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1737 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001738 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001739 }
1740}
1741
1742TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServer) {
1743 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07001744 if (!connection_.validate_client_address() ||
birenroyef686222022-09-12 11:34:34 -07001745 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04001746 return;
1747 }
1748 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1749 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1750 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1751 // Discard INITIAL key.
1752 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1753 connection_.NeuterUnencryptedPackets();
1754 // Prevent packets from being coalesced.
1755 EXPECT_CALL(visitor_, GetHandshakeState())
1756 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1757 QuicConnectionPeer::SetAddressValidated(&connection_);
1758 connection_.OnHandshakeComplete();
1759
1760 // Enable 5 RTO
1761 QuicConfig config;
1762 QuicTagVector connection_options;
1763 connection_options.push_back(k5RTO);
1764 config.SetInitialReceivedConnectionOptions(connection_options);
1765 QuicConfigPeer::SetNegotiated(&config, true);
1766 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
1767 connection_.connection_id());
1768 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
1769 QuicConnectionId());
1770 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
1771 connection_.SetFromConfig(config);
1772
1773 // Clear direct_peer_address.
1774 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1775 // Clear effective_peer_address, it is the same as direct_peer_address for
1776 // this test.
1777 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1778 QuicSocketAddress());
1779 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1780
1781 const QuicSocketAddress kNewPeerAddress =
1782 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1783 EXPECT_CALL(visitor_, OnStreamFrame(_))
1784 .WillOnce(Invoke(
1785 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
1786 .WillOnce(Invoke(
1787 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
1788 QuicFrames frames;
1789 frames.push_back(QuicFrame(frame1_));
1790 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1791 ENCRYPTION_FORWARD_SECURE);
1792 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1793 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1794
1795 // Send some data to make connection has packets in flight.
1796 connection_.SendStreamData3();
1797 EXPECT_EQ(1u, writer_->packets_write_attempts());
1798 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
1799 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1800
1801 // Process another packet with a different peer address on server side will
1802 // start connection migration.
1803 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1804 // IETF QUIC send algorithm should be changed to a different object, so no
1805 // OnPacketSent() called on the old send algorithm.
1806 EXPECT_CALL(*send_algorithm_,
1807 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
1808 .Times(0);
1809 // Do not propagate OnCanWrite() to session notifier.
1810 EXPECT_CALL(visitor_, OnCanWrite()).Times(AtLeast(1u));
1811
1812 QuicFrames frames2;
1813 frames2.push_back(QuicFrame(frame2_));
1814 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1815 ENCRYPTION_FORWARD_SECURE);
1816 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1817 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1818 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1819 connection_.active_effective_peer_migration_type());
1820 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
1821 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1822
1823 EXPECT_EQ(2u, writer_->packets_write_attempts());
1824 EXPECT_FALSE(writer_->path_challenge_frames().empty());
1825 QuicPathFrameBuffer payload =
1826 writer_->path_challenge_frames().front().data_buffer;
1827 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
1828 send_algorithm_);
1829 // Switch to use the mock send algorithm.
1830 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
1831 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
1832 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
1833 .WillRepeatedly(Return(kDefaultTCPMSS));
1834 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
1835 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
1836 .Times(AnyNumber())
1837 .WillRepeatedly(Return(QuicBandwidth::Zero()));
1838 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
1839 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
1840 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
1841 connection_.SetSendAlgorithm(send_algorithm_);
1842
1843 // PATH_CHALLENGE is expanded upto the max packet size which may exceeds the
1844 // anti-amplification limit.
1845 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
1846 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1847 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1848 EXPECT_EQ(1u,
1849 connection_.GetStats().num_reverse_path_validtion_upon_migration);
1850
1851 // Verify server is throttled by anti-amplification limit.
1852 connection_.SendCryptoDataWithString("foo", 0);
1853 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1854
1855 // Receiving an ACK to the packet sent after changing peer address doesn't
1856 // finish migration validation.
1857 QuicAckFrame ack_frame = InitAckFrame(2);
1858 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
1859 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
1860 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
1861 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1862 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1863 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
1864 connection_.active_effective_peer_migration_type());
1865
1866 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
1867 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -07001868 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04001869 EXPECT_CALL(visitor_, MaybeSendAddressToken());
1870 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
1871 .Times(testing::AtLeast(1u));
1872 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
1873 ENCRYPTION_FORWARD_SECURE);
1874 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
1875
1876 // Verify the anti-amplification limit is lifted by sending a packet larger
1877 // than the anti-amplification limit.
1878 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
1879 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07001880 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04001881}
1882
1883TEST_P(QuicConnectionTest, PeerIpAddressChangeAtServerWithMissingConnectionId) {
1884 set_perspective(Perspective::IS_SERVER);
1885 if (!connection_.connection_migration_use_new_cid()) {
1886 return;
1887 }
1888 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1889 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1890
1891 QuicConnectionId client_cid0 = TestConnectionId(1);
1892 QuicConnectionId client_cid1 = TestConnectionId(3);
1893 QuicConnectionId server_cid1;
1894 SetClientConnectionId(client_cid0);
1895 connection_.CreateConnectionIdManager();
1896 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1897 // Prevent packets from being coalesced.
1898 EXPECT_CALL(visitor_, GetHandshakeState())
1899 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1900 QuicConnectionPeer::SetAddressValidated(&connection_);
1901
1902 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07001903 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07001904 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
1905 .WillOnce(Return(TestConnectionId(456)));
1906 }
haoyuewangada6b822022-06-23 13:41:18 -07001907 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
1908 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
1909 server_cid1 = cid;
1910 return true;
1911 }));
Bence Békybac04052022-04-07 15:44:29 -04001912 EXPECT_CALL(visitor_, SendNewConnectionId(_));
1913 connection_.OnHandshakeComplete();
1914
1915 // Clear direct_peer_address.
1916 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1917 // Clear effective_peer_address, it is the same as direct_peer_address for
1918 // this test.
1919 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1920 QuicSocketAddress());
1921 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
1922
1923 const QuicSocketAddress kNewPeerAddress =
1924 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
1925 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
1926 QuicFrames frames;
1927 frames.push_back(QuicFrame(frame1_));
1928 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
1929 ENCRYPTION_FORWARD_SECURE);
1930 EXPECT_EQ(kPeerAddress, connection_.peer_address());
1931 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
1932
1933 // Send some data to make connection has packets in flight.
1934 connection_.SendStreamData3();
1935 EXPECT_EQ(1u, writer_->packets_write_attempts());
1936
1937 // Process another packet with a different peer address on server side will
1938 // start connection migration.
1939 peer_creator_.SetServerConnectionId(server_cid1);
1940 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
1941 // Do not propagate OnCanWrite() to session notifier.
1942 EXPECT_CALL(visitor_, OnCanWrite()).Times(AtLeast(1u));
1943
1944 QuicFrames frames2;
1945 frames2.push_back(QuicFrame(frame2_));
birenroyef686222022-09-12 11:34:34 -07001946 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07001947 frames2.push_back(QuicFrame(QuicPaddingFrame(-1)));
1948 }
Bence Békybac04052022-04-07 15:44:29 -04001949 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
1950 ENCRYPTION_FORWARD_SECURE);
1951 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
1952 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
1953
1954 // Writing path response & reverse path challenge is blocked due to missing
1955 // client connection ID, i.e., packets_write_attempts is unchanged.
1956 EXPECT_EQ(1u, writer_->packets_write_attempts());
1957
1958 // Receives new client CID from client would unblock write.
1959 QuicNewConnectionIdFrame new_cid_frame;
1960 new_cid_frame.connection_id = client_cid1;
1961 new_cid_frame.sequence_number = 1u;
1962 new_cid_frame.retire_prior_to = 0u;
1963 connection_.OnNewConnectionIdFrame(new_cid_frame);
1964 connection_.SendStreamData3();
1965
1966 EXPECT_EQ(2u, writer_->packets_write_attempts());
1967}
1968
1969TEST_P(QuicConnectionTest, EffectivePeerAddressChangeAtServer) {
birenroyef686222022-09-12 11:34:34 -07001970 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -07001971 return;
1972 }
Bence Békybac04052022-04-07 15:44:29 -04001973 set_perspective(Perspective::IS_SERVER);
1974 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
1975 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
1976 if (version().SupportsAntiAmplificationLimit()) {
1977 QuicConnectionPeer::SetAddressValidated(&connection_);
1978 }
1979 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
1980 // Discard INITIAL key.
1981 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
1982 connection_.NeuterUnencryptedPackets();
1983 EXPECT_CALL(visitor_, GetHandshakeState())
1984 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
1985
1986 // Clear direct_peer_address.
1987 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
1988 // Clear effective_peer_address, it is different from direct_peer_address for
1989 // this test.
1990 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
1991 QuicSocketAddress());
1992 const QuicSocketAddress kEffectivePeerAddress =
1993 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/43210);
1994 connection_.ReturnEffectivePeerAddressForNextPacket(kEffectivePeerAddress);
1995
1996 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
1997 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
1998 } else {
1999 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2000 }
2001 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2002 ENCRYPTION_FORWARD_SECURE);
2003 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2004 EXPECT_EQ(kEffectivePeerAddress, connection_.effective_peer_address());
2005
2006 // Process another packet with the same direct peer address and different
2007 // effective peer address on server side will start connection migration.
2008 const QuicSocketAddress kNewEffectivePeerAddress =
2009 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/54321);
2010 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2011 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2012 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2013 ENCRYPTION_FORWARD_SECURE);
2014 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2015 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2016 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
2017 if (connection_.validate_client_address()) {
2018 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2019 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -07002020 EXPECT_EQ(1u, connection_.num_linkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -04002021 }
2022
2023 // Process another packet with a different direct peer address and the same
2024 // effective peer address on server side will not start connection migration.
2025 const QuicSocketAddress kNewPeerAddress =
2026 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2027 connection_.ReturnEffectivePeerAddressForNextPacket(kNewEffectivePeerAddress);
2028 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2029
2030 if (!connection_.validate_client_address()) {
2031 // ack_frame is used to complete the migration started by the last packet,
2032 // we need to make sure a new migration does not start after the previous
2033 // one is completed.
2034 QuicAckFrame ack_frame = InitAckFrame(1);
2035 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2036 ProcessFramePacketWithAddresses(QuicFrame(&ack_frame), kSelfAddress,
2037 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2038 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2039 EXPECT_EQ(kNewEffectivePeerAddress, connection_.effective_peer_address());
2040 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2041 }
2042
2043 // Process another packet with different direct peer address and different
2044 // effective peer address on server side will start connection migration.
2045 const QuicSocketAddress kNewerEffectivePeerAddress =
2046 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/65432);
2047 const QuicSocketAddress kFinalPeerAddress =
2048 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/34567);
2049 connection_.ReturnEffectivePeerAddressForNextPacket(
2050 kNewerEffectivePeerAddress);
2051 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2052 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2053 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2054 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2055 EXPECT_EQ(kNewerEffectivePeerAddress, connection_.effective_peer_address());
2056 if (connection_.validate_client_address()) {
2057 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2058 EXPECT_EQ(send_algorithm_,
2059 connection_.sent_packet_manager().GetSendAlgorithm());
2060 EXPECT_EQ(2u, connection_.GetStats().num_validated_peer_migration);
2061 }
2062
2063 // While the previous migration is ongoing, process another packet with the
2064 // same direct peer address and different effective peer address on server
2065 // side will start a new connection migration.
2066 const QuicSocketAddress kNewestEffectivePeerAddress =
2067 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/65430);
2068 connection_.ReturnEffectivePeerAddressForNextPacket(
2069 kNewestEffectivePeerAddress);
2070 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2071 if (!connection_.validate_client_address()) {
2072 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(1);
2073 }
2074 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2075 kFinalPeerAddress, ENCRYPTION_FORWARD_SECURE);
2076 EXPECT_EQ(kFinalPeerAddress, connection_.peer_address());
2077 EXPECT_EQ(kNewestEffectivePeerAddress, connection_.effective_peer_address());
2078 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2079 connection_.active_effective_peer_migration_type());
2080 if (connection_.validate_client_address()) {
2081 EXPECT_NE(send_algorithm_,
2082 connection_.sent_packet_manager().GetSendAlgorithm());
2083 EXPECT_EQ(kFinalPeerAddress, writer_->last_write_peer_address());
2084 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2085 EXPECT_EQ(0u, connection_.GetStats()
2086 .num_peer_migration_while_validating_default_path);
2087 EXPECT_TRUE(connection_.HasPendingPathValidation());
2088 }
2089}
2090
2091// Regression test for b/200020764.
2092TEST_P(QuicConnectionTest, ConnectionMigrationWithPendingPaddingBytes) {
2093 // TODO(haoyuewang) Move these test setup code to a common member function.
2094 set_perspective(Perspective::IS_SERVER);
2095 if (!connection_.connection_migration_use_new_cid()) {
2096 return;
2097 }
2098 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2099 connection_.CreateConnectionIdManager();
2100 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2101 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2102 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2103 QuicConnectionPeer::SetAddressValidated(&connection_);
2104
2105 // Sends new server CID to client.
2106 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002107 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002108 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2109 .WillOnce(Return(TestConnectionId(456)));
2110 }
haoyuewangada6b822022-06-23 13:41:18 -07002111 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2112 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2113 new_cid = cid;
2114 return true;
2115 }));
Bence Békybac04052022-04-07 15:44:29 -04002116 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2117 // Discard INITIAL key.
2118 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2119 connection_.NeuterUnencryptedPackets();
2120 connection_.OnHandshakeComplete();
2121 EXPECT_CALL(visitor_, GetHandshakeState())
2122 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2123
2124 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2125 packet_creator->FlushCurrentPacket();
2126 packet_creator->AddPendingPadding(50u);
2127 const QuicSocketAddress kPeerAddress3 =
2128 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2129 auto ack_frame = InitAckFrame(1);
2130 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
2131 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2132 ProcessFramesPacketWithAddresses({QuicFrame(&ack_frame)}, kSelfAddress,
2133 kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
2134 if (GetQuicReloadableFlag(
2135 quic_flush_pending_frames_and_padding_bytes_on_migration)) {
2136 // Any pending frames/padding should be flushed before default_path_ is
2137 // temporarily reset.
2138 ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2139 .host()
2140 .address_family(),
2141 IpAddressFamily::IP_V6);
2142 } else {
2143 ASSERT_EQ(connection_.self_address_on_default_path_while_sending_packet()
2144 .host()
2145 .address_family(),
2146 IpAddressFamily::IP_UNSPEC);
2147 }
2148}
2149
2150// Regression test for b/196208556.
2151TEST_P(QuicConnectionTest,
2152 ReversePathValidationResponseReceivedFromUnexpectedPeerAddress) {
2153 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07002154 if (!connection_.connection_migration_use_new_cid() ||
birenroyef686222022-09-12 11:34:34 -07002155 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04002156 return;
2157 }
2158 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2159 connection_.CreateConnectionIdManager();
2160 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2161 QuicConnectionPeer::SetPeerAddress(&connection_, kPeerAddress);
2162 QuicConnectionPeer::SetEffectivePeerAddress(&connection_, kPeerAddress);
2163 QuicConnectionPeer::SetAddressValidated(&connection_);
2164 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2165 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2166
2167 // Sends new server CID to client.
2168 QuicConnectionId new_cid;
martinduke08e3ff82022-10-18 09:06:26 -07002169 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002170 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2171 .WillOnce(Return(TestConnectionId(456)));
2172 }
haoyuewangada6b822022-06-23 13:41:18 -07002173 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2174 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2175 new_cid = cid;
2176 return true;
2177 }));
Bence Békybac04052022-04-07 15:44:29 -04002178 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2179 // Discard INITIAL key.
2180 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2181 connection_.NeuterUnencryptedPackets();
2182 connection_.OnHandshakeComplete();
2183 EXPECT_CALL(visitor_, GetHandshakeState())
2184 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2185
2186 // Process a non-probing packet to migrate to path 2 and kick off reverse path
2187 // validation.
2188 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2189 const QuicSocketAddress kPeerAddress2 =
2190 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2191 peer_creator_.SetServerConnectionId(new_cid);
2192 ProcessFramesPacketWithAddresses({QuicFrame(QuicPingFrame())}, kSelfAddress,
2193 kPeerAddress2, ENCRYPTION_FORWARD_SECURE);
2194 EXPECT_FALSE(writer_->path_challenge_frames().empty());
2195 QuicPathFrameBuffer reverse_path_challenge_payload =
2196 writer_->path_challenge_frames().front().data_buffer;
2197
2198 // Receiveds a packet from path 3 with PATH_RESPONSE frame intended to
2199 // validate path 2 and a non-probing frame.
2200 {
2201 QuicConnection::ScopedPacketFlusher flusher(&connection_);
2202 const QuicSocketAddress kPeerAddress3 =
2203 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/56789);
2204 auto ack_frame = InitAckFrame(1);
2205 EXPECT_CALL(visitor_, OnConnectionMigration(IPV4_TO_IPV6_CHANGE)).Times(1);
2206 EXPECT_CALL(visitor_, MaybeSendAddressToken()).WillOnce(Invoke([this]() {
2207 connection_.SendControlFrame(
2208 QuicFrame(new QuicNewTokenFrame(1, "new_token")));
2209 return true;
2210 }));
wubd0152ca2022-04-08 08:26:44 -07002211 ProcessFramesPacketWithAddresses(
2212 {QuicFrame(QuicPathResponseFrame(0, reverse_path_challenge_payload)),
2213 QuicFrame(&ack_frame)},
2214 kSelfAddress, kPeerAddress3, ENCRYPTION_FORWARD_SECURE);
Bence Békybac04052022-04-07 15:44:29 -04002215 }
2216}
2217
2218TEST_P(QuicConnectionTest, ReversePathValidationFailureAtServer) {
2219 set_perspective(Perspective::IS_SERVER);
2220 if (!connection_.connection_migration_use_new_cid()) {
2221 return;
2222 }
2223 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2224 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2225 SetClientConnectionId(TestConnectionId(1));
2226 connection_.CreateConnectionIdManager();
2227 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2228 // Discard INITIAL key.
2229 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
2230 connection_.NeuterUnencryptedPackets();
2231 // Prevent packets from being coalesced.
2232 EXPECT_CALL(visitor_, GetHandshakeState())
2233 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2234 QuicConnectionPeer::SetAddressValidated(&connection_);
2235
2236 QuicConnectionId client_cid0 = connection_.client_connection_id();
2237 QuicConnectionId client_cid1 = TestConnectionId(2);
2238 QuicConnectionId server_cid0 = connection_.connection_id();
2239 QuicConnectionId server_cid1;
2240 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -07002241 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -07002242 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
2243 .WillOnce(Return(TestConnectionId(456)));
2244 }
haoyuewangada6b822022-06-23 13:41:18 -07002245 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
2246 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
2247 server_cid1 = cid;
2248 return true;
2249 }));
Bence Békybac04052022-04-07 15:44:29 -04002250 EXPECT_CALL(visitor_, SendNewConnectionId(_));
2251 connection_.OnHandshakeComplete();
2252 // Receives new client CID from client.
2253 QuicNewConnectionIdFrame new_cid_frame;
2254 new_cid_frame.connection_id = client_cid1;
2255 new_cid_frame.sequence_number = 1u;
2256 new_cid_frame.retire_prior_to = 0u;
2257 connection_.OnNewConnectionIdFrame(new_cid_frame);
2258 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
2259 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2260 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2261
2262 // Clear direct_peer_address.
2263 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2264 // Clear effective_peer_address, it is the same as direct_peer_address for
2265 // this test.
2266 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2267 QuicSocketAddress());
2268 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2269
2270 const QuicSocketAddress kNewPeerAddress =
2271 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
2272 EXPECT_CALL(visitor_, OnStreamFrame(_))
2273 .WillOnce(Invoke(
2274 [=]() { EXPECT_EQ(kPeerAddress, connection_.peer_address()); }))
2275 .WillOnce(Invoke(
2276 [=]() { EXPECT_EQ(kNewPeerAddress, connection_.peer_address()); }));
2277 QuicFrames frames;
2278 frames.push_back(QuicFrame(frame1_));
2279 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
2280 ENCRYPTION_FORWARD_SECURE);
2281 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2282 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2283
2284 // Process another packet with a different peer address on server side will
2285 // start connection migration.
2286 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
2287 // IETF QUIC send algorithm should be changed to a different object, so no
2288 // OnPacketSent() called on the old send algorithm.
2289 EXPECT_CALL(*send_algorithm_, OnConnectionMigration()).Times(0);
2290
2291 QuicFrames frames2;
2292 frames2.push_back(QuicFrame(frame2_));
2293 QuicPaddingFrame padding;
2294 frames2.push_back(QuicFrame(padding));
2295 peer_creator_.SetServerConnectionId(server_cid1);
2296 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
2297 ENCRYPTION_FORWARD_SECURE);
2298 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2299 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2300 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2301 connection_.active_effective_peer_migration_type());
2302 EXPECT_LT(0u, writer_->packets_write_attempts());
2303 EXPECT_TRUE(connection_.HasPendingPathValidation());
2304 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
2305 send_algorithm_);
2306 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
2307 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2308 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2309 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
2310 const auto* alternative_path =
2311 QuicConnectionPeer::GetAlternativePath(&connection_);
2312 EXPECT_EQ(default_path->client_connection_id, client_cid1);
2313 EXPECT_EQ(default_path->server_connection_id, server_cid1);
2314 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
2315 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
2316 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
2317 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
2318
2319 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes; ++i) {
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 }
2326 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
2327 connection_.active_effective_peer_migration_type());
2328
2329 // Make sure anti-amplification limit is not reached.
2330 ProcessFramesPacketWithAddresses(
2331 {QuicFrame(QuicPingFrame()), QuicFrame(QuicPaddingFrame())}, kSelfAddress,
2332 kNewPeerAddress, ENCRYPTION_FORWARD_SECURE);
2333 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
2334 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2335
2336 // Advance the time so that the reverse path validation times out.
2337 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
2338 static_cast<TestAlarmFactory::TestAlarm*>(
2339 QuicPathValidatorPeer::retry_timer(
2340 QuicConnectionPeer::path_validator(&connection_)))
2341 ->Fire();
2342 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
2343 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2344 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2345 EXPECT_EQ(connection_.sent_packet_manager().GetSendAlgorithm(),
2346 send_algorithm_);
2347 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2348
2349 // Verify that default_path_ is reverted and alternative_path_ is cleared.
2350 EXPECT_EQ(default_path->client_connection_id, client_cid0);
2351 EXPECT_EQ(default_path->server_connection_id, server_cid0);
2352 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
2353 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
2354 auto* retire_peer_issued_cid_alarm =
2355 connection_.GetRetirePeerIssuedConnectionIdAlarm();
2356 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
2357 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
2358 retire_peer_issued_cid_alarm->Fire();
2359 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
2360 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
2361}
2362
2363TEST_P(QuicConnectionTest, ReceivePathProbeWithNoAddressChangeAtServer) {
2364 PathProbeTestInit(Perspective::IS_SERVER);
2365
2366 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2367 EXPECT_CALL(visitor_, OnPacketReceived(_, _, false)).Times(0);
2368
2369 // Process a padded PING packet with no peer address change on server side
2370 // will be ignored. But a PATH CHALLENGE packet with no peer address change
2371 // will be considered as path probing.
2372 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2373
2374 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2375 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2376 probing_packet->encrypted_length),
2377 clock_.Now()));
2378
2379 uint64_t num_probing_received =
2380 connection_.GetStats().num_connectivity_probing_received;
2381 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2382
2383 EXPECT_EQ(
2384 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2385 connection_.GetStats().num_connectivity_probing_received);
2386 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2387 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2388}
2389
2390// Regression test for b/150161358.
2391TEST_P(QuicConnectionTest, BufferedMtuPacketTooBig) {
2392 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
2393 writer_->SetWriteBlocked();
2394
2395 // Send a MTU packet while blocked. It should be buffered.
2396 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
2397 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2398 EXPECT_TRUE(writer_->IsWriteBlocked());
2399
2400 writer_->AlwaysGetPacketTooLarge();
2401 writer_->SetWritable();
2402 connection_.OnCanWrite();
2403}
2404
2405TEST_P(QuicConnectionTest, WriteOutOfOrderQueuedPackets) {
2406 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
2407 if (!IsDefaultTestConfiguration()) {
2408 return;
2409 }
2410
2411 set_perspective(Perspective::IS_CLIENT);
2412
2413 BlockOnNextWrite();
2414
2415 QuicStreamId stream_id = 2;
2416 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
2417
2418 EXPECT_EQ(1u, connection_.NumQueuedPackets());
2419
2420 writer_->SetWritable();
2421 connection_.SendConnectivityProbingPacket(writer_.get(),
2422 connection_.peer_address());
2423 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
2424 connection_.OnCanWrite();
2425}
2426
2427TEST_P(QuicConnectionTest, DiscardQueuedPacketsAfterConnectionClose) {
2428 // Regression test for b/74073386.
2429 {
2430 InSequence seq;
2431 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2432 .Times(AtLeast(1));
2433 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(AtLeast(1));
2434 }
2435
2436 set_perspective(Perspective::IS_CLIENT);
2437
2438 writer_->SimulateNextPacketTooLarge();
2439
2440 // This packet write should fail, which should cause the connection to close
2441 // after sending a connection close packet, then the failed packet should be
2442 // queued.
2443 connection_.SendStreamDataWithString(/*id=*/2, "foo", 0, NO_FIN);
2444
2445 EXPECT_FALSE(connection_.connected());
2446 // No need to buffer packets.
2447 EXPECT_EQ(0u, connection_.NumQueuedPackets());
2448
2449 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2450 connection_.OnCanWrite();
2451 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
2452}
2453
2454class TestQuicPathValidationContext : public QuicPathValidationContext {
2455 public:
2456 TestQuicPathValidationContext(const QuicSocketAddress& self_address,
2457 const QuicSocketAddress& peer_address,
2458
2459 QuicPacketWriter* writer)
2460 : QuicPathValidationContext(self_address, peer_address),
2461 writer_(writer) {}
2462
2463 QuicPacketWriter* WriterToUse() override { return writer_; }
2464
2465 private:
2466 QuicPacketWriter* writer_;
2467};
2468
2469class TestValidationResultDelegate : public QuicPathValidator::ResultDelegate {
2470 public:
2471 TestValidationResultDelegate(QuicConnection* connection,
2472 const QuicSocketAddress& expected_self_address,
2473 const QuicSocketAddress& expected_peer_address,
2474 bool* success)
2475 : QuicPathValidator::ResultDelegate(),
2476 connection_(connection),
2477 expected_self_address_(expected_self_address),
2478 expected_peer_address_(expected_peer_address),
2479 success_(success) {}
2480 void OnPathValidationSuccess(
wub130bde92022-08-01 14:33:14 -07002481 std::unique_ptr<QuicPathValidationContext> context,
2482 QuicTime /*start_time*/) override {
Bence Békybac04052022-04-07 15:44:29 -04002483 EXPECT_EQ(expected_self_address_, context->self_address());
2484 EXPECT_EQ(expected_peer_address_, context->peer_address());
2485 *success_ = true;
2486 }
2487
2488 void OnPathValidationFailure(
2489 std::unique_ptr<QuicPathValidationContext> context) override {
2490 EXPECT_EQ(expected_self_address_, context->self_address());
2491 EXPECT_EQ(expected_peer_address_, context->peer_address());
2492 if (connection_->perspective() == Perspective::IS_CLIENT) {
renjietang864fbda2022-09-08 10:50:07 -07002493 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/false);
Bence Békybac04052022-04-07 15:44:29 -04002494 }
2495 *success_ = false;
2496 }
2497
2498 private:
2499 QuicConnection* connection_;
2500 QuicSocketAddress expected_self_address_;
2501 QuicSocketAddress expected_peer_address_;
2502 bool* success_;
2503};
2504
2505// Receive a path probe request at the server side, i.e.,
2506// in non-IETF version: receive a padded PING packet with a peer addess change;
2507// in IETF version: receive a packet contains PATH CHALLENGE with peer address
2508// change.
2509TEST_P(QuicConnectionTest, ReceivePathProbingAtServer) {
2510 PathProbeTestInit(Perspective::IS_SERVER);
2511
2512 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2513 QuicPathFrameBuffer payload;
2514 if (!GetParam().version.HasIetfQuicFrames()) {
2515 EXPECT_CALL(visitor_,
2516 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2517 .Times(1);
2518 } else {
2519 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2520 if (connection_.validate_client_address()) {
2521 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2522 .Times(AtLeast(1u))
2523 .WillOnce(Invoke([&]() {
2524 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2525 EXPECT_EQ(1u, writer_->path_response_frames().size());
2526 payload = writer_->path_challenge_frames().front().data_buffer;
2527 }));
2528 }
2529 }
2530 // Process a probing packet from a new peer address on server side
2531 // is effectively receiving a connectivity probing.
2532 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
2533 /*port=*/23456);
2534
2535 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2536 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2537 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2538 probing_packet->encrypted_length),
2539 clock_.Now()));
2540 uint64_t num_probing_received =
2541 connection_.GetStats().num_connectivity_probing_received;
2542 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2543
2544 EXPECT_EQ(num_probing_received + 1,
2545 connection_.GetStats().num_connectivity_probing_received);
2546 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2547 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
danzhaf2e52a2022-04-20 07:37:03 -07002548 if (GetParam().version.HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -04002549 QuicByteCount bytes_sent =
2550 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_);
2551 EXPECT_LT(0u, bytes_sent);
2552 EXPECT_EQ(received->length(),
2553 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2554
2555 // Receiving one more probing packet should update the bytes count.
2556 probing_packet = ConstructProbingPacket();
2557 received.reset(ConstructReceivedPacket(
2558 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2559 probing_packet->encrypted_length),
2560 clock_.Now()));
2561 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2562
2563 EXPECT_EQ(num_probing_received + 2,
2564 connection_.GetStats().num_connectivity_probing_received);
2565 EXPECT_EQ(2 * bytes_sent,
2566 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2567 EXPECT_EQ(2 * received->length(),
2568 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2569
2570 bool success = false;
2571 if (!connection_.validate_client_address()) {
2572 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2573 .Times(AtLeast(1u))
2574 .WillOnce(Invoke([&]() {
2575 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
2576 payload = writer_->path_challenge_frames().front().data_buffer;
2577 }));
2578
2579 connection_.ValidatePath(
2580 std::make_unique<TestQuicPathValidationContext>(
2581 connection_.self_address(), kNewPeerAddress, writer_.get()),
2582 std::make_unique<TestValidationResultDelegate>(
2583 &connection_, connection_.self_address(), kNewPeerAddress,
2584 &success));
2585 }
2586 EXPECT_EQ((connection_.validate_client_address() ? 2 : 3) * bytes_sent,
2587 QuicConnectionPeer::BytesSentOnAlternativePath(&connection_));
2588 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -07002589 frames.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -04002590 ProcessFramesPacketWithAddresses(frames, connection_.self_address(),
2591 kNewPeerAddress,
2592 ENCRYPTION_FORWARD_SECURE);
2593 EXPECT_LT(2 * received->length(),
2594 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
2595 if (connection_.validate_client_address()) {
2596 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
2597 }
2598 // Receiving another probing packet from a newer address with a different
2599 // port shouldn't trigger another reverse path validation.
2600 QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
2601 /*port=*/34567);
2602 probing_packet = ConstructProbingPacket();
2603 received.reset(ConstructReceivedPacket(
2604 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2605 probing_packet->encrypted_length),
2606 clock_.Now()));
2607 ProcessReceivedPacket(kSelfAddress, kNewerPeerAddress, *received);
2608 EXPECT_FALSE(connection_.HasPendingPathValidation());
2609 EXPECT_EQ(connection_.validate_client_address(),
2610 QuicConnectionPeer::IsAlternativePathValidated(&connection_));
2611 }
2612
2613 // Process another packet with the old peer address on server side will not
2614 // start peer migration.
2615 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2616 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2617 ENCRYPTION_INITIAL);
2618 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2619 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2620}
2621
2622// Receive a padded PING packet with a port change on server side.
2623TEST_P(QuicConnectionTest, ReceivePaddedPingWithPortChangeAtServer) {
2624 set_perspective(Perspective::IS_SERVER);
2625 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
2626 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
2627 if (version().SupportsAntiAmplificationLimit()) {
2628 QuicConnectionPeer::SetAddressValidated(&connection_);
2629 }
2630
2631 // Clear direct_peer_address.
2632 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2633 // Clear effective_peer_address, it is the same as direct_peer_address for
2634 // this test.
2635 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2636 QuicSocketAddress());
2637 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2638
2639 if (GetParam().version.UsesCryptoFrames()) {
2640 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2641 } else {
2642 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2643 }
2644 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2645 ENCRYPTION_INITIAL);
2646 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2647 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2648
2649 if (GetParam().version.HasIetfQuicFrames()) {
2650 // In IETF version, a padded PING packet with port change is not taken as
2651 // connectivity probe.
2652 EXPECT_CALL(visitor_, GetHandshakeState())
2653 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
2654 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2655 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2656 } else {
2657 // In non-IETF version, process a padded PING packet from a new peer
2658 // address on server side is effectively receiving a connectivity probing.
2659 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2660 EXPECT_CALL(visitor_,
2661 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2662 .Times(1);
2663 }
2664 const QuicSocketAddress kNewPeerAddress =
2665 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2666
2667 QuicFrames frames;
2668 // Write a PING frame, which has no data payload.
2669 QuicPingFrame ping_frame;
2670 frames.push_back(QuicFrame(ping_frame));
2671
2672 // Add padding to the rest of the packet.
2673 QuicPaddingFrame padding_frame;
2674 frames.push_back(QuicFrame(padding_frame));
2675
2676 uint64_t num_probing_received =
2677 connection_.GetStats().num_connectivity_probing_received;
2678
2679 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
2680 ENCRYPTION_INITIAL);
2681
2682 if (GetParam().version.HasIetfQuicFrames()) {
2683 // Padded PING with port changen is not considered as connectivity probe but
2684 // a PORT CHANGE.
2685 EXPECT_EQ(num_probing_received,
2686 connection_.GetStats().num_connectivity_probing_received);
2687 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2688 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2689 } else {
2690 EXPECT_EQ(num_probing_received + 1,
2691 connection_.GetStats().num_connectivity_probing_received);
2692 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2693 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2694 }
2695
2696 if (GetParam().version.HasIetfQuicFrames()) {
2697 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2698 }
2699 // Process another packet with the old peer address on server side. gQUIC
2700 // shouldn't regard this as a peer migration.
2701 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2702 ENCRYPTION_INITIAL);
2703 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2704 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2705}
2706
2707TEST_P(QuicConnectionTest, ReceiveReorderedPathProbingAtServer) {
2708 PathProbeTestInit(Perspective::IS_SERVER);
2709
2710 // Decrease packet number to simulate out-of-order packets.
2711 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 4);
2712
2713 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2714 if (!GetParam().version.HasIetfQuicFrames()) {
2715 EXPECT_CALL(visitor_,
2716 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2717 .Times(1);
2718 } else {
2719 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2720 }
2721
2722 // Process a padded PING packet from a new peer address on server side
2723 // is effectively receiving a connectivity probing, even if a newer packet has
2724 // been received before this one.
2725 const QuicSocketAddress kNewPeerAddress =
2726 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2727
2728 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2729 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2730 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2731 probing_packet->encrypted_length),
2732 clock_.Now()));
2733
2734 uint64_t num_probing_received =
2735 connection_.GetStats().num_connectivity_probing_received;
2736 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2737
2738 EXPECT_EQ(num_probing_received + 1,
2739 connection_.GetStats().num_connectivity_probing_received);
2740 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2741 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2742}
2743
2744TEST_P(QuicConnectionTest, MigrateAfterProbingAtServer) {
2745 PathProbeTestInit(Perspective::IS_SERVER);
2746
2747 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2748 if (!GetParam().version.HasIetfQuicFrames()) {
2749 EXPECT_CALL(visitor_,
2750 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2751 .Times(1);
2752 } else {
2753 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2754 }
2755
2756 // Process a padded PING packet from a new peer address on server side
2757 // is effectively receiving a connectivity probing.
2758 const QuicSocketAddress kNewPeerAddress =
2759 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2760
2761 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2762 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2763 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2764 probing_packet->encrypted_length),
2765 clock_.Now()));
2766 ProcessReceivedPacket(kSelfAddress, kNewPeerAddress, *received);
2767 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2768 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2769
2770 // Process another non-probing packet with the new peer address on server
2771 // side will start peer migration.
2772 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(1);
2773
2774 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2775 kNewPeerAddress, ENCRYPTION_INITIAL);
2776 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2777 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2778}
2779
2780TEST_P(QuicConnectionTest, ReceiveConnectivityProbingPacketAtClient) {
2781 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2782 PathProbeTestInit(Perspective::IS_CLIENT);
2783
2784 // Client takes all padded PING packet as speculative connectivity
2785 // probing packet, and reports to visitor.
2786 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2787
2788 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2789 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2790 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2791 probing_packet->encrypted_length),
2792 clock_.Now()));
2793 uint64_t num_probing_received =
2794 connection_.GetStats().num_connectivity_probing_received;
2795 ProcessReceivedPacket(kSelfAddress, kPeerAddress, *received);
2796
2797 EXPECT_EQ(
2798 num_probing_received + (GetParam().version.HasIetfQuicFrames() ? 1u : 0u),
2799 connection_.GetStats().num_connectivity_probing_received);
2800 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2801 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2802}
2803
2804TEST_P(QuicConnectionTest, ReceiveConnectivityProbingResponseAtClient) {
2805 // TODO(b/150095484): add test coverage for IETF to verify that client takes
2806 // PATH RESPONSE with peer address change as correct validation on the new
2807 // path.
2808 if (GetParam().version.HasIetfQuicFrames()) {
2809 return;
2810 }
2811 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2812 PathProbeTestInit(Perspective::IS_CLIENT);
2813
2814 // Process a padded PING packet with a different self address on client side
2815 // is effectively receiving a connectivity probing.
2816 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2817 if (!GetParam().version.HasIetfQuicFrames()) {
2818 EXPECT_CALL(visitor_,
2819 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
2820 .Times(1);
2821 } else {
2822 EXPECT_CALL(visitor_, OnPacketReceived(_, _, _)).Times(0);
2823 }
2824
2825 const QuicSocketAddress kNewSelfAddress =
2826 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2827
2828 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
2829 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
2830 QuicEncryptedPacket(probing_packet->encrypted_buffer,
2831 probing_packet->encrypted_length),
2832 clock_.Now()));
2833 uint64_t num_probing_received =
2834 connection_.GetStats().num_connectivity_probing_received;
2835 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
2836
2837 EXPECT_EQ(num_probing_received + 1,
2838 connection_.GetStats().num_connectivity_probing_received);
2839 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2840 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2841}
2842
2843TEST_P(QuicConnectionTest, PeerAddressChangeAtClient) {
2844 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2845 set_perspective(Perspective::IS_CLIENT);
2846 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2847
2848 // Clear direct_peer_address.
2849 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
2850 // Clear effective_peer_address, it is the same as direct_peer_address for
2851 // this test.
2852 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
2853 QuicSocketAddress());
2854 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
2855
2856 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2857 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
2858 } else {
2859 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
2860 }
2861 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
2862 ENCRYPTION_INITIAL);
2863 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2864 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2865
2866 // Process another packet with a different peer address on client side will
2867 // only update peer address.
2868 const QuicSocketAddress kNewPeerAddress =
2869 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
2870 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
2871 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress,
2872 kNewPeerAddress, ENCRYPTION_INITIAL);
2873 if (connection_.version().HasIetfQuicFrames()) {
2874 // IETF QUIC disallows server initiated address change.
2875 EXPECT_EQ(kPeerAddress, connection_.peer_address());
2876 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
2877 } else {
2878 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
2879 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
2880 }
2881}
2882
2883TEST_P(QuicConnectionTest, MaxPacketSize) {
2884 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2885 EXPECT_EQ(1250u, connection_.max_packet_length());
2886}
2887
2888TEST_P(QuicConnectionTest, PeerLowersMaxPacketSize) {
2889 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2890
2891 // SetFromConfig is always called after construction from InitializeSession.
2892 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2893 constexpr uint32_t kTestMaxPacketSize = 1233u;
2894 QuicConfig config;
2895 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2896 connection_.SetFromConfig(config);
2897
2898 EXPECT_EQ(kTestMaxPacketSize, connection_.max_packet_length());
2899}
2900
2901TEST_P(QuicConnectionTest, PeerCannotRaiseMaxPacketSize) {
2902 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
2903
2904 // SetFromConfig is always called after construction from InitializeSession.
2905 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
2906 constexpr uint32_t kTestMaxPacketSize = 1450u;
2907 QuicConfig config;
2908 QuicConfigPeer::SetReceivedMaxPacketSize(&config, kTestMaxPacketSize);
2909 connection_.SetFromConfig(config);
2910
2911 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
2912}
2913
2914TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) {
2915 TestConnection connection(TestConnectionId(), kSelfAddress, kPeerAddress,
2916 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07002917 Perspective::IS_SERVER, version(),
2918 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04002919 EXPECT_EQ(Perspective::IS_SERVER, connection.perspective());
2920 EXPECT_EQ(1000u, connection.max_packet_length());
2921}
2922
2923TEST_P(QuicConnectionTest, LowerServerResponseMtuTest) {
2924 set_perspective(Perspective::IS_SERVER);
2925 connection_.SetMaxPacketLength(1000);
2926 EXPECT_EQ(1000u, connection_.max_packet_length());
2927
birenroyef686222022-09-12 11:34:34 -07002928 SetQuicFlag(quic_use_lower_server_response_mtu_for_test, true);
Bence Békybac04052022-04-07 15:44:29 -04002929 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(::testing::AtMost(1));
2930 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(::testing::AtMost(1));
2931 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
2932 EXPECT_EQ(1250u, connection_.max_packet_length());
2933}
2934
2935TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) {
2936 set_perspective(Perspective::IS_SERVER);
2937 connection_.SetMaxPacketLength(1000);
2938
2939 QuicPacketHeader header;
2940 header.destination_connection_id = connection_id_;
2941 header.version_flag = true;
2942 header.packet_number = QuicPacketNumber(12);
2943
2944 if (QuicVersionHasLongHeaderLengths(
2945 peer_framer_.version().transport_version)) {
2946 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07002947 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
2948 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04002949 }
2950
2951 QuicFrames frames;
2952 QuicPaddingFrame padding;
2953 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2954 frames.push_back(QuicFrame(&crypto_frame_));
2955 } else {
2956 frames.push_back(QuicFrame(frame1_));
2957 }
2958 frames.push_back(QuicFrame(padding));
2959 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
2960 char buffer[kMaxOutgoingPacketSize];
2961 size_t encrypted_length =
2962 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
2963 *packet, buffer, kMaxOutgoingPacketSize);
2964 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
2965
2966 framer_.set_version(version());
2967 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
2968 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
2969 } else {
2970 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
2971 }
2972 connection_.ProcessUdpPacket(
2973 kSelfAddress, kPeerAddress,
2974 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
2975 false));
2976
2977 EXPECT_EQ(kMaxOutgoingPacketSize, connection_.max_packet_length());
2978}
2979
2980TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSizeWhileWriterLimited) {
2981 const QuicByteCount lower_max_packet_size = 1240;
2982 writer_->set_max_packet_size(lower_max_packet_size);
2983 set_perspective(Perspective::IS_SERVER);
2984 connection_.SetMaxPacketLength(1000);
2985 EXPECT_EQ(1000u, connection_.max_packet_length());
2986
2987 QuicPacketHeader header;
2988 header.destination_connection_id = connection_id_;
2989 header.version_flag = true;
2990 header.packet_number = QuicPacketNumber(12);
2991
2992 if (QuicVersionHasLongHeaderLengths(
2993 peer_framer_.version().transport_version)) {
2994 header.long_packet_type = INITIAL;
dschinazi35c0ff72022-08-16 12:10:06 -07002995 header.retry_token_length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_1;
2996 header.length_length = quiche::VARIABLE_LENGTH_INTEGER_LENGTH_2;
Bence Békybac04052022-04-07 15:44:29 -04002997 }
2998
2999 QuicFrames frames;
3000 QuicPaddingFrame padding;
3001 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3002 frames.push_back(QuicFrame(&crypto_frame_));
3003 } else {
3004 frames.push_back(QuicFrame(frame1_));
3005 }
3006 frames.push_back(QuicFrame(padding));
3007 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
3008 char buffer[kMaxOutgoingPacketSize];
3009 size_t encrypted_length =
3010 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(12),
3011 *packet, buffer, kMaxOutgoingPacketSize);
3012 EXPECT_EQ(kMaxOutgoingPacketSize, encrypted_length);
3013
3014 framer_.set_version(version());
3015 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3016 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3017 } else {
3018 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3019 }
3020 connection_.ProcessUdpPacket(
3021 kSelfAddress, kPeerAddress,
3022 QuicReceivedPacket(buffer, encrypted_length, clock_.ApproximateNow(),
3023 false));
3024
3025 // Here, the limit imposed by the writer is lower than the size of the packet
3026 // received, so the writer max packet size is used.
3027 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3028}
3029
3030TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriter) {
3031 const QuicByteCount lower_max_packet_size = 1240;
3032 writer_->set_max_packet_size(lower_max_packet_size);
3033
3034 static_assert(lower_max_packet_size < kDefaultMaxPacketSize,
3035 "Default maximum packet size is too low");
3036 connection_.SetMaxPacketLength(kDefaultMaxPacketSize);
3037
3038 EXPECT_EQ(lower_max_packet_size, connection_.max_packet_length());
3039}
3040
3041TEST_P(QuicConnectionTest, LimitMaxPacketSizeByWriterForNewConnection) {
3042 const QuicConnectionId connection_id = TestConnectionId(17);
3043 const QuicByteCount lower_max_packet_size = 1240;
3044 writer_->set_max_packet_size(lower_max_packet_size);
3045 TestConnection connection(connection_id, kSelfAddress, kPeerAddress,
3046 helper_.get(), alarm_factory_.get(), writer_.get(),
martinduke605dca22022-09-01 10:40:19 -07003047 Perspective::IS_CLIENT, version(),
3048 connection_id_generator_);
Bence Békybac04052022-04-07 15:44:29 -04003049 EXPECT_EQ(Perspective::IS_CLIENT, connection.perspective());
3050 EXPECT_EQ(lower_max_packet_size, connection.max_packet_length());
3051}
3052
3053TEST_P(QuicConnectionTest, PacketsInOrder) {
3054 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3055
3056 ProcessPacket(1);
3057 EXPECT_EQ(QuicPacketNumber(1u), LargestAcked(connection_.ack_frame()));
3058 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3059
3060 ProcessPacket(2);
3061 EXPECT_EQ(QuicPacketNumber(2u), LargestAcked(connection_.ack_frame()));
3062 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3063
3064 ProcessPacket(3);
3065 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3066 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
3067}
3068
3069TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
3070 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3071
3072 ProcessPacket(3);
3073 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3074 EXPECT_TRUE(IsMissing(2));
3075 EXPECT_TRUE(IsMissing(1));
3076
3077 ProcessPacket(2);
3078 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3079 EXPECT_FALSE(IsMissing(2));
3080 EXPECT_TRUE(IsMissing(1));
3081
3082 ProcessPacket(1);
3083 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3084 EXPECT_FALSE(IsMissing(2));
3085 EXPECT_FALSE(IsMissing(1));
3086}
3087
3088TEST_P(QuicConnectionTest, DuplicatePacket) {
3089 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3090
3091 ProcessPacket(3);
3092 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3093 EXPECT_TRUE(IsMissing(2));
3094 EXPECT_TRUE(IsMissing(1));
3095
3096 // Send packet 3 again, but do not set the expectation that
3097 // the visitor OnStreamFrame() will be called.
3098 ProcessDataPacket(3);
3099 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3100 EXPECT_TRUE(IsMissing(2));
3101 EXPECT_TRUE(IsMissing(1));
3102}
3103
3104TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
3105 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3106 return;
3107 }
3108 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3109
3110 ProcessPacket(3);
3111 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3112 EXPECT_TRUE(IsMissing(2));
3113 EXPECT_TRUE(IsMissing(1));
3114
3115 ProcessPacket(2);
3116 EXPECT_EQ(QuicPacketNumber(3u), LargestAcked(connection_.ack_frame()));
3117 EXPECT_TRUE(IsMissing(1));
3118
3119 ProcessPacket(5);
3120 EXPECT_EQ(QuicPacketNumber(5u), LargestAcked(connection_.ack_frame()));
3121 EXPECT_TRUE(IsMissing(1));
3122 EXPECT_TRUE(IsMissing(4));
3123
3124 // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
3125 // packet the peer will not retransmit. It indicates this by sending 'least
3126 // awaiting' is 4. The connection should then realize 1 will not be
3127 // retransmitted, and will remove it from the missing list.
3128 QuicAckFrame frame = InitAckFrame(1);
3129 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
3130 ProcessAckPacket(6, &frame);
3131
3132 // Force an ack to be sent.
3133 SendAckPacketToPeer();
3134 EXPECT_TRUE(IsMissing(4));
3135}
3136
3137TEST_P(QuicConnectionTest, RejectUnencryptedStreamData) {
3138 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
3139 if (!IsDefaultTestConfiguration() ||
3140 VersionHasIetfQuicFrames(version().transport_version)) {
3141 return;
3142 }
3143
3144 // Process an unencrypted packet from the non-crypto stream.
3145 frame1_.stream_id = 3;
3146 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3147 EXPECT_CALL(visitor_,
3148 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3149 EXPECT_QUIC_PEER_BUG(ProcessDataPacketAtLevel(1, false, ENCRYPTION_INITIAL),
3150 "");
3151 TestConnectionCloseQuicErrorCode(QUIC_UNENCRYPTED_STREAM_DATA);
3152}
3153
3154TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
3155 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3156
3157 ProcessPacket(3);
3158 // Should not cause an ack.
3159 EXPECT_EQ(0u, writer_->packets_write_attempts());
3160
3161 ProcessPacket(2);
3162 // Should ack immediately, since this fills the last hole.
3163 EXPECT_EQ(1u, writer_->packets_write_attempts());
3164
3165 ProcessPacket(1);
3166 // Should ack immediately, since this fills the last hole.
3167 EXPECT_EQ(2u, writer_->packets_write_attempts());
3168
3169 ProcessPacket(4);
3170 // Should not cause an ack.
3171 EXPECT_EQ(2u, writer_->packets_write_attempts());
3172}
3173
3174TEST_P(QuicConnectionTest, OutOfOrderAckReceiptCausesNoAck) {
3175 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3176
3177 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3178 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3179 EXPECT_EQ(2u, writer_->packets_write_attempts());
3180
3181 QuicAckFrame ack1 = InitAckFrame(1);
3182 QuicAckFrame ack2 = InitAckFrame(2);
3183 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3184 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3185 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(1);
3186 }
3187 ProcessAckPacket(2, &ack2);
3188 // Should ack immediately since we have missing packets.
3189 EXPECT_EQ(2u, writer_->packets_write_attempts());
3190
3191 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3192 EXPECT_CALL(visitor_, OnOneRttPacketAcknowledged()).Times(0);
3193 }
3194 ProcessAckPacket(1, &ack1);
3195 // Should not ack an ack filling a missing packet.
3196 EXPECT_EQ(2u, writer_->packets_write_attempts());
3197}
3198
3199TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
3200 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3201 QuicPacketNumber original, second;
3202
3203 QuicByteCount packet_size =
3204 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
3205 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
3206
3207 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
3208 // First nack triggers early retransmit.
3209 LostPacketVector lost_packets;
3210 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
3211 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3212 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
3213 Return(LossDetectionInterface::DetectionStats())));
3214 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3215 QuicPacketNumber retransmission;
3216 // Packet 1 is short header for IETF QUIC because the encryption level
3217 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
3218 EXPECT_CALL(*send_algorithm_,
3219 OnPacketSent(_, _, _,
3220 GetParam().version.HasIetfInvariantHeader()
3221 ? packet_size
3222 : packet_size - kQuicVersionSize,
3223 _))
3224 .WillOnce(SaveArg<2>(&retransmission));
3225
3226 ProcessAckPacket(&frame);
3227
3228 QuicAckFrame frame2 = ConstructAckFrame(retransmission, original);
3229 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3230 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
3231 ProcessAckPacket(&frame2);
3232
3233 // Now if the peer sends an ack which still reports the retransmitted packet
3234 // as missing, that will bundle an ack with data after two acks in a row
3235 // indicate the high water mark needs to be raised.
3236 EXPECT_CALL(*send_algorithm_,
3237 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3238 connection_.SendStreamDataWithString(3, "foo", 6, NO_FIN);
3239 // No ack sent.
3240 size_t padding_frame_count = writer_->padding_frames().size();
3241 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3242 EXPECT_EQ(1u, writer_->stream_frames().size());
3243
3244 // No more packet loss for the rest of the test.
3245 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3246 .Times(AnyNumber());
3247 ProcessAckPacket(&frame2);
3248 EXPECT_CALL(*send_algorithm_,
3249 OnPacketSent(_, _, _, _, HAS_RETRANSMITTABLE_DATA));
3250 connection_.SendStreamDataWithString(3, "foofoofoo", 9, NO_FIN);
3251 // Ack bundled.
3252 if (GetParam().no_stop_waiting) {
3253 // Do not ACK acks.
3254 EXPECT_EQ(1u, writer_->frame_count());
3255 } else {
3256 EXPECT_EQ(3u, writer_->frame_count());
3257 }
3258 EXPECT_EQ(1u, writer_->stream_frames().size());
3259 if (GetParam().no_stop_waiting) {
3260 EXPECT_TRUE(writer_->ack_frames().empty());
3261 } else {
3262 EXPECT_FALSE(writer_->ack_frames().empty());
3263 }
3264
3265 // But an ack with no missing packets will not send an ack.
3266 AckPacket(original, &frame2);
3267 ProcessAckPacket(&frame2);
3268 ProcessAckPacket(&frame2);
3269}
3270
3271TEST_P(QuicConnectionTest, AckFrequencyUpdatedFromAckFrequencyFrame) {
3272 if (!GetParam().version.HasIetfQuicFrames()) {
3273 return;
3274 }
3275 connection_.set_can_receive_ack_frequency_frame();
3276
3277 // Expect 13 acks, every 3rd packet including the first packet with
3278 // AckFrequencyFrame.
3279 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(13);
3280 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3281
3282 QuicAckFrequencyFrame ack_frequency_frame;
3283 ack_frequency_frame.packet_tolerance = 3;
3284 ProcessFramePacketAtLevel(1, QuicFrame(&ack_frequency_frame),
3285 ENCRYPTION_FORWARD_SECURE);
3286
3287 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(38);
3288 // Receives packets 2 - 39.
3289 for (size_t i = 2; i <= 39; ++i) {
3290 ProcessDataPacket(i);
3291 }
3292}
3293
3294TEST_P(QuicConnectionTest, AckDecimationReducesAcks) {
3295 const size_t kMinRttMs = 40;
3296 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
3297 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
3298 QuicTime::Delta::Zero(), QuicTime::Zero());
3299 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
3300
3301 // Start ack decimation from 10th packet.
3302 connection_.set_min_received_before_ack_decimation(10);
3303
3304 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3305 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(30);
3306
3307 // Expect 6 acks: 5 acks between packets 1-10, and ack at 20.
3308 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
3309 // Receives packets 1 - 29.
3310 for (size_t i = 1; i <= 29; ++i) {
3311 ProcessDataPacket(i);
3312 }
3313
3314 // We now receive the 30th packet, and so we send an ack.
3315 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3316 ProcessDataPacket(30);
3317}
3318
3319TEST_P(QuicConnectionTest, AckNeedsRetransmittableFrames) {
3320 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3321 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3322 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(99);
3323
3324 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3325 // Receives packets 1 - 39.
3326 for (size_t i = 1; i <= 39; ++i) {
3327 ProcessDataPacket(i);
3328 }
3329 // Receiving Packet 40 causes 20th ack to send. Session is informed and adds
3330 // WINDOW_UPDATE.
3331 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3332 .WillOnce(Invoke([this]() {
3333 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3334 }));
3335 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3336 EXPECT_EQ(0u, writer_->window_update_frames().size());
3337 ProcessDataPacket(40);
3338 EXPECT_EQ(1u, writer_->window_update_frames().size());
3339
3340 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3341 // Receives packets 41 - 59.
3342 for (size_t i = 41; i <= 59; ++i) {
3343 ProcessDataPacket(i);
3344 }
3345 // Send a packet containing stream frame.
3346 SendStreamDataToPeer(
3347 QuicUtils::GetFirstBidirectionalStreamId(
3348 connection_.version().transport_version, Perspective::IS_CLIENT),
3349 "bar", 0, NO_FIN, nullptr);
3350
3351 // Session will not be informed until receiving another 20 packets.
3352 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(19);
3353 for (size_t i = 60; i <= 98; ++i) {
3354 ProcessDataPacket(i);
3355 EXPECT_EQ(0u, writer_->window_update_frames().size());
3356 }
3357 // Session does not add a retransmittable frame.
3358 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3359 .WillOnce(Invoke([this]() {
3360 connection_.SendControlFrame(QuicFrame(QuicPingFrame(1)));
3361 }));
3362 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3363 EXPECT_EQ(0u, writer_->ping_frames().size());
3364 ProcessDataPacket(99);
3365 EXPECT_EQ(0u, writer_->window_update_frames().size());
3366 // A ping frame will be added.
3367 EXPECT_EQ(1u, writer_->ping_frames().size());
3368}
3369
3370TEST_P(QuicConnectionTest, AckNeedsRetransmittableFramesAfterPto) {
Bence Békybac04052022-04-07 15:44:29 -04003371 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
3372 QuicConfig config;
3373 QuicTagVector connection_options;
3374 connection_options.push_back(kEACK);
3375 config.SetConnectionOptionsToSend(connection_options);
3376 connection_.SetFromConfig(config);
3377
3378 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3379 connection_.OnHandshakeComplete();
3380
3381 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3382 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(10);
3383
3384 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
3385 // Receive packets 1 - 9.
3386 for (size_t i = 1; i <= 9; ++i) {
3387 ProcessDataPacket(i);
3388 }
3389
3390 // Send a ping and fire the retransmission alarm.
3391 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3392 SendPing();
3393 QuicTime retransmission_time =
3394 connection_.GetRetransmissionAlarm()->deadline();
3395 clock_.AdvanceTime(retransmission_time - clock_.Now());
3396 connection_.GetRetransmissionAlarm()->Fire();
fayang339f0c82022-04-30 14:20:02 -07003397 ASSERT_LT(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04003398
3399 // Process a packet, which requests a retransmittable frame be bundled
3400 // with the ACK.
3401 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
3402 .WillOnce(Invoke([this]() {
3403 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
3404 }));
3405 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3406 ProcessDataPacket(11);
3407 EXPECT_EQ(1u, writer_->window_update_frames().size());
3408}
3409
3410TEST_P(QuicConnectionTest, LeastUnackedLower) {
3411 if (GetParam().version.HasIetfInvariantHeader()) {
3412 return;
3413 }
3414 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3415
3416 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3417 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3418 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3419
3420 // Start out saying the least unacked is 2.
3421 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 5);
3422 ProcessStopWaitingPacket(InitStopWaitingFrame(2));
3423
3424 // Change it to 1, but lower the packet number to fake out-of-order packets.
3425 // This should be fine.
3426 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
3427 // The scheduler will not process out of order acks, but all packet processing
3428 // causes the connection to try to write.
3429 if (!GetParam().no_stop_waiting) {
3430 EXPECT_CALL(visitor_, OnCanWrite());
3431 }
3432 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3433
3434 // Now claim it's one, but set the ordering so it was sent "after" the first
3435 // one. This should cause a connection error.
3436 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 7);
3437 if (!GetParam().no_stop_waiting) {
3438 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3439 .Times(AtLeast(1));
3440 EXPECT_CALL(visitor_,
3441 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
3442 .Times(AtLeast(1));
3443 }
3444 ProcessStopWaitingPacket(InitStopWaitingFrame(1));
3445 if (!GetParam().no_stop_waiting) {
3446 TestConnectionCloseQuicErrorCode(QUIC_INVALID_STOP_WAITING_DATA);
3447 }
3448}
3449
3450TEST_P(QuicConnectionTest, TooManySentPackets) {
3451 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3452
3453 QuicPacketCount max_tracked_packets = 50;
3454 QuicConnectionPeer::SetMaxTrackedPackets(&connection_, max_tracked_packets);
3455
3456 const int num_packets = max_tracked_packets + 5;
3457
3458 for (int i = 0; i < num_packets; ++i) {
3459 SendStreamDataToPeer(1, "foo", 3 * i, NO_FIN, nullptr);
3460 }
3461
3462 EXPECT_CALL(visitor_,
3463 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3464
3465 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3466
3467 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS);
3468}
3469
3470TEST_P(QuicConnectionTest, LargestObservedLower) {
3471 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3472
3473 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
3474 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr);
3475 SendStreamDataToPeer(1, "eep", 6, NO_FIN, nullptr);
3476 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3477
3478 // Start out saying the largest observed is 2.
3479 QuicAckFrame frame1 = InitAckFrame(1);
3480 QuicAckFrame frame2 = InitAckFrame(2);
3481 ProcessAckPacket(&frame2);
3482
3483 EXPECT_CALL(visitor_, OnCanWrite());
3484 ProcessAckPacket(&frame1);
3485}
3486
3487TEST_P(QuicConnectionTest, AckUnsentData) {
3488 // Ack a packet which has not been sent.
3489 EXPECT_CALL(visitor_,
3490 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
3491 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3492 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
3493 QuicAckFrame frame = InitAckFrame(1);
3494 EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
3495 ProcessAckPacket(&frame);
3496 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
3497}
3498
3499TEST_P(QuicConnectionTest, BasicSending) {
3500 if (connection_.SupportsMultiplePacketNumberSpaces()) {
3501 return;
3502 }
3503 const QuicConnectionStats& stats = connection_.GetStats();
3504 EXPECT_FALSE(stats.first_decrypted_packet.IsInitialized());
3505 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3506 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3507 ProcessDataPacket(1);
3508 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3509 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
3510 QuicPacketNumber last_packet;
3511 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
3512 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
3513 SendAckPacketToPeer(); // Packet 2
3514
3515 if (GetParam().no_stop_waiting) {
3516 // Expect no stop waiting frame is sent.
3517 EXPECT_FALSE(least_unacked().IsInitialized());
3518 } else {
3519 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3520 }
3521
3522 SendAckPacketToPeer(); // Packet 3
3523 if (GetParam().no_stop_waiting) {
3524 // Expect no stop waiting frame is sent.
3525 EXPECT_FALSE(least_unacked().IsInitialized());
3526 } else {
3527 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3528 }
3529
3530 SendStreamDataToPeer(1, "bar", 3, NO_FIN, &last_packet); // Packet 4
3531 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
3532 SendAckPacketToPeer(); // Packet 5
3533 if (GetParam().no_stop_waiting) {
3534 // Expect no stop waiting frame is sent.
3535 EXPECT_FALSE(least_unacked().IsInitialized());
3536 } else {
3537 EXPECT_EQ(QuicPacketNumber(1u), least_unacked());
3538 }
3539
3540 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3541
3542 // Peer acks up to packet 3.
3543 QuicAckFrame frame = InitAckFrame(3);
3544 ProcessAckPacket(&frame);
3545 SendAckPacketToPeer(); // Packet 6
3546
3547 // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
3548 // ack for 4.
3549 if (GetParam().no_stop_waiting) {
3550 // Expect no stop waiting frame is sent.
3551 EXPECT_FALSE(least_unacked().IsInitialized());
3552 } else {
3553 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3554 }
3555
3556 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3557
3558 // Peer acks up to packet 4, the last packet.
3559 QuicAckFrame frame2 = InitAckFrame(6);
3560 ProcessAckPacket(&frame2); // Acks don't instigate acks.
3561
3562 // Verify that we did not send an ack.
3563 EXPECT_EQ(QuicPacketNumber(6u), writer_->header().packet_number);
3564
3565 // So the last ack has not changed.
3566 if (GetParam().no_stop_waiting) {
3567 // Expect no stop waiting frame is sent.
3568 EXPECT_FALSE(least_unacked().IsInitialized());
3569 } else {
3570 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
3571 }
3572
3573 // If we force an ack, we shouldn't change our retransmit state.
3574 SendAckPacketToPeer(); // Packet 7
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
3582 // But if we send more data it should.
3583 SendStreamDataToPeer(1, "eep", 6, NO_FIN, &last_packet); // Packet 8
3584 EXPECT_EQ(QuicPacketNumber(8u), last_packet);
3585 SendAckPacketToPeer(); // Packet 9
3586 if (GetParam().no_stop_waiting) {
3587 // Expect no stop waiting frame is sent.
3588 EXPECT_FALSE(least_unacked().IsInitialized());
3589 } else {
3590 EXPECT_EQ(QuicPacketNumber(7u), least_unacked());
3591 }
3592 EXPECT_EQ(QuicPacketNumber(1), stats.first_decrypted_packet);
3593}
3594
3595// QuicConnection should record the packet sent-time prior to sending the
3596// packet.
3597TEST_P(QuicConnectionTest, RecordSentTimeBeforePacketSent) {
3598 // We're using a MockClock for the tests, so we have complete control over the
3599 // time.
3600 // Our recorded timestamp for the last packet sent time will be passed in to
3601 // the send_algorithm. Make sure that it is set to the correct value.
3602 QuicTime actual_recorded_send_time = QuicTime::Zero();
3603 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3604 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3605
3606 // First send without any pause and check the result.
3607 QuicTime expected_recorded_send_time = clock_.Now();
3608 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
3609 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3610 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3611 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3612
3613 // Now pause during the write, and check the results.
3614 actual_recorded_send_time = QuicTime::Zero();
3615 const QuicTime::Delta write_pause_time_delta =
3616 QuicTime::Delta::FromMilliseconds(5000);
3617 SetWritePauseTimeDelta(write_pause_time_delta);
3618 expected_recorded_send_time = clock_.Now();
3619
3620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
3621 .WillOnce(SaveArg<0>(&actual_recorded_send_time));
3622 connection_.SendStreamDataWithString(2, "baz", 0, NO_FIN);
3623 EXPECT_EQ(expected_recorded_send_time, actual_recorded_send_time)
3624 << "Expected time = " << expected_recorded_send_time.ToDebuggingValue()
3625 << ". Actual time = " << actual_recorded_send_time.ToDebuggingValue();
3626}
3627
QUICHE teamac0a8082022-06-13 09:17:05 -07003628TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithRetransmissions) {
3629 // Send two stream frames in 1 packet by queueing them.
3630 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3631
3632 {
3633 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3634 connection_.SaveAndSendStreamData(
3635 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3636 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3637 connection_.SaveAndSendStreamData(
3638 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3639 "helloworld", 0, NO_FIN, LOSS_RETRANSMISSION);
3640 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3641 }
3642
3643 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3644 EXPECT_FALSE(connection_.HasQueuedData());
3645
3646 EXPECT_EQ(2u, writer_->frame_count());
3647 for (auto& frame : writer_->stream_frames()) {
3648 EXPECT_EQ(frame->data_length, 10u);
3649 }
3650
3651 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3652 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 20u);
3653}
3654
3655TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_WithMixedFrames) {
3656 // Send two stream frames in 1 packet by queueing them.
3657 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3658
3659 {
3660 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3661 // First frame is retransmission. Second is NOT_RETRANSMISSION but the
3662 // packet retains the PTO_RETRANSMISSION type.
3663 connection_.SaveAndSendStreamData(
3664 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3665 "helloworld", 0, NO_FIN, PTO_RETRANSMISSION);
3666 connection_.SaveAndSendStreamData(
3667 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3668 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3669 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3670 }
3671
3672 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3673 EXPECT_FALSE(connection_.HasQueuedData());
3674
3675 EXPECT_EQ(2u, writer_->frame_count());
3676 for (auto& frame : writer_->stream_frames()) {
3677 EXPECT_EQ(frame->data_length, 10u);
3678 }
3679
3680 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 1u);
3681 ASSERT_GE(connection_.GetStats().bytes_retransmitted, 10u);
3682}
3683
3684TEST_P(QuicConnectionTest, ConnectionStatsRetransmission_NoRetransmission) {
3685 // Send two stream frames in 1 packet by queueing them.
3686 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3687
3688 {
3689 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3690 // Both frames are NOT_RETRANSMISSION
3691 connection_.SaveAndSendStreamData(
3692 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3693 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3694 connection_.SaveAndSendStreamData(
3695 GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3696 "helloworld", 0, NO_FIN, NOT_RETRANSMISSION);
3697 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3698 }
3699
3700 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3701 EXPECT_FALSE(connection_.HasQueuedData());
3702
3703 EXPECT_EQ(2u, writer_->frame_count());
3704 ASSERT_EQ(connection_.GetStats().packets_retransmitted, 0u);
3705 ASSERT_EQ(connection_.GetStats().bytes_retransmitted, 0u);
3706}
3707
Bence Békybac04052022-04-07 15:44:29 -04003708TEST_P(QuicConnectionTest, FramePacking) {
3709 // Send two stream frames in 1 packet by queueing them.
3710 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3711 {
3712 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3713 connection_.SendStreamData3();
3714 connection_.SendStreamData5();
3715 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3716 }
3717 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3718 EXPECT_FALSE(connection_.HasQueuedData());
3719
3720 // Parse the last packet and ensure it's an ack and two stream frames from
3721 // two different streams.
3722 if (GetParam().no_stop_waiting) {
3723 EXPECT_EQ(2u, writer_->frame_count());
3724 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3725 } else {
3726 EXPECT_EQ(2u, writer_->frame_count());
3727 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3728 }
3729
3730 EXPECT_TRUE(writer_->ack_frames().empty());
3731
3732 ASSERT_EQ(2u, writer_->stream_frames().size());
3733 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3734 writer_->stream_frames()[0]->stream_id);
3735 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3736 writer_->stream_frames()[1]->stream_id);
3737}
3738
3739TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
3740 // Send two stream frames (one non-crypto, then one crypto) in 2 packets by
3741 // queueing them.
3742 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3743 {
3744 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3745 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3746 connection_.SendStreamData3();
3747 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
3748 connection_.SendCryptoStreamData();
3749 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3750 }
3751 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3752 EXPECT_FALSE(connection_.HasQueuedData());
3753
3754 // Parse the last packet and ensure it contains a crypto stream frame.
3755 EXPECT_LE(2u, writer_->frame_count());
3756 ASSERT_LE(1u, writer_->padding_frames().size());
3757 if (!QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3758 ASSERT_EQ(1u, writer_->stream_frames().size());
3759 EXPECT_EQ(QuicUtils::GetCryptoStreamId(connection_.transport_version()),
3760 writer_->stream_frames()[0]->stream_id);
3761 } else {
3762 EXPECT_LE(1u, writer_->crypto_frames().size());
3763 }
3764}
3765
3766TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
3767 // Send two stream frames (one crypto, then one non-crypto) in 2 packets by
3768 // queueing them.
3769 {
3770 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3771 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
3772 QuicConnection::ScopedPacketFlusher flusher(&connection_);
3773 connection_.SendCryptoStreamData();
3774 connection_.SendStreamData3();
3775 }
3776 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3777 EXPECT_FALSE(connection_.HasQueuedData());
3778
3779 // Parse the last packet and ensure it's the stream frame from stream 3.
3780 size_t padding_frame_count = writer_->padding_frames().size();
3781 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
3782 ASSERT_EQ(1u, writer_->stream_frames().size());
3783 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3784 writer_->stream_frames()[0]->stream_id);
3785}
3786
3787TEST_P(QuicConnectionTest, FramePackingAckResponse) {
3788 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3789 // Process a data packet to queue up a pending ack.
3790 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3791 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
3792 } else {
3793 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3794 }
3795 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
3796
3797 QuicPacketNumber last_packet;
3798 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
3799 connection_.SendCryptoDataWithString("foo", 0);
3800 } else {
3801 SendStreamDataToPeer(
3802 QuicUtils::GetCryptoStreamId(connection_.transport_version()), "foo", 0,
3803 NO_FIN, &last_packet);
3804 }
3805 // Verify ack is bundled with outging packet.
3806 EXPECT_FALSE(writer_->ack_frames().empty());
3807
3808 EXPECT_CALL(visitor_, OnCanWrite())
3809 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3810 &connection_, &TestConnection::SendStreamData3)),
3811 IgnoreResult(InvokeWithoutArgs(
3812 &connection_, &TestConnection::SendStreamData5))));
3813
3814 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
3815
3816 // Process a data packet to cause the visitor's OnCanWrite to be invoked.
3817 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
3818 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
3819 std::make_unique<TaggingEncrypter>(0x01));
3820 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
3821 std::make_unique<StrictTaggingDecrypter>(0x01));
3822 ProcessDataPacket(2);
3823
3824 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3825 EXPECT_FALSE(connection_.HasQueuedData());
3826
3827 // Parse the last packet and ensure it's an ack and two stream frames from
3828 // two different streams.
3829 if (GetParam().no_stop_waiting) {
3830 EXPECT_EQ(3u, writer_->frame_count());
3831 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
3832 } else {
3833 EXPECT_EQ(4u, writer_->frame_count());
3834 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
3835 }
3836 EXPECT_FALSE(writer_->ack_frames().empty());
3837 ASSERT_EQ(2u, writer_->stream_frames().size());
3838 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3839 writer_->stream_frames()[0]->stream_id);
3840 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3841 writer_->stream_frames()[1]->stream_id);
3842}
3843
3844TEST_P(QuicConnectionTest, FramePackingSendv) {
3845 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3846 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3847
3848 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3849 connection_.transport_version(), Perspective::IS_CLIENT);
3850 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
3851
3852 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3853 EXPECT_FALSE(connection_.HasQueuedData());
3854
3855 // Parse the last packet and ensure multiple iovector blocks have
3856 // been packed into a single stream frame from one stream.
3857 EXPECT_EQ(1u, writer_->frame_count());
3858 EXPECT_EQ(1u, writer_->stream_frames().size());
3859 EXPECT_EQ(0u, writer_->padding_frames().size());
3860 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
3861 EXPECT_EQ(stream_id, frame->stream_id);
3862 EXPECT_EQ("ABCDEF",
3863 absl::string_view(frame->data_buffer, frame->data_length));
3864}
3865
3866TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
3867 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3868 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3869
3870 BlockOnNextWrite();
3871 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3872 connection_.transport_version(), Perspective::IS_CLIENT);
3873 connection_.SaveAndSendStreamData(stream_id, "ABCDEF", 0, NO_FIN);
3874
3875 EXPECT_EQ(1u, connection_.NumQueuedPackets());
3876 EXPECT_TRUE(connection_.HasQueuedData());
3877
3878 // Unblock the writes and actually send.
3879 writer_->SetWritable();
3880 connection_.OnCanWrite();
3881 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3882
3883 // Parse the last packet and ensure it's one stream frame from one stream.
3884 EXPECT_EQ(1u, writer_->frame_count());
3885 EXPECT_EQ(1u, writer_->stream_frames().size());
3886 EXPECT_EQ(0u, writer_->padding_frames().size());
3887 QuicStreamFrame* frame = writer_->stream_frames()[0].get();
3888 EXPECT_EQ(stream_id, frame->stream_id);
3889 EXPECT_EQ("ABCDEF",
3890 absl::string_view(frame->data_buffer, frame->data_length));
3891}
3892
3893TEST_P(QuicConnectionTest, SendingZeroBytes) {
3894 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3895 // Send a zero byte write with a fin using writev.
3896 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3897 QuicStreamId stream_id = QuicUtils::GetFirstBidirectionalStreamId(
3898 connection_.transport_version(), Perspective::IS_CLIENT);
3899 connection_.SaveAndSendStreamData(stream_id, {}, 0, FIN);
3900
3901 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3902 EXPECT_FALSE(connection_.HasQueuedData());
3903
3904 // Padding frames are added by v99 to ensure a minimum packet size.
3905 size_t extra_padding_frames = 0;
3906 if (GetParam().version.HasHeaderProtection()) {
3907 extra_padding_frames = 1;
3908 }
3909
3910 // Parse the last packet and ensure it's one stream frame from one stream.
3911 EXPECT_EQ(1u + extra_padding_frames, writer_->frame_count());
3912 EXPECT_EQ(extra_padding_frames, writer_->padding_frames().size());
3913 ASSERT_EQ(1u, writer_->stream_frames().size());
3914 EXPECT_EQ(stream_id, writer_->stream_frames()[0]->stream_id);
3915 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3916}
3917
3918TEST_P(QuicConnectionTest, LargeSendWithPendingAck) {
3919 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
3920 EXPECT_CALL(visitor_, GetHandshakeState())
3921 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
3922 // Set the ack alarm by processing a ping frame.
3923 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3924
3925 // Processs a PING frame.
3926 ProcessFramePacket(QuicFrame(QuicPingFrame()));
3927 // Ensure that this has caused the ACK alarm to be set.
3928 EXPECT_TRUE(connection_.HasPendingAcks());
3929
3930 // Send data and ensure the ack is bundled.
3931 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(9);
3932 const std::string data(10000, '?');
3933 QuicConsumedData consumed = connection_.SaveAndSendStreamData(
3934 GetNthClientInitiatedStreamId(0, connection_.transport_version()), data,
3935 0, FIN);
3936 EXPECT_EQ(data.length(), consumed.bytes_consumed);
3937 EXPECT_TRUE(consumed.fin_consumed);
3938 EXPECT_EQ(0u, connection_.NumQueuedPackets());
3939 EXPECT_FALSE(connection_.HasQueuedData());
3940
3941 // Parse the last packet and ensure it's one stream frame with a fin.
3942 EXPECT_EQ(1u, writer_->frame_count());
3943 ASSERT_EQ(1u, writer_->stream_frames().size());
3944 EXPECT_EQ(GetNthClientInitiatedStreamId(0, connection_.transport_version()),
3945 writer_->stream_frames()[0]->stream_id);
3946 EXPECT_TRUE(writer_->stream_frames()[0]->fin);
3947 // Ensure the ack alarm was cancelled when the ack was sent.
3948 EXPECT_FALSE(connection_.HasPendingAcks());
3949}
3950
3951TEST_P(QuicConnectionTest, OnCanWrite) {
3952 // Visitor's OnCanWrite will send data, but will have more pending writes.
3953 EXPECT_CALL(visitor_, OnCanWrite())
3954 .WillOnce(DoAll(IgnoreResult(InvokeWithoutArgs(
3955 &connection_, &TestConnection::SendStreamData3)),
3956 IgnoreResult(InvokeWithoutArgs(
3957 &connection_, &TestConnection::SendStreamData5))));
3958 {
3959 InSequence seq;
3960 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillOnce(Return(true));
3961 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
3962 .WillRepeatedly(Return(false));
3963 }
3964
3965 EXPECT_CALL(*send_algorithm_, CanSend(_))
3966 .WillRepeatedly(testing::Return(true));
3967
3968 connection_.OnCanWrite();
3969
3970 // Parse the last packet and ensure it's the two stream frames from
3971 // two different streams.
3972 EXPECT_EQ(2u, writer_->frame_count());
3973 EXPECT_EQ(2u, writer_->stream_frames().size());
3974 EXPECT_EQ(GetNthClientInitiatedStreamId(1, connection_.transport_version()),
3975 writer_->stream_frames()[0]->stream_id);
3976 EXPECT_EQ(GetNthClientInitiatedStreamId(2, connection_.transport_version()),
3977 writer_->stream_frames()[1]->stream_id);
3978}
3979
3980TEST_P(QuicConnectionTest, RetransmitOnNack) {
3981 QuicPacketNumber last_packet;
3982 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
3983 SendStreamDataToPeer(3, "foos", 3, NO_FIN, &last_packet);
3984 SendStreamDataToPeer(3, "fooos", 7, NO_FIN, &last_packet);
3985
3986 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3987
3988 // Don't lose a packet on an ack, and nothing is retransmitted.
3989 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
3990 QuicAckFrame ack_one = InitAckFrame(1);
3991 ProcessAckPacket(&ack_one);
3992
3993 // Lose a packet and ensure it triggers retransmission.
3994 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
3995 LostPacketVector lost_packets;
3996 lost_packets.push_back(
3997 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
3998 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
3999 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4000 Return(LossDetectionInterface::DetectionStats())));
4001 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4002 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4003 EXPECT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(creator_));
4004 ProcessAckPacket(&nack_two);
4005}
4006
4007TEST_P(QuicConnectionTest, DoNotSendQueuedPacketForResetStream) {
4008 // Block the connection to queue the packet.
4009 BlockOnNextWrite();
4010
4011 QuicStreamId stream_id = 2;
4012 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4013
4014 // Now that there is a queued packet, reset the stream.
4015 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4016
4017 // Unblock the connection and verify that only the RST_STREAM is sent.
4018 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4019 writer_->SetWritable();
4020 connection_.OnCanWrite();
4021 size_t padding_frame_count = writer_->padding_frames().size();
4022 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4023 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4024}
4025
4026TEST_P(QuicConnectionTest, SendQueuedPacketForQuicRstStreamNoError) {
4027 // Block the connection to queue the packet.
4028 BlockOnNextWrite();
4029
4030 QuicStreamId stream_id = 2;
4031 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4032 connection_.SendStreamDataWithString(stream_id, "foo", 0, NO_FIN);
4033
4034 // Now that there is a queued packet, reset the stream.
4035 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4036
4037 // Unblock the connection and verify that the RST_STREAM is sent and the data
4038 // packet is sent.
4039 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4040 writer_->SetWritable();
4041 connection_.OnCanWrite();
4042 size_t padding_frame_count = writer_->padding_frames().size();
4043 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4044 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4045}
4046
4047TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnNack) {
4048 QuicStreamId stream_id = 2;
4049 QuicPacketNumber last_packet;
4050 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4051 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4052 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4053
4054 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4055 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4056
4057 // Lose a packet and ensure it does not trigger retransmission.
4058 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4059 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4060 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4061 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4062 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4063 ProcessAckPacket(&nack_two);
4064}
4065
4066TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnNack) {
4067 QuicStreamId stream_id = 2;
4068 QuicPacketNumber last_packet;
4069 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4070 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4071 SendStreamDataToPeer(stream_id, "fooos", 7, NO_FIN, &last_packet);
4072
4073 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4074 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4075
4076 // Lose a packet, ensure it triggers retransmission.
4077 QuicAckFrame nack_two = ConstructAckFrame(last_packet, last_packet - 1);
4078 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4079 LostPacketVector lost_packets;
4080 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4081 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4082 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4083 Return(LossDetectionInterface::DetectionStats())));
4084 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4085 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
4086 ProcessAckPacket(&nack_two);
4087}
4088
4089TEST_P(QuicConnectionTest, DoNotRetransmitForResetStreamOnRTO) {
4090 QuicStreamId stream_id = 2;
4091 QuicPacketNumber last_packet;
4092 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4093
4094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4095 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4096
4097 // Fire the RTO and verify that the RST_STREAM is resent, not stream data.
4098 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4099 clock_.AdvanceTime(DefaultRetransmissionTime());
4100 connection_.GetRetransmissionAlarm()->Fire();
4101 size_t padding_frame_count = writer_->padding_frames().size();
4102 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4103 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4104 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4105}
4106
4107// Ensure that if the only data in flight is non-retransmittable, the
4108// retransmission alarm is not set.
4109TEST_P(QuicConnectionTest, CancelRetransmissionAlarmAfterResetStream) {
4110 QuicStreamId stream_id = 2;
4111 QuicPacketNumber last_data_packet;
4112 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
4113
4114 // Cancel the stream.
4115 const QuicPacketNumber rst_packet = last_data_packet + 1;
4116 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, rst_packet, _, _)).Times(1);
4117 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
4118
4119 // Ack the RST_STREAM frame (since it's retransmittable), but not the data
4120 // packet, which is no longer retransmittable since the stream was cancelled.
4121 QuicAckFrame nack_stream_data =
4122 ConstructAckFrame(rst_packet, last_data_packet);
4123 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4124 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4125 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4126 ProcessAckPacket(&nack_stream_data);
4127
4128 // Ensure that the data is still in flight, but the retransmission alarm is no
4129 // longer set.
4130 EXPECT_GT(manager_->GetBytesInFlight(), 0u);
4131 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4132}
4133
fayang339f0c82022-04-30 14:20:02 -07004134TEST_P(QuicConnectionTest, RetransmitForQuicRstStreamNoErrorOnPTO) {
Bence Békybac04052022-04-07 15:44:29 -04004135 QuicStreamId stream_id = 2;
4136 QuicPacketNumber last_packet;
4137 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4138
4139 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4140 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 3);
4141
4142 // Fire the RTO and verify that the RST_STREAM is resent, the stream data
4143 // is sent.
fayang339f0c82022-04-30 14:20:02 -07004144 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
Bence Békybac04052022-04-07 15:44:29 -04004145 clock_.AdvanceTime(DefaultRetransmissionTime());
4146 connection_.GetRetransmissionAlarm()->Fire();
4147 size_t padding_frame_count = writer_->padding_frames().size();
4148 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
Bence Békybac04052022-04-07 15:44:29 -04004149}
4150
4151TEST_P(QuicConnectionTest, DoNotSendPendingRetransmissionForResetStream) {
4152 QuicStreamId stream_id = 2;
4153 QuicPacketNumber last_packet;
4154 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4155 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4156 BlockOnNextWrite();
4157 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4158
4159 // Lose a packet which will trigger a pending retransmission.
4160 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4161 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4162 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4163 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4164 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4165 ProcessAckPacket(&ack);
4166
4167 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 12);
4168
4169 // Unblock the connection and verify that the RST_STREAM is sent but not the
4170 // second data packet nor a retransmit.
4171 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4172 writer_->SetWritable();
4173 connection_.OnCanWrite();
4174 size_t padding_frame_count = writer_->padding_frames().size();
4175 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4176 ASSERT_EQ(1u, writer_->rst_stream_frames().size());
4177 EXPECT_EQ(stream_id, writer_->rst_stream_frames().front().stream_id);
4178}
4179
4180TEST_P(QuicConnectionTest, SendPendingRetransmissionForQuicRstStreamNoError) {
4181 QuicStreamId stream_id = 2;
4182 QuicPacketNumber last_packet;
4183 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_packet);
4184 SendStreamDataToPeer(stream_id, "foos", 3, NO_FIN, &last_packet);
4185 BlockOnNextWrite();
4186 connection_.SendStreamDataWithString(stream_id, "fooos", 7, NO_FIN);
4187
4188 // Lose a packet which will trigger a pending retransmission.
4189 QuicAckFrame ack = ConstructAckFrame(last_packet, last_packet - 1);
4190 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4191 LostPacketVector lost_packets;
4192 lost_packets.push_back(LostPacket(last_packet - 1, kMaxOutgoingPacketSize));
4193 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4194 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4195 Return(LossDetectionInterface::DetectionStats())));
4196 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4197 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4198 ProcessAckPacket(&ack);
4199
4200 SendRstStream(stream_id, QUIC_STREAM_NO_ERROR, 12);
4201
4202 // Unblock the connection and verify that the RST_STREAM is sent and the
4203 // second data packet or a retransmit is sent.
4204 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(2));
4205 writer_->SetWritable();
4206 connection_.OnCanWrite();
4207 // The RST_STREAM_FRAME is sent after queued packets and pending
4208 // retransmission.
4209 connection_.SendControlFrame(QuicFrame(
4210 new QuicRstStreamFrame(1, stream_id, QUIC_STREAM_NO_ERROR, 14)));
4211 size_t padding_frame_count = writer_->padding_frames().size();
4212 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4213 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
4214}
4215
4216TEST_P(QuicConnectionTest, RetransmitAckedPacket) {
4217 QuicPacketNumber last_packet;
4218 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4219 SendStreamDataToPeer(1, "foos", 3, NO_FIN, &last_packet); // Packet 2
4220 SendStreamDataToPeer(1, "fooos", 7, NO_FIN, &last_packet); // Packet 3
4221
4222 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4223
4224 // Instigate a loss with an ack.
4225 QuicAckFrame nack_two = ConstructAckFrame(3, 2);
4226 // The first nack should trigger a fast retransmission, but we'll be
4227 // write blocked, so the packet will be queued.
4228 BlockOnNextWrite();
4229
4230 LostPacketVector lost_packets;
4231 lost_packets.push_back(
4232 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
4233 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4234 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4235 Return(LossDetectionInterface::DetectionStats())));
4236 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4237 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4238 .Times(1);
4239 ProcessAckPacket(&nack_two);
4240 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4241
4242 // Now, ack the previous transmission.
4243 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
4244 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(false, _, _, _, _));
4245 QuicAckFrame ack_all = InitAckFrame(3);
4246 ProcessAckPacket(&ack_all);
4247
4248 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _))
4249 .Times(0);
4250
4251 writer_->SetWritable();
4252 connection_.OnCanWrite();
4253
4254 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4255 // We do not store retransmittable frames of this retransmission.
4256 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 4));
4257}
4258
4259TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
4260 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4261 QuicPacketNumber original, second;
4262
4263 QuicByteCount packet_size =
4264 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &original); // 1st packet.
4265 SendStreamDataToPeer(3, "bar", 3, NO_FIN, &second); // 2nd packet.
4266
4267 QuicAckFrame frame = InitAckFrame({{second, second + 1}});
4268 // The first nack should retransmit the largest observed packet.
4269 LostPacketVector lost_packets;
4270 lost_packets.push_back(LostPacket(original, kMaxOutgoingPacketSize));
4271 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4272 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4273 Return(LossDetectionInterface::DetectionStats())));
4274 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4275 // Packet 1 is short header for IETF QUIC because the encryption level
4276 // switched to ENCRYPTION_FORWARD_SECURE in SendStreamDataToPeer.
4277 EXPECT_CALL(*send_algorithm_,
4278 OnPacketSent(_, _, _,
4279 GetParam().version.HasIetfInvariantHeader()
4280 ? packet_size
4281 : packet_size - kQuicVersionSize,
4282 _));
4283 ProcessAckPacket(&frame);
4284}
4285
Bence Békybac04052022-04-07 15:44:29 -04004286TEST_P(QuicConnectionTest, WriteBlockedBufferedThenSent) {
4287 BlockOnNextWrite();
4288 writer_->set_is_write_blocked_data_buffered(true);
4289 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4290 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4291 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4292
4293 writer_->SetWritable();
4294 connection_.OnCanWrite();
4295 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4296}
4297
4298TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
4299 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4300 BlockOnNextWrite();
4301 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4302 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4303 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4304 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4305
4306 // The second packet should also be queued, in order to ensure packets are
4307 // never sent out of order.
4308 writer_->SetWritable();
4309 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4310 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4311 EXPECT_EQ(2u, connection_.NumQueuedPackets());
4312
4313 // Now both are sent in order when we unblock.
4314 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4315 connection_.OnCanWrite();
4316 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4317 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4318}
4319
4320TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
4321 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4322 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4323 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4324
4325 BlockOnNextWrite();
4326 writer_->set_is_write_blocked_data_buffered(true);
4327 // Simulate the retransmission alarm firing.
4328 clock_.AdvanceTime(DefaultRetransmissionTime());
4329 connection_.GetRetransmissionAlarm()->Fire();
4330
4331 // Ack the sent packet before the callback returns, which happens in
4332 // rare circumstances with write blocked sockets.
4333 QuicAckFrame ack = InitAckFrame(1);
4334 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4335 ProcessAckPacket(&ack);
4336
4337 writer_->SetWritable();
4338 connection_.OnCanWrite();
4339 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
fayang339f0c82022-04-30 14:20:02 -07004340 EXPECT_FALSE(QuicConnectionPeer::HasRetransmittableFrames(&connection_, 3));
Bence Békybac04052022-04-07 15:44:29 -04004341}
4342
4343TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
4344 // Block the connection.
4345 BlockOnNextWrite();
4346 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4347 EXPECT_EQ(1u, writer_->packets_write_attempts());
4348 EXPECT_TRUE(writer_->IsWriteBlocked());
4349
4350 // Set the send alarm. Fire the alarm and ensure it doesn't attempt to write.
4351 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
4352 connection_.GetSendAlarm()->Fire();
4353 EXPECT_TRUE(writer_->IsWriteBlocked());
4354 EXPECT_EQ(1u, writer_->packets_write_attempts());
4355}
4356
4357TEST_P(QuicConnectionTest, NoSendAlarmAfterProcessPacketWhenWriteBlocked) {
4358 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4359
4360 // Block the connection.
4361 BlockOnNextWrite();
4362 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
4363 EXPECT_TRUE(writer_->IsWriteBlocked());
4364 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4365 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4366
4367 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4368 // Process packet number 1. Can not call ProcessPacket or ProcessDataPacket
4369 // here, because they will fire the alarm after QuicConnection::ProcessPacket
4370 // is returned.
4371 const uint64_t received_packet_num = 1;
4372 const bool has_stop_waiting = false;
4373 const EncryptionLevel level = ENCRYPTION_FORWARD_SECURE;
4374 std::unique_ptr<QuicPacket> packet(
4375 ConstructDataPacket(received_packet_num, has_stop_waiting, level));
4376 char buffer[kMaxOutgoingPacketSize];
4377 size_t encrypted_length =
4378 peer_framer_.EncryptPayload(level, QuicPacketNumber(received_packet_num),
4379 *packet, buffer, kMaxOutgoingPacketSize);
4380 connection_.ProcessUdpPacket(
4381 kSelfAddress, kPeerAddress,
4382 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
4383
4384 EXPECT_TRUE(writer_->IsWriteBlocked());
4385 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4386}
4387
4388TEST_P(QuicConnectionTest, AddToWriteBlockedListIfWriterBlockedWhenProcessing) {
4389 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4390 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
4391
4392 // Simulate the case where a shared writer gets blocked by another connection.
4393 writer_->SetWriteBlocked();
4394
4395 // Process an ACK, make sure the connection calls visitor_->OnWriteBlocked().
4396 QuicAckFrame ack1 = InitAckFrame(1);
4397 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
4398 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4399 ProcessAckPacket(1, &ack1);
4400}
4401
4402TEST_P(QuicConnectionTest, DoNotAddToWriteBlockedListAfterDisconnect) {
4403 writer_->SetBatchMode(true);
4404 EXPECT_TRUE(connection_.connected());
4405 // Have to explicitly grab the OnConnectionClosed frame and check
4406 // its parameters because this is a silent connection close and the
4407 // frame is not also transmitted to the peer.
4408 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
4409 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
4410
4411 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
4412
4413 {
4414 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4415 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
4416 ConnectionCloseBehavior::SILENT_CLOSE);
4417
4418 EXPECT_FALSE(connection_.connected());
4419 writer_->SetWriteBlocked();
4420 }
4421 EXPECT_EQ(1, connection_close_frame_count_);
4422 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
4423 IsError(QUIC_PEER_GOING_AWAY));
4424}
4425
4426TEST_P(QuicConnectionTest, AddToWriteBlockedListIfBlockedOnFlushPackets) {
4427 writer_->SetBatchMode(true);
4428 writer_->BlockOnNextFlush();
4429
4430 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
4431 {
4432 QuicConnection::ScopedPacketFlusher flusher(&connection_);
4433 // flusher's destructor will call connection_.FlushPackets, which should add
4434 // the connection to the write blocked list.
4435 }
4436}
4437
4438TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
4439 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4440 int offset = 0;
4441 // Send packets 1 to 15.
4442 for (int i = 0; i < 15; ++i) {
4443 SendStreamDataToPeer(1, "foo", offset, NO_FIN, nullptr);
4444 offset += 3;
4445 }
4446
4447 // Ack 15, nack 1-14.
4448
4449 QuicAckFrame nack =
4450 InitAckFrame({{QuicPacketNumber(15), QuicPacketNumber(16)}});
4451
4452 // 14 packets have been NACK'd and lost.
4453 LostPacketVector lost_packets;
4454 for (int i = 1; i < 15; ++i) {
4455 lost_packets.push_back(
4456 LostPacket(QuicPacketNumber(i), kMaxOutgoingPacketSize));
4457 }
4458 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
4459 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
4460 Return(LossDetectionInterface::DetectionStats())));
4461 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4463 ProcessAckPacket(&nack);
4464}
4465
4466// Test sending multiple acks from the connection to the session.
4467TEST_P(QuicConnectionTest, MultipleAcks) {
4468 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4469 return;
4470 }
4471 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4472 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4473 ProcessDataPacket(1);
4474 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4475 QuicPacketNumber last_packet;
4476 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet); // Packet 1
4477 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4478 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 2
4479 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4480 SendAckPacketToPeer(); // Packet 3
4481 SendStreamDataToPeer(5, "foo", 0, NO_FIN, &last_packet); // Packet 4
4482 EXPECT_EQ(QuicPacketNumber(4u), last_packet);
4483 SendStreamDataToPeer(1, "foo", 3, NO_FIN, &last_packet); // Packet 5
4484 EXPECT_EQ(QuicPacketNumber(5u), last_packet);
4485 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 6
4486 EXPECT_EQ(QuicPacketNumber(6u), last_packet);
4487
4488 // Client will ack packets 1, 2, [!3], 4, 5.
4489 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4490 QuicAckFrame frame1 = ConstructAckFrame(5, 3);
4491 ProcessAckPacket(&frame1);
4492
4493 // Now the client implicitly acks 3, and explicitly acks 6.
4494 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4495 QuicAckFrame frame2 = InitAckFrame(6);
4496 ProcessAckPacket(&frame2);
4497}
4498
4499TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
4500 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4501 return;
4502 }
4503 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4504 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4505 ProcessDataPacket(1);
4506 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 2);
4507 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr); // Packet 1;
4508 // From now on, we send acks, so the send algorithm won't mark them pending.
4509 SendAckPacketToPeer(); // Packet 2
4510
4511 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4512 QuicAckFrame frame = InitAckFrame(1);
4513 ProcessAckPacket(&frame);
4514
4515 // Verify that our internal state has least-unacked as 2, because we're still
4516 // waiting for a potential ack for 2.
4517
4518 EXPECT_EQ(QuicPacketNumber(2u), stop_waiting()->least_unacked);
4519
4520 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4521 frame = InitAckFrame(2);
4522 ProcessAckPacket(&frame);
4523 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4524
4525 // When we send an ack, we make sure our least-unacked makes sense. In this
4526 // case since we're not waiting on an ack for 2 and all packets are acked, we
4527 // set it to 3.
4528 SendAckPacketToPeer(); // Packet 3
4529 // Least_unacked remains at 3 until another ack is received.
4530 EXPECT_EQ(QuicPacketNumber(3u), stop_waiting()->least_unacked);
4531 if (GetParam().no_stop_waiting) {
4532 // Expect no stop waiting frame is sent.
4533 EXPECT_FALSE(least_unacked().IsInitialized());
4534 } else {
4535 // Check that the outgoing ack had its packet number as least_unacked.
4536 EXPECT_EQ(QuicPacketNumber(3u), least_unacked());
4537 }
4538
4539 // Ack the ack, which updates the rtt and raises the least unacked.
4540 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4541 frame = InitAckFrame(3);
4542 ProcessAckPacket(&frame);
4543
4544 SendStreamDataToPeer(1, "bar", 3, NO_FIN, nullptr); // Packet 4
4545 EXPECT_EQ(QuicPacketNumber(4u), stop_waiting()->least_unacked);
4546 SendAckPacketToPeer(); // Packet 5
4547 if (GetParam().no_stop_waiting) {
4548 // Expect no stop waiting frame is sent.
4549 EXPECT_FALSE(least_unacked().IsInitialized());
4550 } else {
4551 EXPECT_EQ(QuicPacketNumber(4u), least_unacked());
4552 }
4553
4554 // Send two data packets at the end, and ensure if the last one is acked,
4555 // the least unacked is raised above the ack packets.
4556 SendStreamDataToPeer(1, "bar", 6, NO_FIN, nullptr); // Packet 6
4557 SendStreamDataToPeer(1, "bar", 9, NO_FIN, nullptr); // Packet 7
4558
4559 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4560 frame = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)},
4561 {QuicPacketNumber(7), QuicPacketNumber(8)}});
4562 ProcessAckPacket(&frame);
4563
4564 EXPECT_EQ(QuicPacketNumber(6u), stop_waiting()->least_unacked);
4565}
4566
Bence Békybac04052022-04-07 15:44:29 -04004567TEST_P(QuicConnectionTest, SendHandshakeMessages) {
4568 use_tagging_decrypter();
4569 // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
4570 // the end of the packet. We can test this to check which encrypter was used.
4571 connection_.SetEncrypter(ENCRYPTION_INITIAL,
4572 std::make_unique<TaggingEncrypter>(0x01));
4573
4574 // Attempt to send a handshake message and have the socket block.
4575 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
4576 BlockOnNextWrite();
4577 connection_.SendCryptoDataWithString("foo", 0);
4578 // The packet should be serialized, but not queued.
4579 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4580
4581 // Switch to the new encrypter.
4582 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4583 std::make_unique<TaggingEncrypter>(0x02));
4584 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4585
4586 // Now become writeable and flush the packets.
4587 writer_->SetWritable();
4588 EXPECT_CALL(visitor_, OnCanWrite());
4589 connection_.OnCanWrite();
4590 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4591
4592 // Verify that the handshake packet went out at the null encryption.
4593 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
4594}
4595
4596TEST_P(QuicConnectionTest,
4597 DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
4598 use_tagging_decrypter();
4599 connection_.SetEncrypter(ENCRYPTION_INITIAL,
4600 std::make_unique<TaggingEncrypter>(0x01));
4601 connection_.SendCryptoStreamData();
4602
4603 // Simulate the retransmission alarm firing and the socket blocking.
4604 BlockOnNextWrite();
4605 clock_.AdvanceTime(DefaultRetransmissionTime());
4606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4607 connection_.GetRetransmissionAlarm()->Fire();
4608 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4609
4610 // Go forward secure.
4611 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
4612 std::make_unique<TaggingEncrypter>(0x02));
4613 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
4614 notifier_.NeuterUnencryptedData();
4615 connection_.NeuterUnencryptedPackets();
4616 connection_.OnHandshakeComplete();
4617
4618 EXPECT_EQ(QuicTime::Zero(), connection_.GetRetransmissionAlarm()->deadline());
4619 // Unblock the socket and ensure that no packets are sent.
4620 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4621 writer_->SetWritable();
4622 connection_.OnCanWrite();
4623}
4624
4625TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
4626 use_tagging_decrypter();
4627 connection_.SetEncrypter(ENCRYPTION_INITIAL,
4628 std::make_unique<TaggingEncrypter>(0x01));
4629 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
4630
4631 connection_.SendCryptoDataWithString("foo", 0);
4632
4633 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4634 std::make_unique<TaggingEncrypter>(0x02));
4635 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4636
4637 SendStreamDataToPeer(2, "bar", 0, NO_FIN, nullptr);
4638 EXPECT_FALSE(notifier_.HasLostStreamData());
4639 connection_.MarkZeroRttPacketsForRetransmission(0);
4640 EXPECT_TRUE(notifier_.HasLostStreamData());
4641}
4642
4643TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
4644 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4645 return;
4646 }
4647 // SetFromConfig is always called after construction from InitializeSession.
4648 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4649 QuicConfig config;
4650 connection_.SetFromConfig(config);
4651 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4652 use_tagging_decrypter();
4653
4654 const uint8_t tag = 0x07;
4655 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4656 std::make_unique<TaggingEncrypter>(tag));
4657
4658 // Process an encrypted packet which can not yet be decrypted which should
4659 // result in the packet being buffered.
4660 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4661
4662 // Transition to the new encryption state and process another encrypted packet
4663 // which should result in the original packet being processed.
4664 SetDecrypter(ENCRYPTION_ZERO_RTT,
4665 std::make_unique<StrictTaggingDecrypter>(tag));
4666 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4667 std::make_unique<TaggingEncrypter>(tag));
4668 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4669 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(2);
4670 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4671
4672 // Finally, process a third packet and note that we do not reprocess the
4673 // buffered packet.
4674 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4675 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4676}
4677
Bence Békybac04052022-04-07 15:44:29 -04004678TEST_P(QuicConnectionTest, Buffer100NonDecryptablePacketsThenKeyChange) {
4679 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4680 return;
4681 }
4682 // SetFromConfig is always called after construction from InitializeSession.
4683 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4684 QuicConfig config;
4685 config.set_max_undecryptable_packets(100);
4686 connection_.SetFromConfig(config);
4687 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4688 use_tagging_decrypter();
4689
4690 const uint8_t tag = 0x07;
4691 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4692 std::make_unique<TaggingEncrypter>(tag));
4693
4694 // Process an encrypted packet which can not yet be decrypted which should
4695 // result in the packet being buffered.
4696 for (uint64_t i = 1; i <= 100; ++i) {
4697 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4698 }
4699
4700 // Transition to the new encryption state and process another encrypted packet
4701 // which should result in the original packets being processed.
4702 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4703 SetDecrypter(ENCRYPTION_ZERO_RTT,
4704 std::make_unique<StrictTaggingDecrypter>(tag));
4705 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4706 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
4707 std::make_unique<TaggingEncrypter>(tag));
4708 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
4709
4710 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(100);
4711 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
4712
4713 // Finally, process a third packet and note that we do not reprocess the
4714 // buffered packet.
4715 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
4716 ProcessDataPacketAtLevel(102, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
4717}
4718
4719TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
4720 BlockOnNextWrite();
4721 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
4722 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4723 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4724
4725 // Test that RTO is started once we write to the socket.
4726 writer_->SetWritable();
4727 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
4728 connection_.OnCanWrite();
4729 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
4730}
4731
Bence Békybac04052022-04-07 15:44:29 -04004732TEST_P(QuicConnectionTest, TestQueued) {
Bence Békybac04052022-04-07 15:44:29 -04004733 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4734 BlockOnNextWrite();
4735 connection_.SendStreamDataWithString(1, "foo", 0, NO_FIN);
4736 EXPECT_EQ(1u, connection_.NumQueuedPackets());
4737
4738 // Unblock the writes and actually send.
4739 writer_->SetWritable();
4740 connection_.OnCanWrite();
4741 EXPECT_EQ(0u, connection_.NumQueuedPackets());
4742}
4743
4744TEST_P(QuicConnectionTest, InitialTimeout) {
4745 EXPECT_TRUE(connection_.connected());
4746 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4747 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4748
4749 // SetFromConfig sets the initial timeouts before negotiation.
4750 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4751 QuicConfig config;
4752 connection_.SetFromConfig(config);
4753 // Subtract a second from the idle timeout on the client side.
4754 QuicTime default_timeout =
4755 clock_.ApproximateNow() +
4756 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4757 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
4758
4759 EXPECT_CALL(visitor_,
4760 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4761 // Simulate the timeout alarm firing.
4762 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1));
4763 connection_.GetTimeoutAlarm()->Fire();
4764
4765 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4766 EXPECT_FALSE(connection_.connected());
4767
4768 EXPECT_FALSE(connection_.HasPendingAcks());
4769 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4770 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4771 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4772 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4773 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
4774 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4775}
4776
4777TEST_P(QuicConnectionTest, IdleTimeoutAfterFirstSentPacket) {
4778 EXPECT_TRUE(connection_.connected());
4779 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4780 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4781
4782 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4783 QuicConfig config;
4784 connection_.SetFromConfig(config);
4785 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4786 QuicTime initial_ddl =
4787 clock_.ApproximateNow() +
4788 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4789 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4790 EXPECT_TRUE(connection_.connected());
4791
4792 // Advance the time and send the first packet to the peer.
4793 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4794 QuicPacketNumber last_packet;
4795 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4796 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4797 // This will be the updated deadline for the connection to idle time out.
4798 QuicTime new_ddl = clock_.ApproximateNow() +
4799 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4800
4801 // Simulate the timeout alarm firing, the connection should not be closed as
4802 // a new packet has been sent.
4803 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
4804 QuicTime::Delta delay = initial_ddl - clock_.ApproximateNow();
4805 clock_.AdvanceTime(delay);
4806 // Verify the timeout alarm deadline is updated.
4807 EXPECT_TRUE(connection_.connected());
4808 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4809 EXPECT_EQ(new_ddl, connection_.GetTimeoutAlarm()->deadline());
4810
4811 // Simulate the timeout alarm firing again, the connection now should be
4812 // closed.
4813 EXPECT_CALL(visitor_,
4814 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4815 clock_.AdvanceTime(new_ddl - clock_.ApproximateNow());
4816 connection_.GetTimeoutAlarm()->Fire();
4817 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4818 EXPECT_FALSE(connection_.connected());
4819
4820 EXPECT_FALSE(connection_.HasPendingAcks());
4821 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4822 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4823 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4824 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4825 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4826}
4827
4828TEST_P(QuicConnectionTest, IdleTimeoutAfterSendTwoPackets) {
4829 EXPECT_TRUE(connection_.connected());
4830 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4831 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4832
4833 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
4834 QuicConfig config;
4835 connection_.SetFromConfig(config);
4836 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4837 QuicTime initial_ddl =
4838 clock_.ApproximateNow() +
4839 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
4840 EXPECT_EQ(initial_ddl, connection_.GetTimeoutAlarm()->deadline());
4841 EXPECT_TRUE(connection_.connected());
4842
4843 // Immediately send the first packet, this is a rare case but test code will
4844 // hit this issue often as MockClock used for tests doesn't move with code
4845 // execution until manually adjusted.
4846 QuicPacketNumber last_packet;
4847 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4848 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
4849
4850 // Advance the time and send the second packet to the peer.
4851 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
4852 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
4853 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
4854
4855 // Simulate the timeout alarm firing, the connection will be closed.
4856 EXPECT_CALL(visitor_,
4857 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4858 clock_.AdvanceTime(initial_ddl - clock_.ApproximateNow());
4859 connection_.GetTimeoutAlarm()->Fire();
4860
4861 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4862 EXPECT_FALSE(connection_.connected());
4863
4864 EXPECT_FALSE(connection_.HasPendingAcks());
4865 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4866 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4867 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4868 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
4869 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
4870}
4871
4872TEST_P(QuicConnectionTest, HandshakeTimeout) {
4873 // Use a shorter handshake timeout than idle timeout for this test.
4874 const QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(5);
4875 connection_.SetNetworkTimeouts(timeout, timeout);
4876 EXPECT_TRUE(connection_.connected());
4877 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
4878
4879 QuicTime handshake_timeout =
4880 clock_.ApproximateNow() + timeout - QuicTime::Delta::FromSeconds(1);
4881 EXPECT_EQ(handshake_timeout, connection_.GetTimeoutAlarm()->deadline());
4882 EXPECT_TRUE(connection_.connected());
4883
4884 // Send and ack new data 3 seconds later to lengthen the idle timeout.
4885 SendStreamDataToPeer(
4886 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4887 "GET /", 0, FIN, nullptr);
4888 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(3));
4889 QuicAckFrame frame = InitAckFrame(1);
4890 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4891 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4892 ProcessAckPacket(&frame);
4893
4894 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
4895 EXPECT_TRUE(connection_.connected());
4896
4897 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(2));
4898
4899 EXPECT_CALL(visitor_,
4900 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
4901 // Simulate the timeout alarm firing.
4902 connection_.GetTimeoutAlarm()->Fire();
4903
4904 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
4905 EXPECT_FALSE(connection_.connected());
4906
4907 EXPECT_FALSE(connection_.HasPendingAcks());
4908 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4909 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4910 EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
4911 TestConnectionCloseQuicErrorCode(QUIC_HANDSHAKE_TIMEOUT);
4912}
4913
4914TEST_P(QuicConnectionTest, PingAfterSend) {
4915 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4916 return;
4917 }
4918 EXPECT_TRUE(connection_.connected());
4919 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4920 .WillRepeatedly(Return(true));
4921 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4922
4923 // Advance to 5ms, and send a packet to the peer, which will set
4924 // the ping alarm.
4925 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4926 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4927 SendStreamDataToPeer(
4928 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4929 "GET /", 0, FIN, nullptr);
4930 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4931 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
4932 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4933
4934 // Now recevie an ACK of the previous packet, which will move the
4935 // ping alarm forward.
4936 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4937 QuicAckFrame frame = InitAckFrame(1);
4938 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4939 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4940 ProcessAckPacket(&frame);
4941 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4942 // The ping timer is set slightly less than 15 seconds in the future, because
4943 // of the 1s ping timer alarm granularity.
4944 EXPECT_EQ(
4945 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
4946 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4947
4948 writer_->Reset();
4949 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
4950 connection_.GetPingAlarm()->Fire();
4951 size_t padding_frame_count = writer_->padding_frames().size();
4952 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
4953 ASSERT_EQ(1u, writer_->ping_frames().size());
4954 writer_->Reset();
4955
4956 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4957 .WillRepeatedly(Return(false));
4958 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4959 SendAckPacketToPeer();
4960
4961 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4962}
4963
4964TEST_P(QuicConnectionTest, ReducedPingTimeout) {
4965 if (connection_.SupportsMultiplePacketNumberSpaces()) {
4966 return;
4967 }
4968 EXPECT_TRUE(connection_.connected());
4969 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
4970 .WillRepeatedly(Return(true));
4971 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
4972
4973 // Use a reduced ping timeout for this connection.
fayang5d393332022-04-18 13:34:54 -07004974 connection_.set_keep_alive_ping_timeout(QuicTime::Delta::FromSeconds(10));
Bence Békybac04052022-04-07 15:44:29 -04004975
4976 // Advance to 5ms, and send a packet to the peer, which will set
4977 // the ping alarm.
4978 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4979 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
4980 SendStreamDataToPeer(
4981 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
4982 "GET /", 0, FIN, nullptr);
4983 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4984 EXPECT_EQ(QuicTime::Delta::FromSeconds(10),
4985 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
4986
4987 // Now recevie an ACK of the previous packet, which will move the
4988 // ping alarm forward.
4989 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
4990 QuicAckFrame frame = InitAckFrame(1);
4991 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
4992 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
4993 ProcessAckPacket(&frame);
4994 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
4995 // The ping timer is set slightly less than 10 seconds in the future, because
4996 // of the 1s ping timer alarm granularity.
4997 EXPECT_EQ(
4998 QuicTime::Delta::FromSeconds(10) - QuicTime::Delta::FromMilliseconds(5),
4999 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
5000
5001 writer_->Reset();
5002 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
5003 connection_.GetPingAlarm()->Fire();
5004 size_t padding_frame_count = writer_->padding_frames().size();
5005 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
5006 ASSERT_EQ(1u, writer_->ping_frames().size());
5007 writer_->Reset();
5008
5009 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5010 .WillRepeatedly(Return(false));
5011 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
5012 SendAckPacketToPeer();
5013
5014 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
5015}
5016
5017// Tests whether sending an MTU discovery packet to peer successfully causes the
5018// maximum packet size to increase.
5019TEST_P(QuicConnectionTest, SendMtuDiscoveryPacket) {
5020 MtuDiscoveryTestInit();
5021
5022 // Send an MTU probe.
5023 const size_t new_mtu = kDefaultMaxPacketSize + 100;
5024 QuicByteCount mtu_probe_size;
5025 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5026 .WillOnce(SaveArg<3>(&mtu_probe_size));
5027 connection_.SendMtuDiscoveryPacket(new_mtu);
5028 EXPECT_EQ(new_mtu, mtu_probe_size);
5029 EXPECT_EQ(QuicPacketNumber(1u), creator_->packet_number());
5030
5031 // Send more than MTU worth of data. No acknowledgement was received so far,
5032 // so the MTU should be at its old value.
5033 const std::string data(kDefaultMaxPacketSize + 1, '.');
5034 QuicByteCount size_before_mtu_change;
5035 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5036 .Times(2)
5037 .WillOnce(SaveArg<3>(&size_before_mtu_change))
5038 .WillOnce(Return());
5039 connection_.SendStreamDataWithString(3, data, 0, FIN);
5040 EXPECT_EQ(QuicPacketNumber(3u), creator_->packet_number());
5041 EXPECT_EQ(kDefaultMaxPacketSize, size_before_mtu_change);
5042
5043 // Acknowledge all packets so far.
5044 QuicAckFrame probe_ack = InitAckFrame(3);
5045 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5046 ProcessAckPacket(&probe_ack);
5047 EXPECT_EQ(new_mtu, connection_.max_packet_length());
5048
5049 // Send the same data again. Check that it fits into a single packet now.
5050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
5051 connection_.SendStreamDataWithString(3, data, 0, FIN);
5052 EXPECT_EQ(QuicPacketNumber(4u), creator_->packet_number());
5053}
5054
5055// Verifies that when a MTU probe packet is sent and buffered in a batch writer,
5056// the writer is flushed immediately.
5057TEST_P(QuicConnectionTest, BatchWriterFlushedAfterMtuDiscoveryPacket) {
5058 writer_->SetBatchMode(true);
5059 MtuDiscoveryTestInit();
5060
5061 // Send an MTU probe.
5062 const size_t target_mtu = kDefaultMaxPacketSize + 100;
5063 QuicByteCount mtu_probe_size;
5064 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5065 .WillOnce(SaveArg<3>(&mtu_probe_size));
5066 const uint32_t prior_flush_attempts = writer_->flush_attempts();
5067 connection_.SendMtuDiscoveryPacket(target_mtu);
5068 EXPECT_EQ(target_mtu, mtu_probe_size);
5069 EXPECT_EQ(writer_->flush_attempts(), prior_flush_attempts + 1);
5070}
5071
5072// Tests whether MTU discovery does not happen when it is not explicitly enabled
5073// by the connection options.
5074TEST_P(QuicConnectionTest, MtuDiscoveryDisabled) {
5075 MtuDiscoveryTestInit();
5076
5077 const QuicPacketCount packets_between_probes_base = 10;
5078 set_packets_between_probes_base(packets_between_probes_base);
5079
5080 const QuicPacketCount number_of_packets = packets_between_probes_base * 2;
5081 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5082 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5083 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5084 EXPECT_EQ(0u, connection_.mtu_probe_count());
5085 }
5086}
5087
5088// Tests whether MTU discovery works when all probes are acknowledged on the
5089// first try.
5090TEST_P(QuicConnectionTest, MtuDiscoveryEnabled) {
5091 MtuDiscoveryTestInit();
5092
5093 const QuicPacketCount packets_between_probes_base = 5;
5094 set_packets_between_probes_base(packets_between_probes_base);
5095
5096 connection_.EnablePathMtuDiscovery(send_algorithm_);
5097
5098 // Send enough packets so that the next one triggers path MTU discovery.
5099 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5100 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5101 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5102 }
5103
5104 // Trigger the probe.
5105 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5106 nullptr);
5107 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5108 QuicByteCount probe_size;
5109 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5110 .WillOnce(SaveArg<3>(&probe_size));
5111 connection_.GetMtuDiscoveryAlarm()->Fire();
5112
5113 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5114 kMtuDiscoveryTargetPacketSizeHigh));
5115
5116 const QuicPacketNumber probe_packet_number =
5117 FirstSendingPacketNumber() + packets_between_probes_base;
5118 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5119
5120 // Acknowledge all packets sent so far.
5121 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5122 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5123 .Times(AnyNumber());
5124 ProcessAckPacket(&probe_ack);
5125 EXPECT_EQ(probe_size, connection_.max_packet_length());
5126 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5127
5128 EXPECT_EQ(1u, connection_.mtu_probe_count());
5129
5130 QuicStreamOffset stream_offset = packets_between_probes_base;
5131 QuicByteCount last_probe_size = 0;
5132 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5133 ++num_probes) {
5134 // Send just enough packets without triggering the next probe.
5135 for (QuicPacketCount i = 0;
5136 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5137 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5138 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5139 }
5140
5141 // Trigger the next probe.
5142 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5143 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5144 QuicByteCount new_probe_size;
5145 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5146 .WillOnce(SaveArg<3>(&new_probe_size));
5147 connection_.GetMtuDiscoveryAlarm()->Fire();
5148 EXPECT_THAT(new_probe_size,
5149 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5150 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5151
5152 // Acknowledge all packets sent so far.
5153 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5154 ProcessAckPacket(&probe_ack);
5155 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5156 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5157
5158 last_probe_size = probe_size;
5159 probe_size = new_probe_size;
5160 }
5161
5162 // The last probe size should be equal to the target.
5163 EXPECT_EQ(probe_size, kMtuDiscoveryTargetPacketSizeHigh);
5164
5165 writer_->SetShouldWriteFail();
5166
5167 // Ignore PACKET_WRITE_ERROR once.
5168 SendStreamDataToPeer(3, "(", stream_offset++, NO_FIN, nullptr);
5169 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5170 EXPECT_TRUE(connection_.connected());
5171
5172 // Close connection on another PACKET_WRITE_ERROR.
5173 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5174 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5175 SendStreamDataToPeer(3, ")", stream_offset++, NO_FIN, nullptr);
5176 EXPECT_EQ(last_probe_size, connection_.max_packet_length());
5177 EXPECT_FALSE(connection_.connected());
5178 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5179 IsError(QUIC_PACKET_WRITE_ERROR));
5180}
5181
5182// After a successful MTU probe, one and only one write error should be ignored
5183// if it happened in QuicConnection::FlushPacket.
5184TEST_P(QuicConnectionTest,
5185 MtuDiscoveryIgnoreOneWriteErrorInFlushAfterSuccessfulProbes) {
5186 MtuDiscoveryTestInit();
5187 writer_->SetBatchMode(true);
5188
5189 const QuicPacketCount packets_between_probes_base = 5;
5190 set_packets_between_probes_base(packets_between_probes_base);
5191
5192 connection_.EnablePathMtuDiscovery(send_algorithm_);
5193
5194 const QuicByteCount original_max_packet_length =
5195 connection_.max_packet_length();
5196 // Send enough packets so that the next one triggers path MTU discovery.
5197 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5198 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5199 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5200 }
5201
5202 // Trigger the probe.
5203 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5204 nullptr);
5205 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5206 QuicByteCount probe_size;
5207 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5208 .WillOnce(SaveArg<3>(&probe_size));
5209 connection_.GetMtuDiscoveryAlarm()->Fire();
5210
5211 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5212 kMtuDiscoveryTargetPacketSizeHigh));
5213
5214 const QuicPacketNumber probe_packet_number =
5215 FirstSendingPacketNumber() + packets_between_probes_base;
5216 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5217
5218 // Acknowledge all packets sent so far.
5219 QuicAckFrame probe_ack = InitAckFrame(probe_packet_number);
5220 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5221 .Times(AnyNumber());
5222 ProcessAckPacket(&probe_ack);
5223 EXPECT_EQ(probe_size, connection_.max_packet_length());
5224 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5225
5226 EXPECT_EQ(1u, connection_.mtu_probe_count());
5227
5228 writer_->SetShouldWriteFail();
5229
5230 // Ignore PACKET_WRITE_ERROR once.
5231 {
5232 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5233 // flusher's destructor will call connection_.FlushPackets, which should
5234 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5235 }
5236 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5237 EXPECT_TRUE(connection_.connected());
5238
5239 // Close connection on another PACKET_WRITE_ERROR.
5240 EXPECT_CALL(visitor_, OnConnectionClosed(_, _))
5241 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5242 {
5243 QuicConnection::ScopedPacketFlusher flusher(&connection_);
5244 // flusher's destructor will call connection_.FlushPackets, which should
5245 // get a WRITE_STATUS_ERROR from the writer and ignore it.
5246 }
5247 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5248 EXPECT_FALSE(connection_.connected());
5249 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5250 IsError(QUIC_PACKET_WRITE_ERROR));
5251}
5252
5253// Simulate the case where the first attempt to send a probe is write blocked,
5254// and after unblock, the second attempt returns a MSG_TOO_BIG error.
5255TEST_P(QuicConnectionTest, MtuDiscoveryWriteBlocked) {
5256 MtuDiscoveryTestInit();
5257
5258 const QuicPacketCount packets_between_probes_base = 5;
5259 set_packets_between_probes_base(packets_between_probes_base);
5260
5261 connection_.EnablePathMtuDiscovery(send_algorithm_);
5262
5263 // Send enough packets so that the next one triggers path MTU discovery.
5264 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5265 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5266 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5267 }
5268
5269 QuicByteCount original_max_packet_length = connection_.max_packet_length();
5270
5271 // Trigger the probe.
5272 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5273 nullptr);
5274 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5275 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5276 BlockOnNextWrite();
5277 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5278 connection_.GetMtuDiscoveryAlarm()->Fire();
5279 EXPECT_EQ(1u, connection_.mtu_probe_count());
5280 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5281 ASSERT_TRUE(connection_.connected());
5282
5283 writer_->SetWritable();
5284 SimulateNextPacketTooLarge();
5285 connection_.OnCanWrite();
5286 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5287 EXPECT_EQ(original_max_packet_length, connection_.max_packet_length());
5288 EXPECT_TRUE(connection_.connected());
5289}
5290
5291// Tests whether MTU discovery works correctly when the probes never get
5292// acknowledged.
5293TEST_P(QuicConnectionTest, MtuDiscoveryFailed) {
5294 MtuDiscoveryTestInit();
5295
5296 // Lower the number of probes between packets in order to make the test go
5297 // much faster.
5298 const QuicPacketCount packets_between_probes_base = 5;
5299 set_packets_between_probes_base(packets_between_probes_base);
5300
5301 connection_.EnablePathMtuDiscovery(send_algorithm_);
5302
5303 const QuicTime::Delta rtt = QuicTime::Delta::FromMilliseconds(100);
5304
5305 EXPECT_EQ(packets_between_probes_base,
5306 QuicConnectionPeer::GetPacketsBetweenMtuProbes(&connection_));
5307
5308 // This tests sends more packets than strictly necessary to make sure that if
5309 // the connection was to send more discovery packets than needed, those would
5310 // get caught as well.
5311 const QuicPacketCount number_of_packets =
5312 packets_between_probes_base * (1 << (kMtuDiscoveryAttempts + 1));
5313 std::vector<QuicPacketNumber> mtu_discovery_packets;
5314 // Called on many acks.
5315 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5316 .Times(AnyNumber());
5317 for (QuicPacketCount i = 0; i < number_of_packets; i++) {
5318 SendStreamDataToPeer(3, "!", i, NO_FIN, nullptr);
5319 clock_.AdvanceTime(rtt);
5320
5321 // Receive an ACK, which marks all data packets as received, and all MTU
5322 // discovery packets as missing.
5323
5324 QuicAckFrame ack;
5325
5326 if (!mtu_discovery_packets.empty()) {
5327 QuicPacketNumber min_packet = *min_element(mtu_discovery_packets.begin(),
5328 mtu_discovery_packets.end());
5329 QuicPacketNumber max_packet = *max_element(mtu_discovery_packets.begin(),
5330 mtu_discovery_packets.end());
5331 ack.packets.AddRange(QuicPacketNumber(1), min_packet);
5332 ack.packets.AddRange(QuicPacketNumber(max_packet + 1),
5333 creator_->packet_number() + 1);
5334 ack.largest_acked = creator_->packet_number();
5335
5336 } else {
5337 ack.packets.AddRange(QuicPacketNumber(1), creator_->packet_number() + 1);
5338 ack.largest_acked = creator_->packet_number();
5339 }
5340
5341 ProcessAckPacket(&ack);
5342
5343 // Trigger MTU probe if it would be scheduled now.
5344 if (!connection_.GetMtuDiscoveryAlarm()->IsSet()) {
5345 continue;
5346 }
5347
5348 // Fire the alarm. The alarm should cause a packet to be sent.
5349 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5350 connection_.GetMtuDiscoveryAlarm()->Fire();
5351 // Record the packet number of the MTU discovery packet in order to
5352 // mark it as NACK'd.
5353 mtu_discovery_packets.push_back(creator_->packet_number());
5354 }
5355
5356 // Ensure the number of packets between probes grows exponentially by checking
5357 // it against the closed-form expression for the packet number.
5358 ASSERT_EQ(kMtuDiscoveryAttempts, mtu_discovery_packets.size());
5359 for (uint64_t i = 0; i < kMtuDiscoveryAttempts; i++) {
5360 // 2^0 + 2^1 + 2^2 + ... + 2^n = 2^(n + 1) - 1
5361 const QuicPacketCount packets_between_probes =
5362 packets_between_probes_base * ((1 << (i + 1)) - 1);
5363 EXPECT_EQ(QuicPacketNumber(packets_between_probes + (i + 1)),
5364 mtu_discovery_packets[i]);
5365 }
5366
5367 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5368 EXPECT_EQ(kDefaultMaxPacketSize, connection_.max_packet_length());
5369 EXPECT_EQ(kMtuDiscoveryAttempts, connection_.mtu_probe_count());
5370}
5371
5372// Probe 3 times, the first one succeeds, then fails, then succeeds again.
5373TEST_P(QuicConnectionTest, MtuDiscoverySecondProbeFailed) {
5374 MtuDiscoveryTestInit();
5375
5376 const QuicPacketCount packets_between_probes_base = 5;
5377 set_packets_between_probes_base(packets_between_probes_base);
5378
5379 connection_.EnablePathMtuDiscovery(send_algorithm_);
5380
5381 // Send enough packets so that the next one triggers path MTU discovery.
5382 QuicStreamOffset stream_offset = 0;
5383 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5384 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5385 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5386 }
5387
5388 // Trigger the probe.
5389 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5390 nullptr);
5391 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5392 QuicByteCount probe_size;
5393 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5394 .WillOnce(SaveArg<3>(&probe_size));
5395 connection_.GetMtuDiscoveryAlarm()->Fire();
5396 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(),
5397 kMtuDiscoveryTargetPacketSizeHigh));
5398
5399 const QuicPacketNumber probe_packet_number =
5400 FirstSendingPacketNumber() + packets_between_probes_base;
5401 ASSERT_EQ(probe_packet_number, creator_->packet_number());
5402
5403 // Acknowledge all packets sent so far.
5404 QuicAckFrame first_ack = InitAckFrame(probe_packet_number);
5405 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5406 .Times(AnyNumber());
5407 ProcessAckPacket(&first_ack);
5408 EXPECT_EQ(probe_size, connection_.max_packet_length());
5409 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5410
5411 EXPECT_EQ(1u, connection_.mtu_probe_count());
5412
5413 // Send just enough packets without triggering the second probe.
5414 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 1) - 1; ++i) {
5415 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5416 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5417 }
5418
5419 // Trigger the second probe.
5420 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5421 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5422 QuicByteCount second_probe_size;
5423 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5424 .WillOnce(SaveArg<3>(&second_probe_size));
5425 connection_.GetMtuDiscoveryAlarm()->Fire();
5426 EXPECT_THAT(second_probe_size,
5427 InRange(probe_size, kMtuDiscoveryTargetPacketSizeHigh));
5428 EXPECT_EQ(2u, connection_.mtu_probe_count());
5429
5430 // Acknowledge all packets sent so far, except the second probe.
5431 QuicPacketNumber second_probe_packet_number = creator_->packet_number();
5432 QuicAckFrame second_ack = InitAckFrame(second_probe_packet_number - 1);
5433 ProcessAckPacket(&first_ack);
5434 EXPECT_EQ(probe_size, connection_.max_packet_length());
5435
5436 // Send just enough packets without triggering the third probe.
5437 for (QuicPacketCount i = 0; i < (packets_between_probes_base << 2) - 1; ++i) {
5438 SendStreamDataToPeer(3, "@", stream_offset++, NO_FIN, nullptr);
5439 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5440 }
5441
5442 // Trigger the third probe.
5443 SendStreamDataToPeer(3, "#", stream_offset++, NO_FIN, nullptr);
5444 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5445 QuicByteCount third_probe_size;
5446 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5447 .WillOnce(SaveArg<3>(&third_probe_size));
5448 connection_.GetMtuDiscoveryAlarm()->Fire();
5449 EXPECT_THAT(third_probe_size, InRange(probe_size, second_probe_size));
5450 EXPECT_EQ(3u, connection_.mtu_probe_count());
5451
5452 // Acknowledge all packets sent so far, except the second probe.
5453 QuicAckFrame third_ack =
5454 ConstructAckFrame(creator_->packet_number(), second_probe_packet_number);
5455 ProcessAckPacket(&third_ack);
5456 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5457
5458 SendStreamDataToPeer(3, "$", stream_offset++, NO_FIN, nullptr);
5459 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5460
5461 if (connection_.PathDegradingDetectionInProgress() &&
5462 QuicConnectionPeer::GetPathDegradingDeadline(&connection_) <
5463 QuicConnectionPeer::GetPathMtuReductionDetectionDeadline(
5464 &connection_)) {
5465 // Fire path degrading alarm first.
5466 connection_.PathDegradingTimeout();
5467 }
5468
5469 // Verify the max packet size has not reduced.
5470 EXPECT_EQ(third_probe_size, connection_.max_packet_length());
5471
5472 // Fire alarm to get path mtu reduction callback called.
5473 EXPECT_TRUE(connection_.PathMtuReductionDetectionInProgress());
5474 connection_.GetBlackholeDetectorAlarm()->Fire();
5475
5476 // Verify the max packet size has reduced to the previous value.
5477 EXPECT_EQ(probe_size, connection_.max_packet_length());
5478}
5479
5480// Tests whether MTU discovery works when the writer has a limit on how large a
5481// packet can be.
5482TEST_P(QuicConnectionTest, MtuDiscoveryWriterLimited) {
5483 MtuDiscoveryTestInit();
5484
5485 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5486 writer_->set_max_packet_size(mtu_limit);
5487
5488 const QuicPacketCount packets_between_probes_base = 5;
5489 set_packets_between_probes_base(packets_between_probes_base);
5490
5491 connection_.EnablePathMtuDiscovery(send_algorithm_);
5492
5493 // Send enough packets so that the next one triggers path MTU discovery.
5494 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5495 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5496 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5497 }
5498
5499 // Trigger the probe.
5500 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5501 nullptr);
5502 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5503 QuicByteCount probe_size;
5504 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5505 .WillOnce(SaveArg<3>(&probe_size));
5506 connection_.GetMtuDiscoveryAlarm()->Fire();
5507
5508 EXPECT_THAT(probe_size, InRange(connection_.max_packet_length(), mtu_limit));
5509
5510 const QuicPacketNumber probe_sequence_number =
5511 FirstSendingPacketNumber() + packets_between_probes_base;
5512 ASSERT_EQ(probe_sequence_number, creator_->packet_number());
5513
5514 // Acknowledge all packets sent so far.
5515 QuicAckFrame probe_ack = InitAckFrame(probe_sequence_number);
5516 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
5517 .Times(AnyNumber());
5518 ProcessAckPacket(&probe_ack);
5519 EXPECT_EQ(probe_size, connection_.max_packet_length());
5520 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5521
5522 EXPECT_EQ(1u, connection_.mtu_probe_count());
5523
5524 QuicStreamOffset stream_offset = packets_between_probes_base;
5525 for (size_t num_probes = 1; num_probes < kMtuDiscoveryAttempts;
5526 ++num_probes) {
5527 // Send just enough packets without triggering the next probe.
5528 for (QuicPacketCount i = 0;
5529 i < (packets_between_probes_base << num_probes) - 1; ++i) {
5530 SendStreamDataToPeer(3, ".", stream_offset++, NO_FIN, nullptr);
5531 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5532 }
5533
5534 // Trigger the next probe.
5535 SendStreamDataToPeer(3, "!", stream_offset++, NO_FIN, nullptr);
5536 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5537 QuicByteCount new_probe_size;
5538 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
5539 .WillOnce(SaveArg<3>(&new_probe_size));
5540 connection_.GetMtuDiscoveryAlarm()->Fire();
5541 EXPECT_THAT(new_probe_size, InRange(probe_size, mtu_limit));
5542 EXPECT_EQ(num_probes + 1, connection_.mtu_probe_count());
5543
5544 // Acknowledge all packets sent so far.
5545 QuicAckFrame probe_ack = InitAckFrame(creator_->packet_number());
5546 ProcessAckPacket(&probe_ack);
5547 EXPECT_EQ(new_probe_size, connection_.max_packet_length());
5548 EXPECT_EQ(0u, connection_.GetBytesInFlight());
5549
5550 probe_size = new_probe_size;
5551 }
5552
5553 // The last probe size should be equal to the target.
5554 EXPECT_EQ(probe_size, mtu_limit);
5555}
5556
5557// Tests whether MTU discovery works when the writer returns an error despite
5558// advertising higher packet length.
5559TEST_P(QuicConnectionTest, MtuDiscoveryWriterFailed) {
5560 MtuDiscoveryTestInit();
5561
5562 const QuicByteCount mtu_limit = kMtuDiscoveryTargetPacketSizeHigh - 1;
5563 const QuicByteCount initial_mtu = connection_.max_packet_length();
5564 EXPECT_LT(initial_mtu, mtu_limit);
5565 writer_->set_max_packet_size(mtu_limit);
5566
5567 const QuicPacketCount packets_between_probes_base = 5;
5568 set_packets_between_probes_base(packets_between_probes_base);
5569
5570 connection_.EnablePathMtuDiscovery(send_algorithm_);
5571
5572 // Send enough packets so that the next one triggers path MTU discovery.
5573 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5574 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5575 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5576 }
5577
5578 // Trigger the probe.
5579 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5580 nullptr);
5581 ASSERT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5582 writer_->SimulateNextPacketTooLarge();
5583 connection_.GetMtuDiscoveryAlarm()->Fire();
5584 ASSERT_TRUE(connection_.connected());
5585
5586 // Send more data.
5587 QuicPacketNumber probe_number = creator_->packet_number();
5588 QuicPacketCount extra_packets = packets_between_probes_base * 3;
5589 for (QuicPacketCount i = 0; i < extra_packets; i++) {
5590 connection_.EnsureWritableAndSendStreamData5();
5591 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5592 }
5593
5594 // Acknowledge all packets sent so far, except for the lost probe.
5595 QuicAckFrame probe_ack =
5596 ConstructAckFrame(creator_->packet_number(), probe_number);
5597 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5598 ProcessAckPacket(&probe_ack);
5599 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5600
5601 // Send more packets, and ensure that none of them sets the alarm.
5602 for (QuicPacketCount i = 0; i < 4 * packets_between_probes_base; i++) {
5603 connection_.EnsureWritableAndSendStreamData5();
5604 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5605 }
5606
5607 EXPECT_EQ(initial_mtu, connection_.max_packet_length());
5608 EXPECT_EQ(1u, connection_.mtu_probe_count());
5609}
5610
5611TEST_P(QuicConnectionTest, NoMtuDiscoveryAfterConnectionClosed) {
5612 MtuDiscoveryTestInit();
5613
5614 const QuicPacketCount packets_between_probes_base = 10;
5615 set_packets_between_probes_base(packets_between_probes_base);
5616
5617 connection_.EnablePathMtuDiscovery(send_algorithm_);
5618
5619 // Send enough packets so that the next one triggers path MTU discovery.
5620 for (QuicPacketCount i = 0; i < packets_between_probes_base - 1; i++) {
5621 SendStreamDataToPeer(3, ".", i, NO_FIN, nullptr);
5622 ASSERT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5623 }
5624
5625 SendStreamDataToPeer(3, "!", packets_between_probes_base - 1, NO_FIN,
5626 nullptr);
5627 EXPECT_TRUE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5628
5629 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
5630 connection_.CloseConnection(QUIC_PEER_GOING_AWAY, "no reason",
5631 ConnectionCloseBehavior::SILENT_CLOSE);
5632 EXPECT_FALSE(connection_.GetMtuDiscoveryAlarm()->IsSet());
5633}
5634
5635TEST_P(QuicConnectionTest, TimeoutAfterSendDuringHandshake) {
5636 EXPECT_TRUE(connection_.connected());
5637 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5638 QuicConfig config;
5639 connection_.SetFromConfig(config);
5640
5641 const QuicTime::Delta initial_idle_timeout =
5642 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5643 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5644 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5645
5646 // When we send a packet, the timeout will change to 5ms +
5647 // kInitialIdleTimeoutSecs.
5648 clock_.AdvanceTime(five_ms);
5649 SendStreamDataToPeer(
5650 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5651 0, FIN, nullptr);
5652 EXPECT_EQ(default_timeout + five_ms,
5653 connection_.GetTimeoutAlarm()->deadline());
5654
5655 // Now send more data. This will not move the timeout because
5656 // no data has been received since the previous write.
5657 clock_.AdvanceTime(five_ms);
5658 SendStreamDataToPeer(
5659 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5660 3, FIN, nullptr);
5661 EXPECT_EQ(default_timeout + five_ms,
5662 connection_.GetTimeoutAlarm()->deadline());
5663
5664 // The original alarm will fire. We should not time out because we had a
5665 // network event at t=5ms. The alarm will reregister.
5666 clock_.AdvanceTime(initial_idle_timeout - five_ms - five_ms);
5667 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5668 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5669 EXPECT_TRUE(connection_.connected());
5670 EXPECT_EQ(default_timeout + five_ms,
5671 connection_.GetTimeoutAlarm()->deadline());
5672
5673 // This time, we should time out.
5674 EXPECT_CALL(visitor_,
5675 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5676 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5677 clock_.AdvanceTime(five_ms);
5678 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5679 connection_.GetTimeoutAlarm()->Fire();
5680 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5681 EXPECT_FALSE(connection_.connected());
5682 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5683}
5684
Bence Békybac04052022-04-07 15:44:29 -04005685TEST_P(QuicConnectionTest, TimeoutAfterSendAfterHandshake) {
5686 // When the idle timeout fires, verify that by default we do not send any
5687 // connection close packets.
5688 EXPECT_TRUE(connection_.connected());
5689 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5690 QuicConfig config;
5691
5692 // Create a handshake message that also enables silent close.
5693 CryptoHandshakeMessage msg;
5694 std::string error_details;
5695 QuicConfig client_config;
5696 client_config.SetInitialStreamFlowControlWindowToSend(
5697 kInitialStreamFlowControlWindowForTest);
5698 client_config.SetInitialSessionFlowControlWindowToSend(
5699 kInitialSessionFlowControlWindowForTest);
5700 client_config.SetIdleNetworkTimeout(
5701 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5702 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5703 const QuicErrorCode error =
5704 config.ProcessPeerHello(msg, CLIENT, &error_details);
5705 EXPECT_THAT(error, IsQuicNoError());
5706
5707 if (connection_.version().UsesTls()) {
5708 QuicConfigPeer::SetReceivedOriginalConnectionId(
5709 &config, connection_.connection_id());
5710 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5711 &config, connection_.connection_id());
5712 }
5713 connection_.SetFromConfig(config);
haoyuewang7b43efb2022-04-20 16:26:03 -07005714 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04005715
5716 const QuicTime::Delta default_idle_timeout =
5717 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5718 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5719 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5720
5721 // When we send a packet, the timeout will change to 5ms +
5722 // kInitialIdleTimeoutSecs.
5723 clock_.AdvanceTime(five_ms);
5724 SendStreamDataToPeer(
5725 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5726 0, FIN, nullptr);
5727 EXPECT_EQ(default_timeout + five_ms,
5728 connection_.GetTimeoutAlarm()->deadline());
5729
5730 // Now send more data. This will not move the timeout because
5731 // no data has been received since the previous write.
5732 clock_.AdvanceTime(five_ms);
5733 SendStreamDataToPeer(
5734 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5735 3, FIN, nullptr);
5736 EXPECT_EQ(default_timeout + five_ms,
5737 connection_.GetTimeoutAlarm()->deadline());
5738
5739 // The original alarm will fire. We should not time out because we had a
5740 // network event at t=5ms. The alarm will reregister.
5741 clock_.AdvanceTime(default_idle_timeout - five_ms - five_ms);
5742 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5743 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5744 EXPECT_TRUE(connection_.connected());
5745 EXPECT_EQ(default_timeout + five_ms,
5746 connection_.GetTimeoutAlarm()->deadline());
5747
5748 // This time, we should time out.
5749 // This results in a SILENT_CLOSE, so the writer will not be invoked
5750 // and will not save the frame. Grab the frame from OnConnectionClosed
5751 // directly.
5752 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
5753 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
5754
5755 clock_.AdvanceTime(five_ms);
5756 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5757 connection_.GetTimeoutAlarm()->Fire();
5758 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5759 EXPECT_FALSE(connection_.connected());
5760 EXPECT_EQ(1, connection_close_frame_count_);
5761 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
5762 IsError(QUIC_NETWORK_IDLE_TIMEOUT));
5763}
5764
Bence Békybac04052022-04-07 15:44:29 -04005765TEST_P(QuicConnectionTest, TimeoutAfterSendSilentCloseWithOpenStreams) {
5766 // Same test as above, but having open streams causes a connection close
5767 // to be sent.
5768 EXPECT_TRUE(connection_.connected());
5769 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5770 QuicConfig config;
5771
5772 // Create a handshake message that also enables silent close.
5773 CryptoHandshakeMessage msg;
5774 std::string error_details;
5775 QuicConfig client_config;
5776 client_config.SetInitialStreamFlowControlWindowToSend(
5777 kInitialStreamFlowControlWindowForTest);
5778 client_config.SetInitialSessionFlowControlWindowToSend(
5779 kInitialSessionFlowControlWindowForTest);
5780 client_config.SetIdleNetworkTimeout(
5781 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs));
5782 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
5783 const QuicErrorCode error =
5784 config.ProcessPeerHello(msg, CLIENT, &error_details);
5785 EXPECT_THAT(error, IsQuicNoError());
5786
5787 if (connection_.version().UsesTls()) {
5788 QuicConfigPeer::SetReceivedOriginalConnectionId(
5789 &config, connection_.connection_id());
5790 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
5791 &config, connection_.connection_id());
5792 }
5793 connection_.SetFromConfig(config);
haoyuewang7b43efb2022-04-20 16:26:03 -07005794 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04005795
5796 const QuicTime::Delta default_idle_timeout =
5797 QuicTime::Delta::FromSeconds(kMaximumIdleTimeoutSecs - 1);
5798 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5799 QuicTime default_timeout = clock_.ApproximateNow() + default_idle_timeout;
5800
5801 // When we send a packet, the timeout will change to 5ms +
5802 // kInitialIdleTimeoutSecs.
5803 clock_.AdvanceTime(five_ms);
5804 SendStreamDataToPeer(
5805 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5806 0, FIN, nullptr);
5807 EXPECT_EQ(default_timeout + five_ms,
5808 connection_.GetTimeoutAlarm()->deadline());
5809
5810 // Indicate streams are still open.
5811 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
5812 .WillRepeatedly(Return(true));
5813 if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail)) {
5814 EXPECT_CALL(visitor_, GetStreamsInfoForLogging()).WillOnce(Return(""));
5815 }
5816
5817 // This time, we should time out and send a connection close due to the TLP.
5818 EXPECT_CALL(visitor_,
5819 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5820 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5821 clock_.AdvanceTime(connection_.GetTimeoutAlarm()->deadline() -
5822 clock_.ApproximateNow() + five_ms);
5823 connection_.GetTimeoutAlarm()->Fire();
5824 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5825 EXPECT_FALSE(connection_.connected());
5826 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5827}
5828
5829TEST_P(QuicConnectionTest, TimeoutAfterReceive) {
5830 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5831 EXPECT_TRUE(connection_.connected());
5832 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5833 QuicConfig config;
5834 connection_.SetFromConfig(config);
5835
5836 const QuicTime::Delta initial_idle_timeout =
5837 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5838 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5839 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5840
5841 connection_.SendStreamDataWithString(
5842 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5843 0, NO_FIN);
5844 connection_.SendStreamDataWithString(
5845 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5846 3, NO_FIN);
5847
5848 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5849 clock_.AdvanceTime(five_ms);
5850
5851 // When we receive a packet, the timeout will change to 5ms +
5852 // kInitialIdleTimeoutSecs.
5853 QuicAckFrame ack = InitAckFrame(2);
5854 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5855 ProcessAckPacket(&ack);
5856
5857 // The original alarm will fire. We should not time out because we had a
5858 // network event at t=5ms. The alarm will reregister.
5859 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5860 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5861 EXPECT_TRUE(connection_.connected());
5862 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5863 EXPECT_EQ(default_timeout + five_ms,
5864 connection_.GetTimeoutAlarm()->deadline());
5865
5866 // This time, we should time out.
5867 EXPECT_CALL(visitor_,
5868 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5869 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
5870 clock_.AdvanceTime(five_ms);
5871 EXPECT_EQ(default_timeout + five_ms, clock_.ApproximateNow());
5872 connection_.GetTimeoutAlarm()->Fire();
5873 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5874 EXPECT_FALSE(connection_.connected());
5875 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5876}
5877
5878TEST_P(QuicConnectionTest, TimeoutAfterReceiveNotSendWhenUnacked) {
5879 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
5880 EXPECT_TRUE(connection_.connected());
5881 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
5882 QuicConfig config;
5883 connection_.SetFromConfig(config);
5884
5885 const QuicTime::Delta initial_idle_timeout =
5886 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
5887 connection_.SetNetworkTimeouts(
5888 QuicTime::Delta::Infinite(),
5889 initial_idle_timeout + QuicTime::Delta::FromSeconds(1));
haoyuewang7b43efb2022-04-20 16:26:03 -07005890 QuicConnectionPeer::DisableBandwidthUpdate(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04005891 const QuicTime::Delta five_ms = QuicTime::Delta::FromMilliseconds(5);
5892 QuicTime default_timeout = clock_.ApproximateNow() + initial_idle_timeout;
5893
5894 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5895 connection_.SendStreamDataWithString(
5896 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5897 0, NO_FIN);
5898 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5899 connection_.SendStreamDataWithString(
5900 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
5901 3, NO_FIN);
5902
5903 EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
5904
5905 clock_.AdvanceTime(five_ms);
5906
5907 // When we receive a packet, the timeout will change to 5ms +
5908 // kInitialIdleTimeoutSecs.
5909 QuicAckFrame ack = InitAckFrame(2);
5910 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
5911 ProcessAckPacket(&ack);
5912
5913 // The original alarm will fire. We should not time out because we had a
5914 // network event at t=5ms. The alarm will reregister.
5915 clock_.AdvanceTime(initial_idle_timeout - five_ms);
5916 EXPECT_EQ(default_timeout, clock_.ApproximateNow());
5917 EXPECT_TRUE(connection_.connected());
5918 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
5919 EXPECT_EQ(default_timeout + five_ms,
5920 connection_.GetTimeoutAlarm()->deadline());
5921
5922 // Now, send packets while advancing the time and verify that the connection
5923 // eventually times out.
5924 EXPECT_CALL(visitor_,
5925 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
5926 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
5927 for (int i = 0; i < 100 && connection_.connected(); ++i) {
5928 QUIC_LOG(INFO) << "sending data packet";
5929 connection_.SendStreamDataWithString(
5930 GetNthClientInitiatedStreamId(1, connection_.transport_version()),
5931 "foo", 0, NO_FIN);
5932 connection_.GetTimeoutAlarm()->Fire();
5933 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
5934 }
5935 EXPECT_FALSE(connection_.connected());
5936 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
5937 TestConnectionCloseQuicErrorCode(QUIC_NETWORK_IDLE_TIMEOUT);
5938}
5939
Bence Békybac04052022-04-07 15:44:29 -04005940TEST_P(QuicConnectionTest, SendScheduler) {
5941 // Test that if we send a packet without delay, it is not queued.
5942 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5943 std::unique_ptr<QuicPacket> packet =
5944 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
5945 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5946 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
5947 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
5948 HAS_RETRANSMITTABLE_DATA, false, false);
5949 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5950}
5951
5952TEST_P(QuicConnectionTest, FailToSendFirstPacket) {
5953 // Test that the connection does not crash when it fails to send the first
5954 // packet at which point self_address_ might be uninitialized.
5955 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5956 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
5957 std::unique_ptr<QuicPacket> packet =
5958 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
5959 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5960 writer_->SetShouldWriteFail();
5961 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
5962 HAS_RETRANSMITTABLE_DATA, false, false);
5963}
5964
5965TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
5966 QuicFramerPeer::SetPerspective(&peer_framer_, Perspective::IS_CLIENT);
5967 std::unique_ptr<QuicPacket> packet =
5968 ConstructDataPacket(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
5969 QuicPacketCreatorPeer::SetPacketNumber(creator_, 1);
5970 BlockOnNextWrite();
5971 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(2u), _, _))
5972 .Times(0);
5973 connection_.SendPacket(ENCRYPTION_INITIAL, 1, std::move(packet),
5974 HAS_RETRANSMITTABLE_DATA, false, false);
5975 EXPECT_EQ(1u, connection_.NumQueuedPackets());
5976}
5977
5978TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
5979 // Queue the first packet.
5980 size_t payload_length = connection_.max_packet_length();
5981 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(testing::Return(false));
5982 const std::string payload(payload_length, 'a');
5983 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5984 connection_.version().transport_version, Perspective::IS_CLIENT));
5985 EXPECT_EQ(0u, connection_
5986 .SendStreamDataWithString(first_bidi_stream_id, payload, 0,
5987 NO_FIN)
5988 .bytes_consumed);
5989 EXPECT_EQ(0u, connection_.NumQueuedPackets());
5990}
5991
5992TEST_P(QuicConnectionTest, SendingThreePackets) {
5993 // Make the payload twice the size of the packet, so 3 packets are written.
5994 size_t total_payload_length = 2 * connection_.max_packet_length();
5995 const std::string payload(total_payload_length, 'a');
5996 QuicStreamId first_bidi_stream_id(QuicUtils::GetFirstBidirectionalStreamId(
5997 connection_.version().transport_version, Perspective::IS_CLIENT));
5998 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
5999 EXPECT_EQ(payload.size(), connection_
6000 .SendStreamDataWithString(first_bidi_stream_id,
6001 payload, 0, NO_FIN)
6002 .bytes_consumed);
6003}
6004
6005TEST_P(QuicConnectionTest, LoopThroughSendingPacketsWithTruncation) {
6006 set_perspective(Perspective::IS_SERVER);
6007 if (!GetParam().version.HasIetfInvariantHeader()) {
6008 // For IETF QUIC, encryption level will be switched to FORWARD_SECURE in
6009 // SendStreamDataWithString.
6010 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
6011 }
6012 // Set up a larger payload than will fit in one packet.
6013 const std::string payload(connection_.max_packet_length(), 'a');
6014 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
6015
6016 // Now send some packets with no truncation.
6017 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6018 EXPECT_EQ(payload.size(),
6019 connection_.SendStreamDataWithString(3, payload, 0, NO_FIN)
6020 .bytes_consumed);
6021 // Track the size of the second packet here. The overhead will be the largest
6022 // we see in this test, due to the non-truncated connection id.
6023 size_t non_truncated_packet_size = writer_->last_packet_size();
6024
6025 // Change to a 0 byte connection id.
6026 QuicConfig config;
6027 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
6028 connection_.SetFromConfig(config);
6029 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
6030 EXPECT_EQ(payload.size(),
6031 connection_.SendStreamDataWithString(3, payload, 1350, NO_FIN)
6032 .bytes_consumed);
6033 if (connection_.version().HasIetfInvariantHeader()) {
6034 // Short header packets sent from server omit connection ID already, and
6035 // stream offset size increases from 0 to 2.
6036 EXPECT_EQ(non_truncated_packet_size, writer_->last_packet_size() - 2);
6037 } else {
6038 // Just like above, we save 8 bytes on payload, and 8 on truncation. -2
6039 // because stream offset size is 2 instead of 0.
6040 EXPECT_EQ(non_truncated_packet_size,
6041 writer_->last_packet_size() + 8 * 2 - 2);
6042 }
6043}
6044
6045TEST_P(QuicConnectionTest, SendDelayedAck) {
6046 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6047 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6048 EXPECT_FALSE(connection_.HasPendingAcks());
6049 const uint8_t tag = 0x07;
6050 SetDecrypter(ENCRYPTION_ZERO_RTT,
6051 std::make_unique<StrictTaggingDecrypter>(tag));
6052 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6053 std::make_unique<TaggingEncrypter>(tag));
6054 // Process a packet from the non-crypto stream.
6055 frame1_.stream_id = 3;
6056
6057 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6058 // instead of ENCRYPTION_INITIAL.
6059 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6060 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6061
6062 // Check if delayed ack timer is running for the expected interval.
6063 EXPECT_TRUE(connection_.HasPendingAcks());
6064 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6065 // Simulate delayed ack alarm firing.
6066 clock_.AdvanceTime(DefaultDelayedAckTime());
6067 connection_.GetAckAlarm()->Fire();
6068 // Check that ack is sent and that delayed ack alarm is reset.
6069 size_t padding_frame_count = writer_->padding_frames().size();
6070 if (GetParam().no_stop_waiting) {
6071 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6072 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6073 } else {
6074 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6075 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6076 }
6077 EXPECT_FALSE(writer_->ack_frames().empty());
6078 EXPECT_FALSE(connection_.HasPendingAcks());
6079}
6080
6081TEST_P(QuicConnectionTest, SendDelayedAckDecimation) {
6082 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6083
6084 const size_t kMinRttMs = 40;
6085 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6086 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6087 QuicTime::Delta::Zero(), QuicTime::Zero());
6088 // The ack time should be based on min_rtt/4, since it's less than the
6089 // default delayed ack time.
6090 QuicTime ack_time = clock_.ApproximateNow() +
6091 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6092 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6093 EXPECT_FALSE(connection_.HasPendingAcks());
6094 const uint8_t tag = 0x07;
6095 SetDecrypter(ENCRYPTION_ZERO_RTT,
6096 std::make_unique<StrictTaggingDecrypter>(tag));
6097 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6098 std::make_unique<TaggingEncrypter>(tag));
6099 // Process a packet from the non-crypto stream.
6100 frame1_.stream_id = 3;
6101
6102 // Process all the initial packets in order so there aren't missing packets.
6103 uint64_t kFirstDecimatedPacket = 101;
6104 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6105 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6106 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6107 }
6108 EXPECT_FALSE(connection_.HasPendingAcks());
6109 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6110 // instead of ENCRYPTION_INITIAL.
6111 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6112 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6113 ENCRYPTION_ZERO_RTT);
6114
6115 // Check if delayed ack timer is running for the expected interval.
6116 EXPECT_TRUE(connection_.HasPendingAcks());
6117 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6118
6119 // The 10th received packet causes an ack to be sent.
6120 for (int i = 0; i < 9; ++i) {
6121 EXPECT_TRUE(connection_.HasPendingAcks());
6122 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6123 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6124 ENCRYPTION_ZERO_RTT);
6125 }
6126 // Check that ack is sent and that delayed ack alarm is reset.
6127 size_t padding_frame_count = writer_->padding_frames().size();
6128 if (GetParam().no_stop_waiting) {
6129 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6130 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6131 } else {
6132 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6133 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6134 }
6135 EXPECT_FALSE(writer_->ack_frames().empty());
6136 EXPECT_FALSE(connection_.HasPendingAcks());
6137}
6138
6139TEST_P(QuicConnectionTest, SendDelayedAckDecimationUnlimitedAggregation) {
6140 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6141 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
6142 QuicConfig config;
6143 QuicTagVector connection_options;
6144 // No limit on the number of packets received before sending an ack.
6145 connection_options.push_back(kAKDU);
6146 config.SetConnectionOptionsToSend(connection_options);
6147 connection_.SetFromConfig(config);
6148
6149 const size_t kMinRttMs = 40;
6150 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6151 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6152 QuicTime::Delta::Zero(), QuicTime::Zero());
6153 // The ack time should be based on min_rtt/4, since it's less than the
6154 // default delayed ack time.
6155 QuicTime ack_time = clock_.ApproximateNow() +
6156 QuicTime::Delta::FromMilliseconds(kMinRttMs / 4);
6157 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6158 EXPECT_FALSE(connection_.HasPendingAcks());
6159 const uint8_t tag = 0x07;
6160 SetDecrypter(ENCRYPTION_ZERO_RTT,
6161 std::make_unique<StrictTaggingDecrypter>(tag));
6162 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6163 std::make_unique<TaggingEncrypter>(tag));
6164 // Process a packet from the non-crypto stream.
6165 frame1_.stream_id = 3;
6166
6167 // Process all the initial packets in order so there aren't missing packets.
6168 uint64_t kFirstDecimatedPacket = 101;
6169 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6170 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6171 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6172 }
6173 EXPECT_FALSE(connection_.HasPendingAcks());
6174 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6175 // instead of ENCRYPTION_INITIAL.
6176 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6177 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6178 ENCRYPTION_ZERO_RTT);
6179
6180 // Check if delayed ack timer is running for the expected interval.
6181 EXPECT_TRUE(connection_.HasPendingAcks());
6182 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6183
6184 // 18 packets will not cause an ack to be sent. 19 will because when
6185 // stop waiting frames are in use, we ack every 20 packets no matter what.
6186 for (int i = 0; i < 18; ++i) {
6187 EXPECT_TRUE(connection_.HasPendingAcks());
6188 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6189 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6190 ENCRYPTION_ZERO_RTT);
6191 }
6192 // The delayed ack timer should still be set to the expected deadline.
6193 EXPECT_TRUE(connection_.HasPendingAcks());
6194 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6195}
6196
6197TEST_P(QuicConnectionTest, SendDelayedAckDecimationEighthRtt) {
6198 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame()).Times(AnyNumber());
6199 QuicConnectionPeer::SetAckDecimationDelay(&connection_, 0.125);
6200
6201 const size_t kMinRttMs = 40;
6202 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
6203 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
6204 QuicTime::Delta::Zero(), QuicTime::Zero());
6205 // The ack time should be based on min_rtt/8, since it's less than the
6206 // default delayed ack time.
6207 QuicTime ack_time = clock_.ApproximateNow() +
6208 QuicTime::Delta::FromMilliseconds(kMinRttMs / 8);
6209 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6210 EXPECT_FALSE(connection_.HasPendingAcks());
6211 const uint8_t tag = 0x07;
6212 SetDecrypter(ENCRYPTION_ZERO_RTT,
6213 std::make_unique<StrictTaggingDecrypter>(tag));
6214 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
6215 std::make_unique<TaggingEncrypter>(tag));
6216 // Process a packet from the non-crypto stream.
6217 frame1_.stream_id = 3;
6218
6219 // Process all the initial packets in order so there aren't missing packets.
6220 uint64_t kFirstDecimatedPacket = 101;
6221 for (unsigned int i = 0; i < kFirstDecimatedPacket - 1; ++i) {
6222 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6223 ProcessDataPacketAtLevel(1 + i, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
6224 }
6225 EXPECT_FALSE(connection_.HasPendingAcks());
6226 // The same as ProcessPacket(1) except that ENCRYPTION_ZERO_RTT is used
6227 // instead of ENCRYPTION_INITIAL.
6228 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6229 ProcessDataPacketAtLevel(kFirstDecimatedPacket, !kHasStopWaiting,
6230 ENCRYPTION_ZERO_RTT);
6231
6232 // Check if delayed ack timer is running for the expected interval.
6233 EXPECT_TRUE(connection_.HasPendingAcks());
6234 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6235
6236 // The 10th received packet causes an ack to be sent.
6237 for (int i = 0; i < 9; ++i) {
6238 EXPECT_TRUE(connection_.HasPendingAcks());
6239 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
6240 ProcessDataPacketAtLevel(kFirstDecimatedPacket + 1 + i, !kHasStopWaiting,
6241 ENCRYPTION_ZERO_RTT);
6242 }
6243 // Check that ack is sent and that delayed ack alarm is reset.
6244 size_t padding_frame_count = writer_->padding_frames().size();
6245 if (GetParam().no_stop_waiting) {
6246 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6247 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6248 } else {
6249 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6250 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6251 }
6252 EXPECT_FALSE(writer_->ack_frames().empty());
6253 EXPECT_FALSE(connection_.HasPendingAcks());
6254}
6255
6256TEST_P(QuicConnectionTest, SendDelayedAckOnHandshakeConfirmed) {
6257 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6258 ProcessPacket(1);
6259 // Check that ack is sent and that delayed ack alarm is set.
6260 EXPECT_TRUE(connection_.HasPendingAcks());
6261 QuicTime ack_time = clock_.ApproximateNow() + DefaultDelayedAckTime();
6262 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6263
6264 // Completing the handshake as the server does nothing.
6265 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER);
6266 connection_.OnHandshakeComplete();
6267 EXPECT_TRUE(connection_.HasPendingAcks());
6268 EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
6269
6270 // Complete the handshake as the client decreases the delayed ack time to 0ms.
6271 QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT);
6272 connection_.OnHandshakeComplete();
6273 EXPECT_TRUE(connection_.HasPendingAcks());
6274 if (connection_.SupportsMultiplePacketNumberSpaces()) {
6275 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
6276 connection_.GetAckAlarm()->deadline());
6277 } else {
6278 EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline());
6279 }
6280}
6281
6282TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
6283 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6284 ProcessPacket(1);
6285 ProcessPacket(2);
6286 // Check that ack is sent and that delayed ack alarm is reset.
6287 size_t padding_frame_count = writer_->padding_frames().size();
6288 if (GetParam().no_stop_waiting) {
6289 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
6290 EXPECT_TRUE(writer_->stop_waiting_frames().empty());
6291 } else {
6292 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
6293 EXPECT_FALSE(writer_->stop_waiting_frames().empty());
6294 }
6295 EXPECT_FALSE(writer_->ack_frames().empty());
6296 EXPECT_FALSE(connection_.HasPendingAcks());
6297}
6298
6299TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
6300 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6301 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6302 ProcessPacket(2);
6303 size_t frames_per_ack = GetParam().no_stop_waiting ? 1 : 2;
6304
6305 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6306 ProcessPacket(3);
6307 size_t padding_frame_count = writer_->padding_frames().size();
6308 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6309 EXPECT_FALSE(writer_->ack_frames().empty());
6310 writer_->Reset();
6311
6312 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6313 ProcessPacket(4);
6314 EXPECT_EQ(0u, writer_->frame_count());
6315
6316 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
6317 ProcessPacket(5);
6318 padding_frame_count = writer_->padding_frames().size();
6319 EXPECT_EQ(padding_frame_count + frames_per_ack, writer_->frame_count());
6320 EXPECT_FALSE(writer_->ack_frames().empty());
6321 writer_->Reset();
6322
6323 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
6324 // Now only set the timer on the 6th packet, instead of sending another ack.
6325 ProcessPacket(6);
6326 padding_frame_count = writer_->padding_frames().size();
6327 EXPECT_EQ(padding_frame_count, writer_->frame_count());
6328 EXPECT_TRUE(connection_.HasPendingAcks());
6329}
6330
6331TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
6332 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
6333 EXPECT_CALL(visitor_, OnStreamFrame(_));
6334 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
6335 std::make_unique<TaggingEncrypter>(0x01));
6336 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
6337 std::make_unique<StrictTaggingDecrypter>(0x01));
6338 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());
7163
7164 const char data[] = "data";
7165 size_t data_size = strlen(data);
7166 QuicStreamOffset offset = 0;
7167
7168 for (int i = 0; i < 2; ++i) {
7169 // Send a packet. Now there's a retransmittable packet on the wire, so the
7170 // path degrading detection should be set.
7171 connection_.SendStreamDataWithString(
7172 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7173 offset, NO_FIN);
7174 offset += data_size;
7175 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7176 // Check the deadline of the path degrading detection.
7177 QuicTime::Delta delay =
7178 QuicConnectionPeer::GetSentPacketManager(&connection_)
7179 ->GetPathDegradingDelay();
7180 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7181 clock_.ApproximateNow());
7182
7183 // Send a second packet. The path degrading detection's deadline should
7184 // remain the same.
7185 // Regression test for b/69979024.
7186 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7187 QuicTime prev_deadline =
7188 connection_.GetBlackholeDetectorAlarm()->deadline();
7189 connection_.SendStreamDataWithString(
7190 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
7191 offset, NO_FIN);
7192 offset += data_size;
7193 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7194 EXPECT_EQ(prev_deadline,
7195 connection_.GetBlackholeDetectorAlarm()->deadline());
7196
7197 // Now receive an ACK of the first packet. This should advance the path
7198 // degrading detection's deadline since forward progress has been made.
7199 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7200 if (i == 0) {
7201 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7202 }
7203 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7204 QuicAckFrame frame = InitAckFrame(
7205 {{QuicPacketNumber(1u + 2u * i), QuicPacketNumber(2u + 2u * i)}});
7206 ProcessAckPacket(&frame);
7207 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7208 // Check the deadline of the path degrading detection.
7209 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7210 ->GetPathDegradingDelay();
7211 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7212 clock_.ApproximateNow());
7213
7214 if (i == 0) {
7215 // Now receive an ACK of the second packet. Since there are no more
7216 // retransmittable packets on the wire, this should cancel the path
7217 // degrading detection.
7218 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7219 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7220 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7221 ProcessAckPacket(&frame);
7222 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7223 } else {
7224 // Advance time to the path degrading alarm's deadline and simulate
7225 // firing the alarm.
7226 clock_.AdvanceTime(delay);
7227 EXPECT_CALL(visitor_, OnPathDegrading());
7228 connection_.PathDegradingTimeout();
7229 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7230 }
7231 }
7232 EXPECT_TRUE(connection_.IsPathDegrading());
7233}
7234
7235TEST_P(QuicConnectionTest, RetransmittableOnWireSetsPingAlarm) {
7236 const QuicTime::Delta retransmittable_on_wire_timeout =
7237 QuicTime::Delta::FromMilliseconds(50);
7238 connection_.set_initial_retransmittable_on_wire_timeout(
7239 retransmittable_on_wire_timeout);
7240
7241 EXPECT_TRUE(connection_.connected());
7242 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7243 .WillRepeatedly(Return(true));
7244
7245 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7246 EXPECT_FALSE(connection_.IsPathDegrading());
7247 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7248
7249 const char data[] = "data";
7250 size_t data_size = strlen(data);
7251 QuicStreamOffset offset = 0;
7252
7253 // Send a packet.
7254 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7255 offset += data_size;
7256 // Now there's a retransmittable packet on the wire, so the path degrading
7257 // alarm should be set.
7258 // The retransmittable-on-wire alarm should not be set.
7259 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7260 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7261 ->GetPathDegradingDelay();
7262 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7263 clock_.ApproximateNow());
7264 ASSERT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7265 // The ping alarm is set for the ping timeout, not the shorter
7266 // retransmittable_on_wire_timeout.
7267 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7268 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7269 EXPECT_EQ(ping_delay,
7270 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7271
7272 // Now receive an ACK of the packet.
7273 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7274 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7275 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7276 QuicAckFrame frame =
7277 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7278 ProcessAckPacket(&frame);
7279 // No more retransmittable packets on the wire, so the path degrading alarm
7280 // should be cancelled, and the ping alarm should be set to the
7281 // retransmittable_on_wire_timeout.
7282 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7283 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7284 EXPECT_EQ(retransmittable_on_wire_timeout,
7285 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7286
7287 // Simulate firing the ping alarm and sending a PING.
7288 clock_.AdvanceTime(retransmittable_on_wire_timeout);
7289 connection_.GetPingAlarm()->Fire();
7290
7291 // Now there's a retransmittable packet (PING) on the wire, so the path
7292 // degrading alarm should be set.
7293 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7294 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7295 ->GetPathDegradingDelay();
7296 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7297 clock_.ApproximateNow());
7298}
7299
7300TEST_P(QuicConnectionTest, ServerRetransmittableOnWire) {
7301 set_perspective(Perspective::IS_SERVER);
7302 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7303 SetQuicReloadableFlag(quic_enable_server_on_wire_ping, true);
7304
7305 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7306 QuicConfig config;
7307 QuicTagVector connection_options;
7308 connection_options.push_back(kSRWP);
7309 config.SetInitialReceivedConnectionOptions(connection_options);
7310 connection_.SetFromConfig(config);
7311
7312 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7313 .WillRepeatedly(Return(true));
7314
7315 ProcessPacket(1);
7316
7317 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7318 QuicTime::Delta ping_delay = QuicTime::Delta::FromMilliseconds(200);
7319 EXPECT_EQ(ping_delay,
7320 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7321
7322 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
7323 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
7324 // Verify PING alarm gets cancelled.
7325 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7326
7327 // Now receive an ACK of the packet.
7328 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
7329 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7330 QuicAckFrame frame =
7331 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7332 ProcessAckPacket(2, &frame);
7333 // Verify PING alarm gets scheduled.
7334 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7335 EXPECT_EQ(ping_delay,
7336 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7337}
7338
fayangf6607db2022-04-21 18:10:41 -07007339TEST_P(QuicConnectionTest, RetransmittableOnWireSendFirstPacket) {
fayang327663d2022-05-10 18:25:36 -07007340 if (!GetQuicReloadableFlag(quic_use_ping_manager2) ||
fayangf6607db2022-04-21 18:10:41 -07007341 !VersionHasIetfQuicFrames(connection_.version().transport_version)) {
7342 return;
7343 }
7344 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7345 .WillRepeatedly(Return(true));
7346 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7347
7348 const QuicTime::Delta kRetransmittableOnWireTimeout =
7349 QuicTime::Delta::FromMilliseconds(200);
7350 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7351
7352 connection_.set_initial_retransmittable_on_wire_timeout(
7353 kRetransmittableOnWireTimeout);
7354
7355 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7356 QuicConfig config;
7357 QuicTagVector connection_options;
7358 connection_options.push_back(kROWF);
7359 config.SetClientConnectionOptions(connection_options);
7360 connection_.SetFromConfig(config);
7361
7362 // Send a request.
7363 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7364 // Receive an ACK after 1-RTT.
7365 clock_.AdvanceTime(kTestRtt);
7366 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7367 QuicAckFrame frame =
7368 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7369 ProcessAckPacket(&frame);
7370 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7371 EXPECT_EQ(kRetransmittableOnWireTimeout,
7372 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7373 EXPECT_EQ(1u, writer_->packets_write_attempts());
7374
7375 // Fire retransmittable-on-wire alarm.
7376 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7377 connection_.GetPingAlarm()->Fire();
7378 EXPECT_EQ(2u, writer_->packets_write_attempts());
7379 // Verify alarm is set in keep-alive mode.
7380 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7381 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7382 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7383}
7384
7385TEST_P(QuicConnectionTest, RetransmittableOnWireSendRandomBytes) {
fayang327663d2022-05-10 18:25:36 -07007386 if (!GetQuicReloadableFlag(quic_use_ping_manager2) ||
fayangf6607db2022-04-21 18:10:41 -07007387 !VersionHasIetfQuicFrames(connection_.version().transport_version)) {
7388 return;
7389 }
7390 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7391 .WillRepeatedly(Return(true));
7392 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7393
7394 const QuicTime::Delta kRetransmittableOnWireTimeout =
7395 QuicTime::Delta::FromMilliseconds(200);
7396 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7397
7398 connection_.set_initial_retransmittable_on_wire_timeout(
7399 kRetransmittableOnWireTimeout);
7400
7401 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7402 QuicConfig config;
7403 QuicTagVector connection_options;
7404 connection_options.push_back(kROWR);
7405 config.SetClientConnectionOptions(connection_options);
7406 connection_.SetFromConfig(config);
7407
7408 // Send a request.
7409 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7410 // Receive an ACK after 1-RTT.
7411 clock_.AdvanceTime(kTestRtt);
7412 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7413 QuicAckFrame frame =
7414 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7415 ProcessAckPacket(&frame);
7416 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7417 EXPECT_EQ(kRetransmittableOnWireTimeout,
7418 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7419 EXPECT_EQ(1u, writer_->packets_write_attempts());
7420
7421 // Fire retransmittable-on-wire alarm.
7422 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7423 // Next packet is not processable by the framer in the test writer.
7424 ExpectNextPacketUnprocessable();
7425 connection_.GetPingAlarm()->Fire();
7426 EXPECT_EQ(2u, writer_->packets_write_attempts());
7427 // Verify alarm is set in keep-alive mode.
7428 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7429 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
7430 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7431}
7432
7433TEST_P(QuicConnectionTest,
7434 RetransmittableOnWireSendRandomBytesWithWriterBlocked) {
fayang327663d2022-05-10 18:25:36 -07007435 if (!GetQuicReloadableFlag(quic_use_ping_manager2) ||
fayangf6607db2022-04-21 18:10:41 -07007436 !VersionHasIetfQuicFrames(connection_.version().transport_version)) {
7437 return;
7438 }
7439 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7440 .WillRepeatedly(Return(true));
7441 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7442 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7443
7444 const QuicTime::Delta kRetransmittableOnWireTimeout =
7445 QuicTime::Delta::FromMilliseconds(200);
7446 const QuicTime::Delta kTestRtt = QuicTime::Delta::FromMilliseconds(100);
7447
7448 connection_.set_initial_retransmittable_on_wire_timeout(
7449 kRetransmittableOnWireTimeout);
7450
7451 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7452 QuicConfig config;
7453 QuicTagVector connection_options;
7454 connection_options.push_back(kROWR);
7455 config.SetClientConnectionOptions(connection_options);
7456 connection_.SetFromConfig(config);
7457
7458 // Send a request.
7459 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7460 // Receive an ACK after 1-RTT.
7461 clock_.AdvanceTime(kTestRtt);
7462 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7463 QuicAckFrame frame =
7464 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
7465 ProcessAckPacket(&frame);
7466 ASSERT_TRUE(connection_.GetPingAlarm()->IsSet());
7467 EXPECT_EQ(kRetransmittableOnWireTimeout,
7468 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7469 EXPECT_EQ(1u, writer_->packets_write_attempts());
7470 // Receive an out of order data packet and block the ACK packet.
7471 BlockOnNextWrite();
7472 ProcessDataPacket(3);
7473 EXPECT_EQ(2u, writer_->packets_write_attempts());
7474 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7475
7476 // Fire retransmittable-on-wire alarm.
7477 clock_.AdvanceTime(kRetransmittableOnWireTimeout);
7478 connection_.GetPingAlarm()->Fire();
7479 // Verify the random bytes packet gets queued.
7480 EXPECT_EQ(2u, connection_.NumQueuedPackets());
7481}
7482
Bence Békybac04052022-04-07 15:44:29 -04007483// This test verifies that the connection marks path as degrading and does not
7484// spin timer to detect path degrading when a new packet is sent on the
7485// degraded path.
7486TEST_P(QuicConnectionTest, NoPathDegradingDetectionIfPathIsDegrading) {
7487 EXPECT_TRUE(connection_.connected());
7488 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7489 EXPECT_FALSE(connection_.IsPathDegrading());
7490
7491 const char data[] = "data";
7492 size_t data_size = strlen(data);
7493 QuicStreamOffset offset = 0;
7494
7495 // Send the first packet. Now there's a retransmittable packet on the wire, so
7496 // the path degrading alarm should be set.
7497 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7498 offset += data_size;
7499 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7500 // Check the deadline of the path degrading detection.
7501 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7502 ->GetPathDegradingDelay();
7503 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7504 clock_.ApproximateNow());
7505
7506 // Send a second packet. The path degrading detection's deadline should remain
7507 // the same.
7508 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7509 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7510 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7511 offset += data_size;
7512 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7513 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7514
7515 // Now receive an ACK of the first packet. This should advance the path
7516 // degrading detection's deadline since forward progress has been made.
7517 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7518 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7519 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7520 QuicAckFrame frame =
7521 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7522 ProcessAckPacket(&frame);
7523 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7524 // Check the deadline of the path degrading alarm.
7525 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7526 ->GetPathDegradingDelay();
7527 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7528 clock_.ApproximateNow());
7529
7530 // Advance time to the path degrading detection's deadline and simulate
7531 // firing the path degrading detection. This path will be considered as
7532 // degrading.
7533 clock_.AdvanceTime(delay);
7534 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7535 connection_.PathDegradingTimeout();
7536 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7537 EXPECT_TRUE(connection_.IsPathDegrading());
7538
7539 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7540 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7541 // Send a third packet. The path degrading detection is no longer set but path
7542 // should still be marked as degrading.
7543 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7544 offset += data_size;
7545 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7546 EXPECT_TRUE(connection_.IsPathDegrading());
7547}
7548
7549// This test verifies that the connection unmarks path as degrarding and spins
7550// the timer to detect future path degrading when forward progress is made
7551// after path has been marked degrading.
7552TEST_P(QuicConnectionTest, UnmarkPathDegradingOnForwardProgress) {
7553 EXPECT_TRUE(connection_.connected());
7554 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7555 EXPECT_FALSE(connection_.IsPathDegrading());
7556
7557 const char data[] = "data";
7558 size_t data_size = strlen(data);
7559 QuicStreamOffset offset = 0;
7560
7561 // Send the first packet. Now there's a retransmittable packet on the wire, so
7562 // the path degrading alarm should be set.
7563 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7564 offset += data_size;
7565 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7566 // Check the deadline of the path degrading alarm.
7567 QuicTime::Delta delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7568 ->GetPathDegradingDelay();
7569 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7570 clock_.ApproximateNow());
7571
7572 // Send a second packet. The path degrading alarm's deadline should remain
7573 // the same.
7574 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7575 QuicTime prev_deadline = connection_.GetBlackholeDetectorAlarm()->deadline();
7576 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7577 offset += data_size;
7578 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7579 EXPECT_EQ(prev_deadline, connection_.GetBlackholeDetectorAlarm()->deadline());
7580
7581 // Now receive an ACK of the first packet. This should advance the path
7582 // degrading alarm's deadline since forward progress has been made.
7583 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7584 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7585 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7586 QuicAckFrame frame =
7587 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7588 ProcessAckPacket(&frame);
7589 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7590 // Check the deadline of the path degrading alarm.
7591 delay = QuicConnectionPeer::GetSentPacketManager(&connection_)
7592 ->GetPathDegradingDelay();
7593 EXPECT_EQ(delay, connection_.GetBlackholeDetectorAlarm()->deadline() -
7594 clock_.ApproximateNow());
7595
7596 // Advance time to the path degrading alarm's deadline and simulate
7597 // firing the alarm.
7598 clock_.AdvanceTime(delay);
7599 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
7600 connection_.PathDegradingTimeout();
7601 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7602 EXPECT_TRUE(connection_.IsPathDegrading());
7603
7604 // Send a third packet. The path degrading alarm is no longer set but path
7605 // should still be marked as degrading.
7606 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7607 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7608 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7609 offset += data_size;
7610 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7611 EXPECT_TRUE(connection_.IsPathDegrading());
7612
7613 // Now receive an ACK of the second packet. This should unmark the path as
7614 // degrading. And will set a timer to detect new path degrading.
7615 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7616 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7617 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
7618 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
7619 ProcessAckPacket(&frame);
7620 EXPECT_FALSE(connection_.IsPathDegrading());
7621 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
7622}
7623
7624TEST_P(QuicConnectionTest, NoPathDegradingOnServer) {
7625 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7626 return;
7627 }
7628 set_perspective(Perspective::IS_SERVER);
7629 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
7630
7631 EXPECT_FALSE(connection_.IsPathDegrading());
7632 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7633
7634 // Send data.
7635 const char data[] = "data";
7636 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
7637 EXPECT_FALSE(connection_.IsPathDegrading());
7638 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7639
7640 // Ack data.
7641 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7642 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
7643 QuicAckFrame frame =
7644 InitAckFrame({{QuicPacketNumber(1u), QuicPacketNumber(2u)}});
7645 ProcessAckPacket(&frame);
7646 EXPECT_FALSE(connection_.IsPathDegrading());
7647 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7648}
7649
7650TEST_P(QuicConnectionTest, NoPathDegradingAfterSendingAck) {
7651 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7652 return;
7653 }
7654 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7655 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
7656 ProcessDataPacket(1);
7657 SendAckPacketToPeer();
7658 EXPECT_FALSE(connection_.sent_packet_manager().unacked_packets().empty());
7659 EXPECT_FALSE(connection_.sent_packet_manager().HasInFlightPackets());
7660 EXPECT_FALSE(connection_.IsPathDegrading());
7661 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
7662}
7663
7664TEST_P(QuicConnectionTest, MultipleCallsToCloseConnection) {
7665 // Verifies that multiple calls to CloseConnection do not
7666 // result in multiple attempts to close the connection - it will be marked as
7667 // disconnected after the first call.
7668 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
7669 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7670 ConnectionCloseBehavior::SILENT_CLOSE);
7671 connection_.CloseConnection(QUIC_NO_ERROR, "no reason",
7672 ConnectionCloseBehavior::SILENT_CLOSE);
7673}
7674
7675TEST_P(QuicConnectionTest, ServerReceivesChloOnNonCryptoStream) {
7676 set_perspective(Perspective::IS_SERVER);
7677 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
fayang161ce6e2022-07-01 18:02:11 -07007678 QuicConnectionPeer::SetAddressValidated(&connection_);
Bence Békybac04052022-04-07 15:44:29 -04007679
7680 CryptoHandshakeMessage message;
7681 CryptoFramer framer;
7682 message.set_tag(kCHLO);
7683 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7684 frame1_.stream_id = 10;
7685 frame1_.data_buffer = data->data();
7686 frame1_.data_length = data->length();
7687
7688 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7689 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7690 }
7691 EXPECT_CALL(visitor_,
7692 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7693 ForceProcessFramePacket(QuicFrame(frame1_));
7694 if (VersionHasIetfQuicFrames(version().transport_version)) {
7695 // INITIAL packet should not contain STREAM frame.
7696 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7697 } else {
7698 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7699 }
7700}
7701
7702TEST_P(QuicConnectionTest, ClientReceivesRejOnNonCryptoStream) {
7703 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7704
7705 CryptoHandshakeMessage message;
7706 CryptoFramer framer;
7707 message.set_tag(kREJ);
7708 std::unique_ptr<QuicData> data = framer.ConstructHandshakeMessage(message);
7709 frame1_.stream_id = 10;
7710 frame1_.data_buffer = data->data();
7711 frame1_.data_length = data->length();
7712
7713 EXPECT_CALL(visitor_,
7714 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
7715 ForceProcessFramePacket(QuicFrame(frame1_));
7716 if (VersionHasIetfQuicFrames(version().transport_version)) {
7717 // INITIAL packet should not contain STREAM frame.
7718 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
7719 } else {
7720 TestConnectionCloseQuicErrorCode(QUIC_MAYBE_CORRUPTED_MEMORY);
7721 }
7722}
7723
7724TEST_P(QuicConnectionTest, CloseConnectionOnPacketTooLarge) {
7725 SimulateNextPacketTooLarge();
7726 // A connection close packet is sent
7727 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7728 .Times(1);
7729 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7730 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7731}
7732
7733TEST_P(QuicConnectionTest, AlwaysGetPacketTooLarge) {
7734 // Test even we always get packet too large, we do not infinitely try to send
7735 // close packet.
7736 AlwaysGetPacketTooLarge();
7737 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7738 .Times(1);
7739 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7740 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7741}
7742
7743TEST_P(QuicConnectionTest, CloseConnectionOnQueuedWriteError) {
7744 // Regression test for crbug.com/979507.
7745 //
7746 // If we get a write error when writing queued packets, we should attempt to
7747 // send a connection close packet, but if sending that fails, it shouldn't get
7748 // queued.
7749
7750 // Queue a packet to write.
7751 BlockOnNextWrite();
7752 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7753 EXPECT_EQ(1u, connection_.NumQueuedPackets());
7754
7755 // Configure writer to always fail.
7756 AlwaysGetPacketTooLarge();
7757
7758 // Expect that we attempt to close the connection exactly once.
7759 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7760 .Times(1);
7761
7762 // Unblock the writes and actually send.
7763 writer_->SetWritable();
7764 connection_.OnCanWrite();
7765 EXPECT_EQ(0u, connection_.NumQueuedPackets());
7766
7767 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7768}
7769
7770// Verify that if connection has no outstanding data, it notifies the send
7771// algorithm after the write.
7772TEST_P(QuicConnectionTest, SendDataAndBecomeApplicationLimited) {
7773 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7774 {
7775 InSequence seq;
7776 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7777 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7778 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
7779 .WillRepeatedly(Return(false));
7780 }
7781
7782 connection_.SendStreamData3();
7783}
7784
7785// Verify that the connection does not become app-limited if there is
7786// outstanding data to send after the write.
7787TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedIfMoreDataAvailable) {
7788 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7789 {
7790 InSequence seq;
7791 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
7792 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7793 }
7794
7795 connection_.SendStreamData3();
7796}
7797
7798// Verify that the connection does not become app-limited after blocked write
7799// even if there is outstanding data to send after the write.
7800TEST_P(QuicConnectionTest, NotBecomeApplicationLimitedDueToWriteBlock) {
7801 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(0);
7802 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(true));
7803 BlockOnNextWrite();
7804
7805 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7806 connection_.SendStreamData3();
7807
7808 // Now unblock the writer, become congestion control blocked,
7809 // and ensure we become app-limited after writing.
7810 writer_->SetWritable();
7811 CongestionBlockWrites();
7812 EXPECT_CALL(visitor_, WillingAndAbleToWrite()).WillRepeatedly(Return(false));
7813 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
7814 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(1);
7815 connection_.OnCanWrite();
7816}
7817
Bence Békybac04052022-04-07 15:44:29 -04007818TEST_P(QuicConnectionTest, DoNotForceSendingAckOnPacketTooLarge) {
7819 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7820 // Send an ack by simulating delayed ack alarm firing.
7821 ProcessPacket(1);
7822 EXPECT_TRUE(connection_.HasPendingAcks());
7823 connection_.GetAckAlarm()->Fire();
7824 // Simulate data packet causes write error.
7825 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7826 SimulateNextPacketTooLarge();
7827 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7828 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7829 // Ack frame is not bundled in connection close packet.
7830 EXPECT_TRUE(writer_->ack_frames().empty());
7831 if (writer_->padding_frames().empty()) {
7832 EXPECT_EQ(1u, writer_->frame_count());
7833 } else {
7834 EXPECT_EQ(2u, writer_->frame_count());
7835 }
7836
7837 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7838}
7839
7840TEST_P(QuicConnectionTest, CloseConnectionAllLevels) {
7841 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7842 return;
7843 }
7844
7845 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7846 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7847 connection_.CloseConnection(
7848 kQuicErrorCode, "Some random error message",
7849 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7850
7851 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7852
7853 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7854 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7855
7856 if (!connection_.version().CanSendCoalescedPackets()) {
7857 // Each connection close packet should be sent in distinct UDP packets.
7858 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7859 writer_->connection_close_packets());
7860 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
7861 writer_->packets_write_attempts());
7862 return;
7863 }
7864
7865 // A single UDP packet should be sent with multiple connection close packets
7866 // coalesced together.
7867 EXPECT_EQ(1u, writer_->packets_write_attempts());
7868
7869 // Only the first packet has been processed yet.
7870 EXPECT_EQ(1u, writer_->connection_close_packets());
7871
7872 // ProcessPacket resets the visitor and frees the coalesced packet.
7873 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
7874 auto packet = writer_->coalesced_packet()->Clone();
7875 writer_->framer()->ProcessPacket(*packet);
7876 EXPECT_EQ(1u, writer_->connection_close_packets());
7877 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7878}
7879
7880TEST_P(QuicConnectionTest, CloseConnectionOneLevel) {
7881 if (connection_.SupportsMultiplePacketNumberSpaces()) {
7882 return;
7883 }
7884
7885 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7886 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7887 connection_.CloseConnection(
7888 kQuicErrorCode, "Some random error message",
7889 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7890
7891 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7892
7893 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7894 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7895 EXPECT_EQ(1u, writer_->connection_close_packets());
7896 EXPECT_EQ(1u, writer_->packets_write_attempts());
7897 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
7898}
7899
7900TEST_P(QuicConnectionTest, DoNotPadServerInitialConnectionClose) {
7901 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
7902 return;
7903 }
7904 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -07007905 // Receives packet 1000 in initial data.
7906 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
7907 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -04007908
7909 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
7910 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
7911 }
7912 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
7913 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
7914 connection_.CloseConnection(
7915 kQuicErrorCode, "Some random error message",
7916 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
7917
7918 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
7919
7920 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
7921 EXPECT_EQ(1u, writer_->connection_close_frames().size());
7922 EXPECT_TRUE(writer_->padding_frames().empty());
7923 EXPECT_EQ(ENCRYPTION_INITIAL, writer_->framer()->last_decrypted_level());
7924}
7925
7926// Regression test for b/63620844.
7927TEST_P(QuicConnectionTest, FailedToWriteHandshakePacket) {
7928 SimulateNextPacketTooLarge();
7929 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
7930 .Times(1);
7931
7932 connection_.SendCryptoStreamData();
7933 TestConnectionCloseQuicErrorCode(QUIC_PACKET_WRITE_ERROR);
7934}
7935
7936TEST_P(QuicConnectionTest, MaxPacingRate) {
7937 EXPECT_EQ(0, connection_.MaxPacingRate().ToBytesPerSecond());
7938 connection_.SetMaxPacingRate(QuicBandwidth::FromBytesPerSecond(100));
7939 EXPECT_EQ(100, connection_.MaxPacingRate().ToBytesPerSecond());
7940}
7941
7942TEST_P(QuicConnectionTest, ClientAlwaysSendConnectionId) {
7943 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
7944 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7945 connection_.SendStreamDataWithString(3, "foo", 0, NO_FIN);
7946 EXPECT_EQ(CONNECTION_ID_PRESENT,
7947 writer_->last_packet_header().destination_connection_id_included);
7948
7949 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
7950 QuicConfig config;
7951 QuicConfigPeer::SetReceivedBytesForConnectionId(&config, 0);
7952 connection_.SetFromConfig(config);
7953
7954 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
7955 connection_.SendStreamDataWithString(3, "bar", 3, NO_FIN);
7956 // Verify connection id is still sent in the packet.
7957 EXPECT_EQ(CONNECTION_ID_PRESENT,
7958 writer_->last_packet_header().destination_connection_id_included);
7959}
7960
Bence Békybac04052022-04-07 15:44:29 -04007961TEST_P(QuicConnectionTest, PingAfterLastRetransmittablePacketAcked) {
7962 const QuicTime::Delta retransmittable_on_wire_timeout =
7963 QuicTime::Delta::FromMilliseconds(50);
7964 connection_.set_initial_retransmittable_on_wire_timeout(
7965 retransmittable_on_wire_timeout);
7966
7967 EXPECT_TRUE(connection_.connected());
7968 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
7969 .WillRepeatedly(Return(true));
7970
7971 const char data[] = "data";
7972 size_t data_size = strlen(data);
7973 QuicStreamOffset offset = 0;
7974
7975 // Advance 5ms, send a retransmittable packet to the peer.
7976 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7977 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
7978 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7979 offset += data_size;
7980 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
7981 // The ping alarm is set for the ping timeout, not the shorter
7982 // retransmittable_on_wire_timeout.
7983 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7984 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
7985 EXPECT_EQ(ping_delay,
7986 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
7987
7988 // Advance 5ms, send a second retransmittable packet to the peer.
7989 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7990 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7991 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
7992 offset += data_size;
7993 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
7994
7995 // Now receive an ACK of the first packet. This should not set the
7996 // retransmittable-on-wire alarm since packet 2 is still on the wire.
7997 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
7998 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
7999 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8000 QuicAckFrame frame =
8001 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8002 ProcessAckPacket(&frame);
8003 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8004 // The ping alarm is set for the ping timeout, not the shorter
8005 // retransmittable_on_wire_timeout.
8006 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8007 // The ping alarm has a 1 second granularity, and the clock has been advanced
8008 // 10ms since it was originally set.
8009 EXPECT_EQ(ping_delay - QuicTime::Delta::FromMilliseconds(10),
8010 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8011
8012 // Now receive an ACK of the second packet. This should set the
8013 // retransmittable-on-wire alarm now that no retransmittable packets are on
8014 // the wire.
8015 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8016 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8017 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8018 ProcessAckPacket(&frame);
8019 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8020 EXPECT_EQ(retransmittable_on_wire_timeout,
8021 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8022
8023 // Now receive a duplicate ACK of the second packet. This should not update
8024 // the ping alarm.
8025 QuicTime prev_deadline = connection_.GetPingAlarm()->deadline();
8026 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8027 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8028 ProcessAckPacket(&frame);
8029 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8030 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8031
8032 // Now receive a non-ACK packet. This should not update the ping alarm.
8033 prev_deadline = connection_.GetPingAlarm()->deadline();
8034 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8035 ProcessPacket(4);
8036 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8037 EXPECT_EQ(prev_deadline, connection_.GetPingAlarm()->deadline());
8038
8039 // Simulate the alarm firing and check that a PING is sent.
8040 connection_.GetPingAlarm()->Fire();
8041 size_t padding_frame_count = writer_->padding_frames().size();
8042 if (GetParam().no_stop_waiting) {
8043 EXPECT_EQ(padding_frame_count + 2u, writer_->frame_count());
8044 } else {
8045 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
8046 }
8047 ASSERT_EQ(1u, writer_->ping_frames().size());
8048}
8049
8050TEST_P(QuicConnectionTest, NoPingIfRetransmittablePacketSent) {
8051 const QuicTime::Delta retransmittable_on_wire_timeout =
8052 QuicTime::Delta::FromMilliseconds(50);
8053 connection_.set_initial_retransmittable_on_wire_timeout(
8054 retransmittable_on_wire_timeout);
8055
8056 EXPECT_TRUE(connection_.connected());
8057 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8058 .WillRepeatedly(Return(true));
8059
8060 const char data[] = "data";
8061 size_t data_size = strlen(data);
8062 QuicStreamOffset offset = 0;
8063
8064 // Advance 5ms, send a retransmittable packet to the peer.
8065 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8066 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8067 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8068 offset += data_size;
8069 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8070 // The ping alarm is set for the ping timeout, not the shorter
8071 // retransmittable_on_wire_timeout.
8072 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8073 QuicTime::Delta ping_delay = QuicTime::Delta::FromSeconds(kPingTimeoutSecs);
8074 EXPECT_EQ(ping_delay,
8075 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8076
8077 // Now receive an ACK of the first packet. This should set the
8078 // retransmittable-on-wire alarm now that no retransmittable packets are on
8079 // the wire.
8080 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8081 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8082 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8083 QuicAckFrame frame =
8084 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8085 ProcessAckPacket(&frame);
8086 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8087 EXPECT_EQ(retransmittable_on_wire_timeout,
8088 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8089
8090 // Before the alarm fires, send another retransmittable packet. This should
8091 // cancel the retransmittable-on-wire alarm since now there's a
8092 // retransmittable packet on the wire.
8093 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8094 offset += data_size;
8095 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8096
8097 // Now receive an ACK of the second packet. This should set the
8098 // retransmittable-on-wire alarm now that no retransmittable packets are on
8099 // the wire.
8100 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8101 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8102 frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
8103 ProcessAckPacket(&frame);
8104 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8105 EXPECT_EQ(retransmittable_on_wire_timeout,
8106 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8107
8108 // Simulate the alarm firing and check that a PING is sent.
8109 writer_->Reset();
8110 connection_.GetPingAlarm()->Fire();
8111 size_t padding_frame_count = writer_->padding_frames().size();
8112 if (GetParam().no_stop_waiting) {
8113 // Do not ACK acks.
8114 EXPECT_EQ(padding_frame_count + 1u, writer_->frame_count());
8115 } else {
8116 EXPECT_EQ(padding_frame_count + 3u, writer_->frame_count());
8117 }
8118 ASSERT_EQ(1u, writer_->ping_frames().size());
8119}
8120
8121// When there is no stream data received but are open streams, send the
8122// first few consecutive pings with aggressive retransmittable-on-wire
8123// timeout. Exponentially back off the retransmittable-on-wire ping timeout
8124// afterwards until it exceeds the default ping timeout.
8125TEST_P(QuicConnectionTest, BackOffRetransmittableOnWireTimeout) {
8126 int max_aggressive_retransmittable_on_wire_ping_count = 5;
birenroyef686222022-09-12 11:34:34 -07008127 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008128 max_aggressive_retransmittable_on_wire_ping_count);
8129 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8130 QuicTime::Delta::FromMilliseconds(200);
8131 connection_.set_initial_retransmittable_on_wire_timeout(
8132 initial_retransmittable_on_wire_timeout);
8133
8134 EXPECT_TRUE(connection_.connected());
8135 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8136 .WillRepeatedly(Return(true));
8137
8138 const char data[] = "data";
8139 // Advance 5ms, send a retransmittable data packet to the peer.
8140 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8141 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8142 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8143 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8144 // The ping alarm is set for the ping timeout, not the shorter
8145 // retransmittable_on_wire_timeout.
8146 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008147 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008148 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8149
8150 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8151 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8152 .Times(AnyNumber());
8153
8154 // Verify that the first few consecutive retransmittable on wire pings are
8155 // sent with aggressive timeout.
8156 for (int i = 0; i <= max_aggressive_retransmittable_on_wire_ping_count; i++) {
8157 // Receive an ACK of the previous packet. This should set the ping alarm
8158 // with the initial retransmittable-on-wire timeout.
8159 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8160 QuicPacketNumber ack_num = creator_->packet_number();
8161 QuicAckFrame frame = InitAckFrame(
8162 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8163 ProcessAckPacket(&frame);
8164 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8165 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8166 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8167 // Simulate the alarm firing and check that a PING is sent.
8168 writer_->Reset();
8169 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8170 connection_.GetPingAlarm()->Fire();
8171 }
8172
8173 QuicTime::Delta retransmittable_on_wire_timeout =
8174 initial_retransmittable_on_wire_timeout;
8175
8176 // Verify subsequent pings are sent with timeout that is exponentially backed
8177 // off.
fayang5d393332022-04-18 13:34:54 -07008178 while (retransmittable_on_wire_timeout * 2 <
8179 QuicTime::Delta::FromSeconds(kPingTimeoutSecs)) {
Bence Békybac04052022-04-07 15:44:29 -04008180 // Receive an ACK for the previous PING. This should set the
8181 // ping alarm with backed off retransmittable-on-wire timeout.
8182 retransmittable_on_wire_timeout = retransmittable_on_wire_timeout * 2;
8183 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8184 QuicPacketNumber ack_num = creator_->packet_number();
8185 QuicAckFrame frame = InitAckFrame(
8186 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8187 ProcessAckPacket(&frame);
8188 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8189 EXPECT_EQ(retransmittable_on_wire_timeout,
8190 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8191
8192 // Simulate the alarm firing and check that a PING is sent.
8193 writer_->Reset();
8194 clock_.AdvanceTime(retransmittable_on_wire_timeout);
8195 connection_.GetPingAlarm()->Fire();
8196 }
8197
8198 // The ping alarm is set with default ping timeout.
8199 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008200 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008201 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8202
8203 // Receive an ACK for the previous PING. The ping alarm is set with an
8204 // earlier deadline.
8205 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8206 QuicPacketNumber ack_num = creator_->packet_number();
8207 QuicAckFrame frame = InitAckFrame(
8208 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8209 ProcessAckPacket(&frame);
8210 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008211 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs) -
8212 QuicTime::Delta::FromMilliseconds(5),
Bence Békybac04052022-04-07 15:44:29 -04008213 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8214}
8215
8216// This test verify that the count of consecutive aggressive pings is reset
8217// when new data is received. And it also verifies the connection resets
8218// the exponential back-off of the retransmittable-on-wire ping timeout
8219// after receiving new stream data.
8220TEST_P(QuicConnectionTest, ResetBackOffRetransmitableOnWireTimeout) {
8221 int max_aggressive_retransmittable_on_wire_ping_count = 3;
birenroyef686222022-09-12 11:34:34 -07008222 SetQuicFlag(quic_max_aggressive_retransmittable_on_wire_ping_count, 3);
Bence Békybac04052022-04-07 15:44:29 -04008223 const QuicTime::Delta initial_retransmittable_on_wire_timeout =
8224 QuicTime::Delta::FromMilliseconds(200);
8225 connection_.set_initial_retransmittable_on_wire_timeout(
8226 initial_retransmittable_on_wire_timeout);
8227
8228 EXPECT_TRUE(connection_.connected());
8229 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8230 .WillRepeatedly(Return(true));
8231 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8232 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8233 .Times(AnyNumber());
8234
8235 const char data[] = "data";
8236 // Advance 5ms, send a retransmittable data packet to the peer.
8237 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8238 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8239 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8240 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8241 // The ping alarm is set for the ping timeout, not the shorter
8242 // retransmittable_on_wire_timeout.
8243 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008244 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008245 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8246
8247 // Receive an ACK of the first packet. This should set the ping alarm with
8248 // initial retransmittable-on-wire timeout since there is no retransmittable
8249 // packet on the wire.
8250 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8251 QuicAckFrame frame =
8252 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(2)}});
8253 ProcessAckPacket(&frame);
8254 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8255 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8256 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8257
8258 // Simulate the alarm firing and check that a PING is sent.
8259 writer_->Reset();
8260 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8261 connection_.GetPingAlarm()->Fire();
8262
8263 // Receive an ACK for the previous PING. Ping alarm will be set with
8264 // aggressive timeout.
8265 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8266 QuicPacketNumber ack_num = creator_->packet_number();
8267 frame = InitAckFrame(
8268 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8269 ProcessAckPacket(&frame);
8270 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8271 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8272 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8273
8274 // Process a data packet.
8275 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8276 ProcessDataPacket(peer_creator_.packet_number() + 1);
8277 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8278 peer_creator_.packet_number() + 1);
8279 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8280 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
fayang327663d2022-05-10 18:25:36 -07008281 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8282 connection_.GetPingAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -04008283
8284 // Verify the count of consecutive aggressive pings is reset.
8285 for (int i = 0; i < max_aggressive_retransmittable_on_wire_ping_count; i++) {
8286 // Receive an ACK of the previous packet. This should set the ping alarm
8287 // with the initial retransmittable-on-wire timeout.
8288 QuicPacketNumber ack_num = creator_->packet_number();
8289 QuicAckFrame frame = InitAckFrame(
8290 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8291 ProcessAckPacket(&frame);
8292 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8293 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8294 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8295 // Simulate the alarm firing and check that a PING is sent.
8296 writer_->Reset();
8297 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8298 connection_.GetPingAlarm()->Fire();
8299 // Advance 5ms to receive next packet.
8300 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8301 }
8302
8303 // Receive another ACK for the previous PING. This should set the
8304 // ping alarm with backed off retransmittable-on-wire timeout.
8305 ack_num = creator_->packet_number();
8306 frame = InitAckFrame(
8307 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8308 ProcessAckPacket(&frame);
8309 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8310 EXPECT_EQ(initial_retransmittable_on_wire_timeout * 2,
8311 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8312
8313 writer_->Reset();
8314 clock_.AdvanceTime(2 * initial_retransmittable_on_wire_timeout);
8315 connection_.GetPingAlarm()->Fire();
8316
8317 // Process another data packet and a new ACK packet. The ping alarm is set
8318 // with aggressive ping timeout again.
8319 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8320 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8321 ProcessDataPacket(peer_creator_.packet_number() + 1);
8322 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_,
8323 peer_creator_.packet_number() + 1);
8324 ack_num = creator_->packet_number();
8325 frame = InitAckFrame(
8326 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8327 ProcessAckPacket(&frame);
8328 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8329 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8330 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8331}
8332
8333// Make sure that we never send more retransmissible on the wire pings than
8334// the limit in FLAGS_quic_max_retransmittable_on_wire_ping_count.
8335TEST_P(QuicConnectionTest, RetransmittableOnWirePingLimit) {
8336 static constexpr int kMaxRetransmittableOnWirePingCount = 3;
birenroyef686222022-09-12 11:34:34 -07008337 SetQuicFlag(quic_max_retransmittable_on_wire_ping_count,
Bence Békybac04052022-04-07 15:44:29 -04008338 kMaxRetransmittableOnWirePingCount);
8339 static constexpr QuicTime::Delta initial_retransmittable_on_wire_timeout =
8340 QuicTime::Delta::FromMilliseconds(200);
8341 static constexpr QuicTime::Delta short_delay =
8342 QuicTime::Delta::FromMilliseconds(5);
8343 ASSERT_LT(short_delay * 10, initial_retransmittable_on_wire_timeout);
8344 connection_.set_initial_retransmittable_on_wire_timeout(
8345 initial_retransmittable_on_wire_timeout);
8346
8347 EXPECT_TRUE(connection_.connected());
8348 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
8349 .WillRepeatedly(Return(true));
8350
8351 const char data[] = "data";
8352 // Advance 5ms, send a retransmittable data packet to the peer.
8353 clock_.AdvanceTime(short_delay);
8354 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
8355 connection_.SendStreamDataWithString(1, data, 0, NO_FIN);
8356 EXPECT_TRUE(connection_.sent_packet_manager().HasInFlightPackets());
8357 // The ping alarm is set for the ping timeout, not the shorter
8358 // retransmittable_on_wire_timeout.
8359 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008360 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008361 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8362
8363 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)).Times(AnyNumber());
8364 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _))
8365 .Times(AnyNumber());
8366
8367 // Verify that the first few consecutive retransmittable on wire pings are
8368 // sent with aggressive timeout.
8369 for (int i = 0; i <= kMaxRetransmittableOnWirePingCount; i++) {
8370 // Receive an ACK of the previous packet. This should set the ping alarm
8371 // with the initial retransmittable-on-wire timeout.
8372 clock_.AdvanceTime(short_delay);
8373 QuicPacketNumber ack_num = creator_->packet_number();
8374 QuicAckFrame frame = InitAckFrame(
8375 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8376 ProcessAckPacket(&frame);
8377 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
8378 EXPECT_EQ(initial_retransmittable_on_wire_timeout,
8379 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8380 // Simulate the alarm firing and check that a PING is sent.
8381 writer_->Reset();
8382 clock_.AdvanceTime(initial_retransmittable_on_wire_timeout);
8383 connection_.GetPingAlarm()->Fire();
8384 }
8385
8386 // Receive an ACK of the previous packet. This should set the ping alarm
8387 // but this time with the default ping timeout.
8388 QuicPacketNumber ack_num = creator_->packet_number();
8389 QuicAckFrame frame = InitAckFrame(
8390 {{QuicPacketNumber(ack_num), QuicPacketNumber(ack_num + 1)}});
8391 ProcessAckPacket(&frame);
8392 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
fayang5d393332022-04-18 13:34:54 -07008393 EXPECT_EQ(QuicTime::Delta::FromSeconds(kPingTimeoutSecs),
Bence Békybac04052022-04-07 15:44:29 -04008394 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
8395}
8396
8397TEST_P(QuicConnectionTest, ValidStatelessResetToken) {
8398 const StatelessResetToken kTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8399 0, 1, 0, 1, 0, 1, 0, 1};
8400 const StatelessResetToken kWrongTestToken{0, 1, 0, 1, 0, 1, 0, 1,
8401 0, 1, 0, 1, 0, 1, 0, 2};
8402 QuicConfig config;
8403 // No token has been received.
8404 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kTestToken));
8405
8406 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(2);
8407 // Token is different from received token.
8408 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8409 connection_.SetFromConfig(config);
8410 EXPECT_FALSE(connection_.IsValidStatelessResetToken(kWrongTestToken));
8411
8412 QuicConfigPeer::SetReceivedStatelessResetToken(&config, kTestToken);
8413 connection_.SetFromConfig(config);
8414 EXPECT_TRUE(connection_.IsValidStatelessResetToken(kTestToken));
8415}
8416
8417TEST_P(QuicConnectionTest, WriteBlockedWithInvalidAck) {
8418 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8419 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
8420 BlockOnNextWrite();
8421 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8422 connection_.SendStreamDataWithString(5, "foo", 0, FIN);
8423 // This causes connection to be closed because packet 1 has not been sent yet.
8424 QuicAckFrame frame = InitAckFrame(1);
8425 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
8426 ProcessAckPacket(1, &frame);
8427 EXPECT_EQ(0, connection_close_frame_count_);
8428}
8429
8430TEST_P(QuicConnectionTest, SendMessage) {
8431 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
8432 return;
8433 }
8434 if (connection_.version().UsesTls()) {
8435 QuicConfig config;
8436 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8437 &config, kMaxAcceptedDatagramFrameSize);
8438 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8439 connection_.SetFromConfig(config);
8440 }
8441 std::string message(connection_.GetCurrentLargestMessagePayload() * 2, 'a');
8442 quiche::QuicheMemSlice slice;
8443 {
8444 QuicConnection::ScopedPacketFlusher flusher(&connection_);
8445 connection_.SendStreamData3();
8446 // Send a message which cannot fit into current open packet, and 2 packets
8447 // get sent, one contains stream frame, and the other only contains the
8448 // message frame.
8449 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8450 slice = MemSliceFromString(absl::string_view(
8451 message.data(), connection_.GetCurrentLargestMessagePayload()));
8452 EXPECT_EQ(MESSAGE_STATUS_SUCCESS,
8453 connection_.SendMessage(1, absl::MakeSpan(&slice, 1), false));
8454 }
8455 // Fail to send a message if connection is congestion control blocked.
8456 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillOnce(Return(false));
8457 slice = MemSliceFromString("message");
8458 EXPECT_EQ(MESSAGE_STATUS_BLOCKED,
8459 connection_.SendMessage(2, absl::MakeSpan(&slice, 1), false));
8460
8461 // Always fail to send a message which cannot fit into one packet.
8462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8463 slice = MemSliceFromString(absl::string_view(
8464 message.data(), connection_.GetCurrentLargestMessagePayload() + 1));
8465 EXPECT_EQ(MESSAGE_STATUS_TOO_LARGE,
8466 connection_.SendMessage(3, absl::MakeSpan(&slice, 1), false));
8467}
8468
8469TEST_P(QuicConnectionTest, GetCurrentLargestMessagePayload) {
8470 if (!connection_.version().SupportsMessageFrames()) {
8471 return;
8472 }
8473 // Force use of this encrypter to simplify test expectations by making sure
8474 // that the encryption overhead is constant across versions.
8475 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8476 std::make_unique<TaggingEncrypter>(0x00));
martinduke225e91a2022-11-28 17:18:13 -08008477 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008478 if (connection_.version().SendsVariableLengthPacketNumberInLongHeader()) {
8479 expected_largest_payload += 3;
8480 }
8481 if (connection_.version().HasLongHeaderLengths()) {
8482 expected_largest_payload -= 2;
8483 }
8484 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8485 expected_largest_payload -= 1;
8486 }
8487 if (connection_.version().UsesTls()) {
8488 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8489 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8490 QuicConfig config;
8491 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8492 &config, kMaxAcceptedDatagramFrameSize);
8493 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8494 connection_.SetFromConfig(config);
8495 // Verify the value post-handshake.
8496 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8497 expected_largest_payload);
8498 } else {
8499 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(),
8500 expected_largest_payload);
8501 }
8502}
8503
8504TEST_P(QuicConnectionTest, GetGuaranteedLargestMessagePayload) {
8505 if (!connection_.version().SupportsMessageFrames()) {
8506 return;
8507 }
8508 // Force use of this encrypter to simplify test expectations by making sure
8509 // that the encryption overhead is constant across versions.
8510 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8511 std::make_unique<TaggingEncrypter>(0x00));
martinduke225e91a2022-11-28 17:18:13 -08008512 QuicPacketLength expected_largest_payload = 1215;
Bence Békybac04052022-04-07 15:44:29 -04008513 if (connection_.version().HasLongHeaderLengths()) {
8514 expected_largest_payload -= 2;
8515 }
8516 if (connection_.version().HasLengthPrefixedConnectionIds()) {
8517 expected_largest_payload -= 1;
8518 }
8519 if (connection_.version().UsesTls()) {
8520 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8521 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8522 QuicConfig config;
8523 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
8524 &config, kMaxAcceptedDatagramFrameSize);
8525 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8526 connection_.SetFromConfig(config);
8527 // Verify the value post-handshake.
8528 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8529 expected_largest_payload);
8530 } else {
8531 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8532 expected_largest_payload);
8533 }
8534}
8535
8536TEST_P(QuicConnectionTest, LimitedLargestMessagePayload) {
8537 if (!connection_.version().SupportsMessageFrames() ||
8538 !connection_.version().UsesTls()) {
8539 return;
8540 }
8541 constexpr QuicPacketLength kFrameSizeLimit = 1000;
8542 constexpr QuicPacketLength kPayloadSizeLimit =
8543 kFrameSizeLimit - kQuicFrameTypeSize;
8544 // QUIC+TLS disallows DATAGRAM/MESSAGE frames before the handshake.
8545 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), 0);
8546 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(), 0);
8547 QuicConfig config;
8548 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(&config, kFrameSizeLimit);
8549 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8550 connection_.SetFromConfig(config);
8551 // Verify the value post-handshake.
8552 EXPECT_EQ(connection_.GetCurrentLargestMessagePayload(), kPayloadSizeLimit);
8553 EXPECT_EQ(connection_.GetGuaranteedLargestMessagePayload(),
8554 kPayloadSizeLimit);
8555}
8556
8557// Test to check that the path challenge/path response logic works
8558// correctly. This test is only for version-99
8559TEST_P(QuicConnectionTest, ServerResponseToPathChallenge) {
8560 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8561 return;
8562 }
8563 PathProbeTestInit(Perspective::IS_SERVER);
8564 QuicConnectionPeer::SetAddressValidated(&connection_);
8565 // First check if the server can send probing packet.
8566 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8567
8568 // Create and send the probe request (PATH_CHALLENGE frame).
8569 // SendConnectivityProbingPacket ends up calling
8570 // TestPacketWriter::WritePacket() which in turns receives and parses the
8571 // packet by calling framer_.ProcessPacket() -- which in turn calls
8572 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8573 // the packet in writer_->path_challenge_frames()
8574 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8575 connection_.SendConnectivityProbingPacket(writer_.get(),
8576 connection_.peer_address());
8577 // Save the random contents of the challenge for later comparison to the
8578 // response.
8579 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8580 QuicPathFrameBuffer challenge_data =
8581 writer_->path_challenge_frames().front().data_buffer;
8582
8583 // Normally, QuicConnection::OnPathChallengeFrame and OnPaddingFrame would be
8584 // called and it will perform actions to ensure that the rest of the protocol
8585 // is performed.
8586 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8587 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8588 writer_->path_challenge_frames().front()));
8589 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8590 creator_->FlushCurrentPacket();
8591
8592 // The final check is to ensure that the random data in the response matches
8593 // the random data from the challenge.
8594 EXPECT_EQ(1u, writer_->path_response_frames().size());
8595 EXPECT_EQ(0, memcmp(&challenge_data,
8596 &(writer_->path_response_frames().front().data_buffer),
8597 sizeof(challenge_data)));
8598}
8599
8600TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnDefaulSocket) {
8601 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
8602 return;
8603 }
8604 PathProbeTestInit(Perspective::IS_CLIENT);
8605 // First check if the client can send probing packet.
8606 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8607
8608 // Create and send the probe request (PATH_CHALLENGE frame).
8609 // SendConnectivityProbingPacket ends up calling
8610 // TestPacketWriter::WritePacket() which in turns receives and parses the
8611 // packet by calling framer_.ProcessPacket() -- which in turn calls
8612 // SimpleQuicFramer::OnPathChallengeFrame(). SimpleQuicFramer saves
8613 // the packet in writer_->path_challenge_frames()
8614 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8615 connection_.SendConnectivityProbingPacket(writer_.get(),
8616 connection_.peer_address());
8617 // Save the random contents of the challenge for later validation against the
8618 // response.
8619 ASSERT_GE(writer_->path_challenge_frames().size(), 1u);
8620 QuicPathFrameBuffer challenge_data =
8621 writer_->path_challenge_frames().front().data_buffer;
8622
8623 // Normally, QuicConnection::OnPathChallengeFrame would be
8624 // called and it will perform actions to ensure that the rest of the protocol
8625 // is performed.
8626 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8627 EXPECT_TRUE(connection_.OnPathChallengeFrame(
8628 writer_->path_challenge_frames().front()));
8629 EXPECT_TRUE(connection_.OnPaddingFrame(writer_->padding_frames().front()));
8630 creator_->FlushCurrentPacket();
8631
8632 // The final check is to ensure that the random data in the response matches
8633 // the random data from the challenge.
8634 EXPECT_EQ(1u, writer_->path_response_frames().size());
8635 EXPECT_EQ(0, memcmp(&challenge_data,
8636 &(writer_->path_response_frames().front().data_buffer),
8637 sizeof(challenge_data)));
8638}
8639
8640TEST_P(QuicConnectionTest, ClientResponseToPathChallengeOnAlternativeSocket) {
danzh87605712022-04-11 14:36:39 -07008641 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -04008642 return;
8643 }
8644 PathProbeTestInit(Perspective::IS_CLIENT);
8645 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
8646
8647 QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8648 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8649 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8650 .Times(AtLeast(1u))
8651 .WillOnce(Invoke([&]() {
8652 EXPECT_EQ(1u, new_writer.packets_write_attempts());
8653 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
8654 EXPECT_EQ(1u, new_writer.padding_frames().size());
8655 EXPECT_EQ(kNewSelfAddress.host(),
8656 new_writer.last_write_source_address());
8657 }));
8658 bool success = false;
8659 connection_.ValidatePath(
8660 std::make_unique<TestQuicPathValidationContext>(
8661 kNewSelfAddress, connection_.peer_address(), &new_writer),
8662 std::make_unique<TestValidationResultDelegate>(
8663 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
8664
8665 // Receiving a PATH_CHALLENGE on the alternative path. Response to this
8666 // PATH_CHALLENGE should be sent via the alternative writer.
8667 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
8668 .Times(AtLeast(1u))
8669 .WillOnce(Invoke([&]() {
8670 EXPECT_EQ(2u, new_writer.packets_write_attempts());
8671 EXPECT_EQ(1u, new_writer.path_response_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 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8677 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8678 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8679 probing_packet->encrypted_length),
8680 clock_.Now()));
8681 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8682
8683 QuicSocketAddress kNewerSelfAddress(QuicIpAddress::Loopback6(),
8684 /*port=*/34567);
8685 // Receiving a PATH_CHALLENGE on an unknown socket should be ignored.
8686 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
8687 ProcessReceivedPacket(kNewerSelfAddress, kPeerAddress, *received);
8688}
8689
8690TEST_P(QuicConnectionTest,
8691 RestartPathDegradingDetectionAfterMigrationWithProbe) {
8692 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8693 PathProbeTestInit(Perspective::IS_CLIENT);
8694
8695 // Send data and verify the path degrading detection is set.
8696 const char data[] = "data";
8697 size_t data_size = strlen(data);
8698 QuicStreamOffset offset = 0;
8699 connection_.SendStreamDataWithString(1, data, offset, NO_FIN);
8700 offset += data_size;
8701
8702 // Verify the path degrading detection is in progress.
8703 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8704 EXPECT_FALSE(connection_.IsPathDegrading());
8705 QuicTime ddl = connection_.GetBlackholeDetectorAlarm()->deadline();
8706
8707 // Simulate the firing of path degrading.
8708 clock_.AdvanceTime(ddl - clock_.ApproximateNow());
8709 EXPECT_CALL(visitor_, OnPathDegrading()).Times(1);
8710 connection_.PathDegradingTimeout();
8711 EXPECT_TRUE(connection_.IsPathDegrading());
8712 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8713
8714 if (!GetParam().version.HasIetfQuicFrames()) {
8715 // Simulate path degrading handling by sending a probe on an alternet path.
8716 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
8717 TestPacketWriter probing_writer(version(), &clock_, Perspective::IS_CLIENT);
8718 connection_.SendConnectivityProbingPacket(&probing_writer,
8719 connection_.peer_address());
8720 // Verify that path degrading detection is not reset.
8721 EXPECT_FALSE(connection_.PathDegradingDetectionInProgress());
8722
8723 // Simulate successful path degrading handling by receiving probe response.
8724 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
8725
8726 EXPECT_CALL(visitor_,
8727 OnPacketReceived(_, _, /*is_connectivity_probe=*/true))
8728 .Times(1);
8729 const QuicSocketAddress kNewSelfAddress =
8730 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
8731
8732 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
8733 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
8734 QuicEncryptedPacket(probing_packet->encrypted_buffer,
8735 probing_packet->encrypted_length),
8736 clock_.Now()));
8737 uint64_t num_probing_received =
8738 connection_.GetStats().num_connectivity_probing_received;
8739 ProcessReceivedPacket(kNewSelfAddress, kPeerAddress, *received);
8740
8741 EXPECT_EQ(num_probing_received + 1,
8742 connection_.GetStats().num_connectivity_probing_received);
8743 EXPECT_EQ(kPeerAddress, connection_.peer_address());
8744 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
8745 EXPECT_TRUE(connection_.IsPathDegrading());
8746 }
8747
8748 // Verify new path degrading detection is activated.
8749 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading()).Times(1);
8750 connection_.OnSuccessfulMigration(/*is_port_change*/ true);
8751 EXPECT_FALSE(connection_.IsPathDegrading());
8752 EXPECT_TRUE(connection_.PathDegradingDetectionInProgress());
8753}
8754
8755TEST_P(QuicConnectionTest, ClientsResetCwndAfterConnectionMigration) {
8756 if (!GetParam().version.HasIetfQuicFrames()) {
8757 return;
8758 }
8759 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8760 PathProbeTestInit(Perspective::IS_CLIENT);
8761 EXPECT_EQ(kSelfAddress, connection_.self_address());
8762
8763 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
8764 QuicTime::Delta default_init_rtt = rtt_stats->initial_rtt();
8765 rtt_stats->set_initial_rtt(default_init_rtt * 2);
8766 EXPECT_EQ(2 * default_init_rtt, rtt_stats->initial_rtt());
8767
fayang339f0c82022-04-30 14:20:02 -07008768 QuicSentPacketManagerPeer::SetConsecutivePtoCount(manager_, 1);
8769 EXPECT_EQ(1u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008770 const SendAlgorithmInterface* send_algorithm = manager_->GetSendAlgorithm();
8771
8772 // Migrate to a new address with different IP.
8773 const QuicSocketAddress kNewSelfAddress =
8774 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
8775 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
8776 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
8777 &new_writer, false);
8778 EXPECT_EQ(default_init_rtt, manager_->GetRttStats()->initial_rtt());
fayang339f0c82022-04-30 14:20:02 -07008779 EXPECT_EQ(0u, manager_->GetConsecutivePtoCount());
Bence Békybac04052022-04-07 15:44:29 -04008780 EXPECT_NE(send_algorithm, manager_->GetSendAlgorithm());
8781}
8782
8783// Regression test for b/110259444
8784TEST_P(QuicConnectionTest, DoNotScheduleSpuriousAckAlarm) {
8785 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8786 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
8787 writer_->SetWriteBlocked();
8788
8789 ProcessPacket(1);
8790 // Verify ack alarm is set.
8791 EXPECT_TRUE(connection_.HasPendingAcks());
8792 // Fire the ack alarm, verify no packet is sent because the writer is blocked.
8793 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8794 connection_.GetAckAlarm()->Fire();
8795
8796 writer_->SetWritable();
8797 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
8798 ProcessPacket(2);
8799 // Verify ack alarm is not set.
8800 EXPECT_FALSE(connection_.HasPendingAcks());
8801}
8802
8803TEST_P(QuicConnectionTest, DisablePacingOffloadConnectionOptions) {
8804 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8805 writer_->set_supports_release_time(true);
8806 QuicConfig config;
8807 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8808 connection_.SetFromConfig(config);
8809 EXPECT_TRUE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8810
8811 QuicTagVector connection_options;
8812 connection_options.push_back(kNPCO);
8813 config.SetConnectionOptionsToSend(connection_options);
8814 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
8815 connection_.SetFromConfig(config);
8816 // Verify pacing offload is disabled.
8817 EXPECT_FALSE(QuicConnectionPeer::SupportsReleaseTime(&connection_));
8818}
8819
8820// Regression test for b/110259444
8821// Get a path response without having issued a path challenge...
8822TEST_P(QuicConnectionTest, OrphanPathResponse) {
8823 QuicPathFrameBuffer data = {{0, 1, 2, 3, 4, 5, 6, 7}};
8824
8825 QuicPathResponseFrame frame(99, data);
8826 EXPECT_TRUE(connection_.OnPathResponseFrame(frame));
8827 // If PATH_RESPONSE was accepted (payload matches the payload saved
8828 // in QuicConnection::transmitted_connectivity_probe_payload_) then
8829 // current_packet_content_ would be set to FIRST_FRAME_IS_PING.
8830 // Since this PATH_RESPONSE does not match, current_packet_content_
8831 // must not be FIRST_FRAME_IS_PING.
8832 EXPECT_NE(QuicConnection::FIRST_FRAME_IS_PING,
8833 QuicConnectionPeer::GetCurrentPacketContent(&connection_));
8834}
8835
8836// Regression test for b/120791670
8837TEST_P(QuicConnectionTest, StopProcessingGQuicPacketInIetfQuicConnection) {
8838 // This test mimics a problematic scenario where a QUIC connection using a
8839 // modern version received a Q043 packet and processed it incorrectly.
8840 // We can remove this test once Q043 is deprecated.
8841 if (!version().HasIetfInvariantHeader()) {
8842 return;
8843 }
8844 set_perspective(Perspective::IS_SERVER);
8845 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8846 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
8847 } else {
8848 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
8849 }
8850 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
8851 ENCRYPTION_INITIAL);
8852
8853 // Let connection process a Google QUIC packet.
8854 peer_framer_.set_version_for_tests(ParsedQuicVersion::Q043());
8855 std::unique_ptr<QuicPacket> packet(
8856 ConstructDataPacket(2, !kHasStopWaiting, ENCRYPTION_INITIAL));
8857 char buffer[kMaxOutgoingPacketSize];
8858 size_t encrypted_length =
8859 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
8860 *packet, buffer, kMaxOutgoingPacketSize);
8861 // Make sure no stream frame is processed.
8862 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
8863 connection_.ProcessUdpPacket(
8864 kSelfAddress, kPeerAddress,
8865 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
8866
8867 EXPECT_EQ(2u, connection_.GetStats().packets_received);
8868 EXPECT_EQ(1u, connection_.GetStats().packets_processed);
8869}
8870
8871TEST_P(QuicConnectionTest, AcceptPacketNumberZero) {
8872 if (!VersionHasIetfQuicFrames(version().transport_version)) {
8873 return;
8874 }
8875 // Set first_sending_packet_number to be 0 to allow successfully processing
8876 // acks which ack packet number 0.
8877 QuicFramerPeer::SetFirstSendingPacketNumber(writer_->framer()->framer(), 0);
8878 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8879
8880 ProcessPacket(0);
8881 EXPECT_EQ(QuicPacketNumber(0), LargestAcked(connection_.ack_frame()));
8882 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8883
8884 ProcessPacket(1);
8885 EXPECT_EQ(QuicPacketNumber(1), LargestAcked(connection_.ack_frame()));
8886 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8887
8888 ProcessPacket(2);
8889 EXPECT_EQ(QuicPacketNumber(2), LargestAcked(connection_.ack_frame()));
8890 EXPECT_EQ(1u, connection_.ack_frame().packets.NumIntervals());
8891}
8892
8893TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicSending) {
8894 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8895 return;
8896 }
8897 use_tagging_decrypter();
8898 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8899 std::make_unique<TaggingEncrypter>(0x01));
8900
8901 connection_.SendCryptoStreamData();
8902 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8903 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8904 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8905 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8906 QuicAckFrame frame1 = InitAckFrame(1);
8907 // Received ACK for packet 1.
8908 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8909
8910 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
8911 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8912 NO_FIN);
8913 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8914 NO_FIN);
8915 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8916 8, NO_FIN);
8917 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8918 12, FIN);
8919 // Received ACK for packets 2, 4, 5.
8920 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8921 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8922 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8923 QuicAckFrame frame2 =
8924 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
8925 {QuicPacketNumber(4), QuicPacketNumber(6)}});
8926 // Make sure although the same packet number is used, but they are in
8927 // different packet number spaces.
8928 ProcessFramePacketAtLevel(30, QuicFrame(&frame2), ENCRYPTION_FORWARD_SECURE);
8929}
8930
8931TEST_P(QuicConnectionTest, PeerAcksPacketsInWrongPacketNumberSpace) {
8932 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8933 return;
8934 }
8935 use_tagging_decrypter();
8936 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8937 std::make_unique<TaggingEncrypter>(0x01));
8938 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8939 std::make_unique<TaggingEncrypter>(0x01));
8940
8941 connection_.SendCryptoStreamData();
8942 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8943 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
8944 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
8945 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
8946 QuicAckFrame frame1 = InitAckFrame(1);
8947 // Received ACK for packet 1.
8948 ProcessFramePacketAtLevel(30, QuicFrame(&frame1), ENCRYPTION_INITIAL);
8949
8950 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8951 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 0,
8952 NO_FIN);
8953 connection_.SendApplicationDataAtLevel(ENCRYPTION_ZERO_RTT, 5, "data", 4,
8954 NO_FIN);
8955
8956 // Received ACK for packets 2 and 3 in wrong packet number space.
8957 QuicAckFrame invalid_ack =
8958 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(4)}});
8959 EXPECT_CALL(visitor_,
8960 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
8961 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
8962 ProcessFramePacketAtLevel(300, QuicFrame(&invalid_ack), ENCRYPTION_INITIAL);
8963 TestConnectionCloseQuicErrorCode(QUIC_INVALID_ACK_DATA);
8964}
8965
8966TEST_P(QuicConnectionTest, MultiplePacketNumberSpacesBasicReceiving) {
8967 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
8968 return;
8969 }
8970 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
8971 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
8972 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
8973 }
8974 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
8975 use_tagging_decrypter();
8976 // Receives packet 1000 in initial data.
8977 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
8978 EXPECT_TRUE(connection_.HasPendingAcks());
8979 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
8980 std::make_unique<TaggingEncrypter>(0x02));
8981 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
8982 std::make_unique<StrictTaggingDecrypter>(0x02));
8983 connection_.SetEncrypter(ENCRYPTION_INITIAL,
8984 std::make_unique<TaggingEncrypter>(0x02));
8985 // Receives packet 1000 in application data.
8986 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
8987 EXPECT_TRUE(connection_.HasPendingAcks());
8988 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
8989 0, NO_FIN);
8990 // Verify application data ACK gets bundled with outgoing data.
8991 EXPECT_EQ(2u, writer_->frame_count());
8992 // Make sure ACK alarm is still set because initial data is not ACKed.
8993 EXPECT_TRUE(connection_.HasPendingAcks());
8994 // Receive packet 1001 in application data.
8995 ProcessDataPacketAtLevel(1001, false, ENCRYPTION_FORWARD_SECURE);
8996 clock_.AdvanceTime(DefaultRetransmissionTime());
8997 // Simulates ACK alarm fires and verify two ACKs are flushed.
8998 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
8999 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9000 std::make_unique<TaggingEncrypter>(0x02));
9001 connection_.GetAckAlarm()->Fire();
9002 EXPECT_FALSE(connection_.HasPendingAcks());
9003 // Receives more packets in application data.
9004 ProcessDataPacketAtLevel(1002, false, ENCRYPTION_FORWARD_SECURE);
9005 EXPECT_TRUE(connection_.HasPendingAcks());
9006
9007 // Verify zero rtt and forward secure packets get acked in the same packet.
9008 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9009 ProcessDataPacket(1003);
9010 EXPECT_FALSE(connection_.HasPendingAcks());
9011}
9012
9013TEST_P(QuicConnectionTest, CancelAckAlarmOnWriteBlocked) {
9014 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
9015 return;
9016 }
9017 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9018 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9019 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9020 }
9021 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9022 use_tagging_decrypter();
9023 // Receives packet 1000 in initial data.
9024 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
9025 EXPECT_TRUE(connection_.HasPendingAcks());
9026 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
9027 std::make_unique<TaggingEncrypter>(0x02));
9028 SetDecrypter(ENCRYPTION_ZERO_RTT,
9029 std::make_unique<StrictTaggingDecrypter>(0x02));
9030 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9031 std::make_unique<TaggingEncrypter>(0x02));
9032 // Receives packet 1000 in application data.
9033 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
9034 EXPECT_TRUE(connection_.HasPendingAcks());
9035
9036 writer_->SetWriteBlocked();
9037 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
9038 // Simulates ACK alarm fires and verify no ACK is flushed because of write
9039 // blocked.
9040 clock_.AdvanceTime(DefaultDelayedAckTime());
9041 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9042 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9043 std::make_unique<TaggingEncrypter>(0x02));
9044 connection_.GetAckAlarm()->Fire();
9045 // Verify ACK alarm is not set.
9046 EXPECT_FALSE(connection_.HasPendingAcks());
9047
9048 writer_->SetWritable();
9049 // Verify 2 ACKs are sent when connection gets unblocked.
9050 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
9051 connection_.OnCanWrite();
9052 EXPECT_FALSE(connection_.HasPendingAcks());
9053}
9054
9055// Make sure a packet received with the right client connection ID is processed.
9056TEST_P(QuicConnectionTest, ValidClientConnectionId) {
9057 if (!framer_.version().SupportsClientConnectionIds()) {
9058 return;
9059 }
9060 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9061 SetClientConnectionId(TestConnectionId(0x33));
9062 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9063 header.destination_connection_id = TestConnectionId(0x33);
9064 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9065 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9066 QuicFrames frames;
9067 QuicPingFrame ping_frame;
9068 QuicPaddingFrame padding_frame;
9069 frames.push_back(QuicFrame(ping_frame));
9070 frames.push_back(QuicFrame(padding_frame));
9071 std::unique_ptr<QuicPacket> packet =
9072 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9073 char buffer[kMaxOutgoingPacketSize];
9074 size_t encrypted_length = peer_framer_.EncryptPayload(
9075 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9076 kMaxOutgoingPacketSize);
9077 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9078 false);
9079 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9080 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9081 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9082}
9083
9084// Make sure a packet received with a different client connection ID is dropped.
9085TEST_P(QuicConnectionTest, InvalidClientConnectionId) {
9086 if (!framer_.version().SupportsClientConnectionIds()) {
9087 return;
9088 }
9089 SetClientConnectionId(TestConnectionId(0x33));
9090 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_FORWARD_SECURE);
9091 header.destination_connection_id = TestConnectionId(0xbad);
9092 header.destination_connection_id_included = CONNECTION_ID_PRESENT;
9093 header.source_connection_id_included = CONNECTION_ID_ABSENT;
9094 QuicFrames frames;
9095 QuicPingFrame ping_frame;
9096 QuicPaddingFrame padding_frame;
9097 frames.push_back(QuicFrame(ping_frame));
9098 frames.push_back(QuicFrame(padding_frame));
9099 std::unique_ptr<QuicPacket> packet =
9100 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9101 char buffer[kMaxOutgoingPacketSize];
9102 size_t encrypted_length = peer_framer_.EncryptPayload(
9103 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(1), *packet, buffer,
9104 kMaxOutgoingPacketSize);
9105 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9106 false);
9107 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9108 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9109 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9110}
9111
9112// Make sure the first packet received with a different client connection ID on
9113// the server is processed and it changes the client connection ID.
9114TEST_P(QuicConnectionTest, UpdateClientConnectionIdFromFirstPacket) {
9115 if (!framer_.version().SupportsClientConnectionIds()) {
9116 return;
9117 }
9118 set_perspective(Perspective::IS_SERVER);
9119 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9120 header.source_connection_id = TestConnectionId(0x33);
9121 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9122 QuicFrames frames;
9123 QuicPingFrame ping_frame;
9124 QuicPaddingFrame padding_frame;
9125 frames.push_back(QuicFrame(ping_frame));
9126 frames.push_back(QuicFrame(padding_frame));
9127 std::unique_ptr<QuicPacket> packet =
9128 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9129 char buffer[kMaxOutgoingPacketSize];
9130 size_t encrypted_length =
9131 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9132 *packet, buffer, kMaxOutgoingPacketSize);
9133 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9134 false);
9135 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9136 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9137 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9138 EXPECT_EQ(TestConnectionId(0x33), connection_.client_connection_id());
9139}
9140void QuicConnectionTest::TestReplaceConnectionIdFromInitial() {
9141 if (!framer_.version().AllowsVariableLengthConnectionIds()) {
9142 return;
9143 }
9144 // We start with a known connection ID.
9145 EXPECT_TRUE(connection_.connected());
9146 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9147 EXPECT_NE(TestConnectionId(0x33), connection_.connection_id());
9148 // Receiving an initial can replace the connection ID once.
9149 {
9150 QuicPacketHeader header = ConstructPacketHeader(1, ENCRYPTION_INITIAL);
9151 header.source_connection_id = TestConnectionId(0x33);
9152 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9153 QuicFrames frames;
9154 QuicPingFrame ping_frame;
9155 QuicPaddingFrame padding_frame;
9156 frames.push_back(QuicFrame(ping_frame));
9157 frames.push_back(QuicFrame(padding_frame));
9158 std::unique_ptr<QuicPacket> packet =
9159 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9160 char buffer[kMaxOutgoingPacketSize];
9161 size_t encrypted_length =
9162 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(1),
9163 *packet, buffer, kMaxOutgoingPacketSize);
9164 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9165 false);
9166 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9167 }
9168 EXPECT_TRUE(connection_.connected());
9169 EXPECT_EQ(0u, connection_.GetStats().packets_dropped);
9170 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9171 // Trying to replace the connection ID a second time drops the packet.
9172 {
9173 QuicPacketHeader header = ConstructPacketHeader(2, ENCRYPTION_INITIAL);
9174 header.source_connection_id = TestConnectionId(0x66);
9175 header.source_connection_id_included = CONNECTION_ID_PRESENT;
9176 QuicFrames frames;
9177 QuicPingFrame ping_frame;
9178 QuicPaddingFrame padding_frame;
9179 frames.push_back(QuicFrame(ping_frame));
9180 frames.push_back(QuicFrame(padding_frame));
9181 std::unique_ptr<QuicPacket> packet =
9182 BuildUnsizedDataPacket(&peer_framer_, header, frames);
9183 char buffer[kMaxOutgoingPacketSize];
9184 size_t encrypted_length =
9185 peer_framer_.EncryptPayload(ENCRYPTION_INITIAL, QuicPacketNumber(2),
9186 *packet, buffer, kMaxOutgoingPacketSize);
9187 QuicReceivedPacket received_packet(buffer, encrypted_length, clock_.Now(),
9188 false);
9189 ProcessReceivedPacket(kSelfAddress, kPeerAddress, received_packet);
9190 }
9191 EXPECT_TRUE(connection_.connected());
9192 EXPECT_EQ(1u, connection_.GetStats().packets_dropped);
9193 EXPECT_EQ(TestConnectionId(0x33), connection_.connection_id());
9194}
9195
9196TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromInitial) {
9197 TestReplaceConnectionIdFromInitial();
9198}
9199
9200TEST_P(QuicConnectionTest, ReplaceServerConnectionIdFromRetryAndInitial) {
9201 // First make the connection process a RETRY and replace the server connection
9202 // ID a first time.
9203 TestClientRetryHandling(/*invalid_retry_tag=*/false,
9204 /*missing_original_id_in_config=*/false,
9205 /*wrong_original_id_in_config=*/false,
9206 /*missing_retry_id_in_config=*/false,
9207 /*wrong_retry_id_in_config=*/false);
9208 // Reset the test framer to use the right connection ID.
9209 peer_framer_.SetInitialObfuscators(connection_.connection_id());
9210 // Now process an INITIAL and replace the server connection ID a second time.
9211 TestReplaceConnectionIdFromInitial();
9212}
9213
9214// Regression test for b/134416344.
9215TEST_P(QuicConnectionTest, CheckConnectedBeforeFlush) {
9216 // This test mimics a scenario where a connection processes 2 packets and the
9217 // 2nd packet contains connection close frame. When the 2nd flusher goes out
9218 // of scope, a delayed ACK is pending, and ACK alarm should not be scheduled
9219 // because connection is disconnected.
9220 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9221 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9222 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
9223 const QuicErrorCode kErrorCode = QUIC_INTERNAL_ERROR;
9224 std::unique_ptr<QuicConnectionCloseFrame> connection_close_frame(
9225 new QuicConnectionCloseFrame(connection_.transport_version(), kErrorCode,
9226 NO_IETF_QUIC_ERROR, "",
9227 /*transport_close_frame_type=*/0));
9228
9229 // Received 2 packets.
9230 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9231 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9232 } else {
9233 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
9234 }
9235 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
9236 ENCRYPTION_INITIAL);
9237 EXPECT_TRUE(connection_.HasPendingAcks());
9238 ProcessFramePacketWithAddresses(QuicFrame(connection_close_frame.release()),
9239 kSelfAddress, kPeerAddress,
9240 ENCRYPTION_INITIAL);
9241 // Verify ack alarm is not set.
9242 EXPECT_FALSE(connection_.HasPendingAcks());
9243}
9244
9245// Verify that a packet containing three coalesced packets is parsed correctly.
9246TEST_P(QuicConnectionTest, CoalescedPacket) {
9247 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9248 // Coalesced packets can only be encoded using long header lengths.
9249 return;
9250 }
9251 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9252 EXPECT_TRUE(connection_.connected());
9253 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9254 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(3);
9255 } else {
9256 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(3);
9257 }
9258
9259 uint64_t packet_numbers[3] = {1, 2, 3};
9260 EncryptionLevel encryption_levels[3] = {
9261 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9262 char buffer[kMaxOutgoingPacketSize] = {};
9263 size_t total_encrypted_length = 0;
9264 for (int i = 0; i < 3; i++) {
9265 QuicPacketHeader header =
9266 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9267 QuicFrames frames;
9268 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9269 frames.push_back(QuicFrame(&crypto_frame_));
9270 } else {
9271 frames.push_back(QuicFrame(frame1_));
9272 }
9273 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9274 peer_creator_.set_encryption_level(encryption_levels[i]);
9275 size_t encrypted_length = peer_framer_.EncryptPayload(
9276 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9277 buffer + total_encrypted_length,
9278 sizeof(buffer) - total_encrypted_length);
9279 EXPECT_GT(encrypted_length, 0u);
9280 total_encrypted_length += encrypted_length;
9281 }
9282 connection_.ProcessUdpPacket(
9283 kSelfAddress, kPeerAddress,
9284 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9285 if (connection_.GetSendAlarm()->IsSet()) {
9286 connection_.GetSendAlarm()->Fire();
9287 }
9288
9289 EXPECT_TRUE(connection_.connected());
9290}
9291
9292// Regression test for crbug.com/992831.
9293TEST_P(QuicConnectionTest, CoalescedPacketThatSavesFrames) {
9294 if (!QuicVersionHasLongHeaderLengths(connection_.transport_version())) {
9295 // Coalesced packets can only be encoded using long header lengths.
9296 return;
9297 }
9298 if (connection_.SupportsMultiplePacketNumberSpaces()) {
9299 // TODO(b/129151114) Enable this test with multiple packet number spaces.
9300 return;
9301 }
9302 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9303 EXPECT_TRUE(connection_.connected());
9304 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9305 EXPECT_CALL(visitor_, OnCryptoFrame(_))
9306 .Times(3)
9307 .WillRepeatedly([this](const QuicCryptoFrame& /*frame*/) {
9308 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009309 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009310 });
9311 } else {
9312 EXPECT_CALL(visitor_, OnStreamFrame(_))
9313 .Times(3)
9314 .WillRepeatedly([this](const QuicStreamFrame& /*frame*/) {
9315 // QuicFrame takes ownership of the QuicBlockedFrame.
QUICHE team1a271082022-05-18 10:22:22 -07009316 connection_.SendControlFrame(QuicFrame(QuicBlockedFrame(1, 3, 0)));
Bence Békybac04052022-04-07 15:44:29 -04009317 });
9318 }
9319
9320 uint64_t packet_numbers[3] = {1, 2, 3};
9321 EncryptionLevel encryption_levels[3] = {
9322 ENCRYPTION_INITIAL, ENCRYPTION_INITIAL, ENCRYPTION_FORWARD_SECURE};
9323 char buffer[kMaxOutgoingPacketSize] = {};
9324 size_t total_encrypted_length = 0;
9325 for (int i = 0; i < 3; i++) {
9326 QuicPacketHeader header =
9327 ConstructPacketHeader(packet_numbers[i], encryption_levels[i]);
9328 QuicFrames frames;
9329 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
9330 frames.push_back(QuicFrame(&crypto_frame_));
9331 } else {
9332 frames.push_back(QuicFrame(frame1_));
9333 }
9334 std::unique_ptr<QuicPacket> packet = ConstructPacket(header, frames);
9335 peer_creator_.set_encryption_level(encryption_levels[i]);
9336 size_t encrypted_length = peer_framer_.EncryptPayload(
9337 encryption_levels[i], QuicPacketNumber(packet_numbers[i]), *packet,
9338 buffer + total_encrypted_length,
9339 sizeof(buffer) - total_encrypted_length);
9340 EXPECT_GT(encrypted_length, 0u);
9341 total_encrypted_length += encrypted_length;
9342 }
9343 connection_.ProcessUdpPacket(
9344 kSelfAddress, kPeerAddress,
9345 QuicReceivedPacket(buffer, total_encrypted_length, clock_.Now(), false));
9346 if (connection_.GetSendAlarm()->IsSet()) {
9347 connection_.GetSendAlarm()->Fire();
9348 }
9349
9350 EXPECT_TRUE(connection_.connected());
9351
9352 SendAckPacketToPeer();
9353}
9354
9355// Regresstion test for b/138962304.
9356TEST_P(QuicConnectionTest, RtoAndWriteBlocked) {
9357 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9358
9359 QuicStreamId stream_id = 2;
9360 QuicPacketNumber last_data_packet;
9361 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9362 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9363
9364 // Writer gets blocked.
9365 writer_->SetWriteBlocked();
9366
9367 // Cancel the stream.
9368 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9369 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9370 EXPECT_CALL(visitor_, WillingAndAbleToWrite())
9371 .WillRepeatedly(
9372 Invoke(&notifier_, &SimpleSessionNotifier::WillingToWrite));
9373 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9374
9375 // Retransmission timer fires in RTO mode.
9376 connection_.GetRetransmissionAlarm()->Fire();
9377 // Verify no packets get flushed when writer is blocked.
9378 EXPECT_EQ(0u, connection_.NumQueuedPackets());
9379}
9380
9381// Regresstion test for b/138962304.
fayang339f0c82022-04-30 14:20:02 -07009382TEST_P(QuicConnectionTest, PtoAndWriteBlocked) {
Bence Békybac04052022-04-07 15:44:29 -04009383 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
Bence Békybac04052022-04-07 15:44:29 -04009384
9385 QuicStreamId stream_id = 2;
9386 QuicPacketNumber last_data_packet;
9387 SendStreamDataToPeer(stream_id, "foo", 0, NO_FIN, &last_data_packet);
9388 SendStreamDataToPeer(4, "foo", 0, NO_FIN, &last_data_packet);
9389 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9390
9391 // Writer gets blocked.
9392 writer_->SetWriteBlocked();
9393
9394 // Cancel stream 2.
9395 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9396 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
9397 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9398
9399 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9400 // Retransmission timer fires in TLP mode.
9401 connection_.GetRetransmissionAlarm()->Fire();
9402 // Verify one packets is forced flushed when writer is blocked.
9403 EXPECT_EQ(1u, connection_.NumQueuedPackets());
9404}
9405
Bence Békybac04052022-04-07 15:44:29 -04009406TEST_P(QuicConnectionTest, ProbeTimeout) {
9407 QuicConfig config;
9408 QuicTagVector connection_options;
9409 connection_options.push_back(k2PTO);
9410 config.SetConnectionOptionsToSend(connection_options);
9411 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9412 connection_.SetFromConfig(config);
9413 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9414
9415 QuicStreamId stream_id = 2;
9416 QuicPacketNumber last_packet;
9417 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9418 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9419 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9420
9421 // Reset stream.
9422 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9423 SendRstStream(stream_id, QUIC_ERROR_PROCESSING_STREAM, 3);
9424
9425 // Fire the PTO and verify only the RST_STREAM is resent, not stream data.
9426 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9427 connection_.GetRetransmissionAlarm()->Fire();
9428 EXPECT_EQ(0u, writer_->stream_frames().size());
9429 EXPECT_EQ(1u, writer_->rst_stream_frames().size());
9430 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9431}
9432
9433TEST_P(QuicConnectionTest, CloseConnectionAfter6ClientPTOs) {
9434 QuicConfig config;
9435 QuicTagVector connection_options;
9436 connection_options.push_back(k1PTO);
9437 connection_options.push_back(k6PTO);
9438 config.SetConnectionOptionsToSend(connection_options);
9439 QuicConfigPeer::SetNegotiated(&config, true);
9440 if (connection_.version().UsesTls()) {
9441 QuicConfigPeer::SetReceivedOriginalConnectionId(
9442 &config, connection_.connection_id());
9443 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9444 &config, connection_.connection_id());
9445 }
9446 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9447 connection_.SetFromConfig(config);
9448 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
9449 EXPECT_CALL(visitor_, GetHandshakeState())
9450 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9451 }
9452 connection_.OnHandshakeComplete();
9453 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9454
9455 // Send stream data.
9456 SendStreamDataToPeer(
9457 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9458 0, FIN, nullptr);
9459
9460 // Fire the retransmission alarm 5 times.
9461 for (int i = 0; i < 5; ++i) {
9462 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9463 connection_.GetRetransmissionAlarm()->Fire();
9464 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9465 EXPECT_TRUE(connection_.connected());
9466 }
9467 EXPECT_CALL(visitor_, OnPathDegrading());
9468 connection_.PathDegradingTimeout();
9469
Bence Békybac04052022-04-07 15:44:29 -04009470 EXPECT_EQ(5u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9471 // Closes connection on 6th PTO.
9472 // May send multiple connecction close packets with multiple PN spaces.
9473 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9474 EXPECT_CALL(visitor_,
9475 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9476 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9477 connection_.GetBlackholeDetectorAlarm()->Fire();
9478 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9479 EXPECT_FALSE(connection_.connected());
9480 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9481}
9482
9483TEST_P(QuicConnectionTest, CloseConnectionAfter7ClientPTOs) {
9484 QuicConfig config;
9485 QuicTagVector connection_options;
9486 connection_options.push_back(k2PTO);
9487 connection_options.push_back(k7PTO);
9488 config.SetConnectionOptionsToSend(connection_options);
9489 QuicConfigPeer::SetNegotiated(&config, true);
9490 if (connection_.version().UsesTls()) {
9491 QuicConfigPeer::SetReceivedOriginalConnectionId(
9492 &config, connection_.connection_id());
9493 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9494 &config, connection_.connection_id());
9495 }
9496 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9497 connection_.SetFromConfig(config);
9498 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
9499 EXPECT_CALL(visitor_, GetHandshakeState())
9500 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9501 }
9502 connection_.OnHandshakeComplete();
9503 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9504
9505 // Send stream data.
9506 SendStreamDataToPeer(
9507 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9508 0, FIN, nullptr);
9509
9510 // Fire the retransmission alarm 6 times.
9511 for (int i = 0; i < 6; ++i) {
9512 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9513 connection_.GetRetransmissionAlarm()->Fire();
9514 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9515 EXPECT_TRUE(connection_.connected());
9516 }
9517 EXPECT_CALL(visitor_, OnPathDegrading());
9518 connection_.PathDegradingTimeout();
9519
Bence Békybac04052022-04-07 15:44:29 -04009520 EXPECT_EQ(6u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9521 // Closes connection on 7th PTO.
9522 EXPECT_CALL(visitor_,
9523 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9524 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9525 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9526 connection_.GetBlackholeDetectorAlarm()->Fire();
9527 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9528 EXPECT_FALSE(connection_.connected());
9529 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9530}
9531
9532TEST_P(QuicConnectionTest, CloseConnectionAfter8ClientPTOs) {
9533 QuicConfig config;
9534 QuicTagVector connection_options;
9535 connection_options.push_back(k2PTO);
9536 connection_options.push_back(k8PTO);
9537 QuicConfigPeer::SetNegotiated(&config, true);
9538 if (connection_.version().UsesTls()) {
9539 QuicConfigPeer::SetReceivedOriginalConnectionId(
9540 &config, connection_.connection_id());
9541 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
9542 &config, connection_.connection_id());
9543 }
9544 config.SetConnectionOptionsToSend(connection_options);
9545 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9546 connection_.SetFromConfig(config);
9547 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
9548 EXPECT_CALL(visitor_, GetHandshakeState())
9549 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
9550 }
9551 connection_.OnHandshakeComplete();
9552 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9553
9554 // Send stream data.
9555 SendStreamDataToPeer(
9556 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
9557 0, FIN, nullptr);
9558
9559 // Fire the retransmission alarm 7 times.
9560 for (int i = 0; i < 7; ++i) {
9561 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
9562 connection_.GetRetransmissionAlarm()->Fire();
9563 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
9564 EXPECT_TRUE(connection_.connected());
9565 }
9566 EXPECT_CALL(visitor_, OnPathDegrading());
9567 connection_.PathDegradingTimeout();
9568
Bence Békybac04052022-04-07 15:44:29 -04009569 EXPECT_EQ(7u, connection_.sent_packet_manager().GetConsecutivePtoCount());
9570 // Closes connection on 8th PTO.
9571 EXPECT_CALL(visitor_,
9572 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
9573 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AtLeast(1));
9574 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
9575 connection_.GetBlackholeDetectorAlarm()->Fire();
9576 EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
9577 EXPECT_FALSE(connection_.connected());
9578 TestConnectionCloseQuicErrorCode(QUIC_TOO_MANY_RTOS);
9579}
9580
9581TEST_P(QuicConnectionTest, DeprecateHandshakeMode) {
9582 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9583 return;
9584 }
9585 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
9586 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9587
9588 // Send CHLO.
9589 connection_.SendCryptoStreamData();
9590 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9591
9592 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _));
9593 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
9594 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9595 QuicAckFrame frame1 = InitAckFrame(1);
9596 // Received ACK for packet 1.
9597 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
9598
9599 // Verify retransmission alarm is still set because handshake is not
9600 // confirmed although there is nothing in flight.
9601 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9602 EXPECT_EQ(0u, connection_.GetStats().pto_count);
9603 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
9604
9605 // PTO fires, verify a PING packet gets sent because there is no data to send.
9606 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
9607 connection_.GetRetransmissionAlarm()->Fire();
9608 EXPECT_EQ(1u, connection_.GetStats().pto_count);
9609 EXPECT_EQ(1u, connection_.GetStats().crypto_retransmit_count);
9610 EXPECT_EQ(1u, writer_->ping_frames().size());
9611}
9612
9613TEST_P(QuicConnectionTest, AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009614 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009615 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009616 return;
9617 }
9618 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9619
9620 set_perspective(Perspective::IS_SERVER);
9621 // Verify no data can be sent at the beginning because bytes received is 0.
9622 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9623 connection_.SendCryptoDataWithString("foo", 0);
9624 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9625 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9626 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9627
9628 // Receives packet 1.
9629 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9630 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9631
9632 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -07009633 GetQuicFlag(quic_anti_amplification_factor);
Bence Békybac04052022-04-07 15:44:29 -04009634 // Verify now packets can be sent.
9635 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9636 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9637 connection_.SendCryptoDataWithString("foo", i * 3);
9638 // Verify retransmission alarm is not set if throttled by anti-amplification
9639 // limit.
9640 EXPECT_EQ(i != anti_amplification_factor - 1,
9641 connection_.GetRetransmissionAlarm()->IsSet());
9642 }
9643 // Verify server is throttled by anti-amplification limit.
9644 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9645 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9646
9647 // Receives packet 2.
9648 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9649 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9650 // Verify more packets can be sent.
9651 for (size_t i = anti_amplification_factor + 1;
9652 i < anti_amplification_factor * 2; ++i) {
9653 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9654 connection_.SendCryptoDataWithString("foo", i * 3);
9655 }
9656 // Verify server is throttled by anti-amplification limit.
9657 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9658 connection_.SendCryptoDataWithString("foo",
9659 2 * anti_amplification_factor * 3);
9660
9661 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9662 ProcessPacket(3);
9663 // Verify anti-amplification limit is gone after address validation.
9664 for (size_t i = 0; i < 100; ++i) {
9665 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9666 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9667 }
9668}
9669
9670TEST_P(QuicConnectionTest, 3AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009671 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009672 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009673 return;
9674 }
9675 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9676
9677 set_perspective(Perspective::IS_SERVER);
9678 QuicConfig config;
9679 QuicTagVector connection_options;
9680 connection_options.push_back(k3AFF);
9681 config.SetInitialReceivedConnectionOptions(connection_options);
9682 if (connection_.version().UsesTls()) {
9683 QuicConfigPeer::SetReceivedOriginalConnectionId(
9684 &config, connection_.connection_id());
9685 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9686 QuicConnectionId());
9687 }
9688 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9689 connection_.SetFromConfig(config);
9690
9691 // Verify no data can be sent at the beginning because bytes received is 0.
9692 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9693 connection_.SendCryptoDataWithString("foo", 0);
9694 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9695 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9696 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9697
9698 // Receives packet 1.
9699 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9700 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9701
9702 const size_t anti_amplification_factor = 3;
9703 // Verify now packets can be sent.
9704 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9705 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9706 connection_.SendCryptoDataWithString("foo", i * 3);
9707 // Verify retransmission alarm is not set if throttled by anti-amplification
9708 // limit.
9709 EXPECT_EQ(i != anti_amplification_factor - 1,
9710 connection_.GetRetransmissionAlarm()->IsSet());
9711 }
9712 // Verify server is throttled by anti-amplification limit.
9713 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9714 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9715
9716 // Receives packet 2.
9717 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9718 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9719 // Verify more packets can be sent.
9720 for (size_t i = anti_amplification_factor + 1;
9721 i < anti_amplification_factor * 2; ++i) {
9722 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9723 connection_.SendCryptoDataWithString("foo", i * 3);
9724 }
9725 // Verify server is throttled by anti-amplification limit.
9726 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9727 connection_.SendCryptoDataWithString("foo",
9728 2 * anti_amplification_factor * 3);
9729
9730 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9731 ProcessPacket(3);
9732 // Verify anti-amplification limit is gone after address validation.
9733 for (size_t i = 0; i < 100; ++i) {
9734 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9735 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9736 }
9737}
9738
9739TEST_P(QuicConnectionTest, 10AntiAmplificationLimit) {
fayang161ce6e2022-07-01 18:02:11 -07009740 if (!connection_.version().SupportsAntiAmplificationLimit() ||
birenroyef686222022-09-12 11:34:34 -07009741 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009742 return;
9743 }
9744 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9745
9746 set_perspective(Perspective::IS_SERVER);
9747 QuicConfig config;
9748 QuicTagVector connection_options;
9749 connection_options.push_back(k10AF);
9750 config.SetInitialReceivedConnectionOptions(connection_options);
9751 if (connection_.version().UsesTls()) {
9752 QuicConfigPeer::SetReceivedOriginalConnectionId(
9753 &config, connection_.connection_id());
9754 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
9755 QuicConnectionId());
9756 }
9757 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9758 connection_.SetFromConfig(config);
9759
9760 // Verify no data can be sent at the beginning because bytes received is 0.
9761 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9762 connection_.SendCryptoDataWithString("foo", 0);
9763 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
9764 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
9765 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9766
9767 // Receives packet 1.
9768 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9769 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9770
9771 const size_t anti_amplification_factor = 10;
9772 // Verify now packets can be sent.
9773 for (size_t i = 1; i < anti_amplification_factor; ++i) {
9774 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9775 connection_.SendCryptoDataWithString("foo", i * 3);
9776 // Verify retransmission alarm is not set if throttled by anti-amplification
9777 // limit.
9778 EXPECT_EQ(i != anti_amplification_factor - 1,
9779 connection_.GetRetransmissionAlarm()->IsSet());
9780 }
9781 // Verify server is throttled by anti-amplification limit.
9782 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9783 connection_.SendCryptoDataWithString("foo", anti_amplification_factor * 3);
9784
9785 // Receives packet 2.
9786 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9787 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9788 // Verify more packets can be sent.
9789 for (size_t i = anti_amplification_factor + 1;
9790 i < anti_amplification_factor * 2; ++i) {
9791 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9792 connection_.SendCryptoDataWithString("foo", i * 3);
9793 }
9794 // Verify server is throttled by anti-amplification limit.
9795 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9796 connection_.SendCryptoDataWithString("foo",
9797 2 * anti_amplification_factor * 3);
9798
9799 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9800 ProcessPacket(3);
9801 // Verify anti-amplification limit is gone after address validation.
9802 for (size_t i = 0; i < 100; ++i) {
9803 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9804 connection_.SendStreamDataWithString(3, "first", i * 0, NO_FIN);
9805 }
9806}
9807
9808TEST_P(QuicConnectionTest, AckPendingWithAmplificationLimited) {
9809 if (!connection_.version().SupportsAntiAmplificationLimit()) {
9810 return;
9811 }
9812 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
9813 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
9814 set_perspective(Perspective::IS_SERVER);
9815 use_tagging_decrypter();
9816 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9817 std::make_unique<TaggingEncrypter>(0x01));
9818 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9819 // Receives packet 1.
9820 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
9821 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9822 std::make_unique<TaggingEncrypter>(0x02));
9823 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9824 EXPECT_TRUE(connection_.HasPendingAcks());
9825 // Send response in different encryption level and cause amplification factor
9826 // throttled.
9827 size_t i = 0;
9828 while (connection_.CanWrite(HAS_RETRANSMITTABLE_DATA)) {
9829 connection_.SendCryptoDataWithString(std::string(1024, 'a'), i * 1024,
9830 ENCRYPTION_HANDSHAKE);
9831 ++i;
9832 }
9833 // Verify ACK is still pending.
9834 EXPECT_TRUE(connection_.HasPendingAcks());
9835
9836 // Fire ACK alarm and verify ACK cannot be sent due to amplification factor.
9837 clock_.AdvanceTime(connection_.GetAckAlarm()->deadline() - clock_.Now());
9838 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
9839 connection_.GetAckAlarm()->Fire();
9840 // Verify ACK alarm is cancelled.
9841 EXPECT_FALSE(connection_.HasPendingAcks());
9842
9843 // Receives packet 2 and verify ACK gets flushed.
9844 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9845 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
9846 EXPECT_FALSE(writer_->ack_frames().empty());
9847}
9848
9849TEST_P(QuicConnectionTest, ConnectionCloseFrameType) {
9850 if (!VersionHasIetfQuicFrames(version().transport_version)) {
9851 // Test relevent only for IETF QUIC.
9852 return;
9853 }
9854 const QuicErrorCode kQuicErrorCode = IETF_QUIC_PROTOCOL_VIOLATION;
9855 // Use the (unknown) frame type of 9999 to avoid triggering any logic
9856 // which might be associated with the processing of a known frame type.
9857 const uint64_t kTransportCloseFrameType = 9999u;
9858 QuicFramerPeer::set_current_received_frame_type(
9859 QuicConnectionPeer::GetFramer(&connection_), kTransportCloseFrameType);
9860 // Do a transport connection close
9861 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
9862 connection_.CloseConnection(
9863 kQuicErrorCode, "Some random error message",
9864 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
9865 const std::vector<QuicConnectionCloseFrame>& connection_close_frames =
9866 writer_->connection_close_frames();
9867 ASSERT_EQ(1u, connection_close_frames.size());
9868 EXPECT_EQ(IETF_QUIC_TRANSPORT_CONNECTION_CLOSE,
9869 connection_close_frames[0].close_type);
9870 EXPECT_EQ(kQuicErrorCode, connection_close_frames[0].quic_error_code);
9871 EXPECT_EQ(kTransportCloseFrameType,
9872 connection_close_frames[0].transport_close_frame_type);
9873}
9874
Bence Békybac04052022-04-07 15:44:29 -04009875TEST_P(QuicConnectionTest, PtoSkipsPacketNumber) {
9876 QuicConfig config;
9877 QuicTagVector connection_options;
9878 connection_options.push_back(k1PTO);
9879 connection_options.push_back(kPTOS);
9880 config.SetConnectionOptionsToSend(connection_options);
9881 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
9882 connection_.SetFromConfig(config);
9883 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
9884
9885 QuicStreamId stream_id = 2;
9886 QuicPacketNumber last_packet;
9887 SendStreamDataToPeer(stream_id, "foooooo", 0, NO_FIN, &last_packet);
9888 SendStreamDataToPeer(stream_id, "foooooo", 7, NO_FIN, &last_packet);
9889 EXPECT_EQ(QuicPacketNumber(2), last_packet);
9890 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9891
9892 // Fire PTO and verify the PTO retransmission skips one packet number.
9893 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
9894 connection_.GetRetransmissionAlarm()->Fire();
9895 EXPECT_EQ(1u, writer_->stream_frames().size());
9896 EXPECT_EQ(QuicPacketNumber(4), writer_->last_packet_header().packet_number);
9897 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
9898}
9899
9900TEST_P(QuicConnectionTest, SendCoalescedPackets) {
9901 if (!connection_.version().CanSendCoalescedPackets()) {
9902 return;
9903 }
9904 MockQuicConnectionDebugVisitor debug_visitor;
9905 connection_.set_debug_visitor(&debug_visitor);
9906 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _)).Times(3);
9907 EXPECT_CALL(debug_visitor, OnCoalescedPacketSent(_, _)).Times(1);
9908 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
9909 {
9910 QuicConnection::ScopedPacketFlusher flusher(&connection_);
9911 use_tagging_decrypter();
9912 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9913 std::make_unique<TaggingEncrypter>(0x01));
9914 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9915 connection_.SendCryptoDataWithString("foo", 0);
9916 // Verify this packet is on hold.
9917 EXPECT_EQ(0u, writer_->packets_write_attempts());
9918
9919 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9920 std::make_unique<TaggingEncrypter>(0x02));
9921 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9922 connection_.SendCryptoDataWithString("bar", 3);
9923 EXPECT_EQ(0u, writer_->packets_write_attempts());
9924
9925 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9926 std::make_unique<TaggingEncrypter>(0x03));
9927 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9928 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
9929 }
9930 // Verify all 3 packets are coalesced in the same UDP datagram.
9931 EXPECT_EQ(1u, writer_->packets_write_attempts());
9932 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
9933 // Verify the packet is padded to full.
9934 EXPECT_EQ(connection_.max_packet_length(), writer_->last_packet_size());
9935
9936 // Verify packet process.
9937 EXPECT_EQ(1u, writer_->crypto_frames().size());
9938 EXPECT_EQ(0u, writer_->stream_frames().size());
9939 // Verify there is coalesced packet.
9940 EXPECT_NE(nullptr, writer_->coalesced_packet());
9941}
9942
9943TEST_P(QuicConnectionTest, FailToCoalescePacket) {
9944 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
9945 if (!IsDefaultTestConfiguration() ||
fayang161ce6e2022-07-01 18:02:11 -07009946 !connection_.version().CanSendCoalescedPackets() ||
birenroyef686222022-09-12 11:34:34 -07009947 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -04009948 return;
9949 }
9950
9951 set_perspective(Perspective::IS_SERVER);
9952 use_tagging_decrypter();
9953
Bence Békybac04052022-04-07 15:44:29 -04009954 auto test_body = [&] {
vasilvvac2e30d2022-06-02 14:26:59 -07009955 EXPECT_CALL(visitor_,
9956 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
9957 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
Bence Békybac04052022-04-07 15:44:29 -04009958
vasilvvac2e30d2022-06-02 14:26:59 -07009959 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_INITIAL);
Bence Békybac04052022-04-07 15:44:29 -04009960
vasilvvac2e30d2022-06-02 14:26:59 -07009961 {
9962 QuicConnection::ScopedPacketFlusher flusher(&connection_);
9963 connection_.SetEncrypter(ENCRYPTION_INITIAL,
9964 std::make_unique<TaggingEncrypter>(0x01));
9965 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
9966 connection_.SendCryptoDataWithString("foo", 0);
9967 // Verify this packet is on hold.
9968 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -04009969
vasilvvac2e30d2022-06-02 14:26:59 -07009970 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
9971 std::make_unique<TaggingEncrypter>(0x02));
9972 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
9973 connection_.SendCryptoDataWithString("bar", 3);
9974 EXPECT_EQ(0u, writer_->packets_write_attempts());
Bence Békybac04052022-04-07 15:44:29 -04009975
vasilvvac2e30d2022-06-02 14:26:59 -07009976 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
9977 std::make_unique<TaggingEncrypter>(0x03));
9978 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
9979 SendStreamDataToPeer(2, "baz", 3, NO_FIN, nullptr);
Bence Békybac04052022-04-07 15:44:29 -04009980
vasilvvac2e30d2022-06-02 14:26:59 -07009981 creator_->Flush();
9982
9983 auto& coalesced_packet =
9984 QuicConnectionPeer::GetCoalescedPacket(&connection_);
9985 QuicPacketLength coalesced_packet_max_length =
9986 coalesced_packet.max_packet_length();
9987 QuicCoalescedPacketPeer::SetMaxPacketLength(coalesced_packet,
9988 coalesced_packet.length());
9989
9990 // Make the coalescer's FORWARD_SECURE packet longer.
9991 *QuicCoalescedPacketPeer::GetMutableEncryptedBuffer(
9992 coalesced_packet, ENCRYPTION_FORWARD_SECURE) += "!!! TEST !!!";
9993
9994 QUIC_LOG(INFO) << "Reduced coalesced_packet_max_length from "
9995 << coalesced_packet_max_length << " to "
9996 << coalesced_packet.max_packet_length()
9997 << ", coalesced_packet.length:"
9998 << coalesced_packet.length()
9999 << ", coalesced_packet.packet_lengths:"
10000 << absl::StrJoin(coalesced_packet.packet_lengths(), ":");
10001 }
10002
10003 EXPECT_FALSE(connection_.connected());
10004 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10005 IsError(QUIC_FAILED_TO_SERIALIZE_PACKET));
10006 EXPECT_EQ(saved_connection_close_frame_.error_details,
10007 "Failed to serialize coalesced packet.");
Bence Békybac04052022-04-07 15:44:29 -040010008 };
10009
10010 EXPECT_QUIC_BUG(test_body(), "SerializeCoalescedPacket failed.");
Bence Békybac04052022-04-07 15:44:29 -040010011}
10012
Bence Békybac04052022-04-07 15:44:29 -040010013TEST_P(QuicConnectionTest, ClientReceivedHandshakeDone) {
10014 if (!connection_.version().UsesTls()) {
10015 return;
10016 }
10017 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
10018 QuicFrames frames;
10019 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10020 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10021 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10022}
10023
10024TEST_P(QuicConnectionTest, ServerReceivedHandshakeDone) {
10025 if (!connection_.version().UsesTls()) {
10026 return;
10027 }
10028 set_perspective(Perspective::IS_SERVER);
10029 EXPECT_CALL(visitor_, OnHandshakeDoneReceived()).Times(0);
10030 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
10031 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
10032 }
10033 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10034 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
10035 QuicFrames frames;
10036 frames.push_back(QuicFrame(QuicHandshakeDoneFrame()));
10037 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10038 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10039 EXPECT_EQ(1, connection_close_frame_count_);
10040 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
10041 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
10042}
10043
10044TEST_P(QuicConnectionTest, MultiplePacketNumberSpacePto) {
10045 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10046 return;
10047 }
10048 use_tagging_decrypter();
10049 // Send handshake packet.
10050 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10051 std::make_unique<TaggingEncrypter>(0x02));
10052 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10053 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10054 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10055 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
10056
10057 // Send application data.
10058 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10059 0, NO_FIN);
10060 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10061 QuicTime retransmission_time =
10062 connection_.GetRetransmissionAlarm()->deadline();
10063 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10064
10065 // Retransmit handshake data.
10066 clock_.AdvanceTime(retransmission_time - clock_.Now());
10067 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(4), _, _));
10068 connection_.GetRetransmissionAlarm()->Fire();
10069 // Verify 1-RTT packet gets coalesced with handshake retransmission.
10070 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10071
10072 // Send application data.
10073 connection_.SendApplicationDataAtLevel(ENCRYPTION_FORWARD_SECURE, 5, "data",
10074 4, NO_FIN);
10075 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10076 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10077 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10078
10079 // Retransmit handshake data again.
10080 clock_.AdvanceTime(retransmission_time - clock_.Now());
10081 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(9), _, _));
10082 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(8), _, _));
10083 connection_.GetRetransmissionAlarm()->Fire();
10084 // Verify 1-RTT packet gets coalesced with handshake retransmission.
10085 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10086
10087 // Discard handshake key.
10088 connection_.OnHandshakeComplete();
10089 retransmission_time = connection_.GetRetransmissionAlarm()->deadline();
10090 EXPECT_NE(QuicTime::Zero(), retransmission_time);
10091
10092 // Retransmit application data.
10093 clock_.AdvanceTime(retransmission_time - clock_.Now());
10094 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(11), _, _));
10095 connection_.GetRetransmissionAlarm()->Fire();
10096 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
10097}
10098
10099void QuicConnectionTest::TestClientRetryHandling(
10100 bool invalid_retry_tag, bool missing_original_id_in_config,
10101 bool wrong_original_id_in_config, bool missing_retry_id_in_config,
10102 bool wrong_retry_id_in_config) {
10103 if (invalid_retry_tag) {
10104 ASSERT_FALSE(missing_original_id_in_config);
10105 ASSERT_FALSE(wrong_original_id_in_config);
10106 ASSERT_FALSE(missing_retry_id_in_config);
10107 ASSERT_FALSE(wrong_retry_id_in_config);
10108 } else {
10109 ASSERT_FALSE(missing_original_id_in_config && wrong_original_id_in_config);
10110 ASSERT_FALSE(missing_retry_id_in_config && wrong_retry_id_in_config);
10111 }
10112 if (!version().UsesTls()) {
10113 return;
10114 }
10115
10116 // These values come from draft-ietf-quic-v2 Appendix A.4.
10117 uint8_t retry_packet_rfcv2[] = {
10118 0xcf, 0x70, 0x9a, 0x50, 0xc4, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10119 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x1d, 0xc7, 0x11, 0x30,
10120 0xcd, 0x1e, 0xd3, 0x9d, 0x6e, 0xfc, 0xee, 0x5c, 0x85, 0x80, 0x65, 0x01};
10121 // These values come from RFC9001 Appendix A.4.
10122 uint8_t retry_packet_rfcv1[] = {
10123 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10124 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba,
10125 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba};
10126 uint8_t retry_packet29[] = {
10127 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a,
10128 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8,
10129 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a, 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49};
10130
10131 uint8_t* retry_packet;
10132 size_t retry_packet_length;
10133 if (version() == ParsedQuicVersion::V2Draft01()) {
10134 retry_packet = retry_packet_rfcv2;
10135 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv2);
10136 } else if (version() == ParsedQuicVersion::RFCv1()) {
10137 retry_packet = retry_packet_rfcv1;
10138 retry_packet_length = ABSL_ARRAYSIZE(retry_packet_rfcv1);
10139 } else if (version() == ParsedQuicVersion::Draft29()) {
10140 retry_packet = retry_packet29;
10141 retry_packet_length = ABSL_ARRAYSIZE(retry_packet29);
10142 } else {
10143 // TODO(dschinazi) generate retry packets for all versions once we have
10144 // server-side support for generating these programmatically.
10145 return;
10146 }
10147
10148 uint8_t original_connection_id_bytes[] = {0x83, 0x94, 0xc8, 0xf0,
10149 0x3e, 0x51, 0x57, 0x08};
10150 uint8_t new_connection_id_bytes[] = {0xf0, 0x67, 0xa5, 0x50,
10151 0x2a, 0x42, 0x62, 0xb5};
10152 uint8_t retry_token_bytes[] = {0x74, 0x6f, 0x6b, 0x65, 0x6e};
10153
10154 QuicConnectionId original_connection_id(
10155 reinterpret_cast<char*>(original_connection_id_bytes),
10156 ABSL_ARRAYSIZE(original_connection_id_bytes));
10157 QuicConnectionId new_connection_id(
10158 reinterpret_cast<char*>(new_connection_id_bytes),
10159 ABSL_ARRAYSIZE(new_connection_id_bytes));
10160
10161 std::string retry_token(reinterpret_cast<char*>(retry_token_bytes),
10162 ABSL_ARRAYSIZE(retry_token_bytes));
10163
10164 if (invalid_retry_tag) {
10165 // Flip the last bit of the retry packet to prevent the integrity tag
10166 // from validating correctly.
10167 retry_packet[retry_packet_length - 1] ^= 1;
10168 }
10169
10170 QuicConnectionId config_original_connection_id = original_connection_id;
10171 if (wrong_original_id_in_config) {
10172 // Flip the first bit of the connection ID.
10173 ASSERT_FALSE(config_original_connection_id.IsEmpty());
10174 config_original_connection_id.mutable_data()[0] ^= 0x80;
10175 }
10176 QuicConnectionId config_retry_source_connection_id = new_connection_id;
10177 if (wrong_retry_id_in_config) {
10178 // Flip the first bit of the connection ID.
10179 ASSERT_FALSE(config_retry_source_connection_id.IsEmpty());
10180 config_retry_source_connection_id.mutable_data()[0] ^= 0x80;
10181 }
10182
10183 // Make sure the connection uses the connection ID from the test vectors,
10184 QuicConnectionPeer::SetServerConnectionId(&connection_,
10185 original_connection_id);
10186 // Make sure our fake framer has the new post-retry INITIAL keys so that any
10187 // retransmission triggered by retry can be decrypted.
10188 writer_->framer()->framer()->SetInitialObfuscators(new_connection_id);
10189
10190 // Process the RETRY packet.
10191 connection_.ProcessUdpPacket(
10192 kSelfAddress, kPeerAddress,
10193 QuicReceivedPacket(reinterpret_cast<char*>(retry_packet),
10194 retry_packet_length, clock_.Now()));
10195
10196 if (invalid_retry_tag) {
10197 // Make sure we refuse to process a RETRY with invalid tag.
10198 EXPECT_FALSE(connection_.GetStats().retry_packet_processed);
10199 EXPECT_EQ(connection_.connection_id(), original_connection_id);
10200 EXPECT_TRUE(QuicPacketCreatorPeer::GetRetryToken(
10201 QuicConnectionPeer::GetPacketCreator(&connection_))
10202 .empty());
10203 return;
10204 }
10205
10206 // Make sure we correctly parsed the RETRY.
10207 EXPECT_TRUE(connection_.GetStats().retry_packet_processed);
10208 EXPECT_EQ(connection_.connection_id(), new_connection_id);
10209 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
10210 QuicConnectionPeer::GetPacketCreator(&connection_)),
10211 retry_token);
10212
10213 // Test validating the original_connection_id from the config.
10214 QuicConfig received_config;
10215 QuicConfigPeer::SetNegotiated(&received_config, true);
10216 if (connection_.version().UsesTls()) {
10217 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10218 &received_config, connection_.connection_id());
10219 if (!missing_retry_id_in_config) {
10220 QuicConfigPeer::SetReceivedRetrySourceConnectionId(
10221 &received_config, config_retry_source_connection_id);
10222 }
10223 }
10224 if (!missing_original_id_in_config) {
10225 QuicConfigPeer::SetReceivedOriginalConnectionId(
10226 &received_config, config_original_connection_id);
10227 }
10228
10229 if (missing_original_id_in_config || wrong_original_id_in_config ||
10230 missing_retry_id_in_config || wrong_retry_id_in_config) {
10231 EXPECT_CALL(visitor_,
10232 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10233 .Times(1);
10234 } else {
10235 EXPECT_CALL(visitor_,
10236 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10237 .Times(0);
10238 }
10239 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10240 connection_.SetFromConfig(received_config);
10241 if (missing_original_id_in_config || wrong_original_id_in_config ||
10242 missing_retry_id_in_config || wrong_retry_id_in_config) {
10243 ASSERT_FALSE(connection_.connected());
10244 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10245 } else {
10246 EXPECT_TRUE(connection_.connected());
10247 }
10248}
10249
10250TEST_P(QuicConnectionTest, ClientParsesRetry) {
10251 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10252 /*missing_original_id_in_config=*/false,
10253 /*wrong_original_id_in_config=*/false,
10254 /*missing_retry_id_in_config=*/false,
10255 /*wrong_retry_id_in_config=*/false);
10256}
10257
10258TEST_P(QuicConnectionTest, ClientParsesRetryInvalidTag) {
10259 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10260 /*missing_original_id_in_config=*/false,
10261 /*wrong_original_id_in_config=*/false,
10262 /*missing_retry_id_in_config=*/false,
10263 /*wrong_retry_id_in_config=*/false);
10264}
10265
10266TEST_P(QuicConnectionTest, ClientParsesRetryMissingOriginalId) {
10267 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10268 /*missing_original_id_in_config=*/true,
10269 /*wrong_original_id_in_config=*/false,
10270 /*missing_retry_id_in_config=*/false,
10271 /*wrong_retry_id_in_config=*/false);
10272}
10273
10274TEST_P(QuicConnectionTest, ClientParsesRetryWrongOriginalId) {
10275 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10276 /*missing_original_id_in_config=*/false,
10277 /*wrong_original_id_in_config=*/true,
10278 /*missing_retry_id_in_config=*/false,
10279 /*wrong_retry_id_in_config=*/false);
10280}
10281
10282TEST_P(QuicConnectionTest, ClientParsesRetryMissingRetryId) {
10283 if (!connection_.version().UsesTls()) {
10284 // Versions that do not authenticate connection IDs never send the
10285 // retry_source_connection_id transport parameter.
10286 return;
10287 }
10288 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10289 /*missing_original_id_in_config=*/false,
10290 /*wrong_original_id_in_config=*/false,
10291 /*missing_retry_id_in_config=*/true,
10292 /*wrong_retry_id_in_config=*/false);
10293}
10294
10295TEST_P(QuicConnectionTest, ClientParsesRetryWrongRetryId) {
10296 if (!connection_.version().UsesTls()) {
10297 // Versions that do not authenticate connection IDs never send the
10298 // retry_source_connection_id transport parameter.
10299 return;
10300 }
10301 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10302 /*missing_original_id_in_config=*/false,
10303 /*wrong_original_id_in_config=*/false,
10304 /*missing_retry_id_in_config=*/false,
10305 /*wrong_retry_id_in_config=*/true);
10306}
10307
10308TEST_P(QuicConnectionTest, ClientRetransmitsInitialPacketsOnRetry) {
10309 if (!connection_.version().HasIetfQuicFrames()) {
10310 // TestClientRetryHandling() currently only supports IETF draft versions.
10311 return;
10312 }
10313 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10314
10315 connection_.SendCryptoStreamData();
10316
10317 EXPECT_EQ(1u, writer_->packets_write_attempts());
10318 TestClientRetryHandling(/*invalid_retry_tag=*/false,
10319 /*missing_original_id_in_config=*/false,
10320 /*wrong_original_id_in_config=*/false,
10321 /*missing_retry_id_in_config=*/false,
10322 /*wrong_retry_id_in_config=*/false);
10323
10324 // Verify that initial data is retransmitted immediately after receiving
10325 // RETRY.
10326 if (GetParam().ack_response == AckResponse::kImmediate) {
10327 EXPECT_EQ(2u, writer_->packets_write_attempts());
10328 EXPECT_EQ(1u, writer_->framer()->crypto_frames().size());
10329 }
10330}
10331
10332TEST_P(QuicConnectionTest, NoInitialPacketsRetransmissionOnInvalidRetry) {
10333 if (!connection_.version().HasIetfQuicFrames()) {
10334 return;
10335 }
10336 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10337
10338 connection_.SendCryptoStreamData();
10339
10340 EXPECT_EQ(1u, writer_->packets_write_attempts());
10341 TestClientRetryHandling(/*invalid_retry_tag=*/true,
10342 /*missing_original_id_in_config=*/false,
10343 /*wrong_original_id_in_config=*/false,
10344 /*missing_retry_id_in_config=*/false,
10345 /*wrong_retry_id_in_config=*/false);
10346
10347 EXPECT_EQ(1u, writer_->packets_write_attempts());
10348}
10349
10350TEST_P(QuicConnectionTest, ClientReceivesOriginalConnectionIdWithoutRetry) {
10351 if (!connection_.version().UsesTls()) {
10352 // QUIC+TLS is required to transmit connection ID transport parameters.
10353 return;
10354 }
10355 if (connection_.version().UsesTls()) {
10356 // Versions that authenticate connection IDs always send the
10357 // original_destination_connection_id transport parameter.
10358 return;
10359 }
10360 // Make sure that receiving the original_destination_connection_id transport
10361 // parameter fails the handshake when no RETRY packet was received before it.
10362 QuicConfig received_config;
10363 QuicConfigPeer::SetNegotiated(&received_config, true);
10364 QuicConfigPeer::SetReceivedOriginalConnectionId(&received_config,
10365 TestConnectionId(0x12345));
10366 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10367 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10368 .Times(1);
10369 connection_.SetFromConfig(received_config);
10370 EXPECT_FALSE(connection_.connected());
10371 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10372}
10373
10374TEST_P(QuicConnectionTest, ClientReceivesRetrySourceConnectionIdWithoutRetry) {
10375 if (!connection_.version().UsesTls()) {
10376 // Versions that do not authenticate connection IDs never send the
10377 // retry_source_connection_id transport parameter.
10378 return;
10379 }
10380 // Make sure that receiving the retry_source_connection_id transport parameter
10381 // fails the handshake when no RETRY packet was received before it.
10382 QuicConfig received_config;
10383 QuicConfigPeer::SetNegotiated(&received_config, true);
10384 QuicConfigPeer::SetReceivedRetrySourceConnectionId(&received_config,
10385 TestConnectionId(0x12345));
10386 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(AnyNumber());
10387 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
10388 .Times(1);
10389 connection_.SetFromConfig(received_config);
10390 EXPECT_FALSE(connection_.connected());
10391 TestConnectionCloseQuicErrorCode(IETF_QUIC_PROTOCOL_VIOLATION);
10392}
10393
10394// Regression test for http://crbug/1047977
10395TEST_P(QuicConnectionTest, MaxStreamsFrameCausesConnectionClose) {
10396 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10397 return;
10398 }
10399 // Received frame causes connection close.
10400 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_))
10401 .WillOnce(InvokeWithoutArgs([this]() {
10402 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10403 connection_.CloseConnection(
10404 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10405 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10406 return true;
10407 }));
10408 QuicFrames frames;
10409 frames.push_back(QuicFrame(QuicMaxStreamsFrame()));
10410 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10411 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10412}
10413
10414TEST_P(QuicConnectionTest, StreamsBlockedFrameCausesConnectionClose) {
10415 if (!VersionHasIetfQuicFrames(connection_.transport_version())) {
10416 return;
10417 }
10418 // Received frame causes connection close.
10419 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_))
10420 .WillOnce(InvokeWithoutArgs([this]() {
10421 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10422 connection_.CloseConnection(
10423 QUIC_TOO_MANY_BUFFERED_CONTROL_FRAMES, "error",
10424 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10425 return true;
10426 }));
10427 QuicFrames frames;
10428 frames.push_back(
10429 QuicFrame(QuicStreamsBlockedFrame(kInvalidControlFrameId, 10, false)));
10430 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
10431 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
10432}
10433
10434TEST_P(QuicConnectionTest,
10435 BundleAckWithConnectionCloseMultiplePacketNumberSpace) {
10436 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10437 return;
10438 }
10439 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10440 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10441 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10442 // Receives packet 1000 in initial data.
10443 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10444 // Receives packet 2000 in application data.
10445 ProcessDataPacketAtLevel(2000, false, ENCRYPTION_FORWARD_SECURE);
10446 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
10447 const QuicErrorCode kQuicErrorCode = QUIC_INTERNAL_ERROR;
10448 connection_.CloseConnection(
10449 kQuicErrorCode, "Some random error message",
10450 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
10451
10452 EXPECT_EQ(2u, QuicConnectionPeer::GetNumEncryptionLevels(&connection_));
10453
10454 TestConnectionCloseQuicErrorCode(kQuicErrorCode);
10455 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10456 // Verify ack is bundled.
10457 EXPECT_EQ(1u, writer_->ack_frames().size());
10458
10459 if (!connection_.version().CanSendCoalescedPackets()) {
10460 // Each connection close packet should be sent in distinct UDP packets.
10461 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10462 writer_->connection_close_packets());
10463 EXPECT_EQ(QuicConnectionPeer::GetNumEncryptionLevels(&connection_),
10464 writer_->packets_write_attempts());
10465 return;
10466 }
10467
10468 // A single UDP packet should be sent with multiple connection close packets
10469 // coalesced together.
10470 EXPECT_EQ(1u, writer_->packets_write_attempts());
10471
10472 // Only the first packet has been processed yet.
10473 EXPECT_EQ(1u, writer_->connection_close_packets());
10474
10475 // ProcessPacket resets the visitor and frees the coalesced packet.
10476 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
10477 auto packet = writer_->coalesced_packet()->Clone();
10478 writer_->framer()->ProcessPacket(*packet);
10479 EXPECT_EQ(1u, writer_->connection_close_packets());
10480 EXPECT_EQ(1u, writer_->connection_close_frames().size());
10481 // Verify ack is bundled.
10482 EXPECT_EQ(1u, writer_->ack_frames().size());
10483 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
10484}
10485
10486// Regression test for b/151220135.
10487TEST_P(QuicConnectionTest, SendPingWhenSkipPacketNumberForPto) {
10488 if (!VersionSupportsMessageFrames(connection_.transport_version())) {
10489 return;
10490 }
10491 QuicConfig config;
10492 QuicTagVector connection_options;
10493 connection_options.push_back(kPTOS);
10494 connection_options.push_back(k1PTO);
10495 config.SetConnectionOptionsToSend(connection_options);
10496 if (connection_.version().UsesTls()) {
10497 QuicConfigPeer::SetReceivedMaxDatagramFrameSize(
10498 &config, kMaxAcceptedDatagramFrameSize);
10499 }
10500 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10501 connection_.SetFromConfig(config);
10502 connection_.OnHandshakeComplete();
10503 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
10504
10505 EXPECT_EQ(MESSAGE_STATUS_SUCCESS, SendMessage("message"));
10506 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
10507
10508 // PTO fires, verify a PING packet gets sent because there is no data to
10509 // send.
10510 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, QuicPacketNumber(3), _, _));
10511 connection_.GetRetransmissionAlarm()->Fire();
10512 EXPECT_EQ(1u, connection_.GetStats().pto_count);
10513 EXPECT_EQ(0u, connection_.GetStats().crypto_retransmit_count);
10514 EXPECT_EQ(1u, writer_->ping_frames().size());
10515}
10516
10517// Regression test for b/155757133
10518TEST_P(QuicConnectionTest, DonotChangeQueuedAcks) {
10519 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10520 return;
10521 }
10522 const size_t kMinRttMs = 40;
10523 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10524 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
10525 QuicTime::Delta::Zero(), QuicTime::Zero());
10526 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10527 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10528 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10529 // Discard INITIAL key.
10530 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10531 connection_.NeuterUnencryptedPackets();
10532 EXPECT_CALL(visitor_, GetHandshakeState())
10533 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10534
10535 ProcessPacket(2);
10536 ProcessPacket(3);
10537 ProcessPacket(4);
10538 // Process a packet containing stream frame followed by ACK of packets 1.
10539 QuicFrames frames;
10540 frames.push_back(QuicFrame(QuicStreamFrame(
10541 QuicUtils::GetFirstBidirectionalStreamId(
10542 connection_.version().transport_version, Perspective::IS_CLIENT),
10543 false, 0u, absl::string_view())));
10544 QuicAckFrame ack_frame = InitAckFrame(1);
10545 frames.push_back(QuicFrame(&ack_frame));
10546 // Receiving stream frame causes something to send.
10547 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10548 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
10549 // Verify now the queued ACK contains packet number 2.
10550 EXPECT_TRUE(QuicPacketCreatorPeer::QueuedFrames(
10551 QuicConnectionPeer::GetPacketCreator(&connection_))[0]
10552 .ack_frame->packets.Contains(QuicPacketNumber(2)));
10553 }));
10554 ProcessFramesPacketAtLevel(9, frames, ENCRYPTION_FORWARD_SECURE);
10555 EXPECT_TRUE(writer_->ack_frames()[0].packets.Contains(QuicPacketNumber(2)));
10556}
10557
10558TEST_P(QuicConnectionTest, DonotExtendIdleTimeOnUndecryptablePackets) {
10559 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10560 QuicConfig config;
10561 connection_.SetFromConfig(config);
10562 // Subtract a second from the idle timeout on the client side.
10563 QuicTime initial_deadline =
10564 clock_.ApproximateNow() +
10565 QuicTime::Delta::FromSeconds(kInitialIdleTimeoutSecs - 1);
10566 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10567
10568 // Received an undecryptable packet.
10569 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1));
10570 const uint8_t tag = 0x07;
10571 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10572 std::make_unique<TaggingEncrypter>(tag));
10573 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10574 // Verify deadline does not get extended.
10575 EXPECT_EQ(initial_deadline, connection_.GetTimeoutAlarm()->deadline());
10576 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(1);
10577 QuicTime::Delta delay = initial_deadline - clock_.ApproximateNow();
10578 clock_.AdvanceTime(delay);
10579 connection_.GetTimeoutAlarm()->Fire();
10580 // Verify connection gets closed.
10581 EXPECT_FALSE(connection_.connected());
10582}
10583
10584TEST_P(QuicConnectionTest, BundleAckWithImmediateResponse) {
10585 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10586 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10587
10588 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([this]() {
10589 notifier_.WriteOrBufferWindowUpate(0, 0);
10590 }));
10591 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10592 ProcessDataPacket(1);
10593 // Verify ACK is bundled with WINDOW_UPDATE.
10594 EXPECT_FALSE(writer_->ack_frames().empty());
10595 EXPECT_FALSE(connection_.HasPendingAcks());
10596}
10597
10598TEST_P(QuicConnectionTest, AckAlarmFiresEarly) {
10599 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10600 return;
10601 }
10602 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10603 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10604 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10605 }
10606 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10607 use_tagging_decrypter();
10608 // Receives packet 1000 in initial data.
10609 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10610 EXPECT_TRUE(connection_.HasPendingAcks());
10611
10612 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
10613 std::make_unique<TaggingEncrypter>(0x02));
10614 SetDecrypter(ENCRYPTION_ZERO_RTT,
10615 std::make_unique<StrictTaggingDecrypter>(0x02));
10616 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10617 std::make_unique<TaggingEncrypter>(0x02));
10618 // Receives packet 1000 in application data.
10619 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_ZERO_RTT);
10620 EXPECT_TRUE(connection_.HasPendingAcks());
10621 // Verify ACK deadline does not change.
10622 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
10623 connection_.GetAckAlarm()->deadline());
10624
10625 // Ack alarm fires early.
10626 // Verify the earliest ACK is flushed.
10627 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
10628 connection_.GetAckAlarm()->Fire();
10629 EXPECT_TRUE(connection_.HasPendingAcks());
10630 EXPECT_EQ(clock_.ApproximateNow() + DefaultDelayedAckTime(),
10631 connection_.GetAckAlarm()->deadline());
10632}
10633
10634TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionClient) {
10635 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10636 return;
10637 }
10638 QuicConfig config;
10639 QuicTagVector connection_options;
10640 connection_options.push_back(kCBHD);
10641 config.SetConnectionOptionsToSend(connection_options);
10642 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10643 connection_.SetFromConfig(config);
10644 EXPECT_CALL(visitor_, GetHandshakeState())
10645 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10646 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10647 // Send stream data.
10648 SendStreamDataToPeer(
10649 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10650 0, FIN, nullptr);
10651 // Verify blackhole detection is in progress.
10652 EXPECT_TRUE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10653}
10654
10655TEST_P(QuicConnectionTest, ClientOnlyBlackholeDetectionServer) {
10656 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10657 return;
10658 }
10659 set_perspective(Perspective::IS_SERVER);
10660 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
10661 if (version().SupportsAntiAmplificationLimit()) {
10662 QuicConnectionPeer::SetAddressValidated(&connection_);
10663 }
10664 QuicConfig config;
10665 QuicTagVector connection_options;
10666 connection_options.push_back(kCBHD);
10667 config.SetInitialReceivedConnectionOptions(connection_options);
10668 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10669 connection_.SetFromConfig(config);
10670 EXPECT_CALL(visitor_, GetHandshakeState())
10671 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10672 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10673 // Send stream data.
10674 SendStreamDataToPeer(
10675 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
10676 0, FIN, nullptr);
10677 // Verify blackhole detection is disabled.
10678 EXPECT_FALSE(connection_.GetBlackholeDetectorAlarm()->IsSet());
10679}
10680
Bence Békybac04052022-04-07 15:44:29 -040010681// Regresstion test for b/158491591.
10682TEST_P(QuicConnectionTest, MadeForwardProgressOnDiscardingKeys) {
10683 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10684 return;
10685 }
10686 use_tagging_decrypter();
10687 // Send handshake packet.
10688 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10689 std::make_unique<TaggingEncrypter>(0x02));
10690 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10691 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10692 QuicConfig config;
10693 QuicTagVector connection_options;
10694 connection_options.push_back(k5RTO);
10695 config.SetConnectionOptionsToSend(connection_options);
10696 QuicConfigPeer::SetNegotiated(&config, true);
10697 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10698 EXPECT_CALL(visitor_, GetHandshakeState())
10699 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
10700 }
10701 if (connection_.version().UsesTls()) {
10702 QuicConfigPeer::SetReceivedOriginalConnectionId(
10703 &config, connection_.connection_id());
10704 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
10705 &config, connection_.connection_id());
10706 }
10707 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10708 connection_.SetFromConfig(config);
10709
10710 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10711 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10712 // Discard handshake keys.
10713 connection_.OnHandshakeComplete();
10714 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
10715 // Verify blackhole detection stops.
10716 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
10717 } else {
10718 // Problematic: although there is nothing in flight, blackhole detection is
10719 // still in progress.
10720 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
10721 }
10722}
10723
10724TEST_P(QuicConnectionTest, ProcessUndecryptablePacketsBasedOnEncryptionLevel) {
10725 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10726 return;
10727 }
10728 // SetFromConfig is always called after construction from InitializeSession.
10729 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
10730 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
10731 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
10732 QuicConfig config;
10733 connection_.SetFromConfig(config);
10734 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10735 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
10736 use_tagging_decrypter();
10737
10738 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10739 std::make_unique<TaggingEncrypter>(0x01));
10740 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10741 std::make_unique<TaggingEncrypter>(0x02));
10742
10743 for (uint64_t i = 1; i <= 3; ++i) {
10744 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10745 }
10746 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
10747 for (uint64_t j = 5; j <= 7; ++j) {
10748 ProcessDataPacketAtLevel(j, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
10749 }
10750 EXPECT_EQ(7u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10751 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10752 SetDecrypter(ENCRYPTION_HANDSHAKE,
10753 std::make_unique<StrictTaggingDecrypter>(0x01));
10754 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10755 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10756 std::make_unique<TaggingEncrypter>(0x01));
10757 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10758 // Verify all ENCRYPTION_HANDSHAKE packets get processed.
10759 if (!VersionHasIetfQuicFrames(version().transport_version)) {
10760 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(6);
10761 }
10762 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10763 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10764
10765 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
10766 std::make_unique<StrictTaggingDecrypter>(0x02));
10767 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
10768 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10769 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10770 std::make_unique<TaggingEncrypter>(0x02));
10771 // Verify the 1-RTT packet gets processed.
10772 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
10773 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
10774 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
10775}
10776
10777TEST_P(QuicConnectionTest, ServerBundlesInitialDataWithInitialAck) {
10778 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10779 return;
10780 }
10781 set_perspective(Perspective::IS_SERVER);
10782 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10783 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10784 }
10785 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10786 use_tagging_decrypter();
10787 // Receives packet 1000 in initial data.
10788 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10789 EXPECT_TRUE(connection_.HasPendingAcks());
10790
10791 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10792 std::make_unique<TaggingEncrypter>(0x01));
10793 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10794 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10795 QuicTime expected_pto_time =
10796 connection_.sent_packet_manager().GetRetransmissionTime();
10797
10798 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10799 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10800 std::make_unique<TaggingEncrypter>(0x02));
10801 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10802 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10803 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10804 // Verify PTO time does not change.
10805 EXPECT_EQ(expected_pto_time,
10806 connection_.sent_packet_manager().GetRetransmissionTime());
10807
10808 // Receives packet 1001 in initial data.
10809 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_INITIAL);
10810 EXPECT_TRUE(connection_.HasPendingAcks());
10811 // Receives packet 1002 in initial data.
10812 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_INITIAL);
10813 EXPECT_FALSE(writer_->ack_frames().empty());
10814 // Verify CRYPTO frame is bundled with INITIAL ACK.
10815 EXPECT_FALSE(writer_->crypto_frames().empty());
10816 // Verify PTO time changes.
10817 EXPECT_NE(expected_pto_time,
10818 connection_.sent_packet_manager().GetRetransmissionTime());
10819}
10820
10821TEST_P(QuicConnectionTest, ClientBundlesHandshakeDataWithHandshakeAck) {
10822 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10823 return;
10824 }
10825 EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective());
10826 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10827 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10828 }
10829 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10830 use_tagging_decrypter();
10831 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10832 std::make_unique<TaggingEncrypter>(0x02));
10833 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10834 SetDecrypter(ENCRYPTION_HANDSHAKE,
10835 std::make_unique<StrictTaggingDecrypter>(0x02));
10836 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10837 std::make_unique<TaggingEncrypter>(0x02));
10838 // Receives packet 1000 in handshake data.
10839 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_HANDSHAKE);
10840 EXPECT_TRUE(connection_.HasPendingAcks());
10841 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10842 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10843
10844 // Receives packet 1001 in handshake data.
10845 ProcessCryptoPacketAtLevel(1001, ENCRYPTION_HANDSHAKE);
10846 EXPECT_TRUE(connection_.HasPendingAcks());
10847 // Receives packet 1002 in handshake data.
10848 ProcessCryptoPacketAtLevel(1002, ENCRYPTION_HANDSHAKE);
10849 EXPECT_FALSE(writer_->ack_frames().empty());
10850 // Verify CRYPTO frame is bundled with HANDSHAKE ACK.
10851 EXPECT_FALSE(writer_->crypto_frames().empty());
10852}
10853
10854// Regresstion test for b/156232673.
10855TEST_P(QuicConnectionTest, CoalescePacketOfLowerEncryptionLevel) {
10856 if (!connection_.version().CanSendCoalescedPackets()) {
10857 return;
10858 }
10859 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10860 {
10861 QuicConnection::ScopedPacketFlusher flusher(&connection_);
10862 use_tagging_decrypter();
10863 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10864 std::make_unique<TaggingEncrypter>(0x01));
10865 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
10866 std::make_unique<TaggingEncrypter>(0x02));
10867 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
10868 SendStreamDataToPeer(2, std::string(1286, 'a'), 0, NO_FIN, nullptr);
10869 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10870 // Try to coalesce a HANDSHAKE packet after 1-RTT packet.
10871 // Verify soft max packet length gets resumed and handshake packet gets
10872 // successfully sent.
10873 connection_.SendCryptoDataWithString("a", 0, ENCRYPTION_HANDSHAKE);
10874 }
10875}
10876
10877// Regression test for b/160790422.
10878TEST_P(QuicConnectionTest, ServerRetransmitsHandshakeDataEarly) {
10879 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10880 return;
10881 }
10882 set_perspective(Perspective::IS_SERVER);
10883 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10884 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10885 }
10886 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10887 use_tagging_decrypter();
10888 // Receives packet 1000 in initial data.
10889 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10890 EXPECT_TRUE(connection_.HasPendingAcks());
10891
10892 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10893 std::make_unique<TaggingEncrypter>(0x01));
10894 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10895 // Send INITIAL 1.
10896 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
10897 QuicTime expected_pto_time =
10898 connection_.sent_packet_manager().GetRetransmissionTime();
10899
10900 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
10901 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10902 std::make_unique<TaggingEncrypter>(0x02));
10903 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10904 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10905 // Send HANDSHAKE 2 and 3.
10906 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
10907 connection_.SendCryptoDataWithString("bar", 3, ENCRYPTION_HANDSHAKE);
10908 // Verify PTO time does not change.
10909 EXPECT_EQ(expected_pto_time,
10910 connection_.sent_packet_manager().GetRetransmissionTime());
10911
10912 // Receives ACK for HANDSHAKE 2.
10913 QuicFrames frames;
10914 auto ack_frame = InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
10915 frames.push_back(QuicFrame(&ack_frame));
10916 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
10917 ProcessFramesPacketAtLevel(30, frames, ENCRYPTION_HANDSHAKE);
10918 // Discard INITIAL key.
10919 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
10920 connection_.NeuterUnencryptedPackets();
10921 // Receives PING from peer.
10922 frames.clear();
10923 frames.push_back(QuicFrame(QuicPingFrame()));
10924 frames.push_back(QuicFrame(QuicPaddingFrame(3)));
10925 ProcessFramesPacketAtLevel(31, frames, ENCRYPTION_HANDSHAKE);
10926 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
10927 connection_.GetAckAlarm()->deadline());
10928 // Fire ACK alarm.
10929 clock_.AdvanceTime(kAlarmGranularity);
10930 connection_.GetAckAlarm()->Fire();
10931 EXPECT_FALSE(writer_->ack_frames().empty());
10932 // Verify handshake data gets retransmitted early.
10933 EXPECT_FALSE(writer_->crypto_frames().empty());
10934}
10935
10936// Regression test for b/161228202
10937TEST_P(QuicConnectionTest, InflatedRttSample) {
10938 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
10939 return;
10940 }
10941 // 30ms RTT.
10942 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
10943 set_perspective(Perspective::IS_SERVER);
10944 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
10945 use_tagging_decrypter();
10946 // Receives packet 1000 in initial data.
10947 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
10948 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
10949 }
10950 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
10951 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
10952 EXPECT_TRUE(connection_.HasPendingAcks());
10953
10954 connection_.SetEncrypter(ENCRYPTION_INITIAL,
10955 std::make_unique<TaggingEncrypter>(0x01));
10956 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
10957 // Send INITIAL 1.
10958 std::string initial_crypto_data(512, 'a');
10959 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
10960 ENCRYPTION_INITIAL);
10961 ASSERT_TRUE(connection_.sent_packet_manager()
10962 .GetRetransmissionTime()
10963 .IsInitialized());
10964 QuicTime::Delta pto_timeout =
10965 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
10966 // Send Handshake 2.
10967 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
10968 std::make_unique<TaggingEncrypter>(0x02));
10969 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
10970 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
10971 std::string handshake_crypto_data(1024, 'a');
10972 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
10973 ENCRYPTION_HANDSHAKE);
10974
10975 // INITIAL 1 gets lost and PTO fires.
10976 clock_.AdvanceTime(pto_timeout);
10977 connection_.GetRetransmissionAlarm()->Fire();
10978
10979 clock_.AdvanceTime(kTestRTT);
10980 // Assume retransmitted INITIAL gets received.
10981 QuicFrames frames;
10982 auto ack_frame = InitAckFrame({{QuicPacketNumber(4), QuicPacketNumber(5)}});
10983 frames.push_back(QuicFrame(&ack_frame));
10984 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
10985 .Times(AnyNumber());
10986 ProcessFramesPacketAtLevel(1001, frames, ENCRYPTION_INITIAL);
10987 EXPECT_EQ(kTestRTT, rtt_stats->latest_rtt());
10988 // Because retransmitted INITIAL gets received so HANDSHAKE 2 gets processed.
10989 frames.clear();
10990 // HANDSHAKE 5 is also processed.
10991 QuicAckFrame ack_frame2 =
10992 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)},
10993 {QuicPacketNumber(5), QuicPacketNumber(6)}});
10994 ack_frame2.ack_delay_time = QuicTime::Delta::Zero();
10995 frames.push_back(QuicFrame(&ack_frame2));
10996 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_HANDSHAKE);
10997 // Verify RTT inflation gets mitigated.
10998 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
10999}
11000
11001// Regression test for b/161228202
11002TEST_P(QuicConnectionTest, CoalscingPacketCausesInfiniteLoop) {
11003 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
11004 return;
11005 }
11006 set_perspective(Perspective::IS_SERVER);
11007 use_tagging_decrypter();
11008 // Receives packet 1000 in initial data.
11009 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
11010 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
11011 }
11012 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
11013
11014 // Set anti amplification factor to 2, such that RetransmitDataOfSpaceIfAny
11015 // makes no forward progress and causes infinite loop.
birenroyef686222022-09-12 11:34:34 -070011016 SetQuicFlag(quic_anti_amplification_factor, 2);
Bence Békybac04052022-04-07 15:44:29 -040011017
11018 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
11019 EXPECT_TRUE(connection_.HasPendingAcks());
11020
11021 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11022 std::make_unique<TaggingEncrypter>(0x01));
11023 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11024 // Send INITIAL 1.
11025 std::string initial_crypto_data(512, 'a');
11026 connection_.SendCryptoDataWithString(initial_crypto_data, 0,
11027 ENCRYPTION_INITIAL);
11028 ASSERT_TRUE(connection_.sent_packet_manager()
11029 .GetRetransmissionTime()
11030 .IsInitialized());
11031 QuicTime::Delta pto_timeout =
11032 connection_.sent_packet_manager().GetRetransmissionTime() - clock_.Now();
11033 // Send Handshake 2.
11034 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11035 std::make_unique<TaggingEncrypter>(0x02));
11036 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11037 // Verify HANDSHAKE packet is coalesced with INITIAL retransmission.
11038 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
11039 std::string handshake_crypto_data(1024, 'a');
11040 connection_.SendCryptoDataWithString(handshake_crypto_data, 0,
11041 ENCRYPTION_HANDSHAKE);
11042
11043 // INITIAL 1 gets lost and PTO fires.
11044 clock_.AdvanceTime(pto_timeout);
11045 connection_.GetRetransmissionAlarm()->Fire();
11046}
11047
11048TEST_P(QuicConnectionTest, ClientAckDelayForAsyncPacketProcessing) {
11049 if (!version().HasIetfQuicFrames()) {
11050 return;
11051 }
11052 // SetFromConfig is always called after construction from InitializeSession.
11053 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11054 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11055 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11056 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11057 connection_.NeuterUnencryptedPackets();
11058 }));
11059 QuicConfig config;
11060 connection_.SetFromConfig(config);
11061 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11062 use_tagging_decrypter();
11063 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11064 std::make_unique<TaggingEncrypter>(0x01));
11065 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11066 std::make_unique<TaggingEncrypter>(0x01));
11067 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11068
11069 // Received undecryptable HANDSHAKE 2.
11070 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
11071 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
11072 // Received INITIAL 4 (which is retransmission of INITIAL 1) after 100ms.
11073 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
11074 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_INITIAL);
11075 // Generate HANDSHAKE key.
11076 SetDecrypter(ENCRYPTION_HANDSHAKE,
11077 std::make_unique<StrictTaggingDecrypter>(0x01));
11078 EXPECT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
11079 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11080 std::make_unique<TaggingEncrypter>(0x01));
11081 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11082 // Verify HANDSHAKE packet gets processed.
fayangfea655c2022-05-17 08:19:12 -070011083 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
Bence Békybac04052022-04-07 15:44:29 -040011084 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
fayangfea655c2022-05-17 08:19:12 -070011085 // Verify immediate ACK has been sent out when flush went out of scope.
11086 ASSERT_FALSE(connection_.HasPendingAcks());
Bence Békybac04052022-04-07 15:44:29 -040011087 ASSERT_FALSE(writer_->ack_frames().empty());
fayangfea655c2022-05-17 08:19:12 -070011088 // Verify the ack_delay_time in the sent HANDSHAKE ACK frame is 100ms.
11089 EXPECT_EQ(QuicTime::Delta::FromMilliseconds(100),
Bence Békybac04052022-04-07 15:44:29 -040011090 writer_->ack_frames()[0].ack_delay_time);
11091 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
11092}
11093
11094TEST_P(QuicConnectionTest, TestingLiveness) {
11095 const size_t kMinRttMs = 40;
11096 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11097 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(kMinRttMs),
11098 QuicTime::Delta::Zero(), QuicTime::Zero());
11099 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11100 QuicConfig config;
11101
11102 CryptoHandshakeMessage msg;
11103 std::string error_details;
11104 QuicConfig client_config;
11105 client_config.SetInitialStreamFlowControlWindowToSend(
11106 kInitialStreamFlowControlWindowForTest);
11107 client_config.SetInitialSessionFlowControlWindowToSend(
11108 kInitialSessionFlowControlWindowForTest);
11109 client_config.SetIdleNetworkTimeout(QuicTime::Delta::FromSeconds(30));
11110 client_config.ToHandshakeMessage(&msg, connection_.transport_version());
11111 const QuicErrorCode error =
11112 config.ProcessPeerHello(msg, CLIENT, &error_details);
11113 EXPECT_THAT(error, IsQuicNoError());
11114
11115 if (connection_.version().UsesTls()) {
11116 QuicConfigPeer::SetReceivedOriginalConnectionId(
11117 &config, connection_.connection_id());
11118 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11119 &config, connection_.connection_id());
11120 }
11121
11122 connection_.SetFromConfig(config);
11123 connection_.OnHandshakeComplete();
11124 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11125 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11126 EXPECT_FALSE(connection_.MaybeTestLiveness());
11127
haoyuewang7b43efb2022-04-20 16:26:03 -070011128 QuicTime deadline = QuicConnectionPeer::GetIdleNetworkDeadline(&connection_);
Bence Békybac04052022-04-07 15:44:29 -040011129 QuicTime::Delta timeout = deadline - clock_.ApproximateNow();
11130 // Advance time to near the idle timeout.
11131 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(1));
11132 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
11133 EXPECT_TRUE(connection_.MaybeTestLiveness());
11134 // Verify idle deadline does not change.
haoyuewang7b43efb2022-04-20 16:26:03 -070011135 EXPECT_EQ(deadline, QuicConnectionPeer::GetIdleNetworkDeadline(&connection_));
Bence Békybac04052022-04-07 15:44:29 -040011136}
11137
11138TEST_P(QuicConnectionTest, SilentIdleTimeout) {
11139 set_perspective(Perspective::IS_SERVER);
11140 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
11141 if (version().SupportsAntiAmplificationLimit()) {
11142 QuicConnectionPeer::SetAddressValidated(&connection_);
11143 }
11144
11145 QuicConfig config;
11146 QuicConfigPeer::SetNegotiated(&config, true);
11147 if (connection_.version().UsesTls()) {
11148 QuicConfigPeer::SetReceivedOriginalConnectionId(
11149 &config, connection_.connection_id());
11150 QuicConfigPeer::SetReceivedInitialSourceConnectionId(&config,
11151 QuicConnectionId());
11152 }
11153 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11154 connection_.SetFromConfig(config);
11155
11156 EXPECT_TRUE(connection_.connected());
11157 EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11158
11159 if (version().handshake_protocol == PROTOCOL_TLS1_3) {
11160 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
11161 }
11162 EXPECT_CALL(visitor_,
11163 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
11164 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
haoyuewang7b43efb2022-04-20 16:26:03 -070011165 if (!QuicConnectionPeer::GetBandwidthUpdateTimeout(&connection_)
11166 .IsInfinite()) {
11167 // Fires the bandwidth update.
11168 connection_.GetTimeoutAlarm()->Fire();
11169 }
Bence Békybac04052022-04-07 15:44:29 -040011170 connection_.GetTimeoutAlarm()->Fire();
11171 // Verify the connection close packets get serialized and added to
11172 // termination packets list.
11173 EXPECT_NE(nullptr,
11174 QuicConnectionPeer::GetConnectionClosePacket(&connection_));
11175}
11176
11177TEST_P(QuicConnectionTest, DonotSendPing) {
11178 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11179 connection_.OnHandshakeComplete();
11180 EXPECT_TRUE(connection_.connected());
11181 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11182 .WillRepeatedly(Return(true));
11183 EXPECT_FALSE(connection_.GetPingAlarm()->IsSet());
11184 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11185
11186 SendStreamDataToPeer(
11187 GetNthClientInitiatedStreamId(0, connection_.transport_version()),
11188 "GET /", 0, FIN, nullptr);
11189 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11190 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
11191 EXPECT_EQ(QuicTime::Delta::FromSeconds(15),
11192 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11193
11194 // Now recevie an ACK and response of the previous packet, which will move the
11195 // ping alarm forward.
11196 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
11197 QuicFrames frames;
11198 QuicAckFrame ack_frame = InitAckFrame(1);
11199 frames.push_back(QuicFrame(&ack_frame));
11200 frames.push_back(QuicFrame(QuicStreamFrame(
11201 GetNthClientInitiatedStreamId(0, connection_.transport_version()), true,
11202 0u, absl::string_view())));
11203 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
11204 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
11205 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11206 ProcessFramesPacketAtLevel(1, frames, ENCRYPTION_FORWARD_SECURE);
11207 EXPECT_TRUE(connection_.GetPingAlarm()->IsSet());
11208 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
11209 // The ping timer is set slightly less than 15 seconds in the future, because
11210 // of the 1s ping timer alarm granularity.
11211 EXPECT_EQ(
11212 QuicTime::Delta::FromSeconds(15) - QuicTime::Delta::FromMilliseconds(5),
11213 connection_.GetPingAlarm()->deadline() - clock_.ApproximateNow());
11214
11215 clock_.AdvanceTime(QuicTime::Delta::FromSeconds(15));
11216 // Suppose now ShouldKeepConnectionAlive returns false.
11217 EXPECT_CALL(visitor_, ShouldKeepConnectionAlive())
11218 .WillRepeatedly(Return(false));
11219 // Verify PING does not get sent.
11220 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
11221 connection_.GetPingAlarm()->Fire();
11222}
11223
11224// Regression test for b/159698337
11225TEST_P(QuicConnectionTest, DuplicateAckCausesLostPackets) {
11226 if (!GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11227 return;
11228 }
11229 // Finish handshake.
11230 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
11231 notifier_.NeuterUnencryptedData();
11232 connection_.NeuterUnencryptedPackets();
11233 connection_.OnHandshakeComplete();
11234 EXPECT_CALL(visitor_, GetHandshakeState())
11235 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11236
11237 std::string data(1200, 'a');
11238 // Send data packets 1 - 5.
11239 for (size_t i = 0; i < 5; ++i) {
11240 SendStreamDataToPeer(
11241 GetNthClientInitiatedStreamId(1, connection_.transport_version()), data,
11242 i * 1200, i == 4 ? FIN : NO_FIN, nullptr);
11243 }
11244 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
11245
11246 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _)).Times(3);
11247
11248 // ACK packet 5 and 1 and 2 are detected lost.
11249 QuicAckFrame frame =
11250 InitAckFrame({{QuicPacketNumber(5), QuicPacketNumber(6)}});
11251 LostPacketVector lost_packets;
11252 lost_packets.push_back(
11253 LostPacket(QuicPacketNumber(1), kMaxOutgoingPacketSize));
11254 lost_packets.push_back(
11255 LostPacket(QuicPacketNumber(2), kMaxOutgoingPacketSize));
11256 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11257 .Times(AnyNumber())
11258 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11259 Return(LossDetectionInterface::DetectionStats())));
11260 ProcessAckPacket(1, &frame);
11261 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11262 QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
11263 EXPECT_TRUE(retransmission_alarm->IsSet());
11264
11265 // ACK packet 1 - 5 and 7.
11266 QuicAckFrame frame2 =
11267 InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(6)},
11268 {QuicPacketNumber(7), QuicPacketNumber(8)}});
11269 ProcessAckPacket(2, &frame2);
11270 EXPECT_TRUE(connection_.BlackholeDetectionInProgress());
11271
11272 // ACK packet 7 again and assume packet 6 is detected lost.
11273 QuicAckFrame frame3 =
11274 InitAckFrame({{QuicPacketNumber(7), QuicPacketNumber(8)}});
11275 lost_packets.clear();
11276 lost_packets.push_back(
11277 LostPacket(QuicPacketNumber(6), kMaxOutgoingPacketSize));
11278 EXPECT_CALL(*loss_algorithm_, DetectLosses(_, _, _, _, _, _))
11279 .Times(AnyNumber())
11280 .WillOnce(DoAll(SetArgPointee<5>(lost_packets),
11281 Return(LossDetectionInterface::DetectionStats())));
11282 ProcessAckPacket(3, &frame3);
11283 // Make sure loss detection is cancelled even there is no new acked packets.
11284 EXPECT_FALSE(connection_.BlackholeDetectionInProgress());
11285}
11286
11287TEST_P(QuicConnectionTest, ShorterIdleTimeoutOnSentPackets) {
11288 EXPECT_TRUE(connection_.connected());
11289 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
11290 rtt_stats->UpdateRtt(QuicTime::Delta::FromMilliseconds(100),
11291 QuicTime::Delta::Zero(), QuicTime::Zero());
11292
11293 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11294 QuicConfig config;
11295 config.SetClientConnectionOptions(QuicTagVector{kFIDT});
11296 QuicConfigPeer::SetNegotiated(&config, true);
11297 if (GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
11298 EXPECT_CALL(visitor_, GetHandshakeState())
11299 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
11300 }
11301 if (connection_.version().UsesTls()) {
11302 QuicConfigPeer::SetReceivedOriginalConnectionId(
11303 &config, connection_.connection_id());
11304 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
11305 &config, connection_.connection_id());
11306 }
11307 connection_.SetFromConfig(config);
11308
11309 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11310 // Send a packet close to timeout.
11311 QuicTime::Delta timeout =
11312 connection_.GetTimeoutAlarm()->deadline() - clock_.Now();
11313 clock_.AdvanceTime(timeout - QuicTime::Delta::FromSeconds(1));
11314 // Send stream data.
11315 SendStreamDataToPeer(
11316 GetNthClientInitiatedStreamId(1, connection_.transport_version()), "foo",
11317 0, FIN, nullptr);
11318 // Verify this sent packet does not extend idle timeout since 1s is > PTO
11319 // delay.
11320 ASSERT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
11321 EXPECT_EQ(QuicTime::Delta::FromSeconds(1),
11322 connection_.GetTimeoutAlarm()->deadline() - clock_.Now());
11323
11324 // Received an ACK 100ms later.
11325 clock_.AdvanceTime(timeout - QuicTime::Delta::FromMilliseconds(100));
11326 QuicAckFrame ack = InitAckFrame(1);
11327 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
11328 ProcessAckPacket(1, &ack);
11329 // Verify idle timeout gets extended.
11330 EXPECT_EQ(clock_.Now() + timeout, connection_.GetTimeoutAlarm()->deadline());
11331}
11332
11333// Regression test for b/166255274
11334TEST_P(QuicConnectionTest,
11335 ReserializeInitialPacketInCoalescerAfterDiscardingInitialKey) {
11336 if (!connection_.version().CanSendCoalescedPackets()) {
11337 return;
11338 }
11339 use_tagging_decrypter();
11340 connection_.SetEncrypter(ENCRYPTION_INITIAL,
11341 std::make_unique<TaggingEncrypter>(0x01));
11342 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
11343 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
11344 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
11345 EXPECT_TRUE(connection_.HasPendingAcks());
11346 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
11347 std::make_unique<TaggingEncrypter>(0x02));
11348 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
11349 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
11350 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
11351 connection_.NeuterUnencryptedPackets();
11352 }));
11353 {
11354 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11355 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
11356 // Verify the packet is on hold.
11357 EXPECT_EQ(0u, writer_->packets_write_attempts());
11358 // Flush pending ACKs.
11359 connection_.GetAckAlarm()->Fire();
11360 }
11361 EXPECT_FALSE(connection_.packet_creator().HasPendingFrames());
11362 // The ACK frame is deleted along with initial_packet_ in coalescer. Sending
11363 // connection close would cause this (released) ACK frame be serialized (and
11364 // crashes).
11365 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
11366 ProcessDataPacketAtLevel(1000, false, ENCRYPTION_FORWARD_SECURE);
11367 EXPECT_TRUE(connection_.connected());
11368}
11369
11370TEST_P(QuicConnectionTest, PathValidationOnNewSocketSuccess) {
danzh87605712022-04-11 14:36:39 -070011371 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011372 return;
11373 }
11374 PathProbeTestInit(Perspective::IS_CLIENT);
11375 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11376 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11377 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11378 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11379 .Times(AtLeast(1u))
11380 .WillOnce(Invoke([&]() {
11381 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11382 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11383 EXPECT_EQ(1u, new_writer.padding_frames().size());
11384 EXPECT_EQ(kNewSelfAddress.host(),
11385 new_writer.last_write_source_address());
11386 }));
11387 bool success = false;
11388 connection_.ValidatePath(
11389 std::make_unique<TestQuicPathValidationContext>(
11390 kNewSelfAddress, connection_.peer_address(), &new_writer),
11391 std::make_unique<TestValidationResultDelegate>(
11392 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11393 EXPECT_EQ(0u, writer_->packets_write_attempts());
11394
11395 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011396 frames.push_back(QuicFrame(QuicPathResponseFrame(
Bence Békybac04052022-04-07 15:44:29 -040011397 99, new_writer.path_challenge_frames().front().data_buffer)));
11398 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
11399 ENCRYPTION_FORWARD_SECURE);
11400 EXPECT_TRUE(success);
11401}
11402
11403TEST_P(QuicConnectionTest, NewPathValidationCancelsPreviousOne) {
danzh87605712022-04-11 14:36:39 -070011404 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011405 return;
11406 }
11407 PathProbeTestInit(Perspective::IS_CLIENT);
11408 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11409 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11410 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11411 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11412 .Times(AtLeast(1u))
11413 .WillOnce(Invoke([&]() {
11414 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11415 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11416 EXPECT_EQ(1u, new_writer.padding_frames().size());
11417 EXPECT_EQ(kNewSelfAddress.host(),
11418 new_writer.last_write_source_address());
11419 }));
11420 bool success = true;
11421 connection_.ValidatePath(
11422 std::make_unique<TestQuicPathValidationContext>(
11423 kNewSelfAddress, connection_.peer_address(), &new_writer),
11424 std::make_unique<TestValidationResultDelegate>(
11425 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11426 EXPECT_EQ(0u, writer_->packets_write_attempts());
11427
11428 // Start another path validation request.
11429 const QuicSocketAddress kNewSelfAddress2(QuicIpAddress::Any4(), 12346);
11430 EXPECT_NE(kNewSelfAddress2, connection_.self_address());
11431 TestPacketWriter new_writer2(version(), &clock_, Perspective::IS_CLIENT);
11432 if (!connection_.connection_migration_use_new_cid()) {
11433 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11434 .Times(AtLeast(1u))
11435 .WillOnce(Invoke([&]() {
11436 EXPECT_EQ(1u, new_writer2.packets_write_attempts());
11437 EXPECT_EQ(1u, new_writer2.path_challenge_frames().size());
11438 EXPECT_EQ(1u, new_writer2.padding_frames().size());
11439 EXPECT_EQ(kNewSelfAddress2.host(),
11440 new_writer2.last_write_source_address());
11441 }));
11442 }
11443 bool success2 = false;
11444 connection_.ValidatePath(
11445 std::make_unique<TestQuicPathValidationContext>(
11446 kNewSelfAddress2, connection_.peer_address(), &new_writer2),
11447 std::make_unique<TestValidationResultDelegate>(
11448 &connection_, kNewSelfAddress2, connection_.peer_address(),
11449 &success2));
11450 EXPECT_FALSE(success);
11451 if (connection_.connection_migration_use_new_cid()) {
11452 // There is no pening path validation as there is no available connection
11453 // ID.
11454 EXPECT_FALSE(connection_.HasPendingPathValidation());
11455 } else {
11456 EXPECT_TRUE(connection_.HasPendingPathValidation());
11457 }
11458}
11459
11460// Regression test for b/182571515.
11461TEST_P(QuicConnectionTest, PathValidationRetry) {
danzh87605712022-04-11 14:36:39 -070011462 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011463 return;
11464 }
11465 PathProbeTestInit(Perspective::IS_CLIENT);
11466
11467 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11468 .Times(2u)
11469 .WillRepeatedly(Invoke([&]() {
11470 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11471 EXPECT_EQ(1u, writer_->padding_frames().size());
11472 }));
11473 bool success = true;
11474 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11475 connection_.self_address(),
11476 connection_.peer_address(), writer_.get()),
11477 std::make_unique<TestValidationResultDelegate>(
11478 &connection_, connection_.self_address(),
11479 connection_.peer_address(), &success));
11480 EXPECT_EQ(1u, writer_->packets_write_attempts());
11481 EXPECT_TRUE(connection_.HasPendingPathValidation());
11482
11483 // Retry after time out.
11484 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11485 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11486 static_cast<TestAlarmFactory::TestAlarm*>(
11487 QuicPathValidatorPeer::retry_timer(
11488 QuicConnectionPeer::path_validator(&connection_)))
11489 ->Fire();
11490 EXPECT_EQ(2u, writer_->packets_write_attempts());
11491}
11492
11493TEST_P(QuicConnectionTest, PathValidationReceivesStatelessReset) {
danzh87605712022-04-11 14:36:39 -070011494 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011495 return;
11496 }
11497 PathProbeTestInit(Perspective::IS_CLIENT);
11498 QuicConfig config;
11499 QuicConfigPeer::SetReceivedStatelessResetToken(&config,
11500 kTestStatelessResetToken);
11501 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
11502 connection_.SetFromConfig(config);
11503 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11504 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11505 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11506 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11507 .Times(AtLeast(1u))
11508 .WillOnce(Invoke([&]() {
11509 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11510 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11511 EXPECT_EQ(1u, new_writer.padding_frames().size());
11512 EXPECT_EQ(kNewSelfAddress.host(),
11513 new_writer.last_write_source_address());
11514 }));
11515 bool success = true;
11516 connection_.ValidatePath(
11517 std::make_unique<TestQuicPathValidationContext>(
11518 kNewSelfAddress, connection_.peer_address(), &new_writer),
11519 std::make_unique<TestValidationResultDelegate>(
11520 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11521 EXPECT_EQ(0u, writer_->packets_write_attempts());
11522 EXPECT_TRUE(connection_.HasPendingPathValidation());
11523
11524 std::unique_ptr<QuicEncryptedPacket> packet(
11525 QuicFramer::BuildIetfStatelessResetPacket(connection_id_,
11526 /*received_packet_length=*/100,
11527 kTestStatelessResetToken));
11528 std::unique_ptr<QuicReceivedPacket> received(
11529 ConstructReceivedPacket(*packet, QuicTime::Zero()));
11530 EXPECT_CALL(visitor_, OnConnectionClosed(_, _)).Times(0);
11531 connection_.ProcessUdpPacket(kNewSelfAddress, kPeerAddress, *received);
11532 EXPECT_FALSE(connection_.HasPendingPathValidation());
11533 EXPECT_FALSE(success);
11534}
11535
11536// Tests that PATH_CHALLENGE is dropped if it is sent via a blocked alternative
11537// writer.
11538TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedNewSocket) {
11539 if (!VersionHasIetfQuicFrames(connection_.version().transport_version) ||
11540 !connection_.connection_migration_use_new_cid()) {
11541 return;
11542 }
11543 PathProbeTestInit(Perspective::IS_CLIENT);
11544 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11545 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11546 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11547 new_writer.BlockOnNextWrite();
11548 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(0);
11549 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11550 .Times(AtLeast(1))
11551 .WillOnce(Invoke([&]() {
11552 // Even though the socket is blocked, the PATH_CHALLENGE should still be
11553 // treated as sent.
11554 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11555 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11556 EXPECT_EQ(1u, new_writer.padding_frames().size());
11557 EXPECT_EQ(kNewSelfAddress.host(),
11558 new_writer.last_write_source_address());
11559 }));
11560 bool success = false;
11561 connection_.ValidatePath(
11562 std::make_unique<TestQuicPathValidationContext>(
11563 kNewSelfAddress, connection_.peer_address(), &new_writer),
11564 std::make_unique<TestValidationResultDelegate>(
11565 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11566 EXPECT_EQ(0u, writer_->packets_write_attempts());
11567
11568 new_writer.SetWritable();
11569 // Write event on the default socket shouldn't make any difference.
11570 connection_.OnCanWrite();
11571 // A NEW_CONNECTION_ID frame is received in PathProbeTestInit and OnCanWrite
11572 // will write a acking packet.
11573 EXPECT_EQ(1u, writer_->packets_write_attempts());
11574 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11575}
11576
11577// Tests that PATH_CHALLENGE is dropped if it is sent via the default writer
11578// and the writer is blocked.
11579TEST_P(QuicConnectionTest, SendPathChallengeUsingBlockedDefaultSocket) {
danzh87605712022-04-11 14:36:39 -070011580 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011581 return;
11582 }
11583 PathProbeTestInit(Perspective::IS_SERVER);
11584 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11585 writer_->BlockOnNextWrite();
11586 // 1st time is after writer returns WRITE_STATUS_BLOCKED. 2nd time is in
11587 // ShouldGeneratePacket().
11588 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(2));
11589 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
11590 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11591 .Times(AtLeast(1u))
11592 .WillOnce(Invoke([&]() {
11593 // This packet isn't sent actually, instead it is buffered in the
11594 // connection.
11595 EXPECT_EQ(1u, writer_->packets_write_attempts());
11596 if (connection_.validate_client_address()) {
11597 EXPECT_EQ(1u, writer_->path_response_frames().size());
11598 EXPECT_EQ(0,
11599 memcmp(&path_challenge_payload,
11600 &writer_->path_response_frames().front().data_buffer,
11601 sizeof(path_challenge_payload)));
11602 }
11603 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11604 EXPECT_EQ(1u, writer_->padding_frames().size());
11605 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11606 }))
11607 .WillRepeatedly(Invoke([&]() {
11608 // Only one PATH_CHALLENGE should be sent out.
11609 EXPECT_EQ(0u, writer_->path_challenge_frames().size());
11610 }));
11611 bool success = false;
11612 if (connection_.validate_client_address()) {
11613 // Receiving a PATH_CHALLENGE from the new peer address should trigger
11614 // address validation.
11615 QuicFrames frames;
11616 frames.push_back(
wubd0152ca2022-04-08 08:26:44 -070011617 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040011618 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11619 ENCRYPTION_FORWARD_SECURE);
11620 } else {
11621 // Manually start to validate the new peer address.
11622 connection_.ValidatePath(
11623 std::make_unique<TestQuicPathValidationContext>(
11624 connection_.self_address(), kNewPeerAddress, writer_.get()),
11625 std::make_unique<TestValidationResultDelegate>(
11626 &connection_, connection_.self_address(), kNewPeerAddress,
11627 &success));
11628 }
11629 EXPECT_EQ(1u, writer_->packets_write_attempts());
11630
11631 // Try again with the new socket blocked from the beginning. The 2nd
11632 // PATH_CHALLENGE shouldn't be serialized, but be dropped.
11633 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
11634 static_cast<test::MockRandom*>(helper_->GetRandomGenerator())->ChangeValue();
11635 static_cast<TestAlarmFactory::TestAlarm*>(
11636 QuicPathValidatorPeer::retry_timer(
11637 QuicConnectionPeer::path_validator(&connection_)))
11638 ->Fire();
11639
11640 // No more write attempt should be made.
11641 EXPECT_EQ(1u, writer_->packets_write_attempts());
11642
11643 writer_->SetWritable();
11644 // OnCanWrite() should actually write out the 1st PATH_CHALLENGE packet
11645 // buffered earlier, thus incrementing the write counter. It may also send
11646 // ACKs to previously received packets.
11647 connection_.OnCanWrite();
11648 EXPECT_LE(2u, writer_->packets_write_attempts());
11649}
11650
11651// Tests that write error on the alternate socket should be ignored.
11652TEST_P(QuicConnectionTest, SendPathChallengeFailOnNewSocket) {
danzh87605712022-04-11 14:36:39 -070011653 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011654 return;
11655 }
11656 PathProbeTestInit(Perspective::IS_CLIENT);
11657 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
11658 EXPECT_NE(kNewSelfAddress, connection_.self_address());
11659 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
11660 new_writer.SetShouldWriteFail();
11661 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11662 .Times(0);
11663 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11664
11665 bool success = false;
11666 connection_.ValidatePath(
11667 std::make_unique<TestQuicPathValidationContext>(
11668 kNewSelfAddress, connection_.peer_address(), &new_writer),
11669 std::make_unique<TestValidationResultDelegate>(
11670 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
11671 EXPECT_EQ(1u, new_writer.packets_write_attempts());
11672 EXPECT_EQ(1u, new_writer.path_challenge_frames().size());
11673 EXPECT_EQ(1u, new_writer.padding_frames().size());
11674 EXPECT_EQ(kNewSelfAddress.host(), new_writer.last_write_source_address());
11675
11676 EXPECT_EQ(0u, writer_->packets_write_attempts());
11677 // Regardless of the write error, the connection should still be connected.
11678 EXPECT_TRUE(connection_.connected());
11679}
11680
11681// Tests that write error while sending PATH_CHALLANGE from the default socket
11682// should close the connection.
11683TEST_P(QuicConnectionTest, SendPathChallengeFailOnDefaultPath) {
danzh87605712022-04-11 14:36:39 -070011684 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011685 return;
11686 }
11687 PathProbeTestInit(Perspective::IS_CLIENT);
11688
11689 writer_->SetShouldWriteFail();
11690 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11691 .WillOnce(
11692 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11693 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11694 }));
11695 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11696 {
11697 // Add a flusher to force flush, otherwise the frames will remain in the
11698 // packet creator.
11699 bool success = false;
11700 QuicConnection::ScopedPacketFlusher flusher(&connection_);
11701 connection_.ValidatePath(std::make_unique<TestQuicPathValidationContext>(
11702 connection_.self_address(),
11703 connection_.peer_address(), writer_.get()),
11704 std::make_unique<TestValidationResultDelegate>(
11705 &connection_, connection_.self_address(),
11706 connection_.peer_address(), &success));
11707 }
11708 EXPECT_EQ(1u, writer_->packets_write_attempts());
11709 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11710 EXPECT_EQ(1u, writer_->padding_frames().size());
11711 EXPECT_EQ(connection_.peer_address(), writer_->last_write_peer_address());
11712 EXPECT_FALSE(connection_.connected());
11713 // Closing connection should abandon ongoing path validation.
11714 EXPECT_FALSE(connection_.HasPendingPathValidation());
11715}
11716
11717TEST_P(QuicConnectionTest, SendPathChallengeFailOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011718 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011719 return;
11720 }
11721 PathProbeTestInit(Perspective::IS_CLIENT);
11722
11723 writer_->SetShouldWriteFail();
11724 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11725 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11726 .WillOnce(
11727 Invoke([](QuicConnectionCloseFrame frame, ConnectionCloseSource) {
11728 EXPECT_EQ(QUIC_PACKET_WRITE_ERROR, frame.quic_error_code);
11729 }));
11730 // Sending PATH_CHALLENGE to trigger a flush write which will fail and close
11731 // the connection.
11732 bool success = false;
11733 connection_.ValidatePath(
11734 std::make_unique<TestQuicPathValidationContext>(
11735 connection_.self_address(), kNewPeerAddress, writer_.get()),
11736 std::make_unique<TestValidationResultDelegate>(
11737 &connection_, connection_.self_address(), kNewPeerAddress, &success));
11738
11739 EXPECT_EQ(1u, writer_->packets_write_attempts());
11740 EXPECT_FALSE(connection_.HasPendingPathValidation());
11741 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11742 EXPECT_EQ(1u, writer_->padding_frames().size());
11743 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11744 EXPECT_FALSE(connection_.connected());
11745}
11746
11747TEST_P(QuicConnectionTest,
11748 SendPathChallengeFailPacketTooBigOnAlternativePeerAddress) {
danzh87605712022-04-11 14:36:39 -070011749 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040011750 return;
11751 }
11752 PathProbeTestInit(Perspective::IS_CLIENT);
11753 // Make sure there is no outstanding ACK_FRAME to write.
11754 connection_.OnCanWrite();
11755 uint32_t num_packets_write_attempts = writer_->packets_write_attempts();
11756
11757 writer_->SetShouldWriteFail();
11758 writer_->SetWriteError(*writer_->MessageTooBigErrorCode());
11759 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Any4(), 12345);
11760 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
11761 .Times(0u);
11762 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0u);
11763 // Sending PATH_CHALLENGE to trigger a flush write which will fail with
11764 // MSG_TOO_BIG.
11765 bool success = false;
11766 connection_.ValidatePath(
11767 std::make_unique<TestQuicPathValidationContext>(
11768 connection_.self_address(), kNewPeerAddress, writer_.get()),
11769 std::make_unique<TestValidationResultDelegate>(
11770 &connection_, connection_.self_address(), kNewPeerAddress, &success));
11771 EXPECT_TRUE(connection_.HasPendingPathValidation());
11772 // Connection shouldn't be closed.
11773 EXPECT_TRUE(connection_.connected());
11774 EXPECT_EQ(++num_packets_write_attempts, writer_->packets_write_attempts());
11775 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
11776 EXPECT_EQ(1u, writer_->padding_frames().size());
11777 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11778}
11779
11780// Check that if there are two PATH_CHALLENGE frames in the packet, the latter
11781// one is ignored.
11782TEST_P(QuicConnectionTest, ReceiveMultiplePathChallenge) {
11783 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11784 return;
11785 }
11786 PathProbeTestInit(Perspective::IS_SERVER);
11787
11788 QuicPathFrameBuffer path_frame_buffer1{0, 1, 2, 3, 4, 5, 6, 7};
11789 QuicPathFrameBuffer path_frame_buffer2{8, 9, 10, 11, 12, 13, 14, 15};
11790 QuicFrames frames;
wubd0152ca2022-04-08 08:26:44 -070011791 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer1)));
11792 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer2)));
Bence Békybac04052022-04-07 15:44:29 -040011793 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11794 /*port=*/23456);
11795
11796 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0);
11797
11798 // Expect 2 packets to be sent: the first are padded PATH_RESPONSE(s) to the
11799 // alternative peer address. The 2nd is a ACK-only packet to the original
11800 // peer address.
11801 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11802 .Times(2)
11803 .WillOnce(Invoke([=]() {
11804 EXPECT_EQ(1u, writer_->path_response_frames().size());
11805 // The final check is to ensure that the random data in the response
11806 // matches the random data from the challenge.
11807 EXPECT_EQ(0,
11808 memcmp(path_frame_buffer1.data(),
11809 &(writer_->path_response_frames().front().data_buffer),
11810 sizeof(path_frame_buffer1)));
11811 EXPECT_EQ(1u, writer_->padding_frames().size());
11812 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11813 }))
11814 .WillOnce(Invoke([=]() {
11815 // The last write of ACK-only packet should still use the old peer
11816 // address.
11817 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11818 }));
11819 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11820 ENCRYPTION_FORWARD_SECURE);
11821}
11822
11823TEST_P(QuicConnectionTest, ReceiveStreamFrameBeforePathChallenge) {
11824 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11825 return;
11826 }
11827 PathProbeTestInit(Perspective::IS_SERVER);
11828
11829 QuicFrames frames;
11830 frames.push_back(QuicFrame(frame1_));
11831 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070011832 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
fayang161ce6e2022-07-01 18:02:11 -070011833 frames.push_back(QuicFrame(QuicPaddingFrame(-1)));
Bence Békybac04052022-04-07 15:44:29 -040011834 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
11835 /*port=*/23456);
11836
11837 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
11838 EXPECT_CALL(*send_algorithm_, OnConnectionMigration())
11839 .Times(connection_.validate_client_address() ? 0u : 1u);
11840 EXPECT_CALL(visitor_, OnStreamFrame(_))
11841 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
11842 // Send some data on the stream. The STREAM_FRAME should be built into
11843 // one packet together with the latter PATH_RESPONSE and PATH_CHALLENGE.
11844 const std::string data{"response body"};
11845 connection_.producer()->SaveStreamData(frame.stream_id, data);
11846 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11847 NO_FIN);
11848 }));
11849 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11850 .Times(connection_.validate_client_address() ? 0u : 1u);
11851 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11852 ENCRYPTION_FORWARD_SECURE);
11853
11854 // Verify that this packet contains a STREAM_FRAME and a
11855 // PATH_RESPONSE_FRAME.
11856 EXPECT_EQ(1u, writer_->stream_frames().size());
11857 EXPECT_EQ(1u, writer_->path_response_frames().size());
11858 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
11859 writer_->path_challenge_frames().size());
11860 // The final check is to ensure that the random data in the response
11861 // matches the random data from the challenge.
11862 EXPECT_EQ(0, memcmp(path_frame_buffer.data(),
11863 &(writer_->path_response_frames().front().data_buffer),
11864 sizeof(path_frame_buffer)));
11865 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
11866 writer_->path_challenge_frames().size());
11867 EXPECT_EQ(1u, writer_->padding_frames().size());
11868 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11869 if (connection_.validate_client_address()) {
11870 EXPECT_TRUE(connection_.HasPendingPathValidation());
11871 }
11872}
11873
11874TEST_P(QuicConnectionTest, ReceiveStreamFrameFollowingPathChallenge) {
11875 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11876 return;
11877 }
11878 PathProbeTestInit(Perspective::IS_SERVER);
11879
11880 QuicFrames frames;
11881 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070011882 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040011883 // PATH_RESPONSE should be flushed out before the rest packet is parsed.
11884 frames.push_back(QuicFrame(frame1_));
11885 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
11886 /*port=*/23456);
11887 QuicByteCount received_packet_size;
11888 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11889 .Times(AtLeast(1u))
11890 .WillOnce(Invoke([=, &received_packet_size]() {
11891 // Verify that this packet contains a PATH_RESPONSE_FRAME.
11892 EXPECT_EQ(0u, writer_->stream_frames().size());
11893 EXPECT_EQ(1u, writer_->path_response_frames().size());
11894 // The final check is to ensure that the random data in the response
11895 // matches the random data from the challenge.
11896 EXPECT_EQ(0,
11897 memcmp(path_frame_buffer.data(),
11898 &(writer_->path_response_frames().front().data_buffer),
11899 sizeof(path_frame_buffer)));
11900 EXPECT_EQ(connection_.validate_client_address() ? 1u : 0u,
11901 writer_->path_challenge_frames().size());
11902 EXPECT_EQ(1u, writer_->padding_frames().size());
11903 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11904 received_packet_size =
11905 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_);
11906 }));
11907 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE));
11908 EXPECT_CALL(*send_algorithm_, OnConnectionMigration())
11909 .Times(connection_.validate_client_address() ? 0u : 1u);
11910 EXPECT_CALL(visitor_, OnStreamFrame(_))
11911 .WillOnce(Invoke([=](const QuicStreamFrame& frame) {
11912 // Send some data on the stream. The STREAM_FRAME should be built into a
11913 // new packet but throttled by anti-amplifciation limit.
11914 const std::string data{"response body"};
11915 connection_.producer()->SaveStreamData(frame.stream_id, data);
11916 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11917 NO_FIN);
11918 }));
11919
11920 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11921 ENCRYPTION_FORWARD_SECURE);
11922 if (!connection_.validate_client_address()) {
11923 return;
11924 }
11925 EXPECT_TRUE(connection_.HasPendingPathValidation());
11926 EXPECT_EQ(0u,
11927 QuicConnectionPeer::BytesReceivedOnAlternativePath(&connection_));
11928 EXPECT_EQ(
11929 received_packet_size,
11930 QuicConnectionPeer::BytesReceivedBeforeAddressValidation(&connection_));
11931}
11932
11933// Tests that a PATH_CHALLENGE is received in between other frames in an out of
11934// order packet.
11935TEST_P(QuicConnectionTest, PathChallengeWithDataInOutOfOrderPacket) {
11936 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
11937 return;
11938 }
11939 PathProbeTestInit(Perspective::IS_SERVER);
11940
11941 QuicFrames frames;
11942 frames.push_back(QuicFrame(frame1_));
11943 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070011944 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040011945 frames.push_back(QuicFrame(frame2_));
11946 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
11947 /*port=*/23456);
11948
11949 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
11950 EXPECT_CALL(visitor_, OnStreamFrame(_))
11951 .Times(2)
11952 .WillRepeatedly(Invoke([=](const QuicStreamFrame& frame) {
11953 // Send some data on the stream. The STREAM_FRAME should be built into
11954 // one packet together with the latter PATH_RESPONSE.
11955 const std::string data{"response body"};
11956 connection_.producer()->SaveStreamData(frame.stream_id, data);
11957 return notifier_.WriteOrBufferData(frame.stream_id, data.length(),
11958 NO_FIN);
11959 }));
11960 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
11961 .WillOnce(Invoke([=]() {
11962 // Verify that this packet contains a STREAM_FRAME and is sent to the
11963 // original peer address.
11964 EXPECT_EQ(1u, writer_->stream_frames().size());
11965 // No connection migration should happen because the packet is received
11966 // out of order.
11967 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11968 }))
11969 .WillOnce(Invoke([=]() {
11970 EXPECT_EQ(1u, writer_->path_response_frames().size());
11971 // The final check is to ensure that the random data in the response
11972 // matches the random data from the challenge.
11973 EXPECT_EQ(0,
11974 memcmp(path_frame_buffer.data(),
11975 &(writer_->path_response_frames().front().data_buffer),
11976 sizeof(path_frame_buffer)));
11977 EXPECT_EQ(1u, writer_->padding_frames().size());
11978 // PATH_RESPONSE should be sent in another packet to a different peer
11979 // address.
11980 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
11981 }))
11982 .WillOnce(Invoke([=]() {
11983 // Verify that this packet contains a STREAM_FRAME and is sent to the
11984 // original peer address.
11985 EXPECT_EQ(1u, writer_->stream_frames().size());
11986 // No connection migration should happen because the packet is received
11987 // out of order.
11988 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
11989 }));
11990 // Lower the packet number so that receiving this packet shouldn't trigger
11991 // peer migration.
11992 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
11993 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
11994 ENCRYPTION_FORWARD_SECURE);
11995}
11996
11997// Tests that a PATH_CHALLENGE is cached if its PATH_RESPONSE can't be sent.
11998TEST_P(QuicConnectionTest, FailToWritePathResponse) {
11999 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
12000 return;
12001 }
12002 PathProbeTestInit(Perspective::IS_SERVER);
12003
12004 QuicFrames frames;
12005 QuicPathFrameBuffer path_frame_buffer{0, 1, 2, 3, 4, 5, 6, 7};
wubd0152ca2022-04-08 08:26:44 -070012006 frames.push_back(QuicFrame(QuicPathChallengeFrame(0, path_frame_buffer)));
Bence Békybac04052022-04-07 15:44:29 -040012007 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback6(),
12008 /*port=*/23456);
12009
12010 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
12011 // Lower the packet number so that receiving this packet shouldn't trigger
12012 // peer migration.
12013 QuicPacketCreatorPeer::SetPacketNumber(&peer_creator_, 1);
12014 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
12015 writer_->SetWriteBlocked();
12016 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kNewPeerAddress,
12017 ENCRYPTION_FORWARD_SECURE);
12018}
12019
12020// Regression test for b/168101557.
12021TEST_P(QuicConnectionTest, HandshakeDataDoesNotGetPtoed) {
12022 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12023 return;
12024 }
12025 set_perspective(Perspective::IS_SERVER);
12026 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
12027 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12028 }
12029 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
12030 use_tagging_decrypter();
12031 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12032 EXPECT_TRUE(connection_.HasPendingAcks());
12033
12034 connection_.SetEncrypter(ENCRYPTION_INITIAL,
12035 std::make_unique<TaggingEncrypter>(0x01));
12036 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12037 // Send INITIAL 1.
12038 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12039
12040 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12041 std::make_unique<TaggingEncrypter>(0x02));
12042 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12043 SetDecrypter(ENCRYPTION_HANDSHAKE,
12044 std::make_unique<StrictTaggingDecrypter>(0x02));
12045 // Send HANDSHAKE packets.
12046 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
12047 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12048
12049 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12050 std::make_unique<TaggingEncrypter>(0x03));
12051 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12052 // Send half RTT packet.
12053 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12054
12055 // Receives HANDSHAKE 1.
12056 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12057 std::make_unique<TaggingEncrypter>(0x02));
12058 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
12059 // Discard INITIAL key.
12060 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12061 connection_.NeuterUnencryptedPackets();
12062 // Verify there is pending ACK.
12063 ASSERT_TRUE(connection_.HasPendingAcks());
12064 // Set the send alarm.
12065 connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
12066
12067 // Fire ACK alarm.
12068 connection_.GetAckAlarm()->Fire();
12069 // Verify 1-RTT packet is coalesced with handshake packet.
12070 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12071 connection_.GetSendAlarm()->Fire();
12072
12073 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12074 connection_.GetRetransmissionAlarm()->Fire();
12075 // Verify a handshake packet gets PTOed and 1-RTT packet gets coalesced.
12076 EXPECT_EQ(0x03030303u, writer_->final_bytes_of_last_packet());
12077}
12078
12079// Regression test for b/168294218.
12080TEST_P(QuicConnectionTest, CoalescerHandlesInitialKeyDiscard) {
12081 if (!connection_.version().CanSendCoalescedPackets()) {
12082 return;
12083 }
12084 SetQuicReloadableFlag(quic_discard_initial_packet_with_key_dropped, true);
12085 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
12086 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12087 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12088 connection_.NeuterUnencryptedPackets();
12089 }));
12090 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
12091
12092 EXPECT_EQ(0u, connection_.GetStats().packets_discarded);
12093 {
12094 QuicConnection::ScopedPacketFlusher flusher(&connection_);
12095 use_tagging_decrypter();
12096 ProcessCryptoPacketAtLevel(1000, ENCRYPTION_INITIAL);
12097 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12098 connection_.SetEncrypter(ENCRYPTION_INITIAL,
12099 std::make_unique<TaggingEncrypter>(0x01));
12100 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12101 std::make_unique<TaggingEncrypter>(0x02));
12102 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12103 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
12104 // Verify this packet is on hold.
12105 EXPECT_EQ(0u, writer_->packets_write_attempts());
12106 }
12107 EXPECT_TRUE(connection_.connected());
12108}
12109
12110// Regresstion test for b/168294218
12111TEST_P(QuicConnectionTest, ZeroRttRejectionAndMissingInitialKeys) {
12112 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12113 return;
12114 }
12115 // Not defer send in response to packet.
12116 connection_.set_defer_send_in_response_to_packets(false);
12117 EXPECT_CALL(visitor_, OnHandshakePacketSent()).WillOnce(Invoke([this]() {
12118 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12119 connection_.NeuterUnencryptedPackets();
12120 }));
12121 EXPECT_CALL(visitor_, OnCryptoFrame(_))
12122 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
12123 if (frame.level == ENCRYPTION_HANDSHAKE) {
12124 // 0-RTT gets rejected.
12125 connection_.MarkZeroRttPacketsForRetransmission(0);
12126 // Send Crypto data.
12127 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12128 std::make_unique<TaggingEncrypter>(0x03));
12129 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12130 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
12131 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12132 std::make_unique<TaggingEncrypter>(0x04));
12133 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12134 // Advance INITIAL ack delay to trigger initial ACK to be sent AFTER
12135 // the retransmission of rejected 0-RTT packets while the HANDSHAKE
12136 // packet is still in the coalescer, such that the INITIAL key gets
12137 // dropped between SendAllPendingAcks and actually send the ack frame,
12138 // bummer.
12139 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
12140 }
12141 }));
12142 use_tagging_decrypter();
12143 connection_.SetEncrypter(ENCRYPTION_INITIAL,
12144 std::make_unique<TaggingEncrypter>(0x01));
12145 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
12146 // Send 0-RTT packet.
12147 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
12148 std::make_unique<TaggingEncrypter>(0x02));
12149 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12150 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12151
12152 QuicAckFrame frame1 = InitAckFrame(1);
12153 // Received ACK for packet 1.
12154 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
12155 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
12156 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12157
12158 // Fire retransmission alarm.
12159 connection_.GetRetransmissionAlarm()->Fire();
12160
12161 QuicFrames frames1;
12162 frames1.push_back(QuicFrame(&crypto_frame_));
12163 QuicFrames frames2;
12164 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12165 absl::string_view(data1));
12166 frames2.push_back(QuicFrame(&crypto_frame));
12167 ProcessCoalescedPacket(
12168 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
12169}
12170
12171TEST_P(QuicConnectionTest, OnZeroRttPacketAcked) {
12172 if (!connection_.version().UsesTls()) {
12173 return;
12174 }
12175 MockQuicConnectionDebugVisitor debug_visitor;
12176 connection_.set_debug_visitor(&debug_visitor);
12177 use_tagging_decrypter();
12178 connection_.SetEncrypter(ENCRYPTION_INITIAL,
12179 std::make_unique<TaggingEncrypter>(0x01));
12180 connection_.SendCryptoStreamData();
12181 // Send 0-RTT packet.
12182 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
12183 std::make_unique<TaggingEncrypter>(0x02));
12184 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
12185 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
12186 connection_.SendStreamDataWithString(4, "bar", 0, NO_FIN);
12187 // Received ACK for packet 1, HANDSHAKE packet and 1-RTT ACK.
12188 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
12189 .Times(AnyNumber());
12190 QuicFrames frames1;
12191 QuicAckFrame ack_frame1 = InitAckFrame(1);
12192 frames1.push_back(QuicFrame(&ack_frame1));
12193
12194 QuicFrames frames2;
12195 QuicCryptoFrame crypto_frame(ENCRYPTION_HANDSHAKE, 0,
12196 absl::string_view(data1));
12197 frames2.push_back(QuicFrame(&crypto_frame));
12198 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12199 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
12200 ProcessCoalescedPacket(
12201 {{1, frames1, ENCRYPTION_INITIAL}, {2, frames2, ENCRYPTION_HANDSHAKE}});
12202
12203 QuicFrames frames3;
12204 QuicAckFrame ack_frame2 =
12205 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
12206 frames3.push_back(QuicFrame(&ack_frame2));
12207 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(1);
12208 ProcessCoalescedPacket({{3, frames3, ENCRYPTION_FORWARD_SECURE}});
12209
12210 QuicFrames frames4;
12211 QuicAckFrame ack_frame3 =
12212 InitAckFrame({{QuicPacketNumber(3), QuicPacketNumber(4)}});
12213 frames4.push_back(QuicFrame(&ack_frame3));
12214 EXPECT_CALL(debug_visitor, OnZeroRttPacketAcked()).Times(0);
12215 ProcessCoalescedPacket({{4, frames4, ENCRYPTION_FORWARD_SECURE}});
12216}
12217
12218TEST_P(QuicConnectionTest, InitiateKeyUpdate) {
12219 if (!connection_.version().UsesTls()) {
12220 return;
12221 }
12222
12223 TransportParameters params;
12224 QuicConfig config;
12225 std::string error_details;
12226 EXPECT_THAT(config.ProcessTransportParameters(
12227 params, /* is_resumption = */ false, &error_details),
12228 IsQuicNoError());
12229 QuicConfigPeer::SetNegotiated(&config, true);
12230 if (connection_.version().UsesTls()) {
12231 QuicConfigPeer::SetReceivedOriginalConnectionId(
12232 &config, connection_.connection_id());
12233 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12234 &config, connection_.connection_id());
12235 }
12236 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12237 connection_.SetFromConfig(config);
12238
12239 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12240
12241 MockFramerVisitor peer_framer_visitor_;
12242 peer_framer_.set_visitor(&peer_framer_visitor_);
12243
12244 use_tagging_decrypter();
12245
12246 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12247 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12248 std::make_unique<TaggingEncrypter>(0x01));
12249 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12250 std::make_unique<StrictTaggingDecrypter>(0x01));
12251 EXPECT_CALL(visitor_, GetHandshakeState())
12252 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12253 connection_.OnHandshakeComplete();
12254
12255 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12256 std::make_unique<TaggingEncrypter>(0x01));
12257
12258 // Key update should still not be allowed, since no packet has been acked
12259 // from the current key phase.
12260 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12261 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12262
12263 // Send packet 1.
12264 QuicPacketNumber last_packet;
12265 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12266 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12267
12268 // Key update should still not be allowed, even though a packet was sent in
12269 // the current key phase it hasn't been acked yet.
12270 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12271 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12272
12273 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12274 // Receive ack for packet 1.
12275 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12276 QuicAckFrame frame1 = InitAckFrame(1);
12277 ProcessAckPacket(&frame1);
12278
12279 // OnDecryptedFirstPacketInKeyPhase is called even on the first key phase,
12280 // so discard_previous_keys_alarm_ should be set now.
12281 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12282 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12283
12284 // Key update should now be allowed.
12285 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12286 .WillOnce(
12287 []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
12288 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12289 return std::make_unique<TaggingEncrypter>(0x02);
12290 });
12291 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12292 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12293 // discard_previous_keys_alarm_ should not be set until a packet from the new
12294 // key phase has been received. (The alarm that was set above should be
12295 // cleared if it hasn't fired before the next key update happened.)
12296 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12297 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12298
12299 // Pretend that peer accepts the key update.
12300 EXPECT_CALL(peer_framer_visitor_,
12301 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12302 .WillOnce(
12303 []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
12304 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12305 .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); });
12306 peer_framer_.SetKeyUpdateSupportForConnection(true);
12307 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12308
12309 // Another key update should not be allowed yet.
12310 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12311
12312 // Send packet 2.
12313 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12314 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12315 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12316 // Receive ack for packet 2.
12317 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12318 QuicAckFrame frame2 = InitAckFrame(2);
12319 ProcessAckPacket(&frame2);
12320 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12321 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12322
12323 // Key update should be allowed again now that a packet has been acked from
12324 // the current key phase.
12325 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12326 .WillOnce(
12327 []() { return std::make_unique<StrictTaggingDecrypter>(0x03); });
12328 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12329 return std::make_unique<TaggingEncrypter>(0x03);
12330 });
12331 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12332 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12333
12334 // Pretend that peer accepts the key update.
12335 EXPECT_CALL(peer_framer_visitor_,
12336 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12337 .WillOnce(
12338 []() { return std::make_unique<StrictTaggingDecrypter>(0x03); });
12339 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12340 .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x03); });
12341 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12342
12343 // Another key update should not be allowed yet.
12344 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12345
12346 // Send packet 3.
12347 SendStreamDataToPeer(3, "baz", 0, NO_FIN, &last_packet);
12348 EXPECT_EQ(QuicPacketNumber(3u), last_packet);
12349
12350 // Another key update should not be allowed yet.
12351 EXPECT_FALSE(connection_.IsKeyUpdateAllowed());
12352 EXPECT_TRUE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12353
12354 // Receive ack for packet 3.
12355 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12356 QuicAckFrame frame3 = InitAckFrame(3);
12357 ProcessAckPacket(&frame3);
12358 EXPECT_TRUE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12359 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12360
12361 // Key update should be allowed now.
12362 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12363 .WillOnce(
12364 []() { return std::make_unique<StrictTaggingDecrypter>(0x04); });
12365 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12366 return std::make_unique<TaggingEncrypter>(0x04);
12367 });
12368 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12369 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12370 EXPECT_FALSE(connection_.GetDiscardPreviousOneRttKeysAlarm()->IsSet());
12371 EXPECT_FALSE(connection_.HaveSentPacketsInCurrentKeyPhaseButNoneAcked());
12372}
12373
12374TEST_P(QuicConnectionTest, InitiateKeyUpdateApproachingConfidentialityLimit) {
12375 if (!connection_.version().UsesTls()) {
12376 return;
12377 }
12378
birenroyef686222022-09-12 11:34:34 -070012379 SetQuicFlag(quic_key_update_confidentiality_limit, 3U);
Bence Békybac04052022-04-07 15:44:29 -040012380
12381 std::string error_details;
12382 TransportParameters params;
12383 // Key update is enabled.
12384 QuicConfig config;
12385 EXPECT_THAT(config.ProcessTransportParameters(
12386 params, /* is_resumption = */ false, &error_details),
12387 IsQuicNoError());
12388 QuicConfigPeer::SetNegotiated(&config, true);
12389 if (connection_.version().UsesTls()) {
12390 QuicConfigPeer::SetReceivedOriginalConnectionId(
12391 &config, connection_.connection_id());
12392 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12393 &config, connection_.connection_id());
12394 }
12395 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12396 connection_.SetFromConfig(config);
12397
12398 MockFramerVisitor peer_framer_visitor_;
12399 peer_framer_.set_visitor(&peer_framer_visitor_);
12400
12401 use_tagging_decrypter();
12402
12403 uint8_t current_tag = 0x01;
12404
12405 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12406 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12407 std::make_unique<TaggingEncrypter>(current_tag));
12408 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12409 std::make_unique<StrictTaggingDecrypter>(current_tag));
12410 EXPECT_CALL(visitor_, GetHandshakeState())
12411 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12412 connection_.OnHandshakeComplete();
12413
12414 peer_framer_.SetKeyUpdateSupportForConnection(true);
12415 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12416 std::make_unique<TaggingEncrypter>(current_tag));
12417
12418 const QuicConnectionStats& stats = connection_.GetStats();
12419
12420 for (int packet_num = 1; packet_num <= 8; ++packet_num) {
12421 if (packet_num == 3 || packet_num == 6) {
12422 current_tag++;
12423 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12424 .WillOnce([current_tag]() {
12425 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12426 });
12427 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter())
12428 .WillOnce([current_tag]() {
12429 return std::make_unique<TaggingEncrypter>(current_tag);
12430 });
12431 EXPECT_CALL(visitor_,
12432 OnKeyUpdate(KeyUpdateReason::kLocalKeyUpdateLimitOverride));
12433 }
12434 // Send packet.
12435 QuicPacketNumber last_packet;
12436 SendStreamDataToPeer(packet_num, "foo", 0, NO_FIN, &last_packet);
12437 EXPECT_EQ(QuicPacketNumber(packet_num), last_packet);
12438 if (packet_num >= 6) {
12439 EXPECT_EQ(2U, stats.key_update_count);
12440 } else if (packet_num >= 3) {
12441 EXPECT_EQ(1U, stats.key_update_count);
12442 } else {
12443 EXPECT_EQ(0U, stats.key_update_count);
12444 }
12445
12446 if (packet_num == 4 || packet_num == 7) {
12447 // Pretend that peer accepts the key update.
12448 EXPECT_CALL(peer_framer_visitor_,
12449 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12450 .WillOnce([current_tag]() {
12451 return std::make_unique<StrictTaggingDecrypter>(current_tag);
12452 });
12453 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12454 .WillOnce([current_tag]() {
12455 return std::make_unique<TaggingEncrypter>(current_tag);
12456 });
12457 peer_framer_.DoKeyUpdate(KeyUpdateReason::kRemote);
12458 }
12459 // Receive ack for packet.
12460 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12461 QuicAckFrame frame1 = InitAckFrame(packet_num);
12462 ProcessAckPacket(&frame1);
12463 }
12464}
12465
12466TEST_P(QuicConnectionTest,
12467 CloseConnectionOnConfidentialityLimitKeyUpdateNotAllowed) {
12468 if (!connection_.version().UsesTls()) {
12469 return;
12470 }
12471
12472 // Set key update confidentiality limit to 1 packet.
birenroyef686222022-09-12 11:34:34 -070012473 SetQuicFlag(quic_key_update_confidentiality_limit, 1U);
Bence Békybac04052022-04-07 15:44:29 -040012474 // Use confidentiality limit for connection close of 3 packets.
12475 constexpr size_t kConfidentialityLimit = 3U;
12476
12477 std::string error_details;
12478 TransportParameters params;
12479 // Key update is enabled.
12480 QuicConfig config;
12481 EXPECT_THAT(config.ProcessTransportParameters(
12482 params, /* is_resumption = */ false, &error_details),
12483 IsQuicNoError());
12484 QuicConfigPeer::SetNegotiated(&config, true);
12485 if (connection_.version().UsesTls()) {
12486 QuicConfigPeer::SetReceivedOriginalConnectionId(
12487 &config, connection_.connection_id());
12488 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12489 &config, connection_.connection_id());
12490 }
12491 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12492 connection_.SetFromConfig(config);
12493
12494 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12495 connection_.SetEncrypter(
12496 ENCRYPTION_FORWARD_SECURE,
12497 std::make_unique<NullEncrypterWithConfidentialityLimit>(
12498 Perspective::IS_CLIENT, kConfidentialityLimit));
12499 EXPECT_CALL(visitor_, GetHandshakeState())
12500 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12501 connection_.OnHandshakeComplete();
12502
12503 QuicPacketNumber last_packet;
12504 // Send 3 packets without receiving acks for any of them. Key update will not
12505 // be allowed, so the confidentiality limit should be reached, forcing the
12506 // connection to be closed.
12507 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12508 EXPECT_TRUE(connection_.connected());
12509 SendStreamDataToPeer(2, "foo", 0, NO_FIN, &last_packet);
12510 EXPECT_TRUE(connection_.connected());
12511 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12512 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet);
12513 EXPECT_FALSE(connection_.connected());
12514 const QuicConnectionStats& stats = connection_.GetStats();
12515 EXPECT_EQ(0U, stats.key_update_count);
12516 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12517}
12518
12519TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitDuringHandshake) {
12520 if (!connection_.version().UsesTls()) {
12521 return;
12522 }
12523
12524 constexpr uint8_t correct_tag = 0x01;
12525 constexpr uint8_t wrong_tag = 0xFE;
12526 constexpr QuicPacketCount kIntegrityLimit = 3;
12527
12528 SetDecrypter(ENCRYPTION_HANDSHAKE,
12529 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12530 correct_tag, kIntegrityLimit));
12531 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12532 std::make_unique<TaggingEncrypter>(correct_tag));
12533 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12534 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12535 std::make_unique<TaggingEncrypter>(wrong_tag));
12536 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12537 EXPECT_TRUE(connection_.connected());
12538 if (i == kIntegrityLimit) {
12539 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12540 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
12541 }
12542 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12543 EXPECT_EQ(
12544 i, connection_.GetStats().num_failed_authentication_packets_received);
12545 }
12546 EXPECT_FALSE(connection_.connected());
12547 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12548}
12549
12550TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAfterHandshake) {
12551 if (!connection_.version().UsesTls()) {
12552 return;
12553 }
12554
12555 constexpr uint8_t correct_tag = 0x01;
12556 constexpr uint8_t wrong_tag = 0xFE;
12557 constexpr QuicPacketCount kIntegrityLimit = 3;
12558
12559 use_tagging_decrypter();
12560 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12561 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12562 correct_tag, kIntegrityLimit));
12563 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12564 std::make_unique<TaggingEncrypter>(correct_tag));
12565 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12566 EXPECT_CALL(visitor_, GetHandshakeState())
12567 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12568 connection_.OnHandshakeComplete();
12569 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12570 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12571 std::make_unique<TaggingEncrypter>(wrong_tag));
12572 for (uint64_t i = 1; i <= kIntegrityLimit; ++i) {
12573 EXPECT_TRUE(connection_.connected());
12574 if (i == kIntegrityLimit) {
12575 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12576 }
12577 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12578 EXPECT_EQ(
12579 i, connection_.GetStats().num_failed_authentication_packets_received);
12580 }
12581 EXPECT_FALSE(connection_.connected());
12582 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12583}
12584
12585TEST_P(QuicConnectionTest,
12586 CloseConnectionOnIntegrityLimitAcrossEncryptionLevels) {
12587 if (!connection_.version().UsesTls()) {
12588 return;
12589 }
12590
12591 constexpr uint8_t correct_tag = 0x01;
12592 constexpr uint8_t wrong_tag = 0xFE;
12593 constexpr QuicPacketCount kIntegrityLimit = 4;
12594
12595 use_tagging_decrypter();
12596 SetDecrypter(ENCRYPTION_HANDSHAKE,
12597 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12598 correct_tag, kIntegrityLimit));
12599 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12600 std::make_unique<TaggingEncrypter>(correct_tag));
12601 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12602 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12603 std::make_unique<TaggingEncrypter>(wrong_tag));
12604 for (uint64_t i = 1; i <= 2; ++i) {
12605 EXPECT_TRUE(connection_.connected());
12606 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
12607 EXPECT_EQ(
12608 i, connection_.GetStats().num_failed_authentication_packets_received);
12609 }
12610
12611 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12612 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12613 correct_tag, kIntegrityLimit));
12614 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12615 std::make_unique<TaggingEncrypter>(correct_tag));
12616 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12617 EXPECT_CALL(visitor_, GetHandshakeState())
12618 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12619 connection_.OnHandshakeComplete();
12620 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12621 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
12622 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12623 std::make_unique<TaggingEncrypter>(wrong_tag));
12624 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12625 EXPECT_TRUE(connection_.connected());
12626 if (i == kIntegrityLimit) {
12627 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12628 }
12629 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12630 EXPECT_EQ(
12631 i, connection_.GetStats().num_failed_authentication_packets_received);
12632 }
12633 EXPECT_FALSE(connection_.connected());
12634 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12635}
12636
12637TEST_P(QuicConnectionTest, IntegrityLimitDoesNotApplyWithoutDecryptionKey) {
12638 if (!connection_.version().UsesTls()) {
12639 return;
12640 }
12641
12642 constexpr uint8_t correct_tag = 0x01;
12643 constexpr uint8_t wrong_tag = 0xFE;
12644 constexpr QuicPacketCount kIntegrityLimit = 3;
12645
12646 use_tagging_decrypter();
12647 SetDecrypter(ENCRYPTION_HANDSHAKE,
12648 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12649 correct_tag, kIntegrityLimit));
12650 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12651 std::make_unique<TaggingEncrypter>(correct_tag));
12652 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12653 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
12654
12655 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12656 std::make_unique<TaggingEncrypter>(wrong_tag));
12657 for (uint64_t i = 1; i <= kIntegrityLimit * 2; ++i) {
12658 EXPECT_TRUE(connection_.connected());
12659 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12660 EXPECT_EQ(
12661 0u, connection_.GetStats().num_failed_authentication_packets_received);
12662 }
12663 EXPECT_TRUE(connection_.connected());
12664}
12665
12666TEST_P(QuicConnectionTest, CloseConnectionOnIntegrityLimitAcrossKeyPhases) {
12667 if (!connection_.version().UsesTls()) {
12668 return;
12669 }
12670
12671 constexpr QuicPacketCount kIntegrityLimit = 4;
12672
12673 TransportParameters params;
12674 QuicConfig config;
12675 std::string error_details;
12676 EXPECT_THAT(config.ProcessTransportParameters(
12677 params, /* is_resumption = */ false, &error_details),
12678 IsQuicNoError());
12679 QuicConfigPeer::SetNegotiated(&config, true);
12680 if (connection_.version().UsesTls()) {
12681 QuicConfigPeer::SetReceivedOriginalConnectionId(
12682 &config, connection_.connection_id());
12683 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
12684 &config, connection_.connection_id());
12685 }
12686 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12687 connection_.SetFromConfig(config);
12688
12689 MockFramerVisitor peer_framer_visitor_;
12690 peer_framer_.set_visitor(&peer_framer_visitor_);
12691
12692 use_tagging_decrypter();
12693 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12694 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12695 std::make_unique<TaggingEncrypter>(0x01));
12696 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
12697 std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12698 0x01, kIntegrityLimit));
12699 EXPECT_CALL(visitor_, GetHandshakeState())
12700 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12701 connection_.OnHandshakeComplete();
12702 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
12703
12704 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12705 std::make_unique<TaggingEncrypter>(0xFF));
12706 for (uint64_t i = 1; i <= 2; ++i) {
12707 EXPECT_TRUE(connection_.connected());
12708 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12709 EXPECT_EQ(
12710 i, connection_.GetStats().num_failed_authentication_packets_received);
12711 }
12712
12713 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12714 std::make_unique<TaggingEncrypter>(0x01));
12715 // Send packet 1.
12716 QuicPacketNumber last_packet;
12717 SendStreamDataToPeer(1, "foo", 0, NO_FIN, &last_packet);
12718 EXPECT_EQ(QuicPacketNumber(1u), last_packet);
12719 // Receive ack for packet 1.
12720 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12721 QuicAckFrame frame1 = InitAckFrame(1);
12722 ProcessAckPacket(&frame1);
12723 // Key update should now be allowed, initiate it.
12724 EXPECT_CALL(visitor_, AdvanceKeysAndCreateCurrentOneRttDecrypter())
12725 .WillOnce([kIntegrityLimit]() {
12726 return std::make_unique<StrictTaggingDecrypterWithIntegrityLimit>(
12727 0x02, kIntegrityLimit);
12728 });
12729 EXPECT_CALL(visitor_, CreateCurrentOneRttEncrypter()).WillOnce([]() {
12730 return std::make_unique<TaggingEncrypter>(0x02);
12731 });
12732 EXPECT_CALL(visitor_, OnKeyUpdate(KeyUpdateReason::kLocalForTests));
12733 EXPECT_TRUE(connection_.InitiateKeyUpdate(KeyUpdateReason::kLocalForTests));
12734
12735 // Pretend that peer accepts the key update.
12736 EXPECT_CALL(peer_framer_visitor_,
12737 AdvanceKeysAndCreateCurrentOneRttDecrypter())
12738 .WillOnce(
12739 []() { return std::make_unique<StrictTaggingDecrypter>(0x02); });
12740 EXPECT_CALL(peer_framer_visitor_, CreateCurrentOneRttEncrypter())
12741 .WillOnce([]() { return std::make_unique<TaggingEncrypter>(0x02); });
12742 peer_framer_.SetKeyUpdateSupportForConnection(true);
12743 peer_framer_.DoKeyUpdate(KeyUpdateReason::kLocalForTests);
12744
12745 // Send packet 2.
12746 SendStreamDataToPeer(2, "bar", 0, NO_FIN, &last_packet);
12747 EXPECT_EQ(QuicPacketNumber(2u), last_packet);
12748 // Receive ack for packet 2.
12749 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(true, _, _, _, _));
12750 QuicAckFrame frame2 = InitAckFrame(2);
12751 ProcessAckPacket(&frame2);
12752
12753 EXPECT_EQ(2u,
12754 connection_.GetStats().num_failed_authentication_packets_received);
12755
12756 // Do two more undecryptable packets. Integrity limit should be reached.
12757 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
12758 std::make_unique<TaggingEncrypter>(0xFF));
12759 for (uint64_t i = 3; i <= kIntegrityLimit; ++i) {
12760 EXPECT_TRUE(connection_.connected());
12761 if (i == kIntegrityLimit) {
12762 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
12763 }
12764 ProcessDataPacketAtLevel(i, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
12765 EXPECT_EQ(
12766 i, connection_.GetStats().num_failed_authentication_packets_received);
12767 }
12768 EXPECT_FALSE(connection_.connected());
12769 TestConnectionCloseQuicErrorCode(QUIC_AEAD_LIMIT_REACHED);
12770}
12771
12772TEST_P(QuicConnectionTest, SendAckFrequencyFrame) {
12773 if (!version().HasIetfQuicFrames()) {
12774 return;
12775 }
12776 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12777 set_perspective(Perspective::IS_SERVER);
12778 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
12779 .Times(AnyNumber());
12780 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12781
12782 QuicConfig config;
12783 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
12784 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12785 connection_.SetFromConfig(config);
12786 QuicConnectionPeer::SetAddressValidated(&connection_);
12787 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12788 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
12789
12790 connection_.OnHandshakeComplete();
12791
12792 writer_->SetWritable();
12793 QuicPacketCreatorPeer::SetPacketNumber(creator_, 99);
12794 // Send packet 100
12795 SendStreamDataToPeer(/*id=*/1, "foo", /*offset=*/0, NO_FIN, nullptr);
12796
12797 QuicAckFrequencyFrame captured_frame;
12798 EXPECT_CALL(visitor_, SendAckFrequency(_))
12799 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
12800 captured_frame = frame;
12801 }));
12802 // Send packet 101.
12803 SendStreamDataToPeer(/*id=*/1, "bar", /*offset=*/3, NO_FIN, nullptr);
12804
12805 EXPECT_EQ(captured_frame.packet_tolerance, 10u);
12806 EXPECT_EQ(captured_frame.max_ack_delay,
12807 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
12808
12809 // Sending packet 102 does not trigger sending another AckFrequencyFrame.
12810 SendStreamDataToPeer(/*id=*/1, "baz", /*offset=*/6, NO_FIN, nullptr);
12811}
12812
12813TEST_P(QuicConnectionTest, SendAckFrequencyFrameUponHandshakeCompletion) {
12814 if (!version().HasIetfQuicFrames()) {
12815 return;
12816 }
12817 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
12818 set_perspective(Perspective::IS_SERVER);
12819 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
12820 .Times(AnyNumber());
12821 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
12822
12823 QuicConfig config;
12824 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
12825 QuicTagVector quic_tag_vector;
12826 // Enable sending AckFrequency upon handshake completion.
12827 quic_tag_vector.push_back(kAFF2);
12828 QuicConfigPeer::SetReceivedConnectionOptions(&config, quic_tag_vector);
12829 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12830 connection_.SetFromConfig(config);
12831 QuicConnectionPeer::SetAddressValidated(&connection_);
12832 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12833 peer_creator_.set_encryption_level(ENCRYPTION_FORWARD_SECURE);
12834
12835 QuicAckFrequencyFrame captured_frame;
12836 EXPECT_CALL(visitor_, SendAckFrequency(_))
12837 .WillOnce(Invoke([&captured_frame](const QuicAckFrequencyFrame& frame) {
12838 captured_frame = frame;
12839 }));
12840
12841 connection_.OnHandshakeComplete();
12842
12843 EXPECT_EQ(captured_frame.packet_tolerance, 2u);
12844 EXPECT_EQ(captured_frame.max_ack_delay,
12845 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
12846}
12847
12848TEST_P(QuicConnectionTest, FastRecoveryOfLostServerHello) {
12849 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12850 return;
12851 }
12852 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12853 QuicConfig config;
12854 connection_.SetFromConfig(config);
12855
12856 use_tagging_decrypter();
12857 connection_.SetEncrypter(ENCRYPTION_INITIAL,
12858 std::make_unique<TaggingEncrypter>(0x01));
12859 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12860 connection_.SendCryptoStreamData();
12861 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
12862
12863 // Assume ServerHello gets lost.
12864 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12865 std::make_unique<TaggingEncrypter>(0x02));
12866 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
12867 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
12868 // Shorten PTO for fast recovery from lost ServerHello.
12869 EXPECT_EQ(clock_.ApproximateNow() + kAlarmGranularity,
12870 connection_.GetRetransmissionAlarm()->deadline());
12871}
12872
12873TEST_P(QuicConnectionTest, ServerHelloGetsReordered) {
12874 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
12875 return;
12876 }
12877 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12878 QuicConfig config;
12879 connection_.SetFromConfig(config);
12880 EXPECT_CALL(visitor_, OnCryptoFrame(_))
12881 .WillRepeatedly(Invoke([=](const QuicCryptoFrame& frame) {
12882 if (frame.level == ENCRYPTION_INITIAL) {
12883 // Install handshake read keys.
12884 SetDecrypter(ENCRYPTION_HANDSHAKE,
12885 std::make_unique<StrictTaggingDecrypter>(0x02));
12886 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12887 std::make_unique<TaggingEncrypter>(0x02));
12888 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
12889 }
12890 }));
12891
12892 use_tagging_decrypter();
12893 connection_.SetEncrypter(ENCRYPTION_INITIAL,
12894 std::make_unique<TaggingEncrypter>(0x01));
12895 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
12896 connection_.SendCryptoStreamData();
12897 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(20));
12898
12899 // Assume ServerHello gets reordered.
12900 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
12901 std::make_unique<TaggingEncrypter>(0x02));
12902 ProcessCryptoPacketAtLevel(2, ENCRYPTION_HANDSHAKE);
12903 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
12904 // Verify fast recovery is not enabled.
12905 EXPECT_EQ(connection_.sent_packet_manager().GetRetransmissionTime(),
12906 connection_.GetRetransmissionAlarm()->deadline());
12907}
12908
12909TEST_P(QuicConnectionTest, MigratePath) {
12910 EXPECT_CALL(visitor_, GetHandshakeState())
12911 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
12912 EXPECT_CALL(visitor_, OnPathDegrading());
12913 connection_.OnPathDegradingDetected();
12914 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
12915 EXPECT_NE(kNewSelfAddress, connection_.self_address());
12916
12917 // Buffer a packet.
12918 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(1);
12919 writer_->SetWriteBlocked();
12920 connection_.SendMtuDiscoveryPacket(kMaxOutgoingPacketSize);
12921 EXPECT_EQ(1u, connection_.NumQueuedPackets());
12922
12923 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
12924 EXPECT_CALL(visitor_, OnForwardProgressMadeAfterPathDegrading());
12925 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
12926 &new_writer, /*owns_writer=*/false);
12927
12928 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
12929 EXPECT_EQ(&new_writer, QuicConnectionPeer::GetWriter(&connection_));
12930 EXPECT_FALSE(connection_.IsPathDegrading());
12931 // Buffered packet on the old path should be discarded.
12932 if (connection_.connection_migration_use_new_cid()) {
12933 EXPECT_EQ(0u, connection_.NumQueuedPackets());
12934 } else {
12935 EXPECT_EQ(1u, connection_.NumQueuedPackets());
12936 }
12937}
12938
12939TEST_P(QuicConnectionTest, MigrateToNewPathDuringProbing) {
danzh87605712022-04-11 14:36:39 -070012940 if (!VersionHasIetfQuicFrames(connection_.version().transport_version)) {
Bence Békybac04052022-04-07 15:44:29 -040012941 return;
12942 }
12943 PathProbeTestInit(Perspective::IS_CLIENT);
12944 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Any4(), 12345);
12945 EXPECT_NE(kNewSelfAddress, connection_.self_address());
12946 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
12947 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
12948 bool success = false;
12949 connection_.ValidatePath(
12950 std::make_unique<TestQuicPathValidationContext>(
12951 kNewSelfAddress, connection_.peer_address(), &new_writer),
12952 std::make_unique<TestValidationResultDelegate>(
12953 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
12954 EXPECT_TRUE(connection_.HasPendingPathValidation());
12955 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
12956 &connection_, kNewSelfAddress, connection_.peer_address()));
12957
12958 connection_.MigratePath(kNewSelfAddress, connection_.peer_address(),
12959 &new_writer, /*owns_writer=*/false);
12960 EXPECT_EQ(kNewSelfAddress, connection_.self_address());
12961 EXPECT_TRUE(connection_.HasPendingPathValidation());
12962 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
12963 &connection_, kNewSelfAddress, connection_.peer_address()));
12964}
12965
renjietangfca5c772022-08-25 13:48:21 -070012966TEST_P(QuicConnectionTest, MultiPortCreation) {
12967 set_perspective(Perspective::IS_CLIENT);
12968 QuicConfig config;
12969 config.SetConnectionOptionsToSend(QuicTagVector{kMPQC, kRVCM});
12970 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
12971 connection_.SetFromConfig(config);
12972 if (!connection_.connection_migration_use_new_cid()) {
12973 return;
12974 }
12975 connection_.CreateConnectionIdManager();
12976 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
12977 connection_.OnHandshakeComplete();
12978
renjietang864fbda2022-09-08 10:50:07 -070012979 EXPECT_CALL(visitor_, OnPathDegrading());
12980 connection_.OnPathDegradingDetected();
12981
renjietangfca5c772022-08-25 13:48:21 -070012982 auto self_address = connection_.self_address();
12983 const QuicSocketAddress kNewSelfAddress(self_address.host(),
12984 self_address.port() + 1);
12985 EXPECT_NE(kNewSelfAddress, self_address);
12986 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
12987
12988 QuicNewConnectionIdFrame frame;
12989 frame.connection_id = TestConnectionId(1234);
12990 ASSERT_NE(frame.connection_id, connection_.connection_id());
12991 frame.stateless_reset_token =
12992 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
12993 frame.retire_prior_to = 0u;
12994 frame.sequence_number = 1u;
12995 EXPECT_CALL(visitor_, CreateContextForMultiPortPath())
12996 .WillRepeatedly(Return(
12997 testing::ByMove(std::make_unique<TestQuicPathValidationContext>(
12998 kNewSelfAddress, connection_.peer_address(), &new_writer))));
12999 connection_.OnNewConnectionIdFrame(frame);
13000 EXPECT_TRUE(connection_.HasPendingPathValidation());
13001 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13002 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013003 auto* alt_path = QuicConnectionPeer::GetAlternativePath(&connection_);
13004 EXPECT_FALSE(alt_path->validated);
renjietangfca5c772022-08-25 13:48:21 -070013005
renjietang864fbda2022-09-08 10:50:07 -070013006 // 30ms RTT.
13007 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
13008 // Fake a response delay.
13009 clock_.AdvanceTime(kTestRTT);
13010
renjietangfca5c772022-08-25 13:48:21 -070013011 QuicFrames frames;
13012 frames.push_back(QuicFrame(QuicPathResponseFrame(
13013 99, new_writer.path_challenge_frames().front().data_buffer)));
13014 ProcessFramesPacketWithAddresses(frames, kNewSelfAddress, kPeerAddress,
13015 ENCRYPTION_FORWARD_SECURE);
13016 // No migration should happen and the alternative path should still be alive.
13017 EXPECT_FALSE(connection_.HasPendingPathValidation());
13018 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13019 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang95731fa2022-09-26 14:06:32 -070013020 EXPECT_TRUE(alt_path->validated);
renjietangfca5c772022-08-25 13:48:21 -070013021
renjietang864fbda2022-09-08 10:50:07 -070013022 auto stats = connection_.multi_port_stats();
13023 EXPECT_EQ(1, stats->num_path_degrading);
13024 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_degrading);
13025 EXPECT_EQ(kTestRTT, stats->rtt_stats.latest_rtt());
13026 EXPECT_EQ(kTestRTT,
13027 stats->rtt_stats_when_default_path_degrading.latest_rtt());
13028
renjietangfca5c772022-08-25 13:48:21 -070013029 connection_.GetMultiPortProbingAlarm()->Fire();
13030 EXPECT_TRUE(connection_.HasPendingPathValidation());
13031 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePath(
13032 &connection_, kNewSelfAddress, connection_.peer_address()));
13033 for (size_t i = 0; i < QuicPathValidator::kMaxRetryTimes + 1; ++i) {
13034 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs));
13035 static_cast<TestAlarmFactory::TestAlarm*>(
13036 QuicPathValidatorPeer::retry_timer(
13037 QuicConnectionPeer::path_validator(&connection_)))
13038 ->Fire();
13039 }
13040
13041 EXPECT_FALSE(connection_.HasPendingPathValidation());
13042 EXPECT_FALSE(QuicConnectionPeer::IsAlternativePath(
13043 &connection_, kNewSelfAddress, connection_.peer_address()));
renjietang864fbda2022-09-08 10:50:07 -070013044 EXPECT_EQ(1, stats->num_path_degrading);
13045 EXPECT_EQ(1, stats->num_multi_port_probe_failures_when_path_degrading);
13046 EXPECT_EQ(0, stats->num_multi_port_probe_failures_when_path_not_degrading);
renjietangfca5c772022-08-25 13:48:21 -070013047}
13048
Bence Békybac04052022-04-07 15:44:29 -040013049TEST_P(QuicConnectionTest, SingleAckInPacket) {
13050 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13051 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13052 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13053 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
13054 connection_.NeuterUnencryptedPackets();
13055 connection_.OnHandshakeComplete();
13056 EXPECT_CALL(visitor_, GetHandshakeState())
13057 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13058
13059 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13060 connection_.SendStreamData3();
13061 connection_.CloseConnection(
13062 QUIC_INTERNAL_ERROR, "error",
13063 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
13064 }));
13065 QuicFrames frames;
13066 frames.push_back(QuicFrame(frame1_));
13067 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
13068 ENCRYPTION_FORWARD_SECURE);
13069 ASSERT_FALSE(writer_->ack_frames().empty());
13070 EXPECT_EQ(1u, writer_->ack_frames().size());
13071}
13072
13073TEST_P(QuicConnectionTest,
13074 ServerReceivedZeroRttPacketAfterOneRttPacketWithRetainedKey) {
13075 if (!connection_.version().UsesTls()) {
13076 return;
13077 }
13078
13079 set_perspective(Perspective::IS_SERVER);
13080 SetDecrypter(ENCRYPTION_ZERO_RTT,
13081 std::make_unique<NullDecrypter>(Perspective::IS_SERVER));
13082
13083 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13084 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13085
13086 // Finish handshake.
13087 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13088 notifier_.NeuterUnencryptedData();
13089 connection_.NeuterUnencryptedPackets();
13090 connection_.OnHandshakeComplete();
13091 EXPECT_CALL(visitor_, GetHandshakeState())
13092 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13093
13094 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13095 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13096 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13097
13098 // 0-RTT packet received out of order should be decoded since the decrypter
13099 // is temporarily retained.
13100 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13101 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13102 EXPECT_EQ(
13103 0u,
13104 connection_.GetStats()
13105 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13106
13107 // Simulate the timeout for discarding 0-RTT keys passing.
13108 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
13109
13110 // Another 0-RTT packet received now should not be decoded.
13111 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13112 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(0);
13113 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13114 EXPECT_EQ(
13115 1u,
13116 connection_.GetStats()
13117 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter);
13118
13119 // The |discard_zero_rtt_decryption_keys_alarm_| should only be set on the
13120 // first 1-RTT packet received.
13121 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13122 ProcessDataPacketAtLevel(5, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13123 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13124}
13125
13126TEST_P(QuicConnectionTest, NewTokenFrameInstigateAcks) {
13127 if (!version().HasIetfQuicFrames()) {
13128 return;
13129 }
13130 EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
13131
13132 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13133 EXPECT_CALL(visitor_, OnNewTokenReceived(_));
13134 ProcessFramePacket(QuicFrame(new_token));
13135
13136 // Ensure that this has caused the ACK alarm to be set.
13137 EXPECT_TRUE(connection_.HasPendingAcks());
13138}
13139
13140TEST_P(QuicConnectionTest, ServerClosesConnectionOnNewTokenFrame) {
13141 if (!version().HasIetfQuicFrames()) {
13142 return;
13143 }
13144 set_perspective(Perspective::IS_SERVER);
13145 QuicNewTokenFrame* new_token = new QuicNewTokenFrame();
13146 EXPECT_CALL(visitor_, OnNewTokenReceived(_)).Times(0);
13147 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13148 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13149 ProcessFramePacket(QuicFrame(new_token));
13150 EXPECT_FALSE(connection_.connected());
13151}
13152
13153TEST_P(QuicConnectionTest, OverrideRetryTokenWithRetryPacket) {
13154 if (!version().HasIetfQuicFrames()) {
13155 return;
13156 }
13157 std::string address_token = "TestAddressToken";
13158 connection_.SetSourceAddressTokenToSend(address_token);
13159 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13160 QuicConnectionPeer::GetPacketCreator(&connection_)),
13161 address_token);
13162 // Passes valid retry and verify token gets overridden.
13163 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13164 /*missing_original_id_in_config=*/false,
13165 /*wrong_original_id_in_config=*/false,
13166 /*missing_retry_id_in_config=*/false,
13167 /*wrong_retry_id_in_config=*/false);
13168}
13169
13170TEST_P(QuicConnectionTest, DonotOverrideRetryTokenWithAddressToken) {
13171 if (!version().HasIetfQuicFrames()) {
13172 return;
13173 }
13174 // Passes valid retry and verify token gets overridden.
13175 TestClientRetryHandling(/*invalid_retry_tag=*/false,
13176 /*missing_original_id_in_config=*/false,
13177 /*wrong_original_id_in_config=*/false,
13178 /*missing_retry_id_in_config=*/false,
13179 /*wrong_retry_id_in_config=*/false);
13180 std::string retry_token = QuicPacketCreatorPeer::GetRetryToken(
13181 QuicConnectionPeer::GetPacketCreator(&connection_));
13182
13183 std::string address_token = "TestAddressToken";
13184 connection_.SetSourceAddressTokenToSend(address_token);
13185 EXPECT_EQ(QuicPacketCreatorPeer::GetRetryToken(
13186 QuicConnectionPeer::GetPacketCreator(&connection_)),
13187 retry_token);
13188}
13189
13190TEST_P(QuicConnectionTest,
13191 ServerReceivedZeroRttWithHigherPacketNumberThanOneRtt) {
13192 if (!connection_.version().UsesTls()) {
13193 return;
13194 }
13195
13196 // The code that checks for this error piggybacks on some book-keeping state
13197 // kept for key update, so enable key update for the test.
13198 std::string error_details;
13199 TransportParameters params;
13200 QuicConfig config;
13201 EXPECT_THAT(config.ProcessTransportParameters(
13202 params, /* is_resumption = */ false, &error_details),
13203 IsQuicNoError());
13204 QuicConfigPeer::SetNegotiated(&config, true);
13205 QuicConfigPeer::SetReceivedOriginalConnectionId(&config,
13206 connection_.connection_id());
13207 QuicConfigPeer::SetReceivedInitialSourceConnectionId(
13208 &config, connection_.connection_id());
13209 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13210 connection_.SetFromConfig(config);
13211
13212 set_perspective(Perspective::IS_SERVER);
13213 SetDecrypter(ENCRYPTION_ZERO_RTT,
13214 std::make_unique<NullDecrypter>(Perspective::IS_SERVER));
13215
13216 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13217 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13218
13219 // Finish handshake.
13220 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13221 notifier_.NeuterUnencryptedData();
13222 connection_.NeuterUnencryptedPackets();
13223 connection_.OnHandshakeComplete();
13224 EXPECT_CALL(visitor_, GetHandshakeState())
13225 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
13226
13227 // Decrypt a 1-RTT packet.
13228 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13229 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13230 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
13231
13232 // 0-RTT packet with higher packet number than a 1-RTT packet is invalid and
13233 // should cause the connection to be closed.
13234 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13235 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
13236 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
13237 EXPECT_FALSE(connection_.connected());
13238 TestConnectionCloseQuicErrorCode(
13239 QUIC_INVALID_0RTT_PACKET_NUMBER_OUT_OF_ORDER);
13240}
13241
13242// Regression test for b/177312785
13243TEST_P(QuicConnectionTest, PeerMigrateBeforeHandshakeConfirm) {
13244 if (!VersionHasIetfQuicFrames(version().transport_version)) {
13245 return;
13246 }
13247 set_perspective(Perspective::IS_SERVER);
13248 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
13249 EXPECT_EQ(Perspective::IS_SERVER, connection_.perspective());
13250 EXPECT_CALL(visitor_, GetHandshakeState())
13251 .WillRepeatedly(Return(HANDSHAKE_START));
13252
13253 // Clear direct_peer_address.
13254 QuicConnectionPeer::SetDirectPeerAddress(&connection_, QuicSocketAddress());
13255 // Clear effective_peer_address, it is the same as direct_peer_address for
13256 // this test.
13257 QuicConnectionPeer::SetEffectivePeerAddress(&connection_,
13258 QuicSocketAddress());
13259 EXPECT_FALSE(connection_.effective_peer_address().IsInitialized());
13260
13261 const QuicSocketAddress kNewPeerAddress =
13262 QuicSocketAddress(QuicIpAddress::Loopback6(), /*port=*/23456);
13263 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
13264 ProcessFramePacketWithAddresses(MakeCryptoFrame(), kSelfAddress, kPeerAddress,
13265 ENCRYPTION_INITIAL);
13266 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13267 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13268
13269 // Process another packet with a different peer address on server side will
13270 // close connection.
13271 QuicAckFrame frame = InitAckFrame(1);
13272 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
13273 EXPECT_CALL(visitor_,
13274 OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF));
13275 EXPECT_CALL(visitor_, OnConnectionMigration(PORT_CHANGE)).Times(0u);
13276
13277 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _)).Times(0);
13278 ProcessFramePacketWithAddresses(QuicFrame(&frame), kSelfAddress,
13279 kNewPeerAddress, ENCRYPTION_INITIAL);
13280 EXPECT_FALSE(connection_.connected());
13281}
13282
13283// Regresstion test for b/175685916
13284TEST_P(QuicConnectionTest, TryToFlushAckWithAckQueued) {
13285 if (!version().HasIetfQuicFrames()) {
13286 return;
13287 }
13288 SetQuicReloadableFlag(quic_can_send_ack_frequency, true);
13289 set_perspective(Perspective::IS_SERVER);
13290
13291 QuicConfig config;
13292 QuicConfigPeer::SetReceivedMinAckDelayMs(&config, /*min_ack_delay_ms=*/1);
13293 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13294 connection_.SetFromConfig(config);
13295 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
13296 connection_.OnHandshakeComplete();
13297 QuicPacketCreatorPeer::SetPacketNumber(creator_, 200);
13298
13299 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
13300 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
13301 // Sending ACK_FREQUENCY bundles ACK. QuicConnectionPeer::SendPing
13302 // will try to bundle ACK but there is no pending ACK.
13303 EXPECT_CALL(visitor_, SendAckFrequency(_))
13304 .WillOnce(Invoke(&notifier_,
13305 &SimpleSessionNotifier::WriteOrBufferAckFrequency));
13306 QuicConnectionPeer::SendPing(&connection_);
13307}
13308
13309TEST_P(QuicConnectionTest, PathChallengeBeforePeerIpAddressChangeAtServer) {
13310 set_perspective(Perspective::IS_SERVER);
13311 if (!connection_.connection_migration_use_new_cid()) {
13312 return;
13313 }
13314 PathProbeTestInit(Perspective::IS_SERVER);
13315 SetClientConnectionId(TestConnectionId(1));
13316 connection_.CreateConnectionIdManager();
13317
13318 QuicConnectionId server_cid0 = connection_.connection_id();
13319 QuicConnectionId client_cid0 = connection_.client_connection_id();
13320 QuicConnectionId client_cid1 = TestConnectionId(2);
13321 QuicConnectionId server_cid1;
13322 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013323 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013324 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13325 .WillOnce(Return(TestConnectionId(456)));
13326 }
haoyuewangada6b822022-06-23 13:41:18 -070013327 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13328 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13329 server_cid1 = cid;
13330 return true;
13331 }));
Bence Békybac04052022-04-07 15:44:29 -040013332 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13333 connection_.MaybeSendConnectionIdToClient();
13334 // Receives new client CID from client.
13335 QuicNewConnectionIdFrame new_cid_frame;
13336 new_cid_frame.connection_id = client_cid1;
13337 new_cid_frame.sequence_number = 1u;
13338 new_cid_frame.retire_prior_to = 0u;
13339 connection_.OnNewConnectionIdFrame(new_cid_frame);
13340 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13341 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13342 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13343
13344 peer_creator_.SetServerConnectionId(server_cid1);
13345 const QuicSocketAddress kNewPeerAddress =
13346 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
13347 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13348 QuicFrames frames1;
13349 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070013350 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040013351 QuicPathFrameBuffer payload;
13352 EXPECT_CALL(*send_algorithm_,
13353 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13354 .Times(AtLeast(1))
13355 .WillOnce(Invoke([&]() {
13356 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13357 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13358 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13359 EXPECT_FALSE(writer_->path_response_frames().empty());
13360 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13361 payload = writer_->path_challenge_frames().front().data_buffer;
13362 }));
13363 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
13364 ENCRYPTION_FORWARD_SECURE);
13365 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13366 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13367 EXPECT_TRUE(connection_.HasPendingPathValidation());
13368 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13369 const auto* alternative_path =
13370 QuicConnectionPeer::GetAlternativePath(&connection_);
13371 EXPECT_EQ(default_path->client_connection_id, client_cid0);
13372 EXPECT_EQ(default_path->server_connection_id, server_cid0);
13373 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
13374 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
13375 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13376 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13377
13378 // Process another packet with a different peer address on server side will
13379 // start connection migration.
13380 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
13381 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13382 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13383 }));
13384 // IETF QUIC send algorithm should be changed to a different object, so no
13385 // OnPacketSent() called on the old send algorithm.
13386 EXPECT_CALL(*send_algorithm_,
13387 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13388 .Times(0);
13389 QuicFrames frames2;
13390 frames2.push_back(QuicFrame(frame2_));
13391 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
13392 ENCRYPTION_FORWARD_SECURE);
13393 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13394 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
13395 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
13396 connection_.active_effective_peer_migration_type());
13397 EXPECT_TRUE(writer_->path_challenge_frames().empty());
13398 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
13399 send_algorithm_);
13400 // Switch to use the mock send algorithm.
13401 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
13402 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
13403 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
13404 .WillRepeatedly(Return(kDefaultTCPMSS));
13405 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
13406 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
13407 .Times(AnyNumber())
13408 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13409 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
13410 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
13411 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
13412 connection_.SetSendAlgorithm(send_algorithm_);
13413 EXPECT_EQ(default_path->client_connection_id, client_cid1);
13414 EXPECT_EQ(default_path->server_connection_id, server_cid1);
13415 // The previous default path is kept as alternative path before reverse path
13416 // validation finishes.
13417 EXPECT_EQ(alternative_path->client_connection_id, client_cid0);
13418 EXPECT_EQ(alternative_path->server_connection_id, server_cid0);
13419 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid1);
13420 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
13421
13422 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13423 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
13424 EXPECT_EQ(IPV6_TO_IPV4_CHANGE,
13425 connection_.active_effective_peer_migration_type());
13426 EXPECT_EQ(1u, connection_.GetStats()
13427 .num_peer_migration_to_proactively_validated_address);
13428
13429 // The PATH_CHALLENGE and PATH_RESPONSE is expanded upto the max packet size
13430 // which may exceeds the anti-amplification limit. Verify server is throttled
13431 // by anti-amplification limit.
13432 connection_.SendCryptoDataWithString("foo", 0);
13433 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
13434
13435 // Receiving PATH_RESPONSE should lift the anti-amplification limit.
13436 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070013437 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040013438 EXPECT_CALL(visitor_, MaybeSendAddressToken());
13439 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
13440 .Times(testing::AtLeast(1u));
13441 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
13442 ENCRYPTION_FORWARD_SECURE);
13443 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
13444 // Verify that alternative_path_ is cleared and the peer CID is retired.
13445 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
13446 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
13447 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
13448 auto* retire_peer_issued_cid_alarm =
13449 connection_.GetRetirePeerIssuedConnectionIdAlarm();
13450 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
13451 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
13452 retire_peer_issued_cid_alarm->Fire();
13453
13454 // Verify the anti-amplification limit is lifted by sending a packet larger
13455 // than the anti-amplification limit.
13456 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
13457 EXPECT_CALL(*send_algorithm_, PacingRate(_))
13458 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13459 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
13460 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
renjietangff3e9602022-10-25 12:16:49 -070013461 EXPECT_EQ(1u, connection_.num_unlinkable_client_migration());
Bence Békybac04052022-04-07 15:44:29 -040013462}
13463
13464TEST_P(QuicConnectionTest,
13465 PathValidationSucceedsBeforePeerIpAddressChangeAtServer) {
13466 set_perspective(Perspective::IS_SERVER);
13467 if (!connection_.connection_migration_use_new_cid()) {
13468 return;
13469 }
13470 PathProbeTestInit(Perspective::IS_SERVER);
13471 connection_.CreateConnectionIdManager();
13472
13473 QuicConnectionId server_cid0 = connection_.connection_id();
13474 QuicConnectionId server_cid1;
13475 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013476 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013477 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13478 .WillOnce(Return(TestConnectionId(456)));
13479 }
haoyuewangada6b822022-06-23 13:41:18 -070013480 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13481 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13482 server_cid1 = cid;
13483 return true;
13484 }));
Bence Békybac04052022-04-07 15:44:29 -040013485 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13486 connection_.MaybeSendConnectionIdToClient();
13487 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13488 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13489
13490 // Receive probing packet with new peer address.
13491 peer_creator_.SetServerConnectionId(server_cid1);
13492 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
13493 /*port=*/23456);
13494 QuicPathFrameBuffer payload;
13495 EXPECT_CALL(*send_algorithm_,
13496 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13497 .WillOnce(Invoke([&]() {
13498 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13499 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13500 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13501 EXPECT_FALSE(writer_->path_response_frames().empty());
13502 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13503 payload = writer_->path_challenge_frames().front().data_buffer;
13504 }))
13505 .WillRepeatedly(Invoke([&]() {
13506 // Only start reverse path validation once.
13507 EXPECT_TRUE(writer_->path_challenge_frames().empty());
13508 }));
13509 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13510 QuicFrames frames1;
13511 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070013512 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040013513 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
13514 ENCRYPTION_FORWARD_SECURE);
13515 EXPECT_TRUE(connection_.HasPendingPathValidation());
13516 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13517 const auto* alternative_path =
13518 QuicConnectionPeer::GetAlternativePath(&connection_);
13519 EXPECT_EQ(default_path->server_connection_id, server_cid0);
13520 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
13521 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13522
13523 // Receive PATH_RESPONSE should mark the new peer address validated.
13524 QuicFrames frames3;
wubd0152ca2022-04-08 08:26:44 -070013525 frames3.push_back(QuicFrame(QuicPathResponseFrame(99, payload)));
Bence Békybac04052022-04-07 15:44:29 -040013526 ProcessFramesPacketWithAddresses(frames3, kSelfAddress, kNewPeerAddress,
13527 ENCRYPTION_FORWARD_SECURE);
13528
13529 // Process another packet with a newer peer address with the same port will
13530 // start connection migration.
13531 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
13532 // IETF QUIC send algorithm should be changed to a different object, so no
13533 // OnPacketSent() called on the old send algorithm.
13534 EXPECT_CALL(*send_algorithm_,
13535 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13536 .Times(0);
13537 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
13538 /*port=*/34567);
13539 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13540 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
13541 }));
13542 EXPECT_CALL(visitor_, MaybeSendAddressToken());
13543 QuicFrames frames2;
13544 frames2.push_back(QuicFrame(frame2_));
13545 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewerPeerAddress,
13546 ENCRYPTION_FORWARD_SECURE);
13547 EXPECT_EQ(kNewerPeerAddress, connection_.peer_address());
13548 EXPECT_EQ(kNewerPeerAddress, connection_.effective_peer_address());
13549 // Since the newer address has the same IP as the previously validated probing
13550 // address. The peer migration becomes validated immediately.
13551 EXPECT_EQ(NO_CHANGE, connection_.active_effective_peer_migration_type());
13552 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
13553 EXPECT_EQ(1u, connection_.GetStats()
13554 .num_peer_migration_to_proactively_validated_address);
13555 EXPECT_FALSE(connection_.HasPendingPathValidation());
13556 EXPECT_NE(connection_.sent_packet_manager().GetSendAlgorithm(),
13557 send_algorithm_);
13558
13559 EXPECT_EQ(default_path->server_connection_id, server_cid1);
13560 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid1);
13561 // Verify that alternative_path_ is cleared.
13562 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
13563 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
13564
13565 // Switch to use the mock send algorithm.
13566 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
13567 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
13568 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
13569 .WillRepeatedly(Return(kDefaultTCPMSS));
13570 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
13571 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
13572 .Times(AnyNumber())
13573 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13574 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
13575 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
13576 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
13577 connection_.SetSendAlgorithm(send_algorithm_);
13578
13579 // Verify the server is not throttled by the anti-amplification limit by
13580 // sending a packet larger than the anti-amplification limit.
13581 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
13582 connection_.SendCryptoDataWithString(std::string(1200, 'a'), 0);
13583 EXPECT_EQ(1u, connection_.GetStats().num_validated_peer_migration);
13584}
13585
danzhb37451f2022-04-19 08:18:54 -070013586// Regression test of b/228645208.
13587TEST_P(QuicConnectionTest, NoNonProbingFrameOnAlternativePath) {
13588 if (!connection_.connection_migration_use_new_cid()) {
13589 return;
13590 }
13591
13592 PathProbeTestInit(Perspective::IS_SERVER);
13593 SetClientConnectionId(TestConnectionId(1));
13594 connection_.CreateConnectionIdManager();
13595
13596 QuicConnectionId server_cid0 = connection_.connection_id();
13597 QuicConnectionId client_cid0 = connection_.client_connection_id();
13598 QuicConnectionId client_cid1 = TestConnectionId(2);
13599 QuicConnectionId server_cid1;
13600 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013601 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013602 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13603 .WillOnce(Return(TestConnectionId(456)));
13604 }
haoyuewangada6b822022-06-23 13:41:18 -070013605 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
13606 .WillOnce(Invoke([&](const QuicConnectionId& cid) {
13607 server_cid1 = cid;
13608 return true;
13609 }));
danzhb37451f2022-04-19 08:18:54 -070013610 EXPECT_CALL(visitor_, SendNewConnectionId(_));
13611 connection_.MaybeSendConnectionIdToClient();
13612 // Receives new client CID from client.
13613 QuicNewConnectionIdFrame new_cid_frame;
13614 new_cid_frame.connection_id = client_cid1;
13615 new_cid_frame.sequence_number = 1u;
13616 new_cid_frame.retire_prior_to = 0u;
13617 connection_.OnNewConnectionIdFrame(new_cid_frame);
13618 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
13619 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13620 ASSERT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13621
13622 peer_creator_.SetServerConnectionId(server_cid1);
13623 const QuicSocketAddress kNewPeerAddress =
13624 QuicSocketAddress(QuicIpAddress::Loopback4(), /*port=*/23456);
13625 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13626 QuicFrames frames1;
13627 frames1.push_back(
13628 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
13629 QuicPathFrameBuffer payload;
13630 EXPECT_CALL(*send_algorithm_,
13631 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13632 .Times(AtLeast(1))
13633 .WillOnce(Invoke([&]() {
13634 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13635 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13636 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13637 EXPECT_FALSE(writer_->path_response_frames().empty());
13638 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13639 payload = writer_->path_challenge_frames().front().data_buffer;
13640 }));
13641 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewPeerAddress,
13642 ENCRYPTION_FORWARD_SECURE);
13643 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13644 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13645 EXPECT_TRUE(connection_.HasPendingPathValidation());
13646 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13647 const auto* alternative_path =
13648 QuicConnectionPeer::GetAlternativePath(&connection_);
13649 EXPECT_EQ(default_path->client_connection_id, client_cid0);
13650 EXPECT_EQ(default_path->server_connection_id, server_cid0);
13651 EXPECT_EQ(alternative_path->client_connection_id, client_cid1);
13652 EXPECT_EQ(alternative_path->server_connection_id, server_cid1);
13653 EXPECT_EQ(packet_creator->GetDestinationConnectionId(), client_cid0);
13654 EXPECT_EQ(packet_creator->GetSourceConnectionId(), server_cid0);
13655
13656 // Process non-probing packets on the default path.
13657 peer_creator_.SetServerConnectionId(server_cid0);
13658 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillRepeatedly(Invoke([=]() {
13659 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13660 }));
13661 // Receives packets 3 - 39 to send 19 ACK-only packets, which will force the
13662 // connection to reach |kMaxConsecutiveNonRetransmittablePackets| while
13663 // sending the next ACK.
13664 for (size_t i = 3; i <= 39; ++i) {
13665 ProcessDataPacket(i);
13666 }
13667 EXPECT_EQ(kPeerAddress, connection_.peer_address());
13668 EXPECT_EQ(kPeerAddress, connection_.effective_peer_address());
13669
13670 EXPECT_TRUE(connection_.HasPendingAcks());
13671 QuicTime ack_time = connection_.GetAckAlarm()->deadline();
13672 QuicTime path_validation_retry_time =
13673 connection_.GetRetryTimeout(kNewPeerAddress, writer_.get());
13674 // Advance time to simultaneously fire path validation retry and ACK alarms.
13675 clock_.AdvanceTime(std::max(ack_time, path_validation_retry_time) -
13676 clock_.ApproximateNow());
13677
13678 // The 20th ACK should bundle with a WINDOW_UPDATE frame.
13679 EXPECT_CALL(visitor_, OnAckNeedsRetransmittableFrame())
13680 .WillOnce(Invoke([this]() {
13681 connection_.SendControlFrame(QuicFrame(QuicWindowUpdateFrame(1, 0, 0)));
13682 }));
martindukee6444ef2022-09-23 12:32:23 -070013683 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
13684 .WillOnce(Invoke([&]() {
13685 EXPECT_EQ(kNewPeerAddress, writer_->last_write_peer_address());
13686 EXPECT_FALSE(writer_->path_challenge_frames().empty());
13687 // Retry path validation shouldn't bundle ACK.
13688 EXPECT_TRUE(writer_->ack_frames().empty());
13689 }))
13690 .WillOnce(Invoke([&]() {
13691 EXPECT_EQ(kPeerAddress, writer_->last_write_peer_address());
13692 EXPECT_FALSE(writer_->ack_frames().empty());
13693 EXPECT_FALSE(writer_->window_update_frames().empty());
13694 }));
13695 static_cast<TestAlarmFactory::TestAlarm*>(
13696 QuicPathValidatorPeer::retry_timer(
13697 QuicConnectionPeer::path_validator(&connection_)))
13698 ->Fire();
danzhb37451f2022-04-19 08:18:54 -070013699}
13700
haoyuewangada6b822022-06-23 13:41:18 -070013701TEST_P(QuicConnectionTest, DoNotIssueNewCidIfVisitorSaysNo) {
13702 set_perspective(Perspective::IS_SERVER);
13703 if (!connection_.connection_migration_use_new_cid()) {
13704 return;
13705 }
13706
13707 connection_.CreateConnectionIdManager();
13708
13709 QuicConnectionId server_cid0 = connection_.connection_id();
13710 QuicConnectionId client_cid1 = TestConnectionId(2);
13711 QuicConnectionId server_cid1;
13712 // Sends new server CID to client.
martinduke08e3ff82022-10-18 09:06:26 -070013713 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070013714 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13715 .WillOnce(Return(TestConnectionId(456)));
13716 }
haoyuewangada6b822022-06-23 13:41:18 -070013717 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_)).WillOnce(Return(false));
13718 if (GetQuicReloadableFlag(quic_check_cid_collision_when_issue_new_cid)) {
13719 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(0);
13720 } else {
13721 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(1);
13722 }
13723 connection_.MaybeSendConnectionIdToClient();
13724}
13725
Bence Békybac04052022-04-07 15:44:29 -040013726TEST_P(QuicConnectionTest,
13727 ProbedOnAnotherPathAfterPeerIpAddressChangeAtServer) {
13728 PathProbeTestInit(Perspective::IS_SERVER);
13729 if (!connection_.validate_client_address()) {
13730 return;
13731 }
13732
13733 const QuicSocketAddress kNewPeerAddress(QuicIpAddress::Loopback4(),
13734 /*port=*/23456);
13735
13736 // Process a packet with a new peer address will start connection migration.
13737 EXPECT_CALL(visitor_, OnConnectionMigration(IPV6_TO_IPV4_CHANGE)).Times(1);
13738 // IETF QUIC send algorithm should be changed to a different object, so no
13739 // OnPacketSent() called on the old send algorithm.
13740 EXPECT_CALL(*send_algorithm_,
13741 OnPacketSent(_, _, _, _, NO_RETRANSMITTABLE_DATA))
13742 .Times(0);
13743 EXPECT_CALL(visitor_, OnStreamFrame(_)).WillOnce(Invoke([=]() {
13744 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13745 }));
13746 QuicFrames frames2;
13747 frames2.push_back(QuicFrame(frame2_));
13748 ProcessFramesPacketWithAddresses(frames2, kSelfAddress, kNewPeerAddress,
13749 ENCRYPTION_FORWARD_SECURE);
13750 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
13751 EXPECT_TRUE(connection_.HasPendingPathValidation());
13752
13753 // Switch to use the mock send algorithm.
13754 send_algorithm_ = new StrictMock<MockSendAlgorithm>();
13755 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(true));
13756 EXPECT_CALL(*send_algorithm_, GetCongestionWindow())
13757 .WillRepeatedly(Return(kDefaultTCPMSS));
13758 EXPECT_CALL(*send_algorithm_, OnApplicationLimited(_)).Times(AnyNumber());
13759 EXPECT_CALL(*send_algorithm_, BandwidthEstimate())
13760 .Times(AnyNumber())
13761 .WillRepeatedly(Return(QuicBandwidth::Zero()));
13762 EXPECT_CALL(*send_algorithm_, InSlowStart()).Times(AnyNumber());
13763 EXPECT_CALL(*send_algorithm_, InRecovery()).Times(AnyNumber());
13764 EXPECT_CALL(*send_algorithm_, PopulateConnectionStats(_)).Times(AnyNumber());
13765 connection_.SetSendAlgorithm(send_algorithm_);
13766
13767 // Receive probing packet with a newer peer address shouldn't override the
13768 // on-going path validation.
13769 const QuicSocketAddress kNewerPeerAddress(QuicIpAddress::Loopback4(),
13770 /*port=*/34567);
13771 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
13772 .WillOnce(Invoke([&]() {
13773 EXPECT_EQ(kNewerPeerAddress, writer_->last_write_peer_address());
13774 EXPECT_FALSE(writer_->path_response_frames().empty());
13775 EXPECT_TRUE(writer_->path_challenge_frames().empty());
13776 }));
13777 QuicPathFrameBuffer path_challenge_payload{0, 1, 2, 3, 4, 5, 6, 7};
13778 QuicFrames frames1;
13779 frames1.push_back(
wubd0152ca2022-04-08 08:26:44 -070013780 QuicFrame(QuicPathChallengeFrame(0, path_challenge_payload)));
Bence Békybac04052022-04-07 15:44:29 -040013781 ProcessFramesPacketWithAddresses(frames1, kSelfAddress, kNewerPeerAddress,
13782 ENCRYPTION_FORWARD_SECURE);
13783 EXPECT_EQ(kNewPeerAddress, connection_.effective_peer_address());
13784 EXPECT_EQ(kNewPeerAddress, connection_.peer_address());
13785 EXPECT_TRUE(QuicConnectionPeer::IsAlternativePathValidated(&connection_));
13786 EXPECT_TRUE(connection_.HasPendingPathValidation());
13787}
13788
13789TEST_P(QuicConnectionTest,
13790 PathValidationFailedOnClientDueToLackOfServerConnectionId) {
13791 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070013792 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040013793 QuicConfig config;
13794 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13795 connection_.SetFromConfig(config);
13796 config.SetConnectionOptionsToSend({kRVCM});
13797 }
13798 if (!connection_.connection_migration_use_new_cid()) {
13799 return;
13800 }
13801 PathProbeTestInit(Perspective::IS_CLIENT,
13802 /*receive_new_server_connection_id=*/false);
13803
13804 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
13805 /*port=*/34567);
13806
13807 bool success;
13808 connection_.ValidatePath(
13809 std::make_unique<TestQuicPathValidationContext>(
13810 kNewSelfAddress, connection_.peer_address(), writer_.get()),
13811 std::make_unique<TestValidationResultDelegate>(
13812 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
13813
13814 EXPECT_FALSE(success);
13815}
13816
13817TEST_P(QuicConnectionTest,
13818 PathValidationFailedOnClientDueToLackOfClientConnectionIdTheSecondTime) {
13819 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070013820 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040013821 QuicConfig config;
13822 config.SetConnectionOptionsToSend({kRVCM});
13823 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13824 connection_.SetFromConfig(config);
13825 }
13826 if (!connection_.connection_migration_use_new_cid()) {
13827 return;
13828 }
13829 PathProbeTestInit(Perspective::IS_CLIENT,
13830 /*receive_new_server_connection_id=*/false);
13831 SetClientConnectionId(TestConnectionId(1));
13832
13833 // Make sure server connection ID is available for the 1st validation.
13834 QuicConnectionId server_cid0 = connection_.connection_id();
13835 QuicConnectionId server_cid1 = TestConnectionId(2);
13836 QuicConnectionId server_cid2 = TestConnectionId(4);
13837 QuicConnectionId client_cid1;
13838 QuicNewConnectionIdFrame frame1;
13839 frame1.connection_id = server_cid1;
13840 frame1.sequence_number = 1u;
13841 frame1.retire_prior_to = 0u;
13842 frame1.stateless_reset_token =
13843 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
13844 connection_.OnNewConnectionIdFrame(frame1);
13845 const auto* packet_creator =
13846 QuicConnectionPeer::GetPacketCreator(&connection_);
13847 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid0);
13848
13849 // Client will issue a new client connection ID to server.
martinduke08e3ff82022-10-18 09:06:26 -070013850 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
13851 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040013852 EXPECT_CALL(visitor_, SendNewConnectionId(_))
13853 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
13854 client_cid1 = frame.connection_id;
13855 }));
13856
13857 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
13858 ASSERT_NE(kSelfAddress1, connection_.self_address());
13859 bool success1;
13860 connection_.ValidatePath(
13861 std::make_unique<TestQuicPathValidationContext>(
13862 kSelfAddress1, connection_.peer_address(), writer_.get()),
13863 std::make_unique<TestValidationResultDelegate>(
13864 &connection_, kSelfAddress1, connection_.peer_address(), &success1));
13865
13866 // Migrate upon 1st validation success.
13867 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13868 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
13869 &new_writer, /*owns_writer=*/false));
13870 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
13871 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
13872 EXPECT_EQ(default_path->client_connection_id, client_cid1);
13873 EXPECT_EQ(default_path->server_connection_id, server_cid1);
13874 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
13875 const auto* alternative_path =
13876 QuicConnectionPeer::GetAlternativePath(&connection_);
13877 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
13878 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
13879 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
13880 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), server_cid1);
13881
13882 // Client will retire server connection ID on old default_path.
13883 auto* retire_peer_issued_cid_alarm =
13884 connection_.GetRetirePeerIssuedConnectionIdAlarm();
13885 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
13886 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
13887 retire_peer_issued_cid_alarm->Fire();
13888
13889 // Another server connection ID is available to client.
13890 QuicNewConnectionIdFrame frame2;
13891 frame2.connection_id = server_cid2;
13892 frame2.sequence_number = 2u;
13893 frame2.retire_prior_to = 1u;
13894 frame2.stateless_reset_token =
13895 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
13896 connection_.OnNewConnectionIdFrame(frame2);
13897
13898 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
13899 /*port=*/45678);
13900 bool success2;
13901 connection_.ValidatePath(
13902 std::make_unique<TestQuicPathValidationContext>(
13903 kSelfAddress2, connection_.peer_address(), writer_.get()),
13904 std::make_unique<TestValidationResultDelegate>(
13905 &connection_, kSelfAddress2, connection_.peer_address(), &success2));
13906 // Since server does not retire any client connection ID yet, 2nd validation
13907 // would fail due to lack of client connection ID.
13908 EXPECT_FALSE(success2);
13909}
13910
13911TEST_P(QuicConnectionTest, ServerConnectionIdRetiredUponPathValidationFailure) {
13912 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070013913 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040013914 QuicConfig config;
13915 config.SetConnectionOptionsToSend({kRVCM});
13916 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13917 connection_.SetFromConfig(config);
13918 }
13919 if (!connection_.connection_migration_use_new_cid()) {
13920 return;
13921 }
13922 PathProbeTestInit(Perspective::IS_CLIENT);
13923
13924 // Make sure server connection ID is available for validation.
13925 QuicNewConnectionIdFrame frame;
13926 frame.connection_id = TestConnectionId(2);
13927 frame.sequence_number = 1u;
13928 frame.retire_prior_to = 0u;
13929 frame.stateless_reset_token =
13930 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
13931 connection_.OnNewConnectionIdFrame(frame);
13932
13933 const QuicSocketAddress kNewSelfAddress(QuicIpAddress::Loopback4(),
13934 /*port=*/34567);
13935 bool success;
13936 connection_.ValidatePath(
13937 std::make_unique<TestQuicPathValidationContext>(
13938 kNewSelfAddress, connection_.peer_address(), writer_.get()),
13939 std::make_unique<TestValidationResultDelegate>(
13940 &connection_, kNewSelfAddress, connection_.peer_address(), &success));
13941
13942 auto* path_validator = QuicConnectionPeer::path_validator(&connection_);
13943 path_validator->CancelPathValidation();
13944 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
13945 EXPECT_FALSE(success);
13946 const auto* alternative_path =
13947 QuicConnectionPeer::GetAlternativePath(&connection_);
13948 EXPECT_TRUE(alternative_path->client_connection_id.IsEmpty());
13949 EXPECT_TRUE(alternative_path->server_connection_id.IsEmpty());
13950 EXPECT_FALSE(alternative_path->stateless_reset_token.has_value());
13951
13952 // Client will retire server connection ID on alternative_path.
13953 auto* retire_peer_issued_cid_alarm =
13954 connection_.GetRetirePeerIssuedConnectionIdAlarm();
13955 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
13956 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/1u));
13957 retire_peer_issued_cid_alarm->Fire();
13958}
13959
13960TEST_P(QuicConnectionTest,
13961 MigratePathDirectlyFailedDueToLackOfServerConnectionId) {
13962 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070013963 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040013964 QuicConfig config;
13965 config.SetConnectionOptionsToSend({kRVCM});
13966 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13967 connection_.SetFromConfig(config);
13968 }
13969 if (!connection_.connection_migration_use_new_cid()) {
13970 return;
13971 }
13972 PathProbeTestInit(Perspective::IS_CLIENT,
13973 /*receive_new_server_connection_id=*/false);
13974 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
13975 ASSERT_NE(kSelfAddress1, connection_.self_address());
13976
13977 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
13978 ASSERT_FALSE(connection_.MigratePath(kSelfAddress1,
13979 connection_.peer_address(), &new_writer,
13980 /*owns_writer=*/false));
13981}
13982
13983TEST_P(QuicConnectionTest,
13984 MigratePathDirectlyFailedDueToLackOfClientConnectionIdTheSecondTime) {
13985 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070013986 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040013987 QuicConfig config;
13988 config.SetConnectionOptionsToSend({kRVCM});
13989 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
13990 connection_.SetFromConfig(config);
13991 }
13992 if (!connection_.connection_migration_use_new_cid()) {
13993 return;
13994 }
13995 PathProbeTestInit(Perspective::IS_CLIENT,
13996 /*receive_new_server_connection_id=*/false);
13997 SetClientConnectionId(TestConnectionId(1));
13998
13999 // Make sure server connection ID is available for the 1st migration.
14000 QuicNewConnectionIdFrame frame1;
14001 frame1.connection_id = TestConnectionId(2);
14002 frame1.sequence_number = 1u;
14003 frame1.retire_prior_to = 0u;
14004 frame1.stateless_reset_token =
14005 QuicUtils::GenerateStatelessResetToken(frame1.connection_id);
14006 connection_.OnNewConnectionIdFrame(frame1);
14007
14008 // Client will issue a new client connection ID to server.
14009 QuicConnectionId new_client_connection_id;
martinduke08e3ff82022-10-18 09:06:26 -070014010 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14011 .WillOnce(Return(TestConnectionId(456)));
Bence Békybac04052022-04-07 15:44:29 -040014012 EXPECT_CALL(visitor_, SendNewConnectionId(_))
14013 .WillOnce(Invoke([&](const QuicNewConnectionIdFrame& frame) {
14014 new_client_connection_id = frame.connection_id;
14015 }));
14016
14017 // 1st migration is successful.
14018 const QuicSocketAddress kSelfAddress1(QuicIpAddress::Any4(), 12345);
14019 ASSERT_NE(kSelfAddress1, connection_.self_address());
14020 TestPacketWriter new_writer(version(), &clock_, Perspective::IS_CLIENT);
14021 ASSERT_TRUE(connection_.MigratePath(kSelfAddress1, connection_.peer_address(),
14022 &new_writer,
14023 /*owns_writer=*/false));
14024 QuicConnectionPeer::RetirePeerIssuedConnectionIdsNoLongerOnPath(&connection_);
14025 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14026 EXPECT_EQ(default_path->client_connection_id, new_client_connection_id);
14027 EXPECT_EQ(default_path->server_connection_id, frame1.connection_id);
14028 EXPECT_EQ(default_path->stateless_reset_token, frame1.stateless_reset_token);
14029
14030 // Client will retire server connection ID on old default_path.
14031 auto* retire_peer_issued_cid_alarm =
14032 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14033 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14034 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14035 retire_peer_issued_cid_alarm->Fire();
14036
14037 // Another server connection ID is available to client.
14038 QuicNewConnectionIdFrame frame2;
14039 frame2.connection_id = TestConnectionId(4);
14040 frame2.sequence_number = 2u;
14041 frame2.retire_prior_to = 1u;
14042 frame2.stateless_reset_token =
14043 QuicUtils::GenerateStatelessResetToken(frame2.connection_id);
14044 connection_.OnNewConnectionIdFrame(frame2);
14045
14046 // Since server does not retire any client connection ID yet, 2nd migration
14047 // would fail due to lack of client connection ID.
14048 const QuicSocketAddress kSelfAddress2(QuicIpAddress::Loopback4(),
14049 /*port=*/45678);
14050 auto new_writer2 = std::make_unique<TestPacketWriter>(version(), &clock_,
14051 Perspective::IS_CLIENT);
14052 ASSERT_FALSE(connection_.MigratePath(
14053 kSelfAddress2, connection_.peer_address(), new_writer2.release(),
14054 /*owns_writer=*/true));
14055}
14056
14057TEST_P(QuicConnectionTest,
14058 CloseConnectionAfterReceiveNewConnectionIdFromPeerUsingEmptyCID) {
14059 if (!version().HasIetfQuicFrames()) {
14060 return;
14061 }
14062 set_perspective(Perspective::IS_SERVER);
14063 ASSERT_TRUE(connection_.client_connection_id().IsEmpty());
14064
14065 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14066 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14067 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14068 QuicNewConnectionIdFrame frame;
14069 frame.sequence_number = 1u;
14070 frame.connection_id = TestConnectionId(1);
14071 frame.stateless_reset_token =
14072 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14073 frame.retire_prior_to = 0u;
14074
14075 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14076
14077 EXPECT_FALSE(connection_.connected());
14078 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14079 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14080}
14081
14082TEST_P(QuicConnectionTest, NewConnectionIdFrameResultsInError) {
14083 if (!version().HasIetfQuicFrames()) {
14084 return;
14085 }
14086 connection_.CreateConnectionIdManager();
14087 ASSERT_FALSE(connection_.connection_id().IsEmpty());
14088
14089 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14090 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14091 QuicNewConnectionIdFrame frame;
14092 frame.sequence_number = 1u;
14093 frame.connection_id = connection_id_; // Reuses connection ID casuing error.
14094 frame.stateless_reset_token =
14095 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14096 frame.retire_prior_to = 0u;
14097
14098 EXPECT_FALSE(connection_.OnNewConnectionIdFrame(frame));
14099
14100 EXPECT_FALSE(connection_.connected());
14101 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14102 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14103}
14104
14105TEST_P(QuicConnectionTest,
14106 ClientRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14107 if (!version().HasIetfQuicFrames()) {
14108 return;
14109 }
14110 connection_.CreateConnectionIdManager();
14111
14112 QuicNewConnectionIdFrame frame;
14113 frame.sequence_number = 1u;
14114 frame.connection_id = TestConnectionId(1);
14115 frame.stateless_reset_token =
14116 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14117 frame.retire_prior_to = 0u;
14118
14119 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14120 auto* retire_peer_issued_cid_alarm =
14121 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14122 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14123
14124 frame.sequence_number = 2u;
14125 frame.connection_id = TestConnectionId(2);
14126 frame.stateless_reset_token =
14127 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14128 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14129
14130 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14131 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14132 EXPECT_EQ(connection_.connection_id(), connection_id_);
14133
14134 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14135 retire_peer_issued_cid_alarm->Fire();
14136 EXPECT_EQ(connection_.connection_id(), TestConnectionId(2));
14137 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14138 TestConnectionId(2));
14139}
14140
14141TEST_P(QuicConnectionTest,
14142 ServerRetirePeerIssuedConnectionIdTriggeredByNewConnectionIdFrame) {
14143 if (!version().HasIetfQuicFrames()) {
14144 return;
14145 }
14146 set_perspective(Perspective::IS_SERVER);
14147 SetClientConnectionId(TestConnectionId(0));
14148
14149 QuicNewConnectionIdFrame frame;
14150 frame.sequence_number = 1u;
14151 frame.connection_id = TestConnectionId(1);
14152 frame.stateless_reset_token =
14153 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14154 frame.retire_prior_to = 0u;
14155
14156 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14157 auto* retire_peer_issued_cid_alarm =
14158 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14159 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14160
14161 frame.sequence_number = 2u;
14162 frame.connection_id = TestConnectionId(2);
14163 frame.stateless_reset_token =
14164 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14165 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14166
14167 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14168 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14169 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14170
14171 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14172 retire_peer_issued_cid_alarm->Fire();
14173 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14174 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14175 TestConnectionId(2));
14176}
14177
14178TEST_P(
14179 QuicConnectionTest,
14180 ReplacePeerIssuedConnectionIdOnBothPathsTriggeredByNewConnectionIdFrame) {
danzhaf2e52a2022-04-20 07:37:03 -070014181 if (!version().HasIetfQuicFrames()) {
Bence Békybac04052022-04-07 15:44:29 -040014182 return;
14183 }
14184 PathProbeTestInit(Perspective::IS_SERVER);
14185 SetClientConnectionId(TestConnectionId(0));
14186
14187 // Populate alternative_path_ with probing packet.
14188 std::unique_ptr<SerializedPacket> probing_packet = ConstructProbingPacket();
14189
14190 std::unique_ptr<QuicReceivedPacket> received(ConstructReceivedPacket(
14191 QuicEncryptedPacket(probing_packet->encrypted_buffer,
14192 probing_packet->encrypted_length),
14193 clock_.Now()));
14194 QuicIpAddress new_host;
14195 new_host.FromString("1.1.1.1");
14196 ProcessReceivedPacket(kSelfAddress,
14197 QuicSocketAddress(new_host, /*port=*/23456), *received);
14198
14199 EXPECT_EQ(
14200 TestConnectionId(0),
14201 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14202
14203 QuicNewConnectionIdFrame frame;
14204 frame.sequence_number = 1u;
14205 frame.connection_id = TestConnectionId(1);
14206 frame.stateless_reset_token =
14207 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14208 frame.retire_prior_to = 0u;
14209
14210 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14211 auto* retire_peer_issued_cid_alarm =
14212 connection_.GetRetirePeerIssuedConnectionIdAlarm();
14213 ASSERT_FALSE(retire_peer_issued_cid_alarm->IsSet());
14214
14215 frame.sequence_number = 2u;
14216 frame.connection_id = TestConnectionId(2);
14217 frame.stateless_reset_token =
14218 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14219 frame.retire_prior_to = 1u; // CID associated with #1 will be retired.
14220
14221 EXPECT_TRUE(connection_.OnNewConnectionIdFrame(frame));
14222 ASSERT_TRUE(retire_peer_issued_cid_alarm->IsSet());
14223 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(0));
14224
14225 EXPECT_CALL(visitor_, SendRetireConnectionId(/*sequence_number=*/0u));
14226 retire_peer_issued_cid_alarm->Fire();
14227 EXPECT_EQ(connection_.client_connection_id(), TestConnectionId(2));
14228 EXPECT_EQ(connection_.packet_creator().GetDestinationConnectionId(),
14229 TestConnectionId(2));
14230 // Clean up alternative path connection ID.
14231 EXPECT_EQ(
14232 TestConnectionId(2),
14233 QuicConnectionPeer::GetClientConnectionIdOnAlternativePath(&connection_));
14234}
14235
14236TEST_P(QuicConnectionTest,
14237 CloseConnectionAfterReceiveRetireConnectionIdWhenNoCIDIssued) {
14238 if (!version().HasIetfQuicFrames() ||
14239 !connection_.connection_migration_use_new_cid()) {
14240 return;
14241 }
14242 set_perspective(Perspective::IS_SERVER);
14243
14244 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14245 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14246 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14247 QuicRetireConnectionIdFrame frame;
14248 frame.sequence_number = 1u;
14249
14250 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14251
14252 EXPECT_FALSE(connection_.connected());
14253 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14254 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14255}
14256
14257TEST_P(QuicConnectionTest, RetireConnectionIdFrameResultsInError) {
14258 if (!version().HasIetfQuicFrames() ||
14259 !connection_.connection_migration_use_new_cid()) {
14260 return;
14261 }
14262 set_perspective(Perspective::IS_SERVER);
14263 connection_.CreateConnectionIdManager();
14264
martinduke08e3ff82022-10-18 09:06:26 -070014265 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014266 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14267 .WillOnce(Return(TestConnectionId(456)));
14268 }
haoyuewangada6b822022-06-23 13:41:18 -070014269 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_));
Bence Békybac04052022-04-07 15:44:29 -040014270 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14271 connection_.MaybeSendConnectionIdToClient();
14272
14273 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14274 EXPECT_CALL(visitor_, OnConnectionClosed(_, ConnectionCloseSource::FROM_SELF))
14275 .WillOnce(Invoke(this, &QuicConnectionTest::SaveConnectionCloseFrame));
14276 QuicRetireConnectionIdFrame frame;
14277 frame.sequence_number = 2u; // The corresponding ID is never issued.
14278
14279 EXPECT_FALSE(connection_.OnRetireConnectionIdFrame(frame));
14280
14281 EXPECT_FALSE(connection_.connected());
14282 EXPECT_THAT(saved_connection_close_frame_.quic_error_code,
14283 IsError(IETF_QUIC_PROTOCOL_VIOLATION));
14284}
14285
14286TEST_P(QuicConnectionTest,
14287 ServerRetireSelfIssuedConnectionIdWithoutSendingNewConnectionIdBefore) {
14288 if (!version().HasIetfQuicFrames()) {
14289 return;
14290 }
14291 set_perspective(Perspective::IS_SERVER);
14292 connection_.CreateConnectionIdManager();
14293
14294 auto* retire_self_issued_cid_alarm =
14295 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14296 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14297
14298 QuicConnectionId cid0 = connection_id_;
14299 QuicRetireConnectionIdFrame frame;
14300 frame.sequence_number = 0u;
14301 if (connection_.connection_migration_use_new_cid()) {
martinduke08e3ff82022-10-18 09:06:26 -070014302 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014303 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(cid0))
14304 .WillOnce(Return(TestConnectionId(456)));
14305 EXPECT_CALL(connection_id_generator_,
14306 GenerateNextConnectionId(TestConnectionId(456)))
14307 .WillOnce(Return(TestConnectionId(789)));
14308 }
haoyuewangada6b822022-06-23 13:41:18 -070014309 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
14310 .Times(2)
14311 .WillRepeatedly(Return(true));
Bence Békybac04052022-04-07 15:44:29 -040014312 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
14313 }
14314 EXPECT_TRUE(connection_.OnRetireConnectionIdFrame(frame));
14315}
14316
14317TEST_P(QuicConnectionTest, ServerRetireSelfIssuedConnectionId) {
14318 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014319 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014320 QuicConfig config;
14321 config.SetConnectionOptionsToSend({kRVCM});
14322 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14323 connection_.SetFromConfig(config);
14324 }
14325 if (!connection_.connection_migration_use_new_cid()) {
14326 return;
14327 }
14328 set_perspective(Perspective::IS_SERVER);
14329 connection_.CreateConnectionIdManager();
14330 QuicConnectionId recorded_cid;
haoyuewangada6b822022-06-23 13:41:18 -070014331 auto cid_recorder = [&recorded_cid](const QuicConnectionId& cid) -> bool {
Bence Békybac04052022-04-07 15:44:29 -040014332 recorded_cid = cid;
haoyuewangada6b822022-06-23 13:41:18 -070014333 return true;
Bence Békybac04052022-04-07 15:44:29 -040014334 };
14335 QuicConnectionId cid0 = connection_id_;
14336 QuicConnectionId cid1;
14337 QuicConnectionId cid2;
14338 EXPECT_EQ(connection_.connection_id(), cid0);
14339 EXPECT_EQ(connection_.GetOneActiveServerConnectionId(), cid0);
14340
14341 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
martinduke08e3ff82022-10-18 09:06:26 -070014342 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014343 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14344 .WillOnce(Return(TestConnectionId(456)));
14345 }
haoyuewangada6b822022-06-23 13:41:18 -070014346 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040014347 .WillOnce(Invoke(cid_recorder));
14348 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14349 connection_.MaybeSendConnectionIdToClient();
14350 cid1 = recorded_cid;
14351
14352 auto* retire_self_issued_cid_alarm =
14353 connection_.GetRetireSelfIssuedConnectionIdAlarm();
14354 ASSERT_FALSE(retire_self_issued_cid_alarm->IsSet());
14355
14356 // Generate three packets with different connection IDs that will arrive out
14357 // of order (2, 1, 3) later.
14358 char buffers[3][kMaxOutgoingPacketSize];
14359 // Destination connection ID of packet1 is cid0.
14360 auto packet1 =
14361 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14362 buffers[0], kMaxOutgoingPacketSize);
14363 peer_creator_.SetServerConnectionId(cid1);
14364 auto retire_cid_frame = std::make_unique<QuicRetireConnectionIdFrame>();
14365 retire_cid_frame->sequence_number = 0u;
14366 // Destination connection ID of packet2 is cid1.
14367 auto packet2 = ConstructPacket({QuicFrame(retire_cid_frame.release())},
14368 ENCRYPTION_FORWARD_SECURE, buffers[1],
14369 kMaxOutgoingPacketSize);
14370 // Destination connection ID of packet3 is cid1.
14371 auto packet3 =
14372 ConstructPacket({QuicFrame(QuicPingFrame())}, ENCRYPTION_FORWARD_SECURE,
14373 buffers[2], kMaxOutgoingPacketSize);
14374
14375 // Packet2 with RetireConnectionId frame trigers sending NewConnectionId
14376 // immediately.
martinduke08e3ff82022-10-18 09:06:26 -070014377 if (!connection_.connection_id().IsEmpty()) {
martinduke605dca22022-09-01 10:40:19 -070014378 EXPECT_CALL(connection_id_generator_, GenerateNextConnectionId(_))
14379 .WillOnce(Return(TestConnectionId(456)));
14380 }
haoyuewangada6b822022-06-23 13:41:18 -070014381 EXPECT_CALL(visitor_, MaybeReserveConnectionId(_))
Bence Békybac04052022-04-07 15:44:29 -040014382 .WillOnce(Invoke(cid_recorder));
14383 EXPECT_CALL(visitor_, SendNewConnectionId(_));
14384 peer_creator_.SetServerConnectionId(cid1);
14385 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet2);
14386 cid2 = recorded_cid;
14387 // cid0 is not retired immediately.
14388 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
14389 ElementsAre(cid0, cid1, cid2));
14390 ASSERT_TRUE(retire_self_issued_cid_alarm->IsSet());
14391 EXPECT_EQ(connection_.connection_id(), cid1);
14392 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
14393 connection_.GetOneActiveServerConnectionId() == cid1 ||
14394 connection_.GetOneActiveServerConnectionId() == cid2);
14395
14396 // Packet1 updates the connection ID on the default path but not the active
14397 // connection ID.
14398 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet1);
14399 EXPECT_EQ(connection_.connection_id(), cid0);
14400 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid0 ||
14401 connection_.GetOneActiveServerConnectionId() == cid1 ||
14402 connection_.GetOneActiveServerConnectionId() == cid2);
14403
14404 // cid0 is retired when the retire CID alarm fires.
14405 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(cid0));
14406 retire_self_issued_cid_alarm->Fire();
14407 EXPECT_THAT(connection_.GetActiveServerConnectionIds(),
14408 ElementsAre(cid1, cid2));
14409 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
14410 connection_.GetOneActiveServerConnectionId() == cid2);
14411
14412 // Packet3 updates the connection ID on the default path.
14413 connection_.ProcessUdpPacket(kSelfAddress, kPeerAddress, *packet3);
14414 EXPECT_EQ(connection_.connection_id(), cid1);
14415 EXPECT_TRUE(connection_.GetOneActiveServerConnectionId() == cid1 ||
14416 connection_.GetOneActiveServerConnectionId() == cid2);
14417}
14418
14419TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoAlternativePath) {
14420 if (!version().HasIetfQuicFrames()) {
14421 return;
14422 }
14423 set_perspective(Perspective::IS_SERVER);
14424 connection_.CreateConnectionIdManager();
14425 connection_.set_client_connection_id(TestConnectionId(1));
14426
14427 // Set up the state after path probing.
14428 const auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14429 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
14430 QuicIpAddress new_host;
14431 new_host.FromString("12.12.12.12");
14432 alternative_path->self_address = default_path->self_address;
14433 alternative_path->peer_address = QuicSocketAddress(new_host, 12345);
14434 alternative_path->server_connection_id = TestConnectionId(3);
14435 ASSERT_TRUE(alternative_path->client_connection_id.IsEmpty());
14436 ASSERT_FALSE(alternative_path->stateless_reset_token.has_value());
14437
14438 QuicNewConnectionIdFrame frame;
14439 frame.sequence_number = 1u;
14440 frame.connection_id = TestConnectionId(5);
14441 frame.stateless_reset_token =
14442 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14443 frame.retire_prior_to = 0u;
14444 // New ID is patched onto the alternative path when the needed
14445 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
14446 connection_.OnNewConnectionIdFrame(frame);
14447
14448 ASSERT_EQ(alternative_path->client_connection_id, frame.connection_id);
14449 ASSERT_EQ(alternative_path->stateless_reset_token,
14450 frame.stateless_reset_token);
14451}
14452
14453TEST_P(QuicConnectionTest, PatchMissingClientConnectionIdOntoDefaultPath) {
14454 if (!version().HasIetfQuicFrames()) {
14455 return;
14456 }
14457 set_perspective(Perspective::IS_SERVER);
14458 connection_.CreateConnectionIdManager();
14459 connection_.set_client_connection_id(TestConnectionId(1));
14460
14461 // Set up the state after peer migration without probing.
14462 auto* default_path = QuicConnectionPeer::GetDefaultPath(&connection_);
14463 auto* alternative_path = QuicConnectionPeer::GetAlternativePath(&connection_);
14464 auto* packet_creator = QuicConnectionPeer::GetPacketCreator(&connection_);
14465 *alternative_path = std::move(*default_path);
14466 QuicIpAddress new_host;
14467 new_host.FromString("12.12.12.12");
14468 default_path->self_address = default_path->self_address;
14469 default_path->peer_address = QuicSocketAddress(new_host, 12345);
14470 default_path->server_connection_id = TestConnectionId(3);
14471 packet_creator->SetDefaultPeerAddress(default_path->peer_address);
14472 packet_creator->SetServerConnectionId(default_path->server_connection_id);
14473 packet_creator->SetClientConnectionId(default_path->client_connection_id);
14474
14475 ASSERT_FALSE(default_path->validated);
14476 ASSERT_TRUE(default_path->client_connection_id.IsEmpty());
14477 ASSERT_FALSE(default_path->stateless_reset_token.has_value());
14478
14479 QuicNewConnectionIdFrame frame;
14480 frame.sequence_number = 1u;
14481 frame.connection_id = TestConnectionId(5);
14482 frame.stateless_reset_token =
14483 QuicUtils::GenerateStatelessResetToken(frame.connection_id);
14484 frame.retire_prior_to = 0u;
14485 // New ID is patched onto the default path when the needed
14486 // NEW_CONNECTION_ID frame is received after PATH_CHALLENGE frame.
14487 connection_.OnNewConnectionIdFrame(frame);
14488
14489 ASSERT_EQ(default_path->client_connection_id, frame.connection_id);
14490 ASSERT_EQ(default_path->stateless_reset_token, frame.stateless_reset_token);
14491 ASSERT_EQ(packet_creator->GetDestinationConnectionId(), frame.connection_id);
14492}
14493
14494TEST_P(QuicConnectionTest, ShouldGeneratePacketBlockedByMissingConnectionId) {
14495 if (!version().HasIetfQuicFrames()) {
14496 return;
14497 }
14498 set_perspective(Perspective::IS_SERVER);
14499 connection_.set_client_connection_id(TestConnectionId(1));
14500 connection_.CreateConnectionIdManager();
14501 if (version().SupportsAntiAmplificationLimit()) {
14502 QuicConnectionPeer::SetAddressValidated(&connection_);
14503 }
14504
14505 ASSERT_TRUE(
14506 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
14507
14508 QuicPacketCreator* packet_creator =
14509 QuicConnectionPeer::GetPacketCreator(&connection_);
14510 QuicIpAddress peer_host1;
14511 peer_host1.FromString("12.12.12.12");
14512 QuicSocketAddress peer_address1(peer_host1, 1235);
14513
14514 {
14515 // No connection ID is available as context is created without any.
14516 QuicPacketCreator::ScopedPeerAddressContext context(
14517 packet_creator, peer_address1, EmptyQuicConnectionId(),
14518 EmptyQuicConnectionId(),
14519 /*update_connection_id=*/true);
14520 ASSERT_FALSE(connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA,
14521 NOT_HANDSHAKE));
14522 }
14523 ASSERT_TRUE(
14524 connection_.ShouldGeneratePacket(NO_RETRANSMITTABLE_DATA, NOT_HANDSHAKE));
14525}
14526
14527// Regression test for b/182571515
14528TEST_P(QuicConnectionTest, LostDataThenGetAcknowledged) {
14529 set_perspective(Perspective::IS_SERVER);
fayang161ce6e2022-07-01 18:02:11 -070014530 if (!connection_.validate_client_address() ||
birenroyef686222022-09-12 11:34:34 -070014531 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040014532 return;
14533 }
14534
14535 QuicPacketCreatorPeer::SetSendVersionInPacket(creator_, false);
14536 if (version().SupportsAntiAmplificationLimit()) {
14537 QuicConnectionPeer::SetAddressValidated(&connection_);
14538 }
14539 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14540 // Discard INITIAL key.
14541 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
14542 connection_.NeuterUnencryptedPackets();
14543 EXPECT_CALL(visitor_, GetHandshakeState())
14544 .WillRepeatedly(Return(HANDSHAKE_CONFIRMED));
14545
14546 QuicPacketNumber last_packet;
14547 // Send packets 1 to 4.
14548 SendStreamDataToPeer(3, "foo", 0, NO_FIN, &last_packet); // Packet 1
14549 SendStreamDataToPeer(3, "foo", 3, NO_FIN, &last_packet); // Packet 2
14550 SendStreamDataToPeer(3, "foo", 6, NO_FIN, &last_packet); // Packet 3
14551 SendStreamDataToPeer(3, "foo", 9, NO_FIN, &last_packet); // Packet 4
14552
14553 // Process a PING packet to set peer address.
14554 ProcessFramePacket(QuicFrame(QuicPingFrame()));
14555
14556 // Process a packet containing a STREAM_FRAME and an ACK with changed peer
14557 // address.
14558 QuicFrames frames;
14559 frames.push_back(QuicFrame(frame1_));
14560 QuicAckFrame ack = InitAckFrame({{QuicPacketNumber(1), QuicPacketNumber(5)}});
14561 frames.push_back(QuicFrame(&ack));
14562
Bence Békybac04052022-04-07 15:44:29 -040014563 // Invoke OnCanWrite.
Bence Békybac04052022-04-07 15:44:29 -040014564 QuicIpAddress ip_address;
14565 ASSERT_TRUE(ip_address.FromString("127.0.52.223"));
vasilvvac2e30d2022-06-02 14:26:59 -070014566 EXPECT_QUIC_BUG(
14567 {
14568 EXPECT_CALL(visitor_, OnConnectionMigration(_)).Times(1);
14569 EXPECT_CALL(visitor_, OnStreamFrame(_))
14570 .WillOnce(InvokeWithoutArgs(&notifier_,
14571 &SimpleSessionNotifier::OnCanWrite));
14572 ProcessFramesPacketWithAddresses(frames, kSelfAddress,
14573 QuicSocketAddress(ip_address, 1000),
14574 ENCRYPTION_FORWARD_SECURE);
14575 EXPECT_EQ(1u, writer_->path_challenge_frames().size());
14576
14577 // Verify stream frame will not be retransmitted.
14578 EXPECT_TRUE(writer_->stream_frames().empty());
14579 },
14580 "Try to write mid packet processing");
Bence Békybac04052022-04-07 15:44:29 -040014581}
14582
14583TEST_P(QuicConnectionTest, PtoSendStreamData) {
14584 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14585 return;
14586 }
14587 set_perspective(Perspective::IS_SERVER);
14588 if (QuicVersionUsesCryptoFrames(connection_.transport_version())) {
14589 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
14590 }
14591 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
14592 use_tagging_decrypter();
14593 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
14594 EXPECT_TRUE(connection_.HasPendingAcks());
14595
14596 connection_.SetEncrypter(ENCRYPTION_INITIAL,
14597 std::make_unique<TaggingEncrypter>(0x01));
14598 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14599 // Send INITIAL 1.
14600 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
14601
14602 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
14603 std::make_unique<TaggingEncrypter>(0x02));
14604 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
14605 SetDecrypter(ENCRYPTION_HANDSHAKE,
14606 std::make_unique<StrictTaggingDecrypter>(0x02));
14607 // Send HANDSHAKE packets.
14608 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
14609 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
14610
14611 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
14612 std::make_unique<TaggingEncrypter>(0x03));
14613 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14614
14615 // Send half RTT packet with congestion control blocked.
14616 EXPECT_CALL(*send_algorithm_, CanSend(_)).WillRepeatedly(Return(false));
14617 connection_.SendStreamDataWithString(2, std::string(1500, 'a'), 0, NO_FIN);
14618
14619 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14620 connection_.GetRetransmissionAlarm()->Fire();
14621 // Verify INITIAL and HANDSHAKE get retransmitted.
14622 EXPECT_EQ(0x02020202u, writer_->final_bytes_of_last_packet());
14623}
14624
14625TEST_P(QuicConnectionTest, SendingZeroRttPacketsDoesNotPostponePTO) {
14626 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14627 return;
14628 }
14629 use_tagging_decrypter();
14630 connection_.SetEncrypter(ENCRYPTION_INITIAL,
14631 std::make_unique<TaggingEncrypter>(0x01));
14632 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14633 // Send CHLO.
14634 connection_.SendCryptoStreamData();
14635 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14636 // Install 0-RTT keys.
14637 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14638 std::make_unique<TaggingEncrypter>(0x02));
14639 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14640
14641 // CHLO gets acknowledged after 10ms.
14642 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
14643 QuicAckFrame frame1 = InitAckFrame(1);
14644 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
14645 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
14646 // Verify PTO is still armed since address validation is not finished yet.
14647 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14648 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14649
14650 // Send 0-RTT packet.
14651 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
14652 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14653 std::make_unique<TaggingEncrypter>(0x02));
14654 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14655 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
14656 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14657 // PTO deadline should be unchanged.
14658 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
14659}
14660
14661TEST_P(QuicConnectionTest, QueueingUndecryptablePacketsDoesntPostponePTO) {
14662 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14663 return;
14664 }
14665 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14666 QuicConfig config;
14667 config.set_max_undecryptable_packets(3);
14668 connection_.SetFromConfig(config);
14669 use_tagging_decrypter();
14670 connection_.SetEncrypter(ENCRYPTION_INITIAL,
14671 std::make_unique<TaggingEncrypter>(0x01));
14672 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14673 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
14674 // Send CHLO.
14675 connection_.SendCryptoStreamData();
14676
14677 // Send 0-RTT packet.
14678 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14679 std::make_unique<TaggingEncrypter>(0x02));
14680 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14681 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
14682
14683 // CHLO gets acknowledged after 10ms.
14684 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
14685 QuicAckFrame frame1 = InitAckFrame(1);
14686 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
14687 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
14688 // Verify PTO is still armed since address validation is not finished yet.
14689 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14690 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14691
14692 // Receive an undecryptable packets.
14693 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
14694 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
14695 std::make_unique<TaggingEncrypter>(0xFF));
14696 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14697 // Verify PTO deadline is sooner.
14698 EXPECT_GT(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
14699 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14700
14701 // PTO fires.
14702 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
14703 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
14704 connection_.GetRetransmissionAlarm()->Fire();
14705 // Verify PTO is still armed since address validation is not finished yet.
14706 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14707 pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14708
14709 // Verify PTO deadline does not change.
14710 ProcessDataPacketAtLevel(4, !kHasStopWaiting, ENCRYPTION_FORWARD_SECURE);
14711 EXPECT_EQ(pto_deadline, connection_.GetRetransmissionAlarm()->deadline());
14712}
14713
14714TEST_P(QuicConnectionTest, QueueUndecryptableHandshakePackets) {
14715 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14716 return;
14717 }
14718 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14719 QuicConfig config;
14720 config.set_max_undecryptable_packets(3);
14721 connection_.SetFromConfig(config);
14722 use_tagging_decrypter();
14723 connection_.SetEncrypter(ENCRYPTION_INITIAL,
14724 std::make_unique<TaggingEncrypter>(0x01));
14725 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14726 connection_.RemoveDecrypter(ENCRYPTION_HANDSHAKE);
14727 // Send CHLO.
14728 connection_.SendCryptoStreamData();
14729
14730 // Send 0-RTT packet.
14731 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14732 std::make_unique<TaggingEncrypter>(0x02));
14733 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14734 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
14735 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
14736
14737 // Receive an undecryptable handshake packet.
14738 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
14739 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
14740 std::make_unique<TaggingEncrypter>(0xFF));
14741 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_HANDSHAKE);
14742 // Verify this handshake packet gets queued.
14743 EXPECT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
14744}
14745
14746TEST_P(QuicConnectionTest, PingNotSentAt0RTTLevelWhenInitialAvailable) {
14747 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
14748 return;
14749 }
14750 use_tagging_decrypter();
14751 connection_.SetEncrypter(ENCRYPTION_INITIAL,
14752 std::make_unique<TaggingEncrypter>(0x01));
14753 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14754 // Send CHLO.
14755 connection_.SendCryptoStreamData();
14756 // Send 0-RTT packet.
14757 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14758 std::make_unique<TaggingEncrypter>(0x02));
14759 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
14760 connection_.SendStreamDataWithString(2, "foo", 0, NO_FIN);
14761
14762 // CHLO gets acknowledged after 10ms.
14763 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
14764 QuicAckFrame frame1 = InitAckFrame(1);
14765 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
14766 ProcessFramePacketAtLevel(1, QuicFrame(&frame1), ENCRYPTION_INITIAL);
14767 // Verify PTO is still armed since address validation is not finished yet.
14768 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
14769 QuicTime pto_deadline = connection_.GetRetransmissionAlarm()->deadline();
14770
14771 // PTO fires.
14772 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
14773 clock_.AdvanceTime(pto_deadline - clock_.ApproximateNow());
14774 connection_.GetRetransmissionAlarm()->Fire();
14775 // Verify the PING gets sent in ENCRYPTION_INITIAL.
14776 EXPECT_EQ(0x01010101u, writer_->final_bytes_of_last_packet());
14777}
14778
14779TEST_P(QuicConnectionTest, AckElicitingFrames) {
14780 if (!GetQuicReloadableFlag(
haoyuewang30045be2022-04-08 12:57:08 -070014781 quic_remove_connection_migration_connection_option_v2)) {
Bence Békybac04052022-04-07 15:44:29 -040014782 QuicConfig config;
14783 config.SetConnectionOptionsToSend({kRVCM});
14784 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
14785 connection_.SetFromConfig(config);
14786 }
14787 if (!version().HasIetfQuicFrames() ||
14788 !connection_.connection_migration_use_new_cid()) {
14789 return;
14790 }
martinduke08e3ff82022-10-18 09:06:26 -070014791 EXPECT_CALL(connection_id_generator_,
14792 GenerateNextConnectionId(TestConnectionId(12)))
14793 .WillOnce(Return(TestConnectionId(456)));
14794 EXPECT_CALL(connection_id_generator_,
14795 GenerateNextConnectionId(TestConnectionId(456)))
14796 .WillOnce(Return(TestConnectionId(789)));
Bence Békybac04052022-04-07 15:44:29 -040014797 EXPECT_CALL(visitor_, SendNewConnectionId(_)).Times(2);
14798 EXPECT_CALL(visitor_, OnRstStream(_));
14799 EXPECT_CALL(visitor_, OnWindowUpdateFrame(_));
14800 EXPECT_CALL(visitor_, OnBlockedFrame(_));
14801 EXPECT_CALL(visitor_, OnHandshakeDoneReceived());
14802 EXPECT_CALL(visitor_, OnStreamFrame(_));
14803 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
14804 EXPECT_CALL(visitor_, OnMaxStreamsFrame(_));
14805 EXPECT_CALL(visitor_, OnStreamsBlockedFrame(_));
14806 EXPECT_CALL(visitor_, OnStopSendingFrame(_));
14807 EXPECT_CALL(visitor_, OnMessageReceived(""));
14808 EXPECT_CALL(visitor_, OnNewTokenReceived(""));
14809
14810 SetClientConnectionId(TestConnectionId(12));
14811 connection_.CreateConnectionIdManager();
14812 QuicConnectionPeer::GetSelfIssuedConnectionIdManager(&connection_)
14813 ->MaybeSendNewConnectionIds();
14814 connection_.set_can_receive_ack_frequency_frame();
14815
14816 QuicAckFrame ack_frame = InitAckFrame(1);
14817 QuicRstStreamFrame rst_stream_frame;
14818 QuicWindowUpdateFrame window_update_frame;
14819 QuicPathChallengeFrame path_challenge_frame;
14820 QuicNewConnectionIdFrame new_connection_id_frame;
14821 QuicRetireConnectionIdFrame retire_connection_id_frame;
14822 retire_connection_id_frame.sequence_number = 1u;
14823 QuicStopSendingFrame stop_sending_frame;
14824 QuicPathResponseFrame path_response_frame;
14825 QuicMessageFrame message_frame;
14826 QuicNewTokenFrame new_token_frame;
14827 QuicAckFrequencyFrame ack_frequency_frame;
14828 QuicBlockedFrame blocked_frame;
14829 size_t packet_number = 1;
14830
14831 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14832
14833 for (uint8_t i = 0; i < NUM_FRAME_TYPES; ++i) {
14834 QuicFrameType frame_type = static_cast<QuicFrameType>(i);
14835 bool skipped = false;
14836 QuicFrame frame;
14837 QuicFrames frames;
14838 // Add some padding to fullfill the min size requirement of header
14839 // protection.
14840 frames.push_back(QuicFrame(QuicPaddingFrame(10)));
14841 switch (frame_type) {
14842 case PADDING_FRAME:
14843 frame = QuicFrame(QuicPaddingFrame(10));
14844 break;
14845 case MTU_DISCOVERY_FRAME:
14846 frame = QuicFrame(QuicMtuDiscoveryFrame());
14847 break;
14848 case PING_FRAME:
14849 frame = QuicFrame(QuicPingFrame());
14850 break;
14851 case MAX_STREAMS_FRAME:
14852 frame = QuicFrame(QuicMaxStreamsFrame());
14853 break;
14854 case STOP_WAITING_FRAME:
14855 // Not supported.
14856 skipped = true;
14857 break;
14858 case STREAMS_BLOCKED_FRAME:
14859 frame = QuicFrame(QuicStreamsBlockedFrame());
14860 break;
14861 case STREAM_FRAME:
14862 frame = QuicFrame(QuicStreamFrame());
14863 break;
14864 case HANDSHAKE_DONE_FRAME:
14865 frame = QuicFrame(QuicHandshakeDoneFrame());
14866 break;
14867 case ACK_FRAME:
14868 frame = QuicFrame(&ack_frame);
14869 break;
14870 case RST_STREAM_FRAME:
14871 frame = QuicFrame(&rst_stream_frame);
14872 break;
14873 case CONNECTION_CLOSE_FRAME:
14874 // Do not test connection close.
14875 skipped = true;
14876 break;
14877 case GOAWAY_FRAME:
14878 // Does not exist in IETF QUIC.
14879 skipped = true;
14880 break;
14881 case BLOCKED_FRAME:
14882 frame = QuicFrame(blocked_frame);
14883 break;
14884 case WINDOW_UPDATE_FRAME:
14885 frame = QuicFrame(window_update_frame);
14886 break;
14887 case PATH_CHALLENGE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070014888 frame = QuicFrame(path_challenge_frame);
Bence Békybac04052022-04-07 15:44:29 -040014889 break;
14890 case STOP_SENDING_FRAME:
14891 frame = QuicFrame(stop_sending_frame);
14892 break;
14893 case NEW_CONNECTION_ID_FRAME:
14894 frame = QuicFrame(&new_connection_id_frame);
14895 break;
14896 case RETIRE_CONNECTION_ID_FRAME:
14897 frame = QuicFrame(&retire_connection_id_frame);
14898 break;
14899 case PATH_RESPONSE_FRAME:
wubd0152ca2022-04-08 08:26:44 -070014900 frame = QuicFrame(path_response_frame);
Bence Békybac04052022-04-07 15:44:29 -040014901 break;
14902 case MESSAGE_FRAME:
14903 frame = QuicFrame(&message_frame);
14904 break;
14905 case CRYPTO_FRAME:
14906 // CRYPTO_FRAME is ack eliciting is covered by other tests.
14907 skipped = true;
14908 break;
14909 case NEW_TOKEN_FRAME:
14910 frame = QuicFrame(&new_token_frame);
14911 break;
14912 case ACK_FREQUENCY_FRAME:
14913 frame = QuicFrame(&ack_frequency_frame);
14914 break;
14915 case NUM_FRAME_TYPES:
14916 skipped = true;
14917 break;
14918 }
14919 if (skipped) {
14920 continue;
14921 }
14922 ASSERT_EQ(frame_type, frame.type);
14923 frames.push_back(frame);
14924 EXPECT_FALSE(connection_.HasPendingAcks());
14925 // Process frame.
14926 ProcessFramesPacketAtLevel(packet_number++, frames,
14927 ENCRYPTION_FORWARD_SECURE);
14928 if (QuicUtils::IsAckElicitingFrame(frame_type)) {
14929 ASSERT_TRUE(connection_.HasPendingAcks()) << frame;
14930 // Flush ACK.
14931 clock_.AdvanceTime(DefaultDelayedAckTime());
14932 connection_.GetAckAlarm()->Fire();
14933 }
14934 EXPECT_FALSE(connection_.HasPendingAcks());
14935 ASSERT_TRUE(connection_.connected());
14936 }
14937}
14938
14939TEST_P(QuicConnectionTest, ReceivedChloAndAck) {
14940 if (!version().HasIetfQuicFrames()) {
14941 return;
14942 }
14943 set_perspective(Perspective::IS_SERVER);
14944 QuicFrames frames;
14945 QuicAckFrame ack_frame = InitAckFrame(1);
14946 frames.push_back(MakeCryptoFrame());
14947 frames.push_back(QuicFrame(&ack_frame));
14948
14949 EXPECT_CALL(visitor_, OnCryptoFrame(_))
14950 .WillOnce(IgnoreResult(InvokeWithoutArgs(
14951 &connection_, &TestConnection::SendCryptoStreamData)));
14952 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
14953 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
14954 ProcessFramesPacketWithAddresses(frames, kSelfAddress, kPeerAddress,
14955 ENCRYPTION_INITIAL);
14956}
14957
14958// Regression test for b/201643321.
14959TEST_P(QuicConnectionTest, FailedToRetransmitShlo) {
fayang161ce6e2022-07-01 18:02:11 -070014960 if (!version().HasIetfQuicFrames() ||
birenroyef686222022-09-12 11:34:34 -070014961 GetQuicFlag(quic_enforce_strict_amplification_factor)) {
Bence Békybac04052022-04-07 15:44:29 -040014962 return;
14963 }
14964 set_perspective(Perspective::IS_SERVER);
14965 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
14966 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
14967 use_tagging_decrypter();
14968 // Received INITIAL 1.
14969 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
14970 EXPECT_TRUE(connection_.HasPendingAcks());
14971
14972 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
14973 std::make_unique<TaggingEncrypter>(0x02));
14974
14975 connection_.SetEncrypter(ENCRYPTION_INITIAL,
14976 std::make_unique<TaggingEncrypter>(0x01));
14977 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
14978 std::make_unique<TaggingEncrypter>(0x03));
14979 SetDecrypter(ENCRYPTION_HANDSHAKE,
14980 std::make_unique<StrictTaggingDecrypter>(0x02));
14981 SetDecrypter(ENCRYPTION_ZERO_RTT,
14982 std::make_unique<StrictTaggingDecrypter>(0x02));
14983 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
14984 std::make_unique<TaggingEncrypter>(0x04));
14985 // Received ENCRYPTION_ZERO_RTT 1.
14986 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
14987 {
14988 QuicConnection::ScopedPacketFlusher flusher(&connection_);
14989 // Send INITIAL 1.
14990 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
14991 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
14992 // Send HANDSHAKE 2.
14993 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
14994 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
14995 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_HANDSHAKE);
14996 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
14997 // Send half RTT data to exhaust amplification credit.
14998 connection_.SendStreamDataWithString(0, std::string(100 * 1024, 'a'), 0,
14999 NO_FIN);
15000 }
15001 // Received INITIAL 2.
15002 ProcessCryptoPacketAtLevel(2, ENCRYPTION_INITIAL);
15003 ASSERT_TRUE(connection_.HasPendingAcks());
15004 // Verify ACK delay is 1ms.
15005 EXPECT_EQ(clock_.Now() + kAlarmGranularity,
15006 connection_.GetAckAlarm()->deadline());
15007 // ACK is not throttled by amplification limit, and SHLO is bundled. Also
15008 // HANDSHAKE + 1RTT packets get coalesced.
fayange9753892022-05-17 03:57:11 -070015009 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
Bence Békybac04052022-04-07 15:44:29 -040015010 // ACK alarm fires.
15011 clock_.AdvanceTime(kAlarmGranularity);
15012 connection_.GetAckAlarm()->Fire();
fayange9753892022-05-17 03:57:11 -070015013 // Verify 1-RTT packet is coalesced.
15014 EXPECT_EQ(0x04040404u, writer_->final_bytes_of_last_packet());
Bence Békybac04052022-04-07 15:44:29 -040015015 // Only the first packet in the coalesced packet has been processed,
15016 // verify SHLO is bundled with INITIAL ACK.
15017 EXPECT_EQ(1u, writer_->ack_frames().size());
15018 EXPECT_EQ(1u, writer_->crypto_frames().size());
15019 // Process the coalesced HANDSHAKE packet.
15020 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15021 auto packet = writer_->coalesced_packet()->Clone();
15022 writer_->framer()->ProcessPacket(*packet);
15023 EXPECT_EQ(0u, writer_->ack_frames().size());
15024 EXPECT_EQ(1u, writer_->crypto_frames().size());
fayange9753892022-05-17 03:57:11 -070015025 // Process the coalesced 1-RTT packet.
15026 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15027 packet = writer_->coalesced_packet()->Clone();
15028 writer_->framer()->ProcessPacket(*packet);
15029 EXPECT_EQ(0u, writer_->crypto_frames().size());
15030 EXPECT_EQ(1u, writer_->stream_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040015031
15032 // Received INITIAL 3.
15033 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(AnyNumber());
15034 ProcessCryptoPacketAtLevel(3, ENCRYPTION_INITIAL);
15035 EXPECT_TRUE(connection_.HasPendingAcks());
15036}
15037
15038// Regression test for b/216133388.
15039TEST_P(QuicConnectionTest, FailedToConsumeCryptoData) {
15040 if (!version().HasIetfQuicFrames()) {
15041 return;
15042 }
15043 set_perspective(Perspective::IS_SERVER);
15044 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15045 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15046 use_tagging_decrypter();
15047 // Received INITIAL 1.
15048 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15049 EXPECT_TRUE(connection_.HasPendingAcks());
15050
15051 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15052 std::make_unique<TaggingEncrypter>(0x02));
15053
15054 connection_.SetEncrypter(ENCRYPTION_INITIAL,
15055 std::make_unique<TaggingEncrypter>(0x01));
15056 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15057 std::make_unique<TaggingEncrypter>(0x03));
15058 SetDecrypter(ENCRYPTION_HANDSHAKE,
15059 std::make_unique<StrictTaggingDecrypter>(0x03));
15060 SetDecrypter(ENCRYPTION_ZERO_RTT,
15061 std::make_unique<StrictTaggingDecrypter>(0x02));
15062 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15063 std::make_unique<TaggingEncrypter>(0x04));
15064 // Received ENCRYPTION_ZERO_RTT 1.
15065 ProcessDataPacketAtLevel(1, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15066 {
15067 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15068 // Send INITIAL 1.
15069 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15070 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15071 // Send HANDSHAKE 2.
15072 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15073 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15074 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15075 ENCRYPTION_HANDSHAKE);
15076 // Send 1-RTT 3.
15077 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15078 connection_.SendStreamDataWithString(0, std::string(40, 'a'), 0, NO_FIN);
15079 }
15080 // Received HANDSHAKE Ping, hence discard INITIAL keys.
15081 peer_framer_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15082 std::make_unique<TaggingEncrypter>(0x03));
15083 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15084 connection_.NeuterUnencryptedPackets();
15085 ProcessCryptoPacketAtLevel(1, ENCRYPTION_HANDSHAKE);
15086 clock_.AdvanceTime(kAlarmGranularity);
15087 {
15088 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15089 // Sending this 1-RTT data would leave the coalescer only have space to
15090 // accommodate the HANDSHAKE ACK. The crypto data cannot be bundled with the
15091 // ACK.
15092 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15093 connection_.SendStreamDataWithString(0, std::string(1395, 'a'), 40, NO_FIN);
15094 }
15095 // Verify retransmission alarm is armed.
15096 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15097 const QuicTime retransmission_time =
15098 connection_.GetRetransmissionAlarm()->deadline();
15099 clock_.AdvanceTime(retransmission_time - clock_.Now());
15100 connection_.GetRetransmissionAlarm()->Fire();
15101
fayang43294412022-04-21 09:22:12 -070015102 // Verify the retransmission is a coalesced packet with HANDSHAKE 2 and
15103 // 1-RTT 3.
15104 EXPECT_EQ(0x04040404u, writer_->final_bytes_of_last_packet());
15105 // Only the first packet in the coalesced packet has been processed.
15106 EXPECT_EQ(1u, writer_->crypto_frames().size());
15107 // Process the coalesced 1-RTT packet.
15108 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15109 auto packet = writer_->coalesced_packet()->Clone();
15110 writer_->framer()->ProcessPacket(*packet);
15111 EXPECT_EQ(1u, writer_->stream_frames().size());
15112 ASSERT_TRUE(writer_->coalesced_packet() == nullptr);
Bence Békybac04052022-04-07 15:44:29 -040015113 // Verify retransmission alarm is still armed.
15114 ASSERT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15115}
15116
15117TEST_P(QuicConnectionTest,
15118 RTTSampleDoesNotIncludeQueuingDelayWithPostponedAckProcessing) {
15119 // An endpoint might postpone the processing of ACK when the corresponding
15120 // decryption key is not available. This test makes sure the RTT sample does
15121 // not include the queuing delay.
15122 if (!version().HasIetfQuicFrames()) {
15123 return;
15124 }
15125 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15126 QuicConfig config;
15127 config.set_max_undecryptable_packets(3);
15128 connection_.SetFromConfig(config);
15129
15130 // 30ms RTT.
15131 const QuicTime::Delta kTestRTT = QuicTime::Delta::FromMilliseconds(30);
15132 RttStats* rtt_stats = const_cast<RttStats*>(manager_->GetRttStats());
15133 rtt_stats->UpdateRtt(kTestRTT, QuicTime::Delta::Zero(), QuicTime::Zero());
15134 use_tagging_decrypter();
15135
15136 // Send 0-RTT packet.
15137 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15138 connection_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15139 std::make_unique<TaggingEncrypter>(0x02));
15140 connection_.SetDefaultEncryptionLevel(ENCRYPTION_ZERO_RTT);
15141 connection_.SendStreamDataWithString(0, std::string(10, 'a'), 0, FIN);
15142
15143 // Receives 1-RTT ACK for 0-RTT packet after RTT + ack_delay.
15144 clock_.AdvanceTime(
15145 kTestRTT + QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs));
15146 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15147 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15148 std::make_unique<TaggingEncrypter>(0x01));
15149 QuicAckFrame ack_frame = InitAckFrame(1);
15150 // Peer reported ACK delay.
15151 ack_frame.ack_delay_time =
15152 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs);
15153 QuicFrames frames;
15154 frames.push_back(QuicFrame(&ack_frame));
15155 QuicPacketHeader header =
15156 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15157 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15158
15159 char buffer[kMaxOutgoingPacketSize];
15160 size_t encrypted_length = peer_framer_.EncryptPayload(
15161 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15162 kMaxOutgoingPacketSize);
15163 connection_.ProcessUdpPacket(
15164 kSelfAddress, kPeerAddress,
15165 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15166 if (connection_.GetSendAlarm()->IsSet()) {
15167 connection_.GetSendAlarm()->Fire();
15168 }
15169 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15170
15171 // Assume 1-RTT decrypter is available after 10ms.
15172 clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(10));
15173 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15174 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
15175 std::make_unique<StrictTaggingDecrypter>(0x01));
15176 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15177
15178 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _));
15179 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15180 // Verify RTT sample does not include queueing delay.
15181 EXPECT_EQ(rtt_stats->latest_rtt(), kTestRTT);
15182}
15183
15184// Regression test for b/112480134.
15185TEST_P(QuicConnectionTest, NoExtraPaddingInReserializedInitial) {
15186 // EXPECT_QUIC_BUG tests are expensive so only run one instance of them.
15187 if (!IsDefaultTestConfiguration() ||
15188 !connection_.version().CanSendCoalescedPackets()) {
15189 return;
15190 }
15191
15192 set_perspective(Perspective::IS_SERVER);
15193 MockQuicConnectionDebugVisitor debug_visitor;
15194 connection_.set_debug_visitor(&debug_visitor);
15195
15196 uint64_t debug_visitor_sent_count = 0;
15197 EXPECT_CALL(debug_visitor, OnPacketSent(_, _, _, _, _, _, _, _))
15198 .WillRepeatedly([&]() { debug_visitor_sent_count++; });
15199
15200 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15201 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15202 use_tagging_decrypter();
15203
15204 // Received INITIAL 1.
15205 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15206
15207 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15208 std::make_unique<TaggingEncrypter>(0x02));
15209
15210 connection_.SetEncrypter(ENCRYPTION_INITIAL,
15211 std::make_unique<TaggingEncrypter>(0x01));
15212 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15213 std::make_unique<TaggingEncrypter>(0x03));
15214 SetDecrypter(ENCRYPTION_HANDSHAKE,
15215 std::make_unique<StrictTaggingDecrypter>(0x03));
15216 SetDecrypter(ENCRYPTION_ZERO_RTT,
15217 std::make_unique<StrictTaggingDecrypter>(0x02));
15218 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15219 std::make_unique<TaggingEncrypter>(0x04));
15220
15221 // Received ENCRYPTION_ZERO_RTT 2.
15222 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15223
15224 {
15225 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15226 // Send INITIAL 1.
15227 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15228 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15229 // Send HANDSHAKE 2.
15230 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15231 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15232 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15233 ENCRYPTION_HANDSHAKE);
15234 // Send 1-RTT 3.
15235 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15236 connection_.SendStreamDataWithString(0, std::string(400, 'b'), 0, NO_FIN);
15237 }
15238
15239 // Arrange the stream data to be sent in response to ENCRYPTION_INITIAL 3.
15240 const std::string data4(1000, '4'); // Data to send in stream id 4
15241 const std::string data8(3000, '8'); // Data to send in stream id 8
15242 EXPECT_CALL(visitor_, OnCanWrite()).WillOnce([&]() {
15243 connection_.producer()->SaveStreamData(4, data4);
15244 connection_.producer()->SaveStreamData(8, data8);
15245
15246 notifier_.WriteOrBufferData(4, data4.size(), FIN_AND_PADDING);
15247
15248 // This should trigger FlushCoalescedPacket.
15249 notifier_.WriteOrBufferData(8, data8.size(), FIN);
15250 });
15251
15252 QuicByteCount pending_padding_after_serialize_2nd_1rtt_packet = 0;
15253 QuicPacketCount num_1rtt_packets_serialized = 0;
15254 EXPECT_CALL(connection_, OnSerializedPacket(_))
15255 .WillRepeatedly([&](SerializedPacket packet) {
15256 if (packet.encryption_level == ENCRYPTION_FORWARD_SECURE) {
15257 num_1rtt_packets_serialized++;
15258 if (num_1rtt_packets_serialized == 2) {
15259 pending_padding_after_serialize_2nd_1rtt_packet =
15260 connection_.packet_creator().pending_padding_bytes();
15261 }
15262 }
15263 connection_.QuicConnection::OnSerializedPacket(std::move(packet));
15264 });
15265
15266 // Server receives INITIAL 3, this will serialzie FS 7 (stream 4, stream 8),
15267 // which will trigger a flush of a coalesced packet consists of INITIAL 4,
15268 // HS 5 and FS 6 (stream 4).
wub08efde42022-05-09 12:25:02 -070015269
15270 // Expect no QUIC_BUG.
15271 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15272 EXPECT_EQ(
15273 debug_visitor_sent_count,
15274 connection_.sent_packet_manager().GetLargestSentPacket().ToUint64());
Bence Békybac04052022-04-07 15:44:29 -040015275
15276 // The error only happens if after serializing the second 1RTT packet(pkt #7),
15277 // the pending padding bytes is non zero.
15278 EXPECT_GT(pending_padding_after_serialize_2nd_1rtt_packet, 0u);
15279 EXPECT_TRUE(connection_.connected());
15280}
15281
15282TEST_P(QuicConnectionTest, ReportedAckDelayIncludesQueuingDelay) {
15283 if (!version().HasIetfQuicFrames()) {
15284 return;
15285 }
15286 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _));
15287 QuicConfig config;
15288 config.set_max_undecryptable_packets(3);
15289 connection_.SetFromConfig(config);
15290
15291 // Receive 1-RTT ack-eliciting packet while keys are not available.
15292 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
15293 peer_framer_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15294 std::make_unique<TaggingEncrypter>(0x01));
15295 QuicFrames frames;
15296 frames.push_back(QuicFrame(QuicPingFrame()));
15297 frames.push_back(QuicFrame(QuicPaddingFrame(100)));
15298 QuicPacketHeader header =
15299 ConstructPacketHeader(30, ENCRYPTION_FORWARD_SECURE);
15300 std::unique_ptr<QuicPacket> packet(ConstructPacket(header, frames));
15301
15302 char buffer[kMaxOutgoingPacketSize];
15303 size_t encrypted_length = peer_framer_.EncryptPayload(
15304 ENCRYPTION_FORWARD_SECURE, QuicPacketNumber(30), *packet, buffer,
15305 kMaxOutgoingPacketSize);
15306 EXPECT_EQ(0u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15307 const QuicTime packet_receipt_time = clock_.Now();
15308 connection_.ProcessUdpPacket(
15309 kSelfAddress, kPeerAddress,
15310 QuicReceivedPacket(buffer, encrypted_length, clock_.Now(), false));
15311 if (connection_.GetSendAlarm()->IsSet()) {
15312 connection_.GetSendAlarm()->Fire();
15313 }
15314 ASSERT_EQ(1u, QuicConnectionPeer::NumUndecryptablePackets(&connection_));
15315 // 1-RTT keys become available after 10ms.
15316 const QuicTime::Delta kQueuingDelay = QuicTime::Delta::FromMilliseconds(10);
15317 clock_.AdvanceTime(kQueuingDelay);
15318 EXPECT_FALSE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15319 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15320 SetDecrypter(ENCRYPTION_FORWARD_SECURE,
15321 std::make_unique<StrictTaggingDecrypter>(0x01));
15322 ASSERT_TRUE(connection_.GetProcessUndecryptablePacketsAlarm()->IsSet());
15323
15324 connection_.GetProcessUndecryptablePacketsAlarm()->Fire();
15325 ASSERT_TRUE(connection_.HasPendingAcks());
fayangfea655c2022-05-17 08:19:12 -070015326 EXPECT_EQ(packet_receipt_time + DefaultDelayedAckTime(),
15327 connection_.GetAckAlarm()->deadline());
15328 clock_.AdvanceTime(packet_receipt_time + DefaultDelayedAckTime() -
15329 clock_.Now());
Bence Békybac04052022-04-07 15:44:29 -040015330 // Fire ACK alarm.
15331 connection_.GetAckAlarm()->Fire();
15332 ASSERT_EQ(1u, writer_->ack_frames().size());
fayangfea655c2022-05-17 08:19:12 -070015333 // Verify ACK delay time does not include queuing delay.
15334 EXPECT_EQ(DefaultDelayedAckTime(), writer_->ack_frames()[0].ack_delay_time);
Bence Békybac04052022-04-07 15:44:29 -040015335}
15336
15337TEST_P(QuicConnectionTest, CoalesceOneRTTPacketWithInitialAndHandshakePackets) {
15338 if (!version().HasIetfQuicFrames()) {
15339 return;
15340 }
15341 set_perspective(Perspective::IS_SERVER);
15342 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15343 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15344 use_tagging_decrypter();
15345
15346 // Received INITIAL 1.
15347 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15348
15349 peer_framer_.SetEncrypter(ENCRYPTION_ZERO_RTT,
15350 std::make_unique<TaggingEncrypter>(0x02));
15351
15352 connection_.SetEncrypter(ENCRYPTION_INITIAL,
15353 std::make_unique<TaggingEncrypter>(0x01));
15354 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15355 std::make_unique<TaggingEncrypter>(0x03));
15356 SetDecrypter(ENCRYPTION_HANDSHAKE,
15357 std::make_unique<StrictTaggingDecrypter>(0x03));
15358 SetDecrypter(ENCRYPTION_ZERO_RTT,
15359 std::make_unique<StrictTaggingDecrypter>(0x02));
15360 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15361 std::make_unique<TaggingEncrypter>(0x04));
15362
15363 // Received ENCRYPTION_ZERO_RTT 2.
15364 ProcessDataPacketAtLevel(2, !kHasStopWaiting, ENCRYPTION_ZERO_RTT);
15365
15366 {
15367 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15368 // Send INITIAL 1.
15369 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15370 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15371 // Send HANDSHAKE 2.
15372 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15373 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15374 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15375 ENCRYPTION_HANDSHAKE);
15376 // Send 1-RTT data.
15377 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15378 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
15379 }
15380 // Verify coalesced packet [INITIAL 1 + HANDSHAKE 2 + part of 1-RTT data] +
15381 // rest of 1-RTT data get sent.
15382 EXPECT_EQ(2u, writer_->packets_write_attempts());
15383
15384 // Received ENCRYPTION_INITIAL 3.
15385 ProcessDataPacketAtLevel(3, !kHasStopWaiting, ENCRYPTION_INITIAL);
15386
15387 // Verify a coalesced packet gets sent.
15388 EXPECT_EQ(3u, writer_->packets_write_attempts());
15389
15390 // Only the first INITIAL packet has been processed yet.
15391 EXPECT_EQ(1u, writer_->ack_frames().size());
15392 EXPECT_EQ(1u, writer_->crypto_frames().size());
15393
15394 // Process HANDSHAKE packet.
15395 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15396 auto packet = writer_->coalesced_packet()->Clone();
15397 writer_->framer()->ProcessPacket(*packet);
15398 EXPECT_EQ(1u, writer_->crypto_frames().size());
Bence Békybac04052022-04-07 15:44:29 -040015399 // Process 1-RTT packet.
15400 ASSERT_TRUE(writer_->coalesced_packet() != nullptr);
15401 packet = writer_->coalesced_packet()->Clone();
15402 writer_->framer()->ProcessPacket(*packet);
15403 EXPECT_EQ(1u, writer_->stream_frames().size());
15404}
15405
15406// Regression test for b/180103273
15407TEST_P(QuicConnectionTest, SendMultipleConnectionCloses) {
15408 if (!version().HasIetfQuicFrames() ||
15409 !GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2)) {
15410 return;
15411 }
15412 set_perspective(Perspective::IS_SERVER);
15413 // Finish handshake.
15414 QuicConnectionPeer::SetAddressValidated(&connection_);
15415 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15416 notifier_.NeuterUnencryptedData();
15417 connection_.NeuterUnencryptedPackets();
15418 connection_.OnHandshakeComplete();
15419 connection_.RemoveEncrypter(ENCRYPTION_INITIAL);
15420 connection_.RemoveEncrypter(ENCRYPTION_HANDSHAKE);
15421 EXPECT_CALL(visitor_, GetHandshakeState())
15422 .WillRepeatedly(Return(HANDSHAKE_COMPLETE));
15423
15424 SendStreamDataToPeer(1, "foo", 0, NO_FIN, nullptr);
15425 ASSERT_TRUE(connection_.BlackholeDetectionInProgress());
bnc3000cba2022-04-18 12:19:14 -070015426 // Verify that BeforeConnectionCloseSent() gets called twice,
15427 // while OnConnectionClosed() is called only once.
Bence Békybac04052022-04-07 15:44:29 -040015428 EXPECT_CALL(visitor_, BeforeConnectionCloseSent()).Times(2);
15429 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15430 // Send connection close w/o closing connection.
15431 QuicConnectionPeer::SendConnectionClosePacket(
15432 &connection_, INTERNAL_ERROR, QUIC_INTERNAL_ERROR, "internal error");
bnc3000cba2022-04-18 12:19:14 -070015433 // Fire blackhole detection alarm. This will invoke
15434 // SendConnectionClosePacket() a second time.
15435 connection_.GetBlackholeDetectorAlarm()->Fire();
Bence Békybac04052022-04-07 15:44:29 -040015436}
15437
15438// Regression test for b/157895910.
15439TEST_P(QuicConnectionTest, EarliestSentTimeNotInitializedWhenPtoFires) {
15440 if (!connection_.SupportsMultiplePacketNumberSpaces()) {
15441 return;
15442 }
15443 set_perspective(Perspective::IS_SERVER);
15444 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(AnyNumber());
15445 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(AnyNumber());
15446 use_tagging_decrypter();
15447
15448 // Received INITIAL 1.
15449 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15450 connection_.SetEncrypter(ENCRYPTION_INITIAL,
15451 std::make_unique<TaggingEncrypter>(0x01));
15452 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15453 std::make_unique<TaggingEncrypter>(0x03));
15454 SetDecrypter(ENCRYPTION_HANDSHAKE,
15455 std::make_unique<StrictTaggingDecrypter>(0x03));
15456 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15457 std::make_unique<TaggingEncrypter>(0x04));
15458 {
15459 QuicConnection::ScopedPacketFlusher flusher(&connection_);
15460 // Send INITIAL 1.
15461 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15462 connection_.SendCryptoDataWithString("foo", 0, ENCRYPTION_INITIAL);
15463 // Send HANDSHAKE 2.
15464 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(1);
15465 connection_.SetDefaultEncryptionLevel(ENCRYPTION_HANDSHAKE);
15466 connection_.SendCryptoDataWithString(std::string(200, 'a'), 0,
15467 ENCRYPTION_HANDSHAKE);
15468 // Send half RTT data.
15469 connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
15470 connection_.SendStreamDataWithString(0, std::string(2000, 'b'), 0, FIN);
15471 }
15472
15473 // Received ACKs for both INITIAL and HANDSHAKE packets.
15474 EXPECT_CALL(*send_algorithm_, OnCongestionEvent(_, _, _, _, _))
15475 .Times(AnyNumber());
15476 QuicFrames frames1;
15477 QuicAckFrame ack_frame1 = InitAckFrame(1);
15478 frames1.push_back(QuicFrame(&ack_frame1));
15479
15480 QuicFrames frames2;
15481 QuicAckFrame ack_frame2 =
15482 InitAckFrame({{QuicPacketNumber(2), QuicPacketNumber(3)}});
15483 frames2.push_back(QuicFrame(&ack_frame2));
15484 ProcessCoalescedPacket(
15485 {{2, frames1, ENCRYPTION_INITIAL}, {3, frames2, ENCRYPTION_HANDSHAKE}});
15486 // Verify PTO is not armed given the only outstanding data is half RTT data.
15487 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15488}
15489
wub47bb7282022-06-14 09:40:33 -070015490TEST_P(QuicConnectionTest, CalculateNetworkBlackholeDelay) {
15491 if (!IsDefaultTestConfiguration()) {
15492 return;
15493 }
15494
15495 const QuicTime::Delta kOneSec = QuicTime::Delta::FromSeconds(1);
15496 const QuicTime::Delta kTwoSec = QuicTime::Delta::FromSeconds(2);
15497 const QuicTime::Delta kFourSec = QuicTime::Delta::FromSeconds(4);
15498
15499 // Normal case: blackhole_delay longer than path_degrading_delay +
15500 // 2*pto_delay.
15501 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
15502 kOneSec),
15503 kFourSec);
15504
15505 EXPECT_EQ(QuicConnection::CalculateNetworkBlackholeDelay(kFourSec, kOneSec,
15506 kTwoSec),
15507 QuicTime::Delta::FromSeconds(5));
15508}
15509
fayangb225e172022-06-27 17:45:38 -070015510TEST_P(QuicConnectionTest, FixBytesAccountingForBufferedCoalescedPackets) {
15511 if (!connection_.version().CanSendCoalescedPackets()) {
15512 return;
15513 }
15514 connection_.SetEncrypter(ENCRYPTION_INITIAL,
15515 std::make_unique<TaggingEncrypter>(0x01));
15516 // Write is blocked.
15517 EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AnyNumber());
15518 writer_->SetWriteBlocked();
15519 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15520 QuicConnectionPeer::SendPing(&connection_);
15521 const QuicConnectionStats& stats = connection_.GetStats();
fayang4e283832022-09-01 12:47:07 -070015522 // Verify padding is accounted.
15523 EXPECT_EQ(stats.bytes_sent, connection_.max_packet_length());
fayangb225e172022-06-27 17:45:38 -070015524}
15525
fayang161ce6e2022-07-01 18:02:11 -070015526TEST_P(QuicConnectionTest, StrictAntiAmplificationLimit) {
15527 if (!connection_.version().SupportsAntiAmplificationLimit()) {
15528 return;
15529 }
15530 EXPECT_CALL(visitor_, OnHandshakePacketSent()).Times(AnyNumber());
15531 set_perspective(Perspective::IS_SERVER);
15532 use_tagging_decrypter();
15533 connection_.SetEncrypter(ENCRYPTION_INITIAL,
15534 std::make_unique<TaggingEncrypter>(0x01));
15535 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15536 // Verify no data can be sent at the beginning because bytes received is 0.
15537 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
15538 connection_.SendCryptoDataWithString("foo", 0);
15539 EXPECT_FALSE(connection_.CanWrite(HAS_RETRANSMITTABLE_DATA));
15540 EXPECT_FALSE(connection_.CanWrite(NO_RETRANSMITTABLE_DATA));
15541 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15542
15543 const size_t anti_amplification_factor =
birenroyef686222022-09-12 11:34:34 -070015544 GetQuicFlag(quic_anti_amplification_factor);
fayang161ce6e2022-07-01 18:02:11 -070015545 // Receives packet 1.
15546 EXPECT_CALL(visitor_, OnCryptoFrame(_)).Times(1);
15547 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
15548 .Times(anti_amplification_factor);
15549 ProcessCryptoPacketAtLevel(1, ENCRYPTION_INITIAL);
15550 connection_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15551 std::make_unique<TaggingEncrypter>(0x02));
15552 connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15553 std::make_unique<TaggingEncrypter>(0x03));
15554
15555 for (size_t i = 1; i < anti_amplification_factor - 1; ++i) {
15556 connection_.SendCryptoDataWithString("foo", i * 3);
15557 }
15558 // Send an addtion packet with max_packet_size - 1.
15559 connection_.SetMaxPacketLength(connection_.max_packet_length() - 1);
15560 connection_.SendCryptoDataWithString("bar",
15561 (anti_amplification_factor - 1) * 3);
15562 EXPECT_LT(writer_->total_bytes_written(),
15563 anti_amplification_factor *
15564 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
birenroyef686222022-09-12 11:34:34 -070015565 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070015566 // 3 connection closes which will be buffered.
15567 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
15568 // Verify retransmission alarm is not set.
15569 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15570 } else {
15571 // Crypto + 3 connection closes.
15572 EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(4);
15573 EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
15574 }
15575 // Try to send another packet with max_packet_size.
15576 connection_.SetMaxPacketLength(connection_.max_packet_length() + 1);
15577 connection_.SendCryptoDataWithString("bar", anti_amplification_factor * 3);
15578 EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
15579 // Close connection.
15580 EXPECT_CALL(visitor_, BeforeConnectionCloseSent());
15581 EXPECT_CALL(visitor_, OnConnectionClosed(_, _));
15582 connection_.CloseConnection(
15583 QUIC_INTERNAL_ERROR, "error",
15584 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
15585 EXPECT_EQ(0u, connection_.NumQueuedPackets());
birenroyef686222022-09-12 11:34:34 -070015586 if (GetQuicFlag(quic_enforce_strict_amplification_factor)) {
fayang161ce6e2022-07-01 18:02:11 -070015587 EXPECT_LT(writer_->total_bytes_written(),
15588 anti_amplification_factor *
15589 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15590 } else {
15591 EXPECT_LT(writer_->total_bytes_written(),
15592 (anti_amplification_factor + 2) *
15593 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15594 EXPECT_GT(writer_->total_bytes_written(),
15595 (anti_amplification_factor + 1) *
15596 QuicConnectionPeer::BytesReceivedOnDefaultPath(&connection_));
15597 }
15598}
15599
martinduke96840a02022-07-14 07:09:06 -070015600TEST_P(QuicConnectionTest, OriginalConnectionId) {
15601 set_perspective(Perspective::IS_SERVER);
15602 EXPECT_FALSE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
15603 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
15604 connection_.connection_id());
15605 QuicConnectionId original({0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08});
15606 connection_.SetOriginalDestinationConnectionId(original);
15607 EXPECT_EQ(original, connection_.GetOriginalDestinationConnectionId());
15608 // Send a 1-RTT packet to start the DiscardZeroRttDecryptionKeys timer.
15609 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
15610 ProcessDataPacketAtLevel(1, false, ENCRYPTION_FORWARD_SECURE);
martindukee6444ef2022-09-23 12:32:23 -070015611 if (connection_.version().UsesTls()) {
martinduke96840a02022-07-14 07:09:06 -070015612 EXPECT_TRUE(connection_.GetDiscardZeroRttDecryptionKeysAlarm()->IsSet());
15613 EXPECT_CALL(visitor_, OnServerConnectionIdRetired(original));
15614 connection_.GetDiscardZeroRttDecryptionKeysAlarm()->Fire();
15615 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(),
15616 connection_.connection_id());
15617 } else {
15618 EXPECT_EQ(connection_.GetOriginalDestinationConnectionId(), original);
15619 }
15620}
15621
martindukebae24052022-10-06 15:27:46 -070015622ACTION_P2(InstallKeys, conn, level) {
15623 uint8_t crypto_input = (level == ENCRYPTION_FORWARD_SECURE) ? 0x03 : 0x02;
15624 conn->SetEncrypter(level, std::make_unique<TaggingEncrypter>(crypto_input));
15625 conn->InstallDecrypter(
15626 level, std::make_unique<StrictTaggingDecrypter>(crypto_input));
15627 conn->SetDefaultEncryptionLevel(level);
martindukec2a33062022-09-30 16:04:13 -070015628}
15629
martindukebae24052022-10-06 15:27:46 -070015630TEST_P(QuicConnectionTest, ServerConnectionIdChangeWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070015631 if (!connection_.version().HasIetfQuicFrames()) {
15632 return;
15633 }
15634 // Call SetFromConfig so that the undecrypted packet buffer size is
15635 // initialized above zero.
15636 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
15637 QuicConfig config;
15638 connection_.SetFromConfig(config);
martindukebae24052022-10-06 15:27:46 -070015639 connection_.RemoveEncrypter(ENCRYPTION_FORWARD_SECURE);
15640 connection_.RemoveDecrypter(ENCRYPTION_FORWARD_SECURE);
martindukec2a33062022-09-30 16:04:13 -070015641
15642 // Send Client Initial.
15643 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15644 connection_.SendCryptoStreamData();
15645
15646 EXPECT_EQ(1u, writer_->packets_write_attempts());
martindukebae24052022-10-06 15:27:46 -070015647 // Server Handshake packet with new connection ID is buffered.
martindukec2a33062022-09-30 16:04:13 -070015648 QuicConnectionId old_id = connection_id_;
15649 connection_id_ = TestConnectionId(2);
15650 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15651 std::make_unique<TaggingEncrypter>(0x02));
15652 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
martindukec2a33062022-09-30 16:04:13 -070015653 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
15654 EXPECT_EQ(connection_.connection_id(), old_id);
15655
martindukebae24052022-10-06 15:27:46 -070015656 // Server 1-RTT Packet is buffered.
15657 peer_creator_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
15658 std::make_unique<TaggingEncrypter>(0x03));
15659 ProcessDataPacket(0);
15660 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 2u);
15661
martindukec2a33062022-09-30 16:04:13 -070015662 // Pretend the server Initial packet will yield the Handshake keys.
15663 EXPECT_CALL(visitor_, OnCryptoFrame(_))
15664 .Times(2)
martindukebae24052022-10-06 15:27:46 -070015665 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE))
15666 .WillOnce(InstallKeys(&connection_, ENCRYPTION_FORWARD_SECURE));
15667 EXPECT_CALL(visitor_, OnStreamFrame(_)).Times(1);
martindukec2a33062022-09-30 16:04:13 -070015668 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
15669 // Two packets processed, connection ID changed.
15670 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
15671 EXPECT_EQ(connection_.connection_id(), connection_id_);
15672}
15673
martindukebae24052022-10-06 15:27:46 -070015674TEST_P(QuicConnectionTest, ServerConnectionIdChangeTwiceWithLateInitial) {
martindukec2a33062022-09-30 16:04:13 -070015675 if (!connection_.version().HasIetfQuicFrames()) {
15676 return;
15677 }
15678 // Call SetFromConfig so that the undecrypted packet buffer size is
15679 // initialized above zero.
15680 EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _)).Times(1);
15681 QuicConfig config;
15682 connection_.SetFromConfig(config);
15683
15684 // Send Client Initial.
15685 connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
15686 connection_.SendCryptoStreamData();
15687
15688 EXPECT_EQ(1u, writer_->packets_write_attempts());
15689 // Server Handshake Packet Arrives with new connection ID.
15690 QuicConnectionId old_id = connection_id_;
15691 connection_id_ = TestConnectionId(2);
15692 peer_creator_.SetEncrypter(ENCRYPTION_HANDSHAKE,
15693 std::make_unique<TaggingEncrypter>(0x02));
15694 ProcessCryptoPacketAtLevel(0, ENCRYPTION_HANDSHAKE);
15695 // Packet is buffered.
15696 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 1u);
15697 EXPECT_EQ(connection_.connection_id(), old_id);
15698
15699 // Pretend the server Initial packet will yield the Handshake keys.
15700 EXPECT_CALL(visitor_, OnCryptoFrame(_))
martindukebae24052022-10-06 15:27:46 -070015701 .WillOnce(InstallKeys(&connection_, ENCRYPTION_HANDSHAKE));
martindukec2a33062022-09-30 16:04:13 -070015702 connection_id_ = TestConnectionId(1);
15703 ProcessCryptoPacketAtLevel(0, ENCRYPTION_INITIAL);
15704 // Handshake packet discarded because there's a different connection ID.
15705 EXPECT_EQ(QuicConnectionPeer::NumUndecryptablePackets(&connection_), 0u);
15706 EXPECT_EQ(connection_.connection_id(), connection_id_);
15707}
15708
Bence Békybac04052022-04-07 15:44:29 -040015709} // namespace
15710} // namespace test
15711} // namespace quic