1 // 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 <string.h>
8 #include <sys/types.h>
9
10 #include <algorithm>
11 #include <cstddef>
12 #include <cstdint>
13 #include <iterator>
14 #include <limits>
15 #include <memory>
16 #include <optional>
17 #include <set>
18 #include <string>
19 #include <utility>
20
21 #include "absl/strings/escaping.h"
22 #include "absl/strings/str_cat.h"
23 #include "absl/strings/string_view.h"
24 #include "quiche/quic/core/congestion_control/rtt_stats.h"
25 #include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
26 #include "quiche/quic/core/crypto/crypto_protocol.h"
27 #include "quiche/quic/core/crypto/crypto_utils.h"
28 #include "quiche/quic/core/crypto/quic_decrypter.h"
29 #include "quiche/quic/core/crypto/quic_encrypter.h"
30 #include "quiche/quic/core/quic_bandwidth.h"
31 #include "quiche/quic/core/quic_config.h"
32 #include "quiche/quic/core/quic_connection_id.h"
33 #include "quiche/quic/core/quic_constants.h"
34 #include "quiche/quic/core/quic_error_codes.h"
35 #include "quiche/quic/core/quic_packet_creator.h"
36 #include "quiche/quic/core/quic_packet_writer.h"
37 #include "quiche/quic/core/quic_packets.h"
38 #include "quiche/quic/core/quic_path_validator.h"
39 #include "quiche/quic/core/quic_time.h"
40 #include "quiche/quic/core/quic_types.h"
41 #include "quiche/quic/core/quic_utils.h"
42 #include "quiche/quic/platform/api/quic_bug_tracker.h"
43 #include "quiche/quic/platform/api/quic_client_stats.h"
44 #include "quiche/quic/platform/api/quic_exported_stats.h"
45 #include "quiche/quic/platform/api/quic_flag_utils.h"
46 #include "quiche/quic/platform/api/quic_flags.h"
47 #include "quiche/quic/platform/api/quic_logging.h"
48 #include "quiche/quic/platform/api/quic_socket_address.h"
49 #include "quiche/common/platform/api/quiche_flag_utils.h"
50 #include "quiche/common/platform/api/quiche_testvalue.h"
51 #include "quiche/common/quiche_text_utils.h"
52
53 namespace quic {
54
55 class QuicDecrypter;
56 class QuicEncrypter;
57
58 namespace {
59
60 // Maximum number of consecutive sent nonretransmittable packets.
61 const QuicPacketCount kMaxConsecutiveNonRetransmittablePackets = 19;
62
63 // The minimum release time into future in ms.
64 const int kMinReleaseTimeIntoFutureMs = 1;
65
66 // The maximum number of recorded client addresses.
67 const size_t kMaxReceivedClientAddressSize = 20;
68
69 // An arbitrary limit on the number of PTOs before giving up on ECN, if no ECN-
70 // marked packet is acked. Avoids abandoning ECN because of one burst loss,
71 // but doesn't allow multiple RTTs of user delay in the hope of using ECN.
72 const uint8_t kEcnPtoLimit = 2;
73
74 // Base class of all alarms owned by a QuicConnection.
75 class QuicConnectionAlarmDelegate : public QuicAlarm::Delegate {
76 public:
QuicConnectionAlarmDelegate(QuicConnection * connection)77 explicit QuicConnectionAlarmDelegate(QuicConnection* connection)
78 : connection_(connection) {}
79 QuicConnectionAlarmDelegate(const QuicConnectionAlarmDelegate&) = delete;
80 QuicConnectionAlarmDelegate& operator=(const QuicConnectionAlarmDelegate&) =
81 delete;
82
GetConnectionContext()83 QuicConnectionContext* GetConnectionContext() override {
84 return (connection_ == nullptr) ? nullptr : connection_->context();
85 }
86
87 protected:
88 QuicConnection* connection_;
89 };
90
91 // An alarm that is scheduled to send an ack if a timeout occurs.
92 class AckAlarmDelegate : public QuicConnectionAlarmDelegate {
93 public:
94 using QuicConnectionAlarmDelegate::QuicConnectionAlarmDelegate;
95
OnAlarm()96 void OnAlarm() override {
97 QUICHE_DCHECK(connection_->ack_frame_updated());
98 QUICHE_DCHECK(connection_->connected());
99 QuicConnection::ScopedPacketFlusher flusher(connection_);
100 if (connection_->SupportsMultiplePacketNumberSpaces()) {
101 connection_->SendAllPendingAcks();
102 } else {
103 connection_->SendAck();
104 }
105 }
106 };
107
108 // This alarm will be scheduled any time a data-bearing packet is sent out.
109 // When the alarm goes off, the connection checks to see if the oldest packets
110 // have been acked, and retransmit them if they have not.
111 class RetransmissionAlarmDelegate : public QuicConnectionAlarmDelegate {
112 public:
113 using QuicConnectionAlarmDelegate::QuicConnectionAlarmDelegate;
114
OnAlarm()115 void OnAlarm() override {
116 QUICHE_DCHECK(connection_->connected());
117 connection_->OnRetransmissionTimeout();
118 }
119 };
120
121 // An alarm that is scheduled when the SentPacketManager requires a delay
122 // before sending packets and fires when the packet may be sent.
123 class SendAlarmDelegate : public QuicConnectionAlarmDelegate {
124 public:
125 using QuicConnectionAlarmDelegate::QuicConnectionAlarmDelegate;
126
OnAlarm()127 void OnAlarm() override {
128 QUICHE_DCHECK(connection_->connected());
129 connection_->OnSendAlarm();
130 }
131 };
132
133 class MtuDiscoveryAlarmDelegate : public QuicConnectionAlarmDelegate {
134 public:
135 using QuicConnectionAlarmDelegate::QuicConnectionAlarmDelegate;
136
OnAlarm()137 void OnAlarm() override {
138 QUICHE_DCHECK(connection_->connected());
139 connection_->DiscoverMtu();
140 }
141 };
142
143 class ProcessUndecryptablePacketsAlarmDelegate
144 : public QuicConnectionAlarmDelegate {
145 public:
146 using QuicConnectionAlarmDelegate::QuicConnectionAlarmDelegate;
147
OnAlarm()148 void OnAlarm() override {
149 QUICHE_DCHECK(connection_->connected());
150 QuicConnection::ScopedPacketFlusher flusher(connection_);
151 connection_->MaybeProcessUndecryptablePackets();
152 }
153 };
154
155 class DiscardPreviousOneRttKeysAlarmDelegate
156 : public QuicConnectionAlarmDelegate {
157 public:
158 using QuicConnectionAlarmDelegate::QuicConnectionAlarmDelegate;
159
OnAlarm()160 void OnAlarm() override {
161 QUICHE_DCHECK(connection_->connected());
162 connection_->DiscardPreviousOneRttKeys();
163 }
164 };
165
166 class DiscardZeroRttDecryptionKeysAlarmDelegate
167 : public QuicConnectionAlarmDelegate {
168 public:
169 using QuicConnectionAlarmDelegate::QuicConnectionAlarmDelegate;
170
OnAlarm()171 void OnAlarm() override {
172 QUICHE_DCHECK(connection_->connected());
173 QUIC_DLOG(INFO) << "0-RTT discard alarm fired";
174 connection_->RemoveDecrypter(ENCRYPTION_ZERO_RTT);
175 connection_->RetireOriginalDestinationConnectionId();
176 }
177 };
178
179 class MultiPortProbingAlarmDelegate : public QuicConnectionAlarmDelegate {
180 public:
181 using QuicConnectionAlarmDelegate::QuicConnectionAlarmDelegate;
182
OnAlarm()183 void OnAlarm() override {
184 QUICHE_DCHECK(connection_->connected());
185 QUIC_DLOG(INFO) << "Alternative path probing alarm fired";
186 connection_->MaybeProbeMultiPortPath();
187 }
188 };
189
190 // When the clearer goes out of scope, the coalesced packet gets cleared.
191 class ScopedCoalescedPacketClearer {
192 public:
ScopedCoalescedPacketClearer(QuicCoalescedPacket * coalesced)193 explicit ScopedCoalescedPacketClearer(QuicCoalescedPacket* coalesced)
194 : coalesced_(coalesced) {}
~ScopedCoalescedPacketClearer()195 ~ScopedCoalescedPacketClearer() { coalesced_->Clear(); }
196
197 private:
198 QuicCoalescedPacket* coalesced_; // Unowned.
199 };
200
201 // Whether this incoming packet is allowed to replace our connection ID.
PacketCanReplaceServerConnectionId(const QuicPacketHeader & header,Perspective perspective)202 bool PacketCanReplaceServerConnectionId(const QuicPacketHeader& header,
203 Perspective perspective) {
204 return perspective == Perspective::IS_CLIENT &&
205 header.form == IETF_QUIC_LONG_HEADER_PACKET &&
206 header.version.IsKnown() &&
207 header.version.AllowsVariableLengthConnectionIds() &&
208 (header.long_packet_type == INITIAL ||
209 header.long_packet_type == RETRY);
210 }
211
212 // Due to a lost Initial packet, a Handshake packet might use a new connection
213 // ID we haven't seen before. We shouldn't update the connection ID based on
214 // this, but should buffer the packet in case it works out.
NewServerConnectionIdMightBeValid(const QuicPacketHeader & header,Perspective perspective,bool connection_id_already_replaced)215 bool NewServerConnectionIdMightBeValid(const QuicPacketHeader& header,
216 Perspective perspective,
217 bool connection_id_already_replaced) {
218 return perspective == Perspective::IS_CLIENT &&
219 header.form == IETF_QUIC_LONG_HEADER_PACKET &&
220 header.version.IsKnown() &&
221 header.version.AllowsVariableLengthConnectionIds() &&
222 header.long_packet_type == HANDSHAKE &&
223 !connection_id_already_replaced;
224 }
225
GetDefaultCongestionControlType()226 CongestionControlType GetDefaultCongestionControlType() {
227 if (GetQuicReloadableFlag(quic_default_to_bbr_v2)) {
228 return kBBRv2;
229 }
230
231 if (GetQuicReloadableFlag(quic_default_to_bbr)) {
232 return kBBR;
233 }
234
235 return kCubicBytes;
236 }
237
ContainsNonProbingFrame(const SerializedPacket & packet)238 bool ContainsNonProbingFrame(const SerializedPacket& packet) {
239 for (const QuicFrame& frame : packet.nonretransmittable_frames) {
240 if (!QuicUtils::IsProbingFrame(frame.type)) {
241 return true;
242 }
243 }
244 for (const QuicFrame& frame : packet.retransmittable_frames) {
245 if (!QuicUtils::IsProbingFrame(frame.type)) {
246 return true;
247 }
248 }
249 return false;
250 }
251
252 } // namespace
253
254 #define ENDPOINT \
255 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
256
QuicConnection(QuicConnectionId server_connection_id,QuicSocketAddress initial_self_address,QuicSocketAddress initial_peer_address,QuicConnectionHelperInterface * helper,QuicAlarmFactory * alarm_factory,QuicPacketWriter * writer,bool owns_writer,Perspective perspective,const ParsedQuicVersionVector & supported_versions,ConnectionIdGeneratorInterface & generator)257 QuicConnection::QuicConnection(
258 QuicConnectionId server_connection_id,
259 QuicSocketAddress initial_self_address,
260 QuicSocketAddress initial_peer_address,
261 QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory,
262 QuicPacketWriter* writer, bool owns_writer, Perspective perspective,
263 const ParsedQuicVersionVector& supported_versions,
264 ConnectionIdGeneratorInterface& generator)
265 : framer_(supported_versions, helper->GetClock()->ApproximateNow(),
266 perspective, server_connection_id.length()),
267 current_packet_content_(NO_FRAMES_RECEIVED),
268 is_current_packet_connectivity_probing_(false),
269 has_path_challenge_in_current_packet_(false),
270 current_effective_peer_migration_type_(NO_CHANGE),
271 helper_(helper),
272 alarm_factory_(alarm_factory),
273 per_packet_options_(nullptr),
274 writer_(writer),
275 owns_writer_(owns_writer),
276 encryption_level_(ENCRYPTION_INITIAL),
277 clock_(helper->GetClock()),
278 random_generator_(helper->GetRandomGenerator()),
279 client_connection_id_is_set_(false),
280 direct_peer_address_(initial_peer_address),
281 default_path_(initial_self_address, QuicSocketAddress(),
282 /*client_connection_id=*/EmptyQuicConnectionId(),
283 server_connection_id,
284 /*stateless_reset_token=*/std::nullopt),
285 active_effective_peer_migration_type_(NO_CHANGE),
286 support_key_update_for_connection_(false),
287 current_packet_data_(nullptr),
288 should_last_packet_instigate_acks_(false),
289 max_undecryptable_packets_(0),
290 max_tracked_packets_(GetQuicFlag(quic_max_tracked_packet_count)),
291 idle_timeout_connection_close_behavior_(
292 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET),
293 num_rtos_for_blackhole_detection_(0),
294 uber_received_packet_manager_(&stats_),
295 pending_retransmission_alarm_(false),
296 defer_send_in_response_to_packets_(false),
297 arena_(),
298 ack_alarm_(alarm_factory_->CreateAlarm(arena_.New<AckAlarmDelegate>(this),
299 &arena_)),
300 retransmission_alarm_(alarm_factory_->CreateAlarm(
301 arena_.New<RetransmissionAlarmDelegate>(this), &arena_)),
302 send_alarm_(alarm_factory_->CreateAlarm(
303 arena_.New<SendAlarmDelegate>(this), &arena_)),
304 mtu_discovery_alarm_(alarm_factory_->CreateAlarm(
305 arena_.New<MtuDiscoveryAlarmDelegate>(this), &arena_)),
306 process_undecryptable_packets_alarm_(alarm_factory_->CreateAlarm(
307 arena_.New<ProcessUndecryptablePacketsAlarmDelegate>(this), &arena_)),
308 discard_previous_one_rtt_keys_alarm_(alarm_factory_->CreateAlarm(
309 arena_.New<DiscardPreviousOneRttKeysAlarmDelegate>(this), &arena_)),
310 discard_zero_rtt_decryption_keys_alarm_(alarm_factory_->CreateAlarm(
311 arena_.New<DiscardZeroRttDecryptionKeysAlarmDelegate>(this),
312 &arena_)),
313 multi_port_probing_alarm_(alarm_factory_->CreateAlarm(
314 arena_.New<MultiPortProbingAlarmDelegate>(this), &arena_)),
315 visitor_(nullptr),
316 debug_visitor_(nullptr),
317 packet_creator_(server_connection_id, &framer_, random_generator_, this),
318 last_received_packet_info_(clock_->ApproximateNow()),
319 sent_packet_manager_(perspective, clock_, random_generator_, &stats_,
320 GetDefaultCongestionControlType()),
321 version_negotiated_(false),
322 perspective_(perspective),
323 connected_(true),
324 can_truncate_connection_ids_(perspective == Perspective::IS_SERVER),
325 mtu_probe_count_(0),
326 previous_validated_mtu_(0),
327 peer_max_packet_size_(kDefaultMaxPacketSizeTransportParam),
328 largest_received_packet_size_(0),
329 write_error_occurred_(false),
330 consecutive_num_packets_with_no_retransmittable_frames_(0),
331 max_consecutive_num_packets_with_no_retransmittable_frames_(
332 kMaxConsecutiveNonRetransmittablePackets),
333 bundle_retransmittable_with_pto_ack_(false),
334 last_control_frame_id_(kInvalidControlFrameId),
335 is_path_degrading_(false),
336 processing_ack_frame_(false),
337 supports_release_time_(false),
338 release_time_into_future_(QuicTime::Delta::Zero()),
339 blackhole_detector_(this, &arena_, alarm_factory_, &context_),
340 idle_network_detector_(this, clock_->ApproximateNow(), &arena_,
341 alarm_factory_, &context_),
342 path_validator_(alarm_factory_, &arena_, this, random_generator_, clock_,
343 &context_),
344 ping_manager_(perspective, this, &arena_, alarm_factory_, &context_),
345 multi_port_probing_interval_(kDefaultMultiPortProbingInterval),
346 connection_id_generator_(generator),
347 received_client_addresses_cache_(kMaxReceivedClientAddressSize) {
348 QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT ||
349 default_path_.self_address.IsInitialized());
350
351 QUIC_DLOG(INFO) << ENDPOINT << "Created connection with server connection ID "
352 << server_connection_id
353 << " and version: " << ParsedQuicVersionToString(version());
354
355 QUIC_BUG_IF(quic_bug_12714_2, !QuicUtils::IsConnectionIdValidForVersion(
356 server_connection_id, transport_version()))
357 << "QuicConnection: attempted to use server connection ID "
358 << server_connection_id << " which is invalid with version " << version();
359 framer_.set_visitor(this);
360 stats_.connection_creation_time = clock_->ApproximateNow();
361 // TODO(ianswett): Supply the NetworkChangeVisitor as a constructor argument
362 // and make it required non-null, because it's always used.
363 sent_packet_manager_.SetNetworkChangeVisitor(this);
364 if (GetQuicRestartFlag(quic_offload_pacing_to_usps2)) {
365 sent_packet_manager_.SetPacingAlarmGranularity(QuicTime::Delta::Zero());
366 release_time_into_future_ =
367 QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs);
368 }
369 // Allow the packet writer to potentially reduce the packet size to a value
370 // even smaller than kDefaultMaxPacketSize.
371 SetMaxPacketLength(perspective_ == Perspective::IS_SERVER
372 ? kDefaultServerMaxPacketSize
373 : kDefaultMaxPacketSize);
374 uber_received_packet_manager_.set_max_ack_ranges(255);
375 MaybeEnableMultiplePacketNumberSpacesSupport();
376 QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT ||
377 supported_versions.size() == 1);
378 InstallInitialCrypters(default_path_.server_connection_id);
379
380 // On the server side, version negotiation has been done by the dispatcher,
381 // and the server connection is created with the right version.
382 if (perspective_ == Perspective::IS_SERVER) {
383 version_negotiated_ = true;
384 }
385 if (default_enable_5rto_blackhole_detection_) {
386 num_rtos_for_blackhole_detection_ = 5;
387 if (GetQuicReloadableFlag(quic_disable_server_blackhole_detection) &&
388 perspective_ == Perspective::IS_SERVER) {
389 QUIC_RELOADABLE_FLAG_COUNT(quic_disable_server_blackhole_detection);
390 blackhole_detection_disabled_ = true;
391 }
392 }
393 if (perspective_ == Perspective::IS_CLIENT) {
394 AddKnownServerAddress(initial_peer_address);
395 }
396 packet_creator_.SetDefaultPeerAddress(initial_peer_address);
397 }
398
InstallInitialCrypters(QuicConnectionId connection_id)399 void QuicConnection::InstallInitialCrypters(QuicConnectionId connection_id) {
400 CrypterPair crypters;
401 CryptoUtils::CreateInitialObfuscators(perspective_, version(), connection_id,
402 &crypters);
403 SetEncrypter(ENCRYPTION_INITIAL, std::move(crypters.encrypter));
404 if (version().KnowsWhichDecrypterToUse()) {
405 InstallDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter));
406 } else {
407 SetDecrypter(ENCRYPTION_INITIAL, std::move(crypters.decrypter));
408 }
409 }
410
~QuicConnection()411 QuicConnection::~QuicConnection() {
412 QUICHE_DCHECK_GE(stats_.max_egress_mtu, long_term_mtu_);
413 if (owns_writer_) {
414 delete writer_;
415 }
416 ClearQueuedPackets();
417 if (stats_
418 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter >
419 0) {
420 QUIC_CODE_COUNT_N(
421 quic_server_received_tls_zero_rtt_packet_after_discarding_decrypter, 2,
422 3);
423 } else {
424 QUIC_CODE_COUNT_N(
425 quic_server_received_tls_zero_rtt_packet_after_discarding_decrypter, 3,
426 3);
427 }
428 }
429
ClearQueuedPackets()430 void QuicConnection::ClearQueuedPackets() { buffered_packets_.clear(); }
431
ValidateConfigConnectionIds(const QuicConfig & config)432 bool QuicConnection::ValidateConfigConnectionIds(const QuicConfig& config) {
433 QUICHE_DCHECK(config.negotiated());
434 if (!version().UsesTls()) {
435 // QUIC+TLS is required to transmit connection ID transport parameters.
436 return true;
437 }
438 // This function validates connection IDs as defined in IETF draft-28 and
439 // later.
440
441 // Validate initial_source_connection_id.
442 QuicConnectionId expected_initial_source_connection_id;
443 if (perspective_ == Perspective::IS_CLIENT) {
444 expected_initial_source_connection_id = default_path_.server_connection_id;
445 } else {
446 expected_initial_source_connection_id = default_path_.client_connection_id;
447 }
448 if (!config.HasReceivedInitialSourceConnectionId() ||
449 config.ReceivedInitialSourceConnectionId() !=
450 expected_initial_source_connection_id) {
451 std::string received_value;
452 if (config.HasReceivedInitialSourceConnectionId()) {
453 received_value = config.ReceivedInitialSourceConnectionId().ToString();
454 } else {
455 received_value = "none";
456 }
457 std::string error_details =
458 absl::StrCat("Bad initial_source_connection_id: expected ",
459 expected_initial_source_connection_id.ToString(),
460 ", received ", received_value);
461 CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, error_details,
462 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
463 return false;
464 }
465 if (perspective_ == Perspective::IS_CLIENT) {
466 // Validate original_destination_connection_id.
467 if (!config.HasReceivedOriginalConnectionId() ||
468 config.ReceivedOriginalConnectionId() !=
469 GetOriginalDestinationConnectionId()) {
470 std::string received_value;
471 if (config.HasReceivedOriginalConnectionId()) {
472 received_value = config.ReceivedOriginalConnectionId().ToString();
473 } else {
474 received_value = "none";
475 }
476 std::string error_details =
477 absl::StrCat("Bad original_destination_connection_id: expected ",
478 GetOriginalDestinationConnectionId().ToString(),
479 ", received ", received_value);
480 CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, error_details,
481 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
482 return false;
483 }
484 // Validate retry_source_connection_id.
485 if (retry_source_connection_id_.has_value()) {
486 // We received a RETRY packet, validate that the retry source
487 // connection ID from the config matches the one from the RETRY.
488 if (!config.HasReceivedRetrySourceConnectionId() ||
489 config.ReceivedRetrySourceConnectionId() !=
490 *retry_source_connection_id_) {
491 std::string received_value;
492 if (config.HasReceivedRetrySourceConnectionId()) {
493 received_value = config.ReceivedRetrySourceConnectionId().ToString();
494 } else {
495 received_value = "none";
496 }
497 std::string error_details =
498 absl::StrCat("Bad retry_source_connection_id: expected ",
499 retry_source_connection_id_->ToString(), ", received ",
500 received_value);
501 CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, error_details,
502 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
503 return false;
504 }
505 } else {
506 // We did not receive a RETRY packet, make sure we did not receive the
507 // retry_source_connection_id transport parameter.
508 if (config.HasReceivedRetrySourceConnectionId()) {
509 std::string error_details = absl::StrCat(
510 "Bad retry_source_connection_id: did not receive RETRY but "
511 "received ",
512 config.ReceivedRetrySourceConnectionId().ToString());
513 CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION, error_details,
514 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
515 return false;
516 }
517 }
518 }
519 return true;
520 }
521
SetFromConfig(const QuicConfig & config)522 void QuicConnection::SetFromConfig(const QuicConfig& config) {
523 if (config.negotiated()) {
524 // Handshake complete, set handshake timeout to Infinite.
525 SetNetworkTimeouts(QuicTime::Delta::Infinite(),
526 config.IdleNetworkTimeout());
527 idle_timeout_connection_close_behavior_ =
528 ConnectionCloseBehavior::SILENT_CLOSE;
529 if (perspective_ == Perspective::IS_SERVER) {
530 idle_timeout_connection_close_behavior_ = ConnectionCloseBehavior::
531 SILENT_CLOSE_WITH_CONNECTION_CLOSE_PACKET_SERIALIZED;
532 }
533 if (config.HasClientRequestedIndependentOption(kNSLC, perspective_)) {
534 idle_timeout_connection_close_behavior_ =
535 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET;
536 }
537 if (!ValidateConfigConnectionIds(config)) {
538 return;
539 }
540 support_key_update_for_connection_ = version().UsesTls();
541 framer_.SetKeyUpdateSupportForConnection(
542 support_key_update_for_connection_);
543 } else {
544 SetNetworkTimeouts(config.max_time_before_crypto_handshake(),
545 config.max_idle_time_before_crypto_handshake());
546 }
547
548 if (version().HasIetfQuicFrames() &&
549 config.HasReceivedPreferredAddressConnectionIdAndToken()) {
550 QuicNewConnectionIdFrame frame;
551 std::tie(frame.connection_id, frame.stateless_reset_token) =
552 config.ReceivedPreferredAddressConnectionIdAndToken();
553 frame.sequence_number = 1u;
554 frame.retire_prior_to = 0u;
555 OnNewConnectionIdFrameInner(frame);
556 }
557
558 if (config.DisableConnectionMigration()) {
559 active_migration_disabled_ = true;
560 }
561
562 sent_packet_manager_.SetFromConfig(config);
563 if (perspective_ == Perspective::IS_SERVER &&
564 config.HasClientSentConnectionOption(kAFF2, perspective_)) {
565 send_ack_frequency_on_handshake_completion_ = true;
566 }
567 if (config.HasReceivedBytesForConnectionId() &&
568 can_truncate_connection_ids_) {
569 packet_creator_.SetServerConnectionIdLength(
570 config.ReceivedBytesForConnectionId());
571 }
572 max_undecryptable_packets_ = config.max_undecryptable_packets();
573
574 if (!GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server)) {
575 if (config.HasClientRequestedIndependentOption(kMTUH, perspective_)) {
576 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh);
577 }
578 }
579 if (config.HasClientRequestedIndependentOption(kMTUL, perspective_)) {
580 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeLow);
581 }
582 if (default_enable_5rto_blackhole_detection_) {
583 if (config.HasClientRequestedIndependentOption(kCBHD, perspective_)) {
584 QUIC_CODE_COUNT(quic_client_only_blackhole_detection);
585 blackhole_detection_disabled_ = true;
586 }
587 if (config.HasClientSentConnectionOption(kNBHD, perspective_)) {
588 blackhole_detection_disabled_ = true;
589 }
590 }
591
592 if (config.HasClientRequestedIndependentOption(kFIDT, perspective_)) {
593 idle_network_detector_.enable_shorter_idle_timeout_on_sent_packet();
594 }
595 if (perspective_ == Perspective::IS_CLIENT && version().HasIetfQuicFrames()) {
596 // Only conduct those experiments in IETF QUIC because random packets may
597 // elicit reset and gQUIC PUBLIC_RESET will cause connection close.
598 if (config.HasClientRequestedIndependentOption(kROWF, perspective_)) {
599 retransmittable_on_wire_behavior_ = SEND_FIRST_FORWARD_SECURE_PACKET;
600 }
601 if (config.HasClientRequestedIndependentOption(kROWR, perspective_)) {
602 retransmittable_on_wire_behavior_ = SEND_RANDOM_BYTES;
603 }
604 }
605 if (config.HasClientRequestedIndependentOption(k3AFF, perspective_)) {
606 anti_amplification_factor_ = 3;
607 }
608 if (config.HasClientRequestedIndependentOption(k10AF, perspective_)) {
609 anti_amplification_factor_ = 10;
610 }
611
612 if (GetQuicReloadableFlag(quic_enable_server_on_wire_ping) &&
613 perspective_ == Perspective::IS_SERVER &&
614 config.HasClientSentConnectionOption(kSRWP, perspective_)) {
615 QUIC_RELOADABLE_FLAG_COUNT(quic_enable_server_on_wire_ping);
616 set_initial_retransmittable_on_wire_timeout(
617 QuicTime::Delta::FromMilliseconds(200));
618 }
619
620 if (debug_visitor_ != nullptr) {
621 debug_visitor_->OnSetFromConfig(config);
622 }
623 uber_received_packet_manager_.SetFromConfig(config, perspective_);
624 if (config.HasClientSentConnectionOption(k5RTO, perspective_)) {
625 num_rtos_for_blackhole_detection_ = 5;
626 }
627 if (config.HasClientSentConnectionOption(k6PTO, perspective_) ||
628 config.HasClientSentConnectionOption(k7PTO, perspective_) ||
629 config.HasClientSentConnectionOption(k8PTO, perspective_)) {
630 num_rtos_for_blackhole_detection_ = 5;
631 }
632 if (config.HasReceivedStatelessResetToken()) {
633 default_path_.stateless_reset_token = config.ReceivedStatelessResetToken();
634 }
635 if (config.HasReceivedAckDelayExponent()) {
636 framer_.set_peer_ack_delay_exponent(config.ReceivedAckDelayExponent());
637 }
638 if (config.HasClientSentConnectionOption(kEACK, perspective_)) {
639 bundle_retransmittable_with_pto_ack_ = true;
640 }
641 if (config.HasClientSentConnectionOption(kDFER, perspective_)) {
642 defer_send_in_response_to_packets_ = false;
643 }
644
645 if (config.HasClientRequestedIndependentOption(kINVC, perspective_)) {
646 send_connection_close_for_invalid_version_ = true;
647 }
648
649 if (version().HasIetfQuicFrames() &&
650 config.HasReceivedPreferredAddressConnectionIdAndToken() &&
651 config.HasClientSentConnectionOption(kSPAD, perspective_)) {
652 if (self_address().host().IsIPv4() &&
653 config.HasReceivedIPv4AlternateServerAddress()) {
654 received_server_preferred_address_ =
655 config.ReceivedIPv4AlternateServerAddress();
656 } else if (self_address().host().IsIPv6() &&
657 config.HasReceivedIPv6AlternateServerAddress()) {
658 received_server_preferred_address_ =
659 config.ReceivedIPv6AlternateServerAddress();
660 }
661 if (received_server_preferred_address_.IsInitialized()) {
662 QUICHE_DLOG(INFO) << ENDPOINT << "Received server preferred address: "
663 << received_server_preferred_address_;
664 if (config.HasClientRequestedIndependentOption(kSPA2, perspective_)) {
665 accelerated_server_preferred_address_ = true;
666 visitor_->OnServerPreferredAddressAvailable(
667 received_server_preferred_address_);
668 }
669 }
670 }
671
672 if (config.HasReceivedMaxPacketSize()) {
673 peer_max_packet_size_ = config.ReceivedMaxPacketSize();
674 packet_creator_.SetMaxPacketLength(
675 GetLimitedMaxPacketSize(packet_creator_.max_packet_length()));
676 }
677 if (config.HasReceivedMaxDatagramFrameSize()) {
678 packet_creator_.SetMaxDatagramFrameSize(
679 config.ReceivedMaxDatagramFrameSize());
680 }
681
682 supports_release_time_ =
683 writer_ != nullptr && writer_->SupportsReleaseTime() &&
684 !config.HasClientSentConnectionOption(kNPCO, perspective_);
685
686 if (supports_release_time_) {
687 UpdateReleaseTimeIntoFuture();
688 }
689
690 if (perspective_ == Perspective::IS_CLIENT && version().HasIetfQuicFrames() &&
691 config.HasClientRequestedIndependentOption(kMPQC, perspective_)) {
692 multi_port_stats_ = std::make_unique<MultiPortStats>();
693 if (config.HasClientRequestedIndependentOption(kMPQM, perspective_)) {
694 multi_port_migration_enabled_ = true;
695 }
696 }
697 }
698
MaybeTestLiveness()699 bool QuicConnection::MaybeTestLiveness() {
700 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
701 if (liveness_testing_disabled_ ||
702 encryption_level_ != ENCRYPTION_FORWARD_SECURE) {
703 return false;
704 }
705 const QuicTime idle_network_deadline =
706 idle_network_detector_.GetIdleNetworkDeadline();
707 if (!idle_network_deadline.IsInitialized()) {
708 return false;
709 }
710 const QuicTime now = clock_->ApproximateNow();
711 if (now > idle_network_deadline) {
712 QUIC_DLOG(WARNING) << "Idle network deadline has passed";
713 return false;
714 }
715 const QuicTime::Delta timeout = idle_network_deadline - now;
716 if (2 * timeout > idle_network_detector_.idle_network_timeout()) {
717 // Do not test liveness if timeout is > half timeout. This is used to
718 // prevent an infinite loop for short idle timeout.
719 return false;
720 }
721 if (!sent_packet_manager_.IsLessThanThreePTOs(timeout)) {
722 return false;
723 }
724 QUIC_LOG_EVERY_N_SEC(INFO, 60)
725 << "Testing liveness, idle_network_timeout: "
726 << idle_network_detector_.idle_network_timeout()
727 << ", timeout: " << timeout
728 << ", Pto delay: " << sent_packet_manager_.GetPtoDelay()
729 << ", smoothed_rtt: "
730 << sent_packet_manager_.GetRttStats()->smoothed_rtt()
731 << ", mean deviation: "
732 << sent_packet_manager_.GetRttStats()->mean_deviation();
733 SendConnectivityProbingPacket(writer_, peer_address());
734 return true;
735 }
736
ApplyConnectionOptions(const QuicTagVector & connection_options)737 void QuicConnection::ApplyConnectionOptions(
738 const QuicTagVector& connection_options) {
739 sent_packet_manager_.ApplyConnectionOptions(connection_options);
740 }
741
OnSendConnectionState(const CachedNetworkParameters & cached_network_params)742 void QuicConnection::OnSendConnectionState(
743 const CachedNetworkParameters& cached_network_params) {
744 if (debug_visitor_ != nullptr) {
745 debug_visitor_->OnSendConnectionState(cached_network_params);
746 }
747 }
748
OnReceiveConnectionState(const CachedNetworkParameters & cached_network_params)749 void QuicConnection::OnReceiveConnectionState(
750 const CachedNetworkParameters& cached_network_params) {
751 if (debug_visitor_ != nullptr) {
752 debug_visitor_->OnReceiveConnectionState(cached_network_params);
753 }
754 }
755
ResumeConnectionState(const CachedNetworkParameters & cached_network_params,bool max_bandwidth_resumption)756 void QuicConnection::ResumeConnectionState(
757 const CachedNetworkParameters& cached_network_params,
758 bool max_bandwidth_resumption) {
759 sent_packet_manager_.ResumeConnectionState(cached_network_params,
760 max_bandwidth_resumption);
761 }
762
SetMaxPacingRate(QuicBandwidth max_pacing_rate)763 void QuicConnection::SetMaxPacingRate(QuicBandwidth max_pacing_rate) {
764 sent_packet_manager_.SetMaxPacingRate(max_pacing_rate);
765 }
766
AdjustNetworkParameters(const SendAlgorithmInterface::NetworkParams & params)767 void QuicConnection::AdjustNetworkParameters(
768 const SendAlgorithmInterface::NetworkParams& params) {
769 sent_packet_manager_.AdjustNetworkParameters(params);
770 }
771
SetLossDetectionTuner(std::unique_ptr<LossDetectionTunerInterface> tuner)772 void QuicConnection::SetLossDetectionTuner(
773 std::unique_ptr<LossDetectionTunerInterface> tuner) {
774 sent_packet_manager_.SetLossDetectionTuner(std::move(tuner));
775 }
776
OnConfigNegotiated()777 void QuicConnection::OnConfigNegotiated() {
778 sent_packet_manager_.OnConfigNegotiated();
779
780 if (GetQuicReloadableFlag(quic_enable_mtu_discovery_at_server) &&
781 perspective_ == Perspective::IS_SERVER) {
782 QUIC_RELOADABLE_FLAG_COUNT(quic_enable_mtu_discovery_at_server);
783 SetMtuDiscoveryTarget(kMtuDiscoveryTargetPacketSizeHigh);
784 }
785 }
786
MaxPacingRate() const787 QuicBandwidth QuicConnection::MaxPacingRate() const {
788 return sent_packet_manager_.MaxPacingRate();
789 }
790
SelectMutualVersion(const ParsedQuicVersionVector & available_versions)791 bool QuicConnection::SelectMutualVersion(
792 const ParsedQuicVersionVector& available_versions) {
793 // Try to find the highest mutual version by iterating over supported
794 // versions, starting with the highest, and breaking out of the loop once we
795 // find a matching version in the provided available_versions vector.
796 const ParsedQuicVersionVector& supported_versions =
797 framer_.supported_versions();
798 for (size_t i = 0; i < supported_versions.size(); ++i) {
799 const ParsedQuicVersion& version = supported_versions[i];
800 if (std::find(available_versions.begin(), available_versions.end(),
801 version) != available_versions.end()) {
802 framer_.set_version(version);
803 return true;
804 }
805 }
806
807 return false;
808 }
809
OnError(QuicFramer * framer)810 void QuicConnection::OnError(QuicFramer* framer) {
811 // Packets that we can not or have not decrypted are dropped.
812 // TODO(rch): add stats to measure this.
813 if (!connected_ || !last_received_packet_info_.decrypted) {
814 return;
815 }
816 CloseConnection(framer->error(), framer->detailed_error(),
817 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
818 }
819
OnPacket()820 void QuicConnection::OnPacket() {
821 last_received_packet_info_.decrypted = false;
822 }
823
OnProtocolVersionMismatch(ParsedQuicVersion received_version)824 bool QuicConnection::OnProtocolVersionMismatch(
825 ParsedQuicVersion received_version) {
826 QUIC_DLOG(INFO) << ENDPOINT << "Received packet with mismatched version "
827 << ParsedQuicVersionToString(received_version);
828 if (perspective_ == Perspective::IS_CLIENT) {
829 const std::string error_details = "Protocol version mismatch.";
830 QUIC_BUG(quic_bug_10511_3) << ENDPOINT << error_details;
831 CloseConnection(QUIC_INTERNAL_ERROR, error_details,
832 ConnectionCloseBehavior::SILENT_CLOSE);
833 }
834
835 // Server drops old packets that were sent by the client before the version
836 // was negotiated.
837 return false;
838 }
839
840 // Handles version negotiation for client connection.
OnVersionNegotiationPacket(const QuicVersionNegotiationPacket & packet)841 void QuicConnection::OnVersionNegotiationPacket(
842 const QuicVersionNegotiationPacket& packet) {
843 // Check that any public reset packet with a different connection ID that was
844 // routed to this QuicConnection has been redirected before control reaches
845 // here. (Check for a bug regression.)
846 QUICHE_DCHECK_EQ(default_path_.server_connection_id, packet.connection_id);
847 if (perspective_ == Perspective::IS_SERVER) {
848 const std::string error_details =
849 "Server received version negotiation packet.";
850 QUIC_BUG(quic_bug_10511_4) << error_details;
851 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_version_negotiation);
852 CloseConnection(QUIC_INTERNAL_ERROR, error_details,
853 ConnectionCloseBehavior::SILENT_CLOSE);
854 return;
855 }
856 if (debug_visitor_ != nullptr) {
857 debug_visitor_->OnVersionNegotiationPacket(packet);
858 }
859
860 if (version_negotiated_) {
861 // Possibly a duplicate version negotiation packet.
862 return;
863 }
864
865 if (std::find(packet.versions.begin(), packet.versions.end(), version()) !=
866 packet.versions.end()) {
867 const std::string error_details = absl::StrCat(
868 "Server already supports client's version ",
869 ParsedQuicVersionToString(version()),
870 " and should have accepted the connection instead of sending {",
871 ParsedQuicVersionVectorToString(packet.versions), "}.");
872 QUIC_DLOG(WARNING) << error_details;
873 CloseConnection(QUIC_INVALID_VERSION_NEGOTIATION_PACKET, error_details,
874 ConnectionCloseBehavior::SILENT_CLOSE);
875 return;
876 }
877
878 server_supported_versions_ = packet.versions;
879 CloseConnection(
880 QUIC_INVALID_VERSION,
881 absl::StrCat(
882 "Client may support one of the versions in the server's list, but "
883 "it's going to close the connection anyway. Supported versions: {",
884 ParsedQuicVersionVectorToString(framer_.supported_versions()),
885 "}, peer supported versions: {",
886 ParsedQuicVersionVectorToString(packet.versions), "}"),
887 send_connection_close_for_invalid_version_
888 ? ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET
889 : ConnectionCloseBehavior::SILENT_CLOSE);
890 }
891
892 // Handles retry for client connection.
OnRetryPacket(QuicConnectionId original_connection_id,QuicConnectionId new_connection_id,absl::string_view retry_token,absl::string_view retry_integrity_tag,absl::string_view retry_without_tag)893 void QuicConnection::OnRetryPacket(QuicConnectionId original_connection_id,
894 QuicConnectionId new_connection_id,
895 absl::string_view retry_token,
896 absl::string_view retry_integrity_tag,
897 absl::string_view retry_without_tag) {
898 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
899 if (version().UsesTls()) {
900 if (!CryptoUtils::ValidateRetryIntegrityTag(
901 version(), default_path_.server_connection_id, retry_without_tag,
902 retry_integrity_tag)) {
903 QUIC_DLOG(ERROR) << "Ignoring RETRY with invalid integrity tag";
904 return;
905 }
906 } else {
907 if (original_connection_id != default_path_.server_connection_id) {
908 QUIC_DLOG(ERROR) << "Ignoring RETRY with original connection ID "
909 << original_connection_id << " not matching expected "
910 << default_path_.server_connection_id << " token "
911 << absl::BytesToHexString(retry_token);
912 return;
913 }
914 }
915 framer_.set_drop_incoming_retry_packets(true);
916 stats_.retry_packet_processed = true;
917 QUIC_DLOG(INFO) << "Received RETRY, replacing connection ID "
918 << default_path_.server_connection_id << " with "
919 << new_connection_id << ", received token "
920 << absl::BytesToHexString(retry_token);
921 if (!original_destination_connection_id_.has_value()) {
922 original_destination_connection_id_ = default_path_.server_connection_id;
923 }
924 QUICHE_DCHECK(!retry_source_connection_id_.has_value())
925 << *retry_source_connection_id_;
926 retry_source_connection_id_ = new_connection_id;
927 ReplaceInitialServerConnectionId(new_connection_id);
928 packet_creator_.SetRetryToken(retry_token);
929
930 // Reinstall initial crypters because the connection ID changed.
931 InstallInitialCrypters(default_path_.server_connection_id);
932
933 sent_packet_manager_.MarkInitialPacketsForRetransmission();
934 }
935
SetOriginalDestinationConnectionId(const QuicConnectionId & original_destination_connection_id)936 void QuicConnection::SetOriginalDestinationConnectionId(
937 const QuicConnectionId& original_destination_connection_id) {
938 QUIC_DLOG(INFO) << "Setting original_destination_connection_id to "
939 << original_destination_connection_id
940 << " on connection with server_connection_id "
941 << default_path_.server_connection_id;
942 QUICHE_DCHECK_NE(original_destination_connection_id,
943 default_path_.server_connection_id);
944 InstallInitialCrypters(original_destination_connection_id);
945 QUICHE_DCHECK(!original_destination_connection_id_.has_value())
946 << *original_destination_connection_id_;
947 original_destination_connection_id_ = original_destination_connection_id;
948 original_destination_connection_id_replacement_ =
949 default_path_.server_connection_id;
950 }
951
GetOriginalDestinationConnectionId() const952 QuicConnectionId QuicConnection::GetOriginalDestinationConnectionId() const {
953 if (original_destination_connection_id_.has_value()) {
954 return *original_destination_connection_id_;
955 }
956 return default_path_.server_connection_id;
957 }
958
RetireOriginalDestinationConnectionId()959 void QuicConnection::RetireOriginalDestinationConnectionId() {
960 if (original_destination_connection_id_.has_value()) {
961 visitor_->OnServerConnectionIdRetired(*original_destination_connection_id_);
962 original_destination_connection_id_.reset();
963 }
964 }
965
ValidateServerConnectionId(const QuicPacketHeader & header) const966 bool QuicConnection::ValidateServerConnectionId(
967 const QuicPacketHeader& header) const {
968 if (perspective_ == Perspective::IS_CLIENT &&
969 header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
970 return true;
971 }
972
973 QuicConnectionId server_connection_id =
974 GetServerConnectionIdAsRecipient(header, perspective_);
975
976 if (server_connection_id == default_path_.server_connection_id ||
977 server_connection_id == original_destination_connection_id_) {
978 return true;
979 }
980
981 if (PacketCanReplaceServerConnectionId(header, perspective_)) {
982 QUIC_DLOG(INFO) << ENDPOINT << "Accepting packet with new connection ID "
983 << server_connection_id << " instead of "
984 << default_path_.server_connection_id;
985 return true;
986 }
987
988 if (version().HasIetfQuicFrames() && perspective_ == Perspective::IS_SERVER &&
989 self_issued_cid_manager_ != nullptr &&
990 self_issued_cid_manager_->IsConnectionIdInUse(server_connection_id)) {
991 return true;
992 }
993
994 if (NewServerConnectionIdMightBeValid(
995 header, perspective_, server_connection_id_replaced_by_initial_)) {
996 return true;
997 }
998
999 return false;
1000 }
1001
OnUnauthenticatedPublicHeader(const QuicPacketHeader & header)1002 bool QuicConnection::OnUnauthenticatedPublicHeader(
1003 const QuicPacketHeader& header) {
1004 last_received_packet_info_.destination_connection_id =
1005 header.destination_connection_id;
1006 // If last packet destination connection ID is the original server
1007 // connection ID chosen by client, replaces it with the connection ID chosen
1008 // by server.
1009 if (perspective_ == Perspective::IS_SERVER &&
1010 original_destination_connection_id_.has_value() &&
1011 last_received_packet_info_.destination_connection_id ==
1012 *original_destination_connection_id_) {
1013 last_received_packet_info_.destination_connection_id =
1014 original_destination_connection_id_replacement_;
1015 }
1016
1017 // As soon as we receive an initial we start ignoring subsequent retries.
1018 if (header.version_flag && header.long_packet_type == INITIAL) {
1019 framer_.set_drop_incoming_retry_packets(true);
1020 }
1021
1022 if (!ValidateServerConnectionId(header)) {
1023 ++stats_.packets_dropped;
1024 QuicConnectionId server_connection_id =
1025 GetServerConnectionIdAsRecipient(header, perspective_);
1026 QUIC_DLOG(INFO) << ENDPOINT
1027 << "Ignoring packet from unexpected server connection ID "
1028 << server_connection_id << " instead of "
1029 << default_path_.server_connection_id;
1030 if (debug_visitor_ != nullptr) {
1031 debug_visitor_->OnIncorrectConnectionId(server_connection_id);
1032 }
1033 QUICHE_DCHECK_NE(Perspective::IS_SERVER, perspective_);
1034 return false;
1035 }
1036
1037 if (!version().SupportsClientConnectionIds()) {
1038 return true;
1039 }
1040
1041 if (perspective_ == Perspective::IS_SERVER &&
1042 header.form == IETF_QUIC_SHORT_HEADER_PACKET) {
1043 return true;
1044 }
1045
1046 QuicConnectionId client_connection_id =
1047 GetClientConnectionIdAsRecipient(header, perspective_);
1048
1049 if (client_connection_id == default_path_.client_connection_id) {
1050 return true;
1051 }
1052
1053 if (!client_connection_id_is_set_ && perspective_ == Perspective::IS_SERVER) {
1054 QUIC_DLOG(INFO) << ENDPOINT
1055 << "Setting client connection ID from first packet to "
1056 << client_connection_id;
1057 set_client_connection_id(client_connection_id);
1058 return true;
1059 }
1060
1061 if (version().HasIetfQuicFrames() && perspective_ == Perspective::IS_CLIENT &&
1062 self_issued_cid_manager_ != nullptr &&
1063 self_issued_cid_manager_->IsConnectionIdInUse(client_connection_id)) {
1064 return true;
1065 }
1066
1067 ++stats_.packets_dropped;
1068 QUIC_DLOG(INFO) << ENDPOINT
1069 << "Ignoring packet from unexpected client connection ID "
1070 << client_connection_id << " instead of "
1071 << default_path_.client_connection_id;
1072 return false;
1073 }
1074
OnUnauthenticatedHeader(const QuicPacketHeader & header)1075 bool QuicConnection::OnUnauthenticatedHeader(const QuicPacketHeader& header) {
1076 if (debug_visitor_ != nullptr) {
1077 debug_visitor_->OnUnauthenticatedHeader(header);
1078 }
1079
1080 // Sanity check on the server connection ID in header.
1081 QUICHE_DCHECK(ValidateServerConnectionId(header));
1082
1083 if (packet_creator_.HasPendingFrames()) {
1084 // Incoming packets may change a queued ACK frame.
1085 const std::string error_details =
1086 "Pending frames must be serialized before incoming packets are "
1087 "processed.";
1088 QUIC_BUG(quic_pending_frames_not_serialized)
1089 << error_details << ", received header: " << header;
1090 CloseConnection(QUIC_INTERNAL_ERROR, error_details,
1091 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1092 return false;
1093 }
1094
1095 return true;
1096 }
1097
OnSuccessfulVersionNegotiation()1098 void QuicConnection::OnSuccessfulVersionNegotiation() {
1099 visitor_->OnSuccessfulVersionNegotiation(version());
1100 if (debug_visitor_ != nullptr) {
1101 debug_visitor_->OnSuccessfulVersionNegotiation(version());
1102 }
1103 }
1104
OnSuccessfulMigration(bool is_port_change)1105 void QuicConnection::OnSuccessfulMigration(bool is_port_change) {
1106 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
1107 if (IsPathDegrading() && !multi_port_stats_) {
1108 // If path was previously degrading, and migration is successful after
1109 // probing, restart the path degrading and blackhole detection.
1110 // In the case of multi-port, since the alt-path state is inferred from
1111 // historical data, we can't trust it until we receive data on the new path.
1112 OnForwardProgressMade();
1113 }
1114 if (IsAlternativePath(default_path_.self_address,
1115 default_path_.peer_address)) {
1116 // Reset alternative path state even if it is still under validation.
1117 alternative_path_.Clear();
1118 }
1119 // TODO(b/159074035): notify SentPacketManger with RTT sample from probing.
1120 if (version().HasIetfQuicFrames() && !is_port_change) {
1121 sent_packet_manager_.OnConnectionMigration(/*reset_send_algorithm=*/true);
1122 }
1123 }
1124
OnTransportParametersSent(const TransportParameters & transport_parameters) const1125 void QuicConnection::OnTransportParametersSent(
1126 const TransportParameters& transport_parameters) const {
1127 if (debug_visitor_ != nullptr) {
1128 debug_visitor_->OnTransportParametersSent(transport_parameters);
1129 }
1130 }
1131
OnTransportParametersReceived(const TransportParameters & transport_parameters) const1132 void QuicConnection::OnTransportParametersReceived(
1133 const TransportParameters& transport_parameters) const {
1134 if (debug_visitor_ != nullptr) {
1135 debug_visitor_->OnTransportParametersReceived(transport_parameters);
1136 }
1137 }
1138
OnTransportParametersResumed(const TransportParameters & transport_parameters) const1139 void QuicConnection::OnTransportParametersResumed(
1140 const TransportParameters& transport_parameters) const {
1141 if (debug_visitor_ != nullptr) {
1142 debug_visitor_->OnTransportParametersResumed(transport_parameters);
1143 }
1144 }
1145
OnEncryptedClientHelloSent(absl::string_view client_hello) const1146 void QuicConnection::OnEncryptedClientHelloSent(
1147 absl::string_view client_hello) const {
1148 if (debug_visitor_ != nullptr) {
1149 debug_visitor_->OnEncryptedClientHelloSent(client_hello);
1150 }
1151 }
1152
OnEncryptedClientHelloReceived(absl::string_view client_hello) const1153 void QuicConnection::OnEncryptedClientHelloReceived(
1154 absl::string_view client_hello) const {
1155 if (debug_visitor_ != nullptr) {
1156 debug_visitor_->OnEncryptedClientHelloReceived(client_hello);
1157 }
1158 }
1159
HasPendingAcks() const1160 bool QuicConnection::HasPendingAcks() const { return ack_alarm_->IsSet(); }
1161
OnUserAgentIdKnown(const std::string &)1162 void QuicConnection::OnUserAgentIdKnown(const std::string& /*user_agent_id*/) {
1163 sent_packet_manager_.OnUserAgentIdKnown();
1164 }
1165
OnDecryptedPacket(size_t,EncryptionLevel level)1166 void QuicConnection::OnDecryptedPacket(size_t /*length*/,
1167 EncryptionLevel level) {
1168 last_received_packet_info_.decrypted_level = level;
1169 last_received_packet_info_.decrypted = true;
1170 if (level == ENCRYPTION_FORWARD_SECURE &&
1171 !have_decrypted_first_one_rtt_packet_) {
1172 have_decrypted_first_one_rtt_packet_ = true;
1173 if (version().UsesTls() && perspective_ == Perspective::IS_SERVER) {
1174 // Servers MAY temporarily retain 0-RTT keys to allow decrypting reordered
1175 // packets without requiring their contents to be retransmitted with 1-RTT
1176 // keys. After receiving a 1-RTT packet, servers MUST discard 0-RTT keys
1177 // within a short time; the RECOMMENDED time period is three times the
1178 // Probe Timeout.
1179 // https://quicwg.org/base-drafts/draft-ietf-quic-tls.html#name-discarding-0-rtt-keys
1180 discard_zero_rtt_decryption_keys_alarm_->Set(
1181 clock_->ApproximateNow() + sent_packet_manager_.GetPtoDelay() * 3);
1182 }
1183 }
1184 if (EnforceAntiAmplificationLimit() && !IsHandshakeConfirmed() &&
1185 (level == ENCRYPTION_HANDSHAKE || level == ENCRYPTION_FORWARD_SECURE)) {
1186 // Address is validated by successfully processing a HANDSHAKE or 1-RTT
1187 // packet.
1188 default_path_.validated = true;
1189 stats_.address_validated_via_decrypting_packet = true;
1190 }
1191 idle_network_detector_.OnPacketReceived(
1192 last_received_packet_info_.receipt_time);
1193
1194 visitor_->OnPacketDecrypted(level);
1195 }
1196
GetEffectivePeerAddressFromCurrentPacket() const1197 QuicSocketAddress QuicConnection::GetEffectivePeerAddressFromCurrentPacket()
1198 const {
1199 // By default, the connection is not proxied, and the effective peer address
1200 // is the packet's source address, i.e. the direct peer address.
1201 return last_received_packet_info_.source_address;
1202 }
1203
OnPacketHeader(const QuicPacketHeader & header)1204 bool QuicConnection::OnPacketHeader(const QuicPacketHeader& header) {
1205 if (debug_visitor_ != nullptr) {
1206 debug_visitor_->OnPacketHeader(header, clock_->ApproximateNow(),
1207 last_received_packet_info_.decrypted_level);
1208 }
1209
1210 // Will be decremented below if we fall through to return true.
1211 ++stats_.packets_dropped;
1212
1213 if (!ProcessValidatedPacket(header)) {
1214 return false;
1215 }
1216
1217 // Initialize the current packet content state.
1218 current_packet_content_ = NO_FRAMES_RECEIVED;
1219 is_current_packet_connectivity_probing_ = false;
1220 has_path_challenge_in_current_packet_ = false;
1221 current_effective_peer_migration_type_ = NO_CHANGE;
1222
1223 if (perspective_ == Perspective::IS_CLIENT) {
1224 if (!GetLargestReceivedPacket().IsInitialized() ||
1225 header.packet_number > GetLargestReceivedPacket()) {
1226 if (version().HasIetfQuicFrames()) {
1227 // Client processes packets from any known server address, but only
1228 // updates peer address on initialization and/or to validated server
1229 // preferred address.
1230 } else {
1231 // Update direct_peer_address_ and default path peer_address immediately
1232 // for client connections.
1233 // TODO(fayang): only change peer addresses in application data packet
1234 // number space.
1235 UpdatePeerAddress(last_received_packet_info_.source_address);
1236 default_path_.peer_address = GetEffectivePeerAddressFromCurrentPacket();
1237 }
1238 }
1239 } else {
1240 // At server, remember the address change type of effective_peer_address
1241 // in current_effective_peer_migration_type_. But this variable alone
1242 // doesn't necessarily starts a migration. A migration will be started
1243 // later, once the current packet is confirmed to meet the following
1244 // conditions:
1245 // 1) current_effective_peer_migration_type_ is not NO_CHANGE.
1246 // 2) The current packet is not a connectivity probing.
1247 // 3) The current packet is not reordered, i.e. its packet number is the
1248 // largest of this connection so far.
1249 // Once the above conditions are confirmed, a new migration will start
1250 // even if there is an active migration underway.
1251 current_effective_peer_migration_type_ =
1252 QuicUtils::DetermineAddressChangeType(
1253 default_path_.peer_address,
1254 GetEffectivePeerAddressFromCurrentPacket());
1255
1256 if (version().HasIetfQuicFrames()) {
1257 auto effective_peer_address = GetEffectivePeerAddressFromCurrentPacket();
1258 // Since server does not send new connection ID to client before handshake
1259 // completion and source connection ID is omitted in short header packet,
1260 // the server_connection_id on PathState on the server side does not
1261 // affect the packets server writes after handshake completion. On the
1262 // other hand, it is still desirable to have the "correct" server
1263 // connection ID set on path.
1264 // 1) If client uses 1 unique server connection ID per path and the packet
1265 // is received from an existing path, then
1266 // last_received_packet_info_.destination_connection_id will always be the
1267 // same as the server connection ID on path. Server side will maintain the
1268 // 1-to-1 mapping from server connection ID to path. 2) If client uses
1269 // multiple server connection IDs on the same path, compared to the
1270 // server_connection_id on path,
1271 // last_received_packet_info_.destination_connection_id has the advantage
1272 // that it is still present in the session map since the packet can be
1273 // routed here regardless of packet reordering.
1274 if (IsDefaultPath(last_received_packet_info_.destination_address,
1275 effective_peer_address)) {
1276 default_path_.server_connection_id =
1277 last_received_packet_info_.destination_connection_id;
1278 } else if (IsAlternativePath(
1279 last_received_packet_info_.destination_address,
1280 effective_peer_address)) {
1281 alternative_path_.server_connection_id =
1282 last_received_packet_info_.destination_connection_id;
1283 }
1284 }
1285
1286 if (last_received_packet_info_.destination_connection_id !=
1287 default_path_.server_connection_id &&
1288 (!original_destination_connection_id_.has_value() ||
1289 last_received_packet_info_.destination_connection_id !=
1290 *original_destination_connection_id_)) {
1291 QUIC_CODE_COUNT(quic_connection_id_change);
1292 }
1293
1294 QUIC_DLOG_IF(INFO, current_effective_peer_migration_type_ != NO_CHANGE)
1295 << ENDPOINT << "Effective peer's ip:port changed from "
1296 << default_path_.peer_address.ToString() << " to "
1297 << GetEffectivePeerAddressFromCurrentPacket().ToString()
1298 << ", active_effective_peer_migration_type is "
1299 << active_effective_peer_migration_type_;
1300 }
1301
1302 --stats_.packets_dropped;
1303 QUIC_DVLOG(1) << ENDPOINT << "Received packet header: " << header;
1304 last_received_packet_info_.header = header;
1305 if (!stats_.first_decrypted_packet.IsInitialized()) {
1306 stats_.first_decrypted_packet =
1307 last_received_packet_info_.header.packet_number;
1308 }
1309
1310 switch (last_received_packet_info_.ecn_codepoint) {
1311 case ECN_NOT_ECT:
1312 break;
1313 case ECN_ECT0:
1314 stats_.num_ecn_marks_received.ect0++;
1315 break;
1316 case ECN_ECT1:
1317 stats_.num_ecn_marks_received.ect1++;
1318 break;
1319 case ECN_CE:
1320 stats_.num_ecn_marks_received.ce++;
1321 break;
1322 }
1323
1324 // Record packet receipt to populate ack info before processing stream
1325 // frames, since the processing may result in sending a bundled ack.
1326 QuicTime receipt_time = idle_network_detector_.time_of_last_received_packet();
1327 if (SupportsMultiplePacketNumberSpaces()) {
1328 receipt_time = last_received_packet_info_.receipt_time;
1329 }
1330 uber_received_packet_manager_.RecordPacketReceived(
1331 last_received_packet_info_.decrypted_level,
1332 last_received_packet_info_.header, receipt_time,
1333 last_received_packet_info_.ecn_codepoint);
1334 if (EnforceAntiAmplificationLimit() && !IsHandshakeConfirmed() &&
1335 !header.retry_token.empty() &&
1336 visitor_->ValidateToken(header.retry_token)) {
1337 QUIC_DLOG(INFO) << ENDPOINT << "Address validated via token.";
1338 QUIC_CODE_COUNT(quic_address_validated_via_token);
1339 default_path_.validated = true;
1340 stats_.address_validated_via_token = true;
1341 }
1342 QUICHE_DCHECK(connected_);
1343 return true;
1344 }
1345
OnStreamFrame(const QuicStreamFrame & frame)1346 bool QuicConnection::OnStreamFrame(const QuicStreamFrame& frame) {
1347 QUIC_BUG_IF(quic_bug_12714_3, !connected_)
1348 << "Processing STREAM frame when connection is closed. Received packet "
1349 "info: "
1350 << last_received_packet_info_;
1351
1352 // Since a stream frame was received, this is not a connectivity probe.
1353 // A probe only contains a PING and full padding.
1354 if (!UpdatePacketContent(STREAM_FRAME)) {
1355 return false;
1356 }
1357
1358 if (debug_visitor_ != nullptr) {
1359 debug_visitor_->OnStreamFrame(frame);
1360 }
1361 if (!QuicUtils::IsCryptoStreamId(transport_version(), frame.stream_id) &&
1362 last_received_packet_info_.decrypted_level == ENCRYPTION_INITIAL) {
1363 if (MaybeConsiderAsMemoryCorruption(frame)) {
1364 CloseConnection(QUIC_MAYBE_CORRUPTED_MEMORY,
1365 "Received crypto frame on non crypto stream.",
1366 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1367 return false;
1368 }
1369
1370 QUIC_PEER_BUG(quic_peer_bug_10511_6)
1371 << ENDPOINT << "Received an unencrypted data frame: closing connection"
1372 << " packet_number:" << last_received_packet_info_.header.packet_number
1373 << " stream_id:" << frame.stream_id
1374 << " received_packets:" << ack_frame();
1375 CloseConnection(QUIC_UNENCRYPTED_STREAM_DATA,
1376 "Unencrypted stream data seen.",
1377 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1378 return false;
1379 }
1380 // TODO(fayang): Consider moving UpdatePacketContent and
1381 // MaybeUpdateAckTimeout to a stand-alone function instead of calling them for
1382 // all frames.
1383 MaybeUpdateAckTimeout();
1384 visitor_->OnStreamFrame(frame);
1385 stats_.stream_bytes_received += frame.data_length;
1386 ping_manager_.reset_consecutive_retransmittable_on_wire_count();
1387 return connected_;
1388 }
1389
OnCryptoFrame(const QuicCryptoFrame & frame)1390 bool QuicConnection::OnCryptoFrame(const QuicCryptoFrame& frame) {
1391 QUIC_BUG_IF(quic_bug_12714_4, !connected_)
1392 << "Processing CRYPTO frame when connection is closed. Received packet "
1393 "info: "
1394 << last_received_packet_info_;
1395
1396 // Since a CRYPTO frame was received, this is not a connectivity probe.
1397 // A probe only contains a PING and full padding.
1398 if (!UpdatePacketContent(CRYPTO_FRAME)) {
1399 return false;
1400 }
1401
1402 if (debug_visitor_ != nullptr) {
1403 debug_visitor_->OnCryptoFrame(frame);
1404 }
1405 MaybeUpdateAckTimeout();
1406 visitor_->OnCryptoFrame(frame);
1407 return connected_;
1408 }
1409
OnAckFrameStart(QuicPacketNumber largest_acked,QuicTime::Delta ack_delay_time)1410 bool QuicConnection::OnAckFrameStart(QuicPacketNumber largest_acked,
1411 QuicTime::Delta ack_delay_time) {
1412 QUIC_BUG_IF(quic_bug_12714_5, !connected_)
1413 << "Processing ACK frame start when connection is closed. Received "
1414 "packet info: "
1415 << last_received_packet_info_;
1416
1417 if (processing_ack_frame_) {
1418 CloseConnection(QUIC_INVALID_ACK_DATA,
1419 "Received a new ack while processing an ack frame.",
1420 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1421 return false;
1422 }
1423
1424 // Since an ack frame was received, this is not a connectivity probe.
1425 // A probe only contains a PING and full padding.
1426 if (!UpdatePacketContent(ACK_FRAME)) {
1427 return false;
1428 }
1429
1430 QUIC_DVLOG(1) << ENDPOINT
1431 << "OnAckFrameStart, largest_acked: " << largest_acked;
1432
1433 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1434 last_received_packet_info_.header.packet_number <=
1435 GetLargestReceivedPacketWithAck()) {
1436 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1437 return true;
1438 }
1439
1440 if (!sent_packet_manager_.GetLargestSentPacket().IsInitialized() ||
1441 largest_acked > sent_packet_manager_.GetLargestSentPacket()) {
1442 QUIC_DLOG(WARNING) << ENDPOINT
1443 << "Peer's observed unsent packet:" << largest_acked
1444 << " vs " << sent_packet_manager_.GetLargestSentPacket()
1445 << ". SupportsMultiplePacketNumberSpaces():"
1446 << SupportsMultiplePacketNumberSpaces()
1447 << ", last_received_packet_info_.decrypted_level:"
1448 << last_received_packet_info_.decrypted_level;
1449 // We got an ack for data we have not sent.
1450 CloseConnection(QUIC_INVALID_ACK_DATA, "Largest observed too high.",
1451 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1452 return false;
1453 }
1454 processing_ack_frame_ = true;
1455 sent_packet_manager_.OnAckFrameStart(
1456 largest_acked, ack_delay_time,
1457 idle_network_detector_.time_of_last_received_packet());
1458 return true;
1459 }
1460
OnAckRange(QuicPacketNumber start,QuicPacketNumber end)1461 bool QuicConnection::OnAckRange(QuicPacketNumber start, QuicPacketNumber end) {
1462 QUIC_BUG_IF(quic_bug_12714_6, !connected_)
1463 << "Processing ACK frame range when connection is closed. Received "
1464 "packet info: "
1465 << last_received_packet_info_;
1466 QUIC_DVLOG(1) << ENDPOINT << "OnAckRange: [" << start << ", " << end << ")";
1467
1468 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1469 last_received_packet_info_.header.packet_number <=
1470 GetLargestReceivedPacketWithAck()) {
1471 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1472 return true;
1473 }
1474
1475 sent_packet_manager_.OnAckRange(start, end);
1476 return true;
1477 }
1478
OnAckTimestamp(QuicPacketNumber packet_number,QuicTime timestamp)1479 bool QuicConnection::OnAckTimestamp(QuicPacketNumber packet_number,
1480 QuicTime timestamp) {
1481 QUIC_BUG_IF(quic_bug_10511_7, !connected_)
1482 << "Processing ACK frame time stamp when connection is closed. Received "
1483 "packet info: "
1484 << last_received_packet_info_;
1485 QUIC_DVLOG(1) << ENDPOINT << "OnAckTimestamp: [" << packet_number << ", "
1486 << timestamp.ToDebuggingValue() << ")";
1487
1488 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1489 last_received_packet_info_.header.packet_number <=
1490 GetLargestReceivedPacketWithAck()) {
1491 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1492 return true;
1493 }
1494
1495 sent_packet_manager_.OnAckTimestamp(packet_number, timestamp);
1496 return true;
1497 }
1498
OnAckFrameEnd(QuicPacketNumber start,const std::optional<QuicEcnCounts> & ecn_counts)1499 bool QuicConnection::OnAckFrameEnd(
1500 QuicPacketNumber start, const std::optional<QuicEcnCounts>& ecn_counts) {
1501 QUIC_BUG_IF(quic_bug_12714_7, !connected_)
1502 << "Processing ACK frame end when connection is closed. Received packet "
1503 "info: "
1504 << last_received_packet_info_;
1505 QUIC_DVLOG(1) << ENDPOINT << "OnAckFrameEnd, start: " << start;
1506
1507 if (GetLargestReceivedPacketWithAck().IsInitialized() &&
1508 last_received_packet_info_.header.packet_number <=
1509 GetLargestReceivedPacketWithAck()) {
1510 QUIC_DLOG(INFO) << ENDPOINT << "Received an old ack frame: ignoring";
1511 return true;
1512 }
1513 const bool one_rtt_packet_was_acked =
1514 sent_packet_manager_.one_rtt_packet_acked();
1515 const bool zero_rtt_packet_was_acked =
1516 sent_packet_manager_.zero_rtt_packet_acked();
1517 const AckResult ack_result = sent_packet_manager_.OnAckFrameEnd(
1518 idle_network_detector_.time_of_last_received_packet(),
1519 last_received_packet_info_.header.packet_number,
1520 last_received_packet_info_.decrypted_level, ecn_counts);
1521 if (ack_result != PACKETS_NEWLY_ACKED &&
1522 ack_result != NO_PACKETS_NEWLY_ACKED) {
1523 // Error occurred (e.g., this ACK tries to ack packets in wrong packet
1524 // number space), and this would cause the connection to be closed.
1525 QUIC_DLOG(ERROR) << ENDPOINT
1526 << "Error occurred when processing an ACK frame: "
1527 << QuicUtils::AckResultToString(ack_result);
1528 return false;
1529 }
1530 if (SupportsMultiplePacketNumberSpaces() && !one_rtt_packet_was_acked &&
1531 sent_packet_manager_.one_rtt_packet_acked()) {
1532 visitor_->OnOneRttPacketAcknowledged();
1533 }
1534 if (debug_visitor_ != nullptr && version().UsesTls() &&
1535 !zero_rtt_packet_was_acked &&
1536 sent_packet_manager_.zero_rtt_packet_acked()) {
1537 debug_visitor_->OnZeroRttPacketAcked();
1538 }
1539 // Cancel the send alarm because new packets likely have been acked, which
1540 // may change the congestion window and/or pacing rate. Canceling the alarm
1541 // causes CanWrite to recalculate the next send time.
1542 if (send_alarm_->IsSet()) {
1543 send_alarm_->Cancel();
1544 }
1545 if (supports_release_time_) {
1546 // Update pace time into future because smoothed RTT is likely updated.
1547 UpdateReleaseTimeIntoFuture();
1548 }
1549 SetLargestReceivedPacketWithAck(
1550 last_received_packet_info_.header.packet_number);
1551 PostProcessAfterAckFrame(ack_result == PACKETS_NEWLY_ACKED);
1552 processing_ack_frame_ = false;
1553 return connected_;
1554 }
1555
OnStopWaitingFrame(const QuicStopWaitingFrame &)1556 bool QuicConnection::OnStopWaitingFrame(const QuicStopWaitingFrame& /*frame*/) {
1557 QUIC_BUG_IF(quic_bug_12714_8, !connected_)
1558 << "Processing STOP_WAITING frame when connection is closed. Received "
1559 "packet info: "
1560 << last_received_packet_info_;
1561
1562 // Since a stop waiting frame was received, this is not a connectivity probe.
1563 // A probe only contains a PING and full padding.
1564 if (!UpdatePacketContent(STOP_WAITING_FRAME)) {
1565 return false;
1566 }
1567 return connected_;
1568 }
1569
OnPaddingFrame(const QuicPaddingFrame & frame)1570 bool QuicConnection::OnPaddingFrame(const QuicPaddingFrame& frame) {
1571 QUIC_BUG_IF(quic_bug_12714_9, !connected_)
1572 << "Processing PADDING frame when connection is closed. Received packet "
1573 "info: "
1574 << last_received_packet_info_;
1575 if (!UpdatePacketContent(PADDING_FRAME)) {
1576 return false;
1577 }
1578
1579 if (debug_visitor_ != nullptr) {
1580 debug_visitor_->OnPaddingFrame(frame);
1581 }
1582 return true;
1583 }
1584
OnPingFrame(const QuicPingFrame & frame)1585 bool QuicConnection::OnPingFrame(const QuicPingFrame& frame) {
1586 QUIC_BUG_IF(quic_bug_12714_10, !connected_)
1587 << "Processing PING frame when connection is closed. Received packet "
1588 "info: "
1589 << last_received_packet_info_;
1590 if (!UpdatePacketContent(PING_FRAME)) {
1591 return false;
1592 }
1593
1594 if (debug_visitor_ != nullptr) {
1595 QuicTime::Delta ping_received_delay = QuicTime::Delta::Zero();
1596 const QuicTime now = clock_->ApproximateNow();
1597 if (now > stats_.connection_creation_time) {
1598 ping_received_delay = now - stats_.connection_creation_time;
1599 }
1600 debug_visitor_->OnPingFrame(frame, ping_received_delay);
1601 }
1602 MaybeUpdateAckTimeout();
1603 return true;
1604 }
1605
OnRstStreamFrame(const QuicRstStreamFrame & frame)1606 bool QuicConnection::OnRstStreamFrame(const QuicRstStreamFrame& frame) {
1607 QUIC_BUG_IF(quic_bug_12714_11, !connected_)
1608 << "Processing RST_STREAM frame when connection is closed. Received "
1609 "packet info: "
1610 << last_received_packet_info_;
1611
1612 // Since a reset stream frame was received, this is not a connectivity probe.
1613 // A probe only contains a PING and full padding.
1614 if (!UpdatePacketContent(RST_STREAM_FRAME)) {
1615 return false;
1616 }
1617
1618 if (debug_visitor_ != nullptr) {
1619 debug_visitor_->OnRstStreamFrame(frame);
1620 }
1621 QUIC_DLOG(INFO) << ENDPOINT
1622 << "RST_STREAM_FRAME received for stream: " << frame.stream_id
1623 << " with error: "
1624 << QuicRstStreamErrorCodeToString(frame.error_code);
1625 MaybeUpdateAckTimeout();
1626 visitor_->OnRstStream(frame);
1627 return connected_;
1628 }
1629
OnStopSendingFrame(const QuicStopSendingFrame & frame)1630 bool QuicConnection::OnStopSendingFrame(const QuicStopSendingFrame& frame) {
1631 QUIC_BUG_IF(quic_bug_12714_12, !connected_)
1632 << "Processing STOP_SENDING frame when connection is closed. Received "
1633 "packet info: "
1634 << last_received_packet_info_;
1635
1636 // Since a reset stream frame was received, this is not a connectivity probe.
1637 // A probe only contains a PING and full padding.
1638 if (!UpdatePacketContent(STOP_SENDING_FRAME)) {
1639 return false;
1640 }
1641
1642 if (debug_visitor_ != nullptr) {
1643 debug_visitor_->OnStopSendingFrame(frame);
1644 }
1645
1646 QUIC_DLOG(INFO) << ENDPOINT << "STOP_SENDING frame received for stream: "
1647 << frame.stream_id
1648 << " with error: " << frame.ietf_error_code;
1649 MaybeUpdateAckTimeout();
1650 visitor_->OnStopSendingFrame(frame);
1651 return connected_;
1652 }
1653
1654 class ReversePathValidationContext : public QuicPathValidationContext {
1655 public:
ReversePathValidationContext(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,const QuicSocketAddress & effective_peer_address,QuicConnection * connection)1656 ReversePathValidationContext(const QuicSocketAddress& self_address,
1657 const QuicSocketAddress& peer_address,
1658 const QuicSocketAddress& effective_peer_address,
1659 QuicConnection* connection)
1660 : QuicPathValidationContext(self_address, peer_address,
1661 effective_peer_address),
1662 connection_(connection) {}
1663
WriterToUse()1664 QuicPacketWriter* WriterToUse() override { return connection_->writer(); }
1665
1666 private:
1667 QuicConnection* connection_;
1668 };
1669
OnPathChallengeFrame(const QuicPathChallengeFrame & frame)1670 bool QuicConnection::OnPathChallengeFrame(const QuicPathChallengeFrame& frame) {
1671 QUIC_BUG_IF(quic_bug_10511_8, !connected_)
1672 << "Processing PATH_CHALLENGE frame when connection is closed. Received "
1673 "packet info: "
1674 << last_received_packet_info_;
1675 if (has_path_challenge_in_current_packet_) {
1676 // Only respond to the 1st PATH_CHALLENGE in the packet.
1677 return true;
1678 }
1679 should_proactively_validate_peer_address_on_path_challenge_ = false;
1680 // UpdatePacketContent() may start reverse path validation.
1681 if (!UpdatePacketContent(PATH_CHALLENGE_FRAME)) {
1682 return false;
1683 }
1684 if (debug_visitor_ != nullptr) {
1685 debug_visitor_->OnPathChallengeFrame(frame);
1686 }
1687 // On the server side, send response to the source address of the current
1688 // incoming packet according to RFC9000.
1689 // On the client side, send response to the default peer address which
1690 // should be on an existing path with a pre-assigned a destination CID.
1691 const QuicSocketAddress effective_peer_address_to_respond =
1692 perspective_ == Perspective::IS_CLIENT
1693 ? effective_peer_address()
1694 : GetEffectivePeerAddressFromCurrentPacket();
1695 const QuicSocketAddress direct_peer_address_to_respond =
1696 perspective_ == Perspective::IS_CLIENT
1697 ? direct_peer_address_
1698 : last_received_packet_info_.source_address;
1699 QuicConnectionId client_cid, server_cid;
1700 FindOnPathConnectionIds(last_received_packet_info_.destination_address,
1701 effective_peer_address_to_respond, &client_cid,
1702 &server_cid);
1703 {
1704 QuicPacketCreator::ScopedPeerAddressContext context(
1705 &packet_creator_, direct_peer_address_to_respond, client_cid,
1706 server_cid);
1707 if (should_proactively_validate_peer_address_on_path_challenge_) {
1708 // Conditions to proactively validate peer address:
1709 // The perspective is server
1710 // The PATH_CHALLENGE is received on an unvalidated alternative path.
1711 // The connection isn't validating migrated peer address, which is of
1712 // higher prority.
1713 QUIC_DVLOG(1) << "Proactively validate the effective peer address "
1714 << effective_peer_address_to_respond;
1715 QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 2, 6);
1716 ValidatePath(
1717 std::make_unique<ReversePathValidationContext>(
1718 default_path_.self_address, direct_peer_address_to_respond,
1719 effective_peer_address_to_respond, this),
1720 std::make_unique<ReversePathValidationResultDelegate>(this,
1721 peer_address()),
1722 PathValidationReason::kReversePathValidation);
1723 }
1724 has_path_challenge_in_current_packet_ = true;
1725 MaybeUpdateAckTimeout();
1726 // Queue or send PATH_RESPONSE.
1727 if (!SendPathResponse(frame.data_buffer, direct_peer_address_to_respond,
1728 effective_peer_address_to_respond)) {
1729 QUIC_CODE_COUNT(quic_failed_to_send_path_response);
1730 }
1731 // TODO(b/150095588): change the stats to
1732 // num_valid_path_challenge_received.
1733 ++stats_.num_connectivity_probing_received;
1734
1735 // Flushing packet creator might cause connection to be closed.
1736 }
1737 return connected_;
1738 }
1739
OnPathResponseFrame(const QuicPathResponseFrame & frame)1740 bool QuicConnection::OnPathResponseFrame(const QuicPathResponseFrame& frame) {
1741 QUIC_BUG_IF(quic_bug_10511_9, !connected_)
1742 << "Processing PATH_RESPONSE frame when connection is closed. Received "
1743 "packet info: "
1744 << last_received_packet_info_;
1745 ++stats_.num_path_response_received;
1746 if (!UpdatePacketContent(PATH_RESPONSE_FRAME)) {
1747 return false;
1748 }
1749 if (debug_visitor_ != nullptr) {
1750 debug_visitor_->OnPathResponseFrame(frame);
1751 }
1752 MaybeUpdateAckTimeout();
1753 path_validator_.OnPathResponse(
1754 frame.data_buffer, last_received_packet_info_.destination_address);
1755 return connected_;
1756 }
1757
OnConnectionCloseFrame(const QuicConnectionCloseFrame & frame)1758 bool QuicConnection::OnConnectionCloseFrame(
1759 const QuicConnectionCloseFrame& frame) {
1760 QUIC_BUG_IF(quic_bug_10511_10, !connected_)
1761 << "Processing CONNECTION_CLOSE frame when connection is closed. "
1762 "Received packet info: "
1763 << last_received_packet_info_;
1764
1765 // Since a connection close frame was received, this is not a connectivity
1766 // probe. A probe only contains a PING and full padding.
1767 if (!UpdatePacketContent(CONNECTION_CLOSE_FRAME)) {
1768 return false;
1769 }
1770
1771 if (debug_visitor_ != nullptr) {
1772 debug_visitor_->OnConnectionCloseFrame(frame);
1773 }
1774 switch (frame.close_type) {
1775 case GOOGLE_QUIC_CONNECTION_CLOSE:
1776 QUIC_DLOG(INFO) << ENDPOINT << "Received ConnectionClose for connection: "
1777 << connection_id() << ", with error: "
1778 << QuicErrorCodeToString(frame.quic_error_code) << " ("
1779 << frame.error_details << ")";
1780 break;
1781 case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE:
1782 QUIC_DLOG(INFO) << ENDPOINT
1783 << "Received Transport ConnectionClose for connection: "
1784 << connection_id() << ", with error: "
1785 << QuicErrorCodeToString(frame.quic_error_code) << " ("
1786 << frame.error_details << ")"
1787 << ", transport error code: "
1788 << QuicIetfTransportErrorCodeString(
1789 static_cast<QuicIetfTransportErrorCodes>(
1790 frame.wire_error_code))
1791 << ", error frame type: "
1792 << frame.transport_close_frame_type;
1793 break;
1794 case IETF_QUIC_APPLICATION_CONNECTION_CLOSE:
1795 QUIC_DLOG(INFO) << ENDPOINT
1796 << "Received Application ConnectionClose for connection: "
1797 << connection_id() << ", with error: "
1798 << QuicErrorCodeToString(frame.quic_error_code) << " ("
1799 << frame.error_details << ")"
1800 << ", application error code: " << frame.wire_error_code;
1801 break;
1802 }
1803
1804 if (frame.quic_error_code == QUIC_BAD_MULTIPATH_FLAG) {
1805 QUIC_LOG_FIRST_N(ERROR, 10)
1806 << "Unexpected QUIC_BAD_MULTIPATH_FLAG error."
1807 << " last_received_header: " << last_received_packet_info_.header
1808 << " encryption_level: " << encryption_level_;
1809 }
1810 TearDownLocalConnectionState(frame, ConnectionCloseSource::FROM_PEER);
1811 return connected_;
1812 }
1813
OnMaxStreamsFrame(const QuicMaxStreamsFrame & frame)1814 bool QuicConnection::OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) {
1815 QUIC_BUG_IF(quic_bug_12714_13, !connected_)
1816 << "Processing MAX_STREAMS frame when connection is closed. Received "
1817 "packet info: "
1818 << last_received_packet_info_;
1819 if (!UpdatePacketContent(MAX_STREAMS_FRAME)) {
1820 return false;
1821 }
1822
1823 if (debug_visitor_ != nullptr) {
1824 debug_visitor_->OnMaxStreamsFrame(frame);
1825 }
1826 MaybeUpdateAckTimeout();
1827 return visitor_->OnMaxStreamsFrame(frame) && connected_;
1828 }
1829
OnStreamsBlockedFrame(const QuicStreamsBlockedFrame & frame)1830 bool QuicConnection::OnStreamsBlockedFrame(
1831 const QuicStreamsBlockedFrame& frame) {
1832 QUIC_BUG_IF(quic_bug_10511_11, !connected_)
1833 << "Processing STREAMS_BLOCKED frame when connection is closed. Received "
1834 "packet info: "
1835 << last_received_packet_info_;
1836 if (!UpdatePacketContent(STREAMS_BLOCKED_FRAME)) {
1837 return false;
1838 }
1839
1840 if (debug_visitor_ != nullptr) {
1841 debug_visitor_->OnStreamsBlockedFrame(frame);
1842 }
1843 MaybeUpdateAckTimeout();
1844 return visitor_->OnStreamsBlockedFrame(frame) && connected_;
1845 }
1846
OnGoAwayFrame(const QuicGoAwayFrame & frame)1847 bool QuicConnection::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
1848 QUIC_BUG_IF(quic_bug_12714_14, !connected_)
1849 << "Processing GOAWAY frame when connection is closed. Received packet "
1850 "info: "
1851 << last_received_packet_info_;
1852
1853 // Since a go away frame was received, this is not a connectivity probe.
1854 // A probe only contains a PING and full padding.
1855 if (!UpdatePacketContent(GOAWAY_FRAME)) {
1856 return false;
1857 }
1858
1859 if (debug_visitor_ != nullptr) {
1860 debug_visitor_->OnGoAwayFrame(frame);
1861 }
1862 QUIC_DLOG(INFO) << ENDPOINT << "GOAWAY_FRAME received with last good stream: "
1863 << frame.last_good_stream_id
1864 << " and error: " << QuicErrorCodeToString(frame.error_code)
1865 << " and reason: " << frame.reason_phrase;
1866 MaybeUpdateAckTimeout();
1867 visitor_->OnGoAway(frame);
1868 return connected_;
1869 }
1870
OnWindowUpdateFrame(const QuicWindowUpdateFrame & frame)1871 bool QuicConnection::OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) {
1872 QUIC_BUG_IF(quic_bug_10511_12, !connected_)
1873 << "Processing WINDOW_UPDATE frame when connection is closed. Received "
1874 "packet info: "
1875 << last_received_packet_info_;
1876
1877 // Since a window update frame was received, this is not a connectivity probe.
1878 // A probe only contains a PING and full padding.
1879 if (!UpdatePacketContent(WINDOW_UPDATE_FRAME)) {
1880 return false;
1881 }
1882
1883 if (debug_visitor_ != nullptr) {
1884 debug_visitor_->OnWindowUpdateFrame(
1885 frame, idle_network_detector_.time_of_last_received_packet());
1886 }
1887 QUIC_DVLOG(1) << ENDPOINT << "WINDOW_UPDATE_FRAME received " << frame;
1888 MaybeUpdateAckTimeout();
1889 visitor_->OnWindowUpdateFrame(frame);
1890 return connected_;
1891 }
1892
OnClientConnectionIdAvailable()1893 void QuicConnection::OnClientConnectionIdAvailable() {
1894 QUICHE_DCHECK(perspective_ == Perspective::IS_SERVER);
1895 if (!peer_issued_cid_manager_->HasUnusedConnectionId()) {
1896 return;
1897 }
1898 if (default_path_.client_connection_id.IsEmpty()) {
1899 const QuicConnectionIdData* unused_cid_data =
1900 peer_issued_cid_manager_->ConsumeOneUnusedConnectionId();
1901 QUIC_DVLOG(1) << ENDPOINT << "Patch connection ID "
1902 << unused_cid_data->connection_id << " to default path";
1903 default_path_.client_connection_id = unused_cid_data->connection_id;
1904 default_path_.stateless_reset_token =
1905 unused_cid_data->stateless_reset_token;
1906 QUICHE_DCHECK(!packet_creator_.HasPendingFrames());
1907 QUICHE_DCHECK(packet_creator_.GetDestinationConnectionId().IsEmpty());
1908 packet_creator_.SetClientConnectionId(default_path_.client_connection_id);
1909 return;
1910 }
1911 if (alternative_path_.peer_address.IsInitialized() &&
1912 alternative_path_.client_connection_id.IsEmpty()) {
1913 const QuicConnectionIdData* unused_cid_data =
1914 peer_issued_cid_manager_->ConsumeOneUnusedConnectionId();
1915 QUIC_DVLOG(1) << ENDPOINT << "Patch connection ID "
1916 << unused_cid_data->connection_id << " to alternative path";
1917 alternative_path_.client_connection_id = unused_cid_data->connection_id;
1918 alternative_path_.stateless_reset_token =
1919 unused_cid_data->stateless_reset_token;
1920 }
1921 }
1922
OnNewConnectionIdFrameInner(const QuicNewConnectionIdFrame & frame)1923 NewConnectionIdResult QuicConnection::OnNewConnectionIdFrameInner(
1924 const QuicNewConnectionIdFrame& frame) {
1925 if (peer_issued_cid_manager_ == nullptr) {
1926 CloseConnection(
1927 IETF_QUIC_PROTOCOL_VIOLATION,
1928 "Receives NEW_CONNECTION_ID while peer uses zero length connection ID",
1929 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1930 return NewConnectionIdResult::kProtocolViolation;
1931 }
1932 std::string error_detail;
1933 bool duplicate_new_connection_id = false;
1934 QuicErrorCode error = peer_issued_cid_manager_->OnNewConnectionIdFrame(
1935 frame, &error_detail, &duplicate_new_connection_id);
1936 if (error != QUIC_NO_ERROR) {
1937 CloseConnection(error, error_detail,
1938 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
1939 return NewConnectionIdResult::kProtocolViolation;
1940 }
1941 if (duplicate_new_connection_id) {
1942 return NewConnectionIdResult::kDuplicateFrame;
1943 }
1944 if (perspective_ == Perspective::IS_SERVER) {
1945 OnClientConnectionIdAvailable();
1946 }
1947 MaybeUpdateAckTimeout();
1948 return NewConnectionIdResult::kOk;
1949 }
1950
OnNewConnectionIdFrame(const QuicNewConnectionIdFrame & frame)1951 bool QuicConnection::OnNewConnectionIdFrame(
1952 const QuicNewConnectionIdFrame& frame) {
1953 QUICHE_DCHECK(version().HasIetfQuicFrames());
1954 QUIC_BUG_IF(quic_bug_10511_13, !connected_)
1955 << "Processing NEW_CONNECTION_ID frame when connection is closed. "
1956 "Received packet info: "
1957 << last_received_packet_info_;
1958 if (!UpdatePacketContent(NEW_CONNECTION_ID_FRAME)) {
1959 return false;
1960 }
1961
1962 if (debug_visitor_ != nullptr) {
1963 debug_visitor_->OnNewConnectionIdFrame(frame);
1964 }
1965
1966 NewConnectionIdResult result = OnNewConnectionIdFrameInner(frame);
1967 switch (result) {
1968 case NewConnectionIdResult::kOk:
1969 if (multi_port_stats_ != nullptr) {
1970 MaybeCreateMultiPortPath();
1971 }
1972 break;
1973 case NewConnectionIdResult::kProtocolViolation:
1974 return false;
1975 case NewConnectionIdResult::kDuplicateFrame:
1976 break;
1977 }
1978 return true;
1979 }
1980
OnRetireConnectionIdFrame(const QuicRetireConnectionIdFrame & frame)1981 bool QuicConnection::OnRetireConnectionIdFrame(
1982 const QuicRetireConnectionIdFrame& frame) {
1983 QUICHE_DCHECK(version().HasIetfQuicFrames());
1984 QUIC_BUG_IF(quic_bug_10511_14, !connected_)
1985 << "Processing RETIRE_CONNECTION_ID frame when connection is closed. "
1986 "Received packet info: "
1987 << last_received_packet_info_;
1988 if (!UpdatePacketContent(RETIRE_CONNECTION_ID_FRAME)) {
1989 return false;
1990 }
1991
1992 if (debug_visitor_ != nullptr) {
1993 debug_visitor_->OnRetireConnectionIdFrame(frame);
1994 }
1995 if (self_issued_cid_manager_ == nullptr) {
1996 CloseConnection(
1997 IETF_QUIC_PROTOCOL_VIOLATION,
1998 "Receives RETIRE_CONNECTION_ID while new connection ID is never issued",
1999 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2000 return false;
2001 }
2002 std::string error_detail;
2003 QuicErrorCode error = self_issued_cid_manager_->OnRetireConnectionIdFrame(
2004 frame, sent_packet_manager_.GetPtoDelay(), &error_detail);
2005 if (error != QUIC_NO_ERROR) {
2006 CloseConnection(error, error_detail,
2007 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2008 return false;
2009 }
2010 // Count successfully received RETIRE_CONNECTION_ID frames.
2011 MaybeUpdateAckTimeout();
2012 return true;
2013 }
2014
OnNewTokenFrame(const QuicNewTokenFrame & frame)2015 bool QuicConnection::OnNewTokenFrame(const QuicNewTokenFrame& frame) {
2016 QUIC_BUG_IF(quic_bug_12714_15, !connected_)
2017 << "Processing NEW_TOKEN frame when connection is closed. Received "
2018 "packet info: "
2019 << last_received_packet_info_;
2020 if (!UpdatePacketContent(NEW_TOKEN_FRAME)) {
2021 return false;
2022 }
2023
2024 if (debug_visitor_ != nullptr) {
2025 debug_visitor_->OnNewTokenFrame(frame);
2026 }
2027 if (perspective_ == Perspective::IS_SERVER) {
2028 CloseConnection(QUIC_INVALID_NEW_TOKEN, "Server received new token frame.",
2029 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2030 return false;
2031 }
2032 // NEW_TOKEN frame should insitgate ACKs.
2033 MaybeUpdateAckTimeout();
2034 visitor_->OnNewTokenReceived(frame.token);
2035 return true;
2036 }
2037
OnMessageFrame(const QuicMessageFrame & frame)2038 bool QuicConnection::OnMessageFrame(const QuicMessageFrame& frame) {
2039 QUIC_BUG_IF(quic_bug_12714_16, !connected_)
2040 << "Processing MESSAGE frame when connection is closed. Received packet "
2041 "info: "
2042 << last_received_packet_info_;
2043
2044 // Since a message frame was received, this is not a connectivity probe.
2045 // A probe only contains a PING and full padding.
2046 if (!UpdatePacketContent(MESSAGE_FRAME)) {
2047 return false;
2048 }
2049
2050 if (debug_visitor_ != nullptr) {
2051 debug_visitor_->OnMessageFrame(frame);
2052 }
2053 MaybeUpdateAckTimeout();
2054 visitor_->OnMessageReceived(
2055 absl::string_view(frame.data, frame.message_length));
2056 return connected_;
2057 }
2058
OnHandshakeDoneFrame(const QuicHandshakeDoneFrame & frame)2059 bool QuicConnection::OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) {
2060 QUIC_BUG_IF(quic_bug_10511_15, !connected_)
2061 << "Processing HANDSHAKE_DONE frame when connection "
2062 "is closed. Received packet "
2063 "info: "
2064 << last_received_packet_info_;
2065 if (!version().UsesTls()) {
2066 CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION,
2067 "Handshake done frame is unsupported",
2068 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2069 return false;
2070 }
2071
2072 if (perspective_ == Perspective::IS_SERVER) {
2073 CloseConnection(IETF_QUIC_PROTOCOL_VIOLATION,
2074 "Server received handshake done frame.",
2075 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2076 return false;
2077 }
2078
2079 // Since a handshake done frame was received, this is not a connectivity
2080 // probe. A probe only contains a PING and full padding.
2081 if (!UpdatePacketContent(HANDSHAKE_DONE_FRAME)) {
2082 return false;
2083 }
2084
2085 if (debug_visitor_ != nullptr) {
2086 debug_visitor_->OnHandshakeDoneFrame(frame);
2087 }
2088 MaybeUpdateAckTimeout();
2089 visitor_->OnHandshakeDoneReceived();
2090 return connected_;
2091 }
2092
OnAckFrequencyFrame(const QuicAckFrequencyFrame & frame)2093 bool QuicConnection::OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) {
2094 QUIC_BUG_IF(quic_bug_10511_16, !connected_)
2095 << "Processing ACK_FREQUENCY frame when connection "
2096 "is closed. Received packet "
2097 "info: "
2098 << last_received_packet_info_;
2099 if (debug_visitor_ != nullptr) {
2100 debug_visitor_->OnAckFrequencyFrame(frame);
2101 }
2102 if (!UpdatePacketContent(ACK_FREQUENCY_FRAME)) {
2103 return false;
2104 }
2105
2106 if (!can_receive_ack_frequency_frame_) {
2107 QUIC_LOG_EVERY_N_SEC(ERROR, 120) << "Get unexpected AckFrequencyFrame.";
2108 return false;
2109 }
2110 if (auto packet_number_space =
2111 QuicUtils::GetPacketNumberSpace(
2112 last_received_packet_info_.decrypted_level) == APPLICATION_DATA) {
2113 uber_received_packet_manager_.OnAckFrequencyFrame(frame);
2114 } else {
2115 QUIC_LOG_EVERY_N_SEC(ERROR, 120)
2116 << "Get AckFrequencyFrame in packet number space "
2117 << packet_number_space;
2118 }
2119 MaybeUpdateAckTimeout();
2120 return true;
2121 }
2122
OnBlockedFrame(const QuicBlockedFrame & frame)2123 bool QuicConnection::OnBlockedFrame(const QuicBlockedFrame& frame) {
2124 QUIC_BUG_IF(quic_bug_12714_17, !connected_)
2125 << "Processing BLOCKED frame when connection is closed. Received packet "
2126 "info: "
2127 << last_received_packet_info_;
2128
2129 // Since a blocked frame was received, this is not a connectivity probe.
2130 // A probe only contains a PING and full padding.
2131 if (!UpdatePacketContent(BLOCKED_FRAME)) {
2132 return false;
2133 }
2134
2135 if (debug_visitor_ != nullptr) {
2136 debug_visitor_->OnBlockedFrame(frame);
2137 }
2138 QUIC_DLOG(INFO) << ENDPOINT
2139 << "BLOCKED_FRAME received for stream: " << frame.stream_id;
2140 MaybeUpdateAckTimeout();
2141 visitor_->OnBlockedFrame(frame);
2142 stats_.blocked_frames_received++;
2143 return connected_;
2144 }
2145
OnPacketComplete()2146 void QuicConnection::OnPacketComplete() {
2147 // Don't do anything if this packet closed the connection.
2148 if (!connected_) {
2149 ClearLastFrames();
2150 return;
2151 }
2152
2153 if (IsCurrentPacketConnectivityProbing()) {
2154 QUICHE_DCHECK(!version().HasIetfQuicFrames() && !ignore_gquic_probing_);
2155 ++stats_.num_connectivity_probing_received;
2156 }
2157
2158 QUIC_DVLOG(1) << ENDPOINT << "Got"
2159 << (SupportsMultiplePacketNumberSpaces()
2160 ? (" " +
2161 EncryptionLevelToString(
2162 last_received_packet_info_.decrypted_level))
2163 : "")
2164 << " packet " << last_received_packet_info_.header.packet_number
2165 << " for "
2166 << GetServerConnectionIdAsRecipient(
2167 last_received_packet_info_.header, perspective_);
2168
2169 QUIC_DLOG_IF(INFO, current_packet_content_ == SECOND_FRAME_IS_PADDING)
2170 << ENDPOINT << "Received a padded PING packet. is_probing: "
2171 << IsCurrentPacketConnectivityProbing();
2172
2173 if (!version().HasIetfQuicFrames() && !ignore_gquic_probing_) {
2174 MaybeRespondToConnectivityProbingOrMigration();
2175 }
2176
2177 current_effective_peer_migration_type_ = NO_CHANGE;
2178
2179 // For IETF QUIC, it is guaranteed that TLS will give connection the
2180 // corresponding write key before read key. In other words, connection should
2181 // never process a packet while an ACK for it cannot be encrypted.
2182 if (!should_last_packet_instigate_acks_) {
2183 uber_received_packet_manager_.MaybeUpdateAckTimeout(
2184 should_last_packet_instigate_acks_,
2185 last_received_packet_info_.decrypted_level,
2186 last_received_packet_info_.header.packet_number,
2187 last_received_packet_info_.receipt_time, clock_->ApproximateNow(),
2188 sent_packet_manager_.GetRttStats());
2189 }
2190
2191 ClearLastFrames();
2192 CloseIfTooManyOutstandingSentPackets();
2193 }
2194
MaybeRespondToConnectivityProbingOrMigration()2195 void QuicConnection::MaybeRespondToConnectivityProbingOrMigration() {
2196 QUICHE_DCHECK(!version().HasIetfQuicFrames());
2197 if (IsCurrentPacketConnectivityProbing()) {
2198 visitor_->OnPacketReceived(last_received_packet_info_.destination_address,
2199 last_received_packet_info_.source_address,
2200 /*is_connectivity_probe=*/true);
2201 return;
2202 }
2203 if (perspective_ == Perspective::IS_CLIENT) {
2204 // This node is a client, notify that a speculative connectivity probing
2205 // packet has been received anyway.
2206 QUIC_DVLOG(1) << ENDPOINT
2207 << "Received a speculative connectivity probing packet for "
2208 << GetServerConnectionIdAsRecipient(
2209 last_received_packet_info_.header, perspective_)
2210 << " from ip:port: "
2211 << last_received_packet_info_.source_address.ToString()
2212 << " to ip:port: "
2213 << last_received_packet_info_.destination_address.ToString();
2214 visitor_->OnPacketReceived(last_received_packet_info_.destination_address,
2215 last_received_packet_info_.source_address,
2216 /*is_connectivity_probe=*/false);
2217 return;
2218 }
2219 }
2220
IsValidStatelessResetToken(const StatelessResetToken & token) const2221 bool QuicConnection::IsValidStatelessResetToken(
2222 const StatelessResetToken& token) const {
2223 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
2224 return default_path_.stateless_reset_token.has_value() &&
2225 QuicUtils::AreStatelessResetTokensEqual(
2226 token, *default_path_.stateless_reset_token);
2227 }
2228
OnAuthenticatedIetfStatelessResetPacket(const QuicIetfStatelessResetPacket &)2229 void QuicConnection::OnAuthenticatedIetfStatelessResetPacket(
2230 const QuicIetfStatelessResetPacket& /*packet*/) {
2231 // TODO(fayang): Add OnAuthenticatedIetfStatelessResetPacket to
2232 // debug_visitor_.
2233 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
2234
2235 if (!IsDefaultPath(last_received_packet_info_.destination_address,
2236 last_received_packet_info_.source_address)) {
2237 // This packet is received on a probing path. Do not close connection.
2238 if (IsAlternativePath(last_received_packet_info_.destination_address,
2239 GetEffectivePeerAddressFromCurrentPacket())) {
2240 QUIC_BUG_IF(quic_bug_12714_18, alternative_path_.validated)
2241 << "STATELESS_RESET received on alternate path after it's "
2242 "validated.";
2243 path_validator_.CancelPathValidation();
2244 } else {
2245 QUIC_BUG(quic_bug_10511_17)
2246 << "Received Stateless Reset on unknown socket.";
2247 }
2248 return;
2249 }
2250
2251 const std::string error_details = "Received stateless reset.";
2252 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_stateless_reset);
2253 TearDownLocalConnectionState(QUIC_PUBLIC_RESET, NO_IETF_QUIC_ERROR,
2254 error_details, ConnectionCloseSource::FROM_PEER);
2255 }
2256
OnKeyUpdate(KeyUpdateReason reason)2257 void QuicConnection::OnKeyUpdate(KeyUpdateReason reason) {
2258 QUICHE_DCHECK(support_key_update_for_connection_);
2259 QUIC_DLOG(INFO) << ENDPOINT << "Key phase updated for " << reason;
2260
2261 lowest_packet_sent_in_current_key_phase_.Clear();
2262 stats_.key_update_count++;
2263
2264 // If another key update triggers while the previous
2265 // discard_previous_one_rtt_keys_alarm_ hasn't fired yet, cancel it since the
2266 // old keys would already be discarded.
2267 discard_previous_one_rtt_keys_alarm_->Cancel();
2268
2269 visitor_->OnKeyUpdate(reason);
2270 }
2271
OnDecryptedFirstPacketInKeyPhase()2272 void QuicConnection::OnDecryptedFirstPacketInKeyPhase() {
2273 QUIC_DLOG(INFO) << ENDPOINT << "OnDecryptedFirstPacketInKeyPhase";
2274 // An endpoint SHOULD retain old read keys for no more than three times the
2275 // PTO after having received a packet protected using the new keys. After this
2276 // period, old read keys and their corresponding secrets SHOULD be discarded.
2277 //
2278 // Note that this will cause an unnecessary
2279 // discard_previous_one_rtt_keys_alarm_ on the first packet in the 1RTT
2280 // encryption level, but this is harmless.
2281 discard_previous_one_rtt_keys_alarm_->Set(
2282 clock_->ApproximateNow() + sent_packet_manager_.GetPtoDelay() * 3);
2283 }
2284
2285 std::unique_ptr<QuicDecrypter>
AdvanceKeysAndCreateCurrentOneRttDecrypter()2286 QuicConnection::AdvanceKeysAndCreateCurrentOneRttDecrypter() {
2287 QUIC_DLOG(INFO) << ENDPOINT << "AdvanceKeysAndCreateCurrentOneRttDecrypter";
2288 return visitor_->AdvanceKeysAndCreateCurrentOneRttDecrypter();
2289 }
2290
CreateCurrentOneRttEncrypter()2291 std::unique_ptr<QuicEncrypter> QuicConnection::CreateCurrentOneRttEncrypter() {
2292 QUIC_DLOG(INFO) << ENDPOINT << "CreateCurrentOneRttEncrypter";
2293 return visitor_->CreateCurrentOneRttEncrypter();
2294 }
2295
ClearLastFrames()2296 void QuicConnection::ClearLastFrames() {
2297 should_last_packet_instigate_acks_ = false;
2298 }
2299
CloseIfTooManyOutstandingSentPackets()2300 void QuicConnection::CloseIfTooManyOutstandingSentPackets() {
2301 // This occurs if we don't discard old packets we've seen fast enough. It's
2302 // possible largest observed is less than leaset unacked.
2303 const bool should_close =
2304 sent_packet_manager_.GetLargestSentPacket().IsInitialized() &&
2305 sent_packet_manager_.GetLargestSentPacket() >
2306 sent_packet_manager_.GetLeastUnacked() + max_tracked_packets_;
2307
2308 if (should_close) {
2309 CloseConnection(
2310 QUIC_TOO_MANY_OUTSTANDING_SENT_PACKETS,
2311 absl::StrCat("More than ", max_tracked_packets_,
2312 " outstanding, least_unacked: ",
2313 sent_packet_manager_.GetLeastUnacked().ToUint64(),
2314 ", packets_processed: ", stats_.packets_processed,
2315 ", last_decrypted_packet_level: ",
2316 EncryptionLevelToString(
2317 last_received_packet_info_.decrypted_level)),
2318 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2319 }
2320 }
2321
GetUpdatedAckFrame()2322 const QuicFrame QuicConnection::GetUpdatedAckFrame() {
2323 QUICHE_DCHECK(!uber_received_packet_manager_.IsAckFrameEmpty(
2324 QuicUtils::GetPacketNumberSpace(encryption_level_)))
2325 << "Try to retrieve an empty ACK frame";
2326 return uber_received_packet_manager_.GetUpdatedAckFrame(
2327 QuicUtils::GetPacketNumberSpace(encryption_level_),
2328 clock_->ApproximateNow());
2329 }
2330
GetLeastUnacked() const2331 QuicPacketNumber QuicConnection::GetLeastUnacked() const {
2332 return sent_packet_manager_.GetLeastUnacked();
2333 }
2334
HandleWriteBlocked()2335 bool QuicConnection::HandleWriteBlocked() {
2336 if (!writer_->IsWriteBlocked()) {
2337 return false;
2338 }
2339
2340 visitor_->OnWriteBlocked();
2341 return true;
2342 }
2343
MaybeSendInResponseToPacket()2344 void QuicConnection::MaybeSendInResponseToPacket() {
2345 if (!connected_) {
2346 return;
2347 }
2348
2349 if (IsMissingDestinationConnectionID()) {
2350 return;
2351 }
2352
2353 // If the writer is blocked, don't attempt to send packets now or in the send
2354 // alarm. When the writer unblocks, OnCanWrite() will be called for this
2355 // connection to send.
2356 if (HandleWriteBlocked()) {
2357 return;
2358 }
2359
2360 if (!defer_send_in_response_to_packets_) {
2361 WriteIfNotBlocked();
2362 return;
2363 }
2364
2365 if (!visitor_->WillingAndAbleToWrite()) {
2366 QUIC_DVLOG(1)
2367 << "No send alarm after processing packet. !WillingAndAbleToWrite.";
2368 return;
2369 }
2370
2371 // If the send alarm is already armed. Record its deadline in |max_deadline|
2372 // and cancel the alarm temporarily. The rest of this function will ensure
2373 // the alarm deadline is no later than |max_deadline| when the function exits.
2374 QuicTime max_deadline = QuicTime::Infinite();
2375 if (send_alarm_->IsSet()) {
2376 QUIC_DVLOG(1) << "Send alarm already set to " << send_alarm_->deadline();
2377 max_deadline = send_alarm_->deadline();
2378 send_alarm_->Cancel();
2379 }
2380
2381 if (CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2382 // Some data can be written immediately. Register for immediate resumption
2383 // so we'll keep writing after other connections.
2384 QUIC_BUG_IF(quic_send_alarm_set_with_data_to_send, send_alarm_->IsSet());
2385 QUIC_DVLOG(1) << "Immediate send alarm scheduled after processing packet.";
2386 send_alarm_->Set(clock_->ApproximateNow() +
2387 sent_packet_manager_.GetDeferredSendAlarmDelay());
2388 return;
2389 }
2390
2391 if (send_alarm_->IsSet()) {
2392 // Pacing limited: CanWrite returned false, and it has scheduled a send
2393 // alarm before it returns.
2394 if (send_alarm_->deadline() > max_deadline) {
2395 QUIC_BUG(quic_send_alarm_postponed)
2396 << "previous deadline:" << max_deadline
2397 << ", deadline from CanWrite:" << send_alarm_->deadline()
2398 << ", last_can_write_reason:"
2399 << static_cast<int>(last_can_write_reason_)
2400 << ", packets_sent_on_last_successful_can_write:"
2401 << packets_sent_on_last_successful_can_write_;
2402 QUIC_DVLOG(1) << "Send alarm restored after processing packet.";
2403 // Restore to the previous, earlier deadline.
2404 send_alarm_->Update(max_deadline, QuicTime::Delta::Zero());
2405 } else {
2406 QUIC_DVLOG(1) << "Future send alarm scheduled after processing packet.";
2407 }
2408 return;
2409 }
2410
2411 if (max_deadline != QuicTime::Infinite()) {
2412 QUIC_DVLOG(1) << "Send alarm restored after processing packet.";
2413 send_alarm_->Set(max_deadline);
2414 return;
2415 }
2416 // Can not send data due to other reasons: congestion blocked, anti
2417 // amplification throttled, etc.
2418 QUIC_DVLOG(1) << "No send alarm after processing packet. Other reasons.";
2419 }
2420
SendCryptoData(EncryptionLevel level,size_t write_length,QuicStreamOffset offset)2421 size_t QuicConnection::SendCryptoData(EncryptionLevel level,
2422 size_t write_length,
2423 QuicStreamOffset offset) {
2424 if (write_length == 0) {
2425 QUIC_BUG(quic_bug_10511_18) << "Attempt to send empty crypto frame";
2426 return 0;
2427 }
2428 ScopedPacketFlusher flusher(this);
2429 return packet_creator_.ConsumeCryptoData(level, write_length, offset);
2430 }
2431
SendStreamData(QuicStreamId id,size_t write_length,QuicStreamOffset offset,StreamSendingState state)2432 QuicConsumedData QuicConnection::SendStreamData(QuicStreamId id,
2433 size_t write_length,
2434 QuicStreamOffset offset,
2435 StreamSendingState state) {
2436 if (state == NO_FIN && write_length == 0) {
2437 QUIC_BUG(quic_bug_10511_19) << "Attempt to send empty stream frame";
2438 return QuicConsumedData(0, false);
2439 }
2440
2441 if (perspective_ == Perspective::IS_SERVER &&
2442 version().CanSendCoalescedPackets() && !IsHandshakeConfirmed()) {
2443 if (in_probe_time_out_ && coalesced_packet_.NumberOfPackets() == 0u) {
2444 // PTO fires while handshake is not confirmed. Do not preempt handshake
2445 // data with stream data.
2446 QUIC_CODE_COUNT(quic_try_to_send_half_rtt_data_when_pto_fires);
2447 return QuicConsumedData(0, false);
2448 }
2449 if (coalesced_packet_.ContainsPacketOfEncryptionLevel(ENCRYPTION_INITIAL) &&
2450 coalesced_packet_.NumberOfPackets() == 1u) {
2451 // Handshake is not confirmed yet, if there is only an initial packet in
2452 // the coalescer, try to bundle an ENCRYPTION_HANDSHAKE packet before
2453 // sending stream data.
2454 sent_packet_manager_.RetransmitDataOfSpaceIfAny(HANDSHAKE_DATA);
2455 }
2456 }
2457 // Opportunistically bundle an ack with every outgoing packet.
2458 // Particularly, we want to bundle with handshake packets since we don't
2459 // know which decrypter will be used on an ack packet following a handshake
2460 // packet (a handshake packet from client to server could result in a REJ or
2461 // a SHLO from the server, leading to two different decrypters at the
2462 // server.)
2463 ScopedPacketFlusher flusher(this);
2464 return packet_creator_.ConsumeData(id, write_length, offset, state);
2465 }
2466
SendControlFrame(const QuicFrame & frame)2467 bool QuicConnection::SendControlFrame(const QuicFrame& frame) {
2468 if (SupportsMultiplePacketNumberSpaces() &&
2469 (encryption_level_ == ENCRYPTION_INITIAL ||
2470 encryption_level_ == ENCRYPTION_HANDSHAKE) &&
2471 frame.type != PING_FRAME) {
2472 // Allow PING frame to be sent without APPLICATION key. For example, when
2473 // anti-amplification limit is used, client needs to send something to avoid
2474 // handshake deadlock.
2475 QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame
2476 << " at encryption level: " << encryption_level_;
2477 return false;
2478 }
2479 ScopedPacketFlusher flusher(this);
2480 const bool consumed =
2481 packet_creator_.ConsumeRetransmittableControlFrame(frame);
2482 if (!consumed) {
2483 QUIC_DVLOG(1) << ENDPOINT << "Failed to send control frame: " << frame;
2484 return false;
2485 }
2486 if (frame.type == PING_FRAME) {
2487 // Flush PING frame immediately.
2488 packet_creator_.FlushCurrentPacket();
2489 stats_.ping_frames_sent++;
2490 if (debug_visitor_ != nullptr) {
2491 debug_visitor_->OnPingSent();
2492 }
2493 }
2494 if (frame.type == BLOCKED_FRAME) {
2495 stats_.blocked_frames_sent++;
2496 }
2497 return true;
2498 }
2499
OnStreamReset(QuicStreamId id,QuicRstStreamErrorCode error)2500 void QuicConnection::OnStreamReset(QuicStreamId id,
2501 QuicRstStreamErrorCode error) {
2502 if (error == QUIC_STREAM_NO_ERROR) {
2503 // All data for streams which are reset with QUIC_STREAM_NO_ERROR must
2504 // be received by the peer.
2505 return;
2506 }
2507 // Flush stream frames of reset stream.
2508 if (packet_creator_.HasPendingStreamFramesOfStream(id)) {
2509 ScopedPacketFlusher flusher(this);
2510 packet_creator_.FlushCurrentPacket();
2511 }
2512 // TODO(ianswett): Consider checking for 3 RTOs when the last stream is
2513 // cancelled as well.
2514 }
2515
GetStats()2516 const QuicConnectionStats& QuicConnection::GetStats() {
2517 const RttStats* rtt_stats = sent_packet_manager_.GetRttStats();
2518
2519 // Update rtt and estimated bandwidth.
2520 QuicTime::Delta min_rtt = rtt_stats->min_rtt();
2521 if (min_rtt.IsZero()) {
2522 // If min RTT has not been set, use initial RTT instead.
2523 min_rtt = rtt_stats->initial_rtt();
2524 }
2525 stats_.min_rtt_us = min_rtt.ToMicroseconds();
2526
2527 QuicTime::Delta srtt = rtt_stats->SmoothedOrInitialRtt();
2528 stats_.srtt_us = srtt.ToMicroseconds();
2529
2530 stats_.estimated_bandwidth = sent_packet_manager_.BandwidthEstimate();
2531 sent_packet_manager_.GetSendAlgorithm()->PopulateConnectionStats(&stats_);
2532 stats_.egress_mtu = long_term_mtu_;
2533 stats_.ingress_mtu = largest_received_packet_size_;
2534 return stats_;
2535 }
2536
OnCoalescedPacket(const QuicEncryptedPacket & packet)2537 void QuicConnection::OnCoalescedPacket(const QuicEncryptedPacket& packet) {
2538 QueueCoalescedPacket(packet);
2539 }
2540
OnUndecryptablePacket(const QuicEncryptedPacket & packet,EncryptionLevel decryption_level,bool has_decryption_key)2541 void QuicConnection::OnUndecryptablePacket(const QuicEncryptedPacket& packet,
2542 EncryptionLevel decryption_level,
2543 bool has_decryption_key) {
2544 QUIC_DVLOG(1) << ENDPOINT << "Received undecryptable packet of length "
2545 << packet.length() << " with"
2546 << (has_decryption_key ? "" : "out") << " key at level "
2547 << decryption_level
2548 << " while connection is at encryption level "
2549 << encryption_level_;
2550 QUICHE_DCHECK(EncryptionLevelIsValid(decryption_level));
2551 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE) {
2552 ++stats_.undecryptable_packets_received_before_handshake_complete;
2553 }
2554
2555 const bool should_enqueue =
2556 ShouldEnqueueUnDecryptablePacket(decryption_level, has_decryption_key);
2557 if (should_enqueue) {
2558 QueueUndecryptablePacket(packet, decryption_level);
2559 }
2560
2561 if (debug_visitor_ != nullptr) {
2562 debug_visitor_->OnUndecryptablePacket(decryption_level,
2563 /*dropped=*/!should_enqueue);
2564 }
2565
2566 if (has_decryption_key) {
2567 stats_.num_failed_authentication_packets_received++;
2568 if (version().UsesTls()) {
2569 // Should always be non-null if has_decryption_key is true.
2570 QUICHE_DCHECK(framer_.GetDecrypter(decryption_level));
2571 const QuicPacketCount integrity_limit =
2572 framer_.GetDecrypter(decryption_level)->GetIntegrityLimit();
2573 QUIC_DVLOG(2) << ENDPOINT << "Checking AEAD integrity limits:"
2574 << " num_failed_authentication_packets_received="
2575 << stats_.num_failed_authentication_packets_received
2576 << " integrity_limit=" << integrity_limit;
2577 if (stats_.num_failed_authentication_packets_received >=
2578 integrity_limit) {
2579 const std::string error_details = absl::StrCat(
2580 "decrypter integrity limit reached:"
2581 " num_failed_authentication_packets_received=",
2582 stats_.num_failed_authentication_packets_received,
2583 " integrity_limit=", integrity_limit);
2584 CloseConnection(QUIC_AEAD_LIMIT_REACHED, error_details,
2585 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2586 }
2587 }
2588 }
2589
2590 if (version().UsesTls() && perspective_ == Perspective::IS_SERVER &&
2591 decryption_level == ENCRYPTION_ZERO_RTT && !has_decryption_key &&
2592 had_zero_rtt_decrypter_) {
2593 QUIC_CODE_COUNT_N(
2594 quic_server_received_tls_zero_rtt_packet_after_discarding_decrypter, 1,
2595 3);
2596 stats_
2597 .num_tls_server_zero_rtt_packets_received_after_discarding_decrypter++;
2598 }
2599 }
2600
ShouldEnqueueUnDecryptablePacket(EncryptionLevel decryption_level,bool has_decryption_key) const2601 bool QuicConnection::ShouldEnqueueUnDecryptablePacket(
2602 EncryptionLevel decryption_level, bool has_decryption_key) const {
2603 if (has_decryption_key) {
2604 // We already have the key for this decryption level, therefore no
2605 // future keys will allow it be decrypted.
2606 return false;
2607 }
2608 if (IsHandshakeComplete()) {
2609 // We do not expect to install any further keys.
2610 return false;
2611 }
2612 if (undecryptable_packets_.size() >= max_undecryptable_packets_) {
2613 // We do not queue more than max_undecryptable_packets_ packets.
2614 return false;
2615 }
2616 if (version().KnowsWhichDecrypterToUse() &&
2617 decryption_level == ENCRYPTION_INITIAL) {
2618 // When the corresponding decryption key is not available, all
2619 // non-Initial packets should be buffered until the handshake is complete.
2620 return false;
2621 }
2622 if (perspective_ == Perspective::IS_CLIENT && version().UsesTls() &&
2623 decryption_level == ENCRYPTION_ZERO_RTT) {
2624 // Only clients send Zero RTT packets in IETF QUIC.
2625 QUIC_PEER_BUG(quic_peer_bug_client_received_zero_rtt)
2626 << "Client received a Zero RTT packet, not buffering.";
2627 return false;
2628 }
2629 return true;
2630 }
2631
UndecryptablePacketsInfo() const2632 std::string QuicConnection::UndecryptablePacketsInfo() const {
2633 std::string info = absl::StrCat(
2634 "num_undecryptable_packets: ", undecryptable_packets_.size(), " {");
2635 for (const auto& packet : undecryptable_packets_) {
2636 absl::StrAppend(&info, "[",
2637 EncryptionLevelToString(packet.encryption_level), ", ",
2638 packet.packet->length(), "]");
2639 }
2640 absl::StrAppend(&info, "}");
2641 return info;
2642 }
2643
ProcessUdpPacket(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,const QuicReceivedPacket & packet)2644 void QuicConnection::ProcessUdpPacket(const QuicSocketAddress& self_address,
2645 const QuicSocketAddress& peer_address,
2646 const QuicReceivedPacket& packet) {
2647 if (!connected_) {
2648 return;
2649 }
2650 QUIC_DVLOG(2) << ENDPOINT << "Received encrypted " << packet.length()
2651 << " bytes:" << std::endl
2652 << quiche::QuicheTextUtils::HexDump(
2653 absl::string_view(packet.data(), packet.length()));
2654 QUIC_BUG_IF(quic_bug_12714_21, current_packet_data_ != nullptr)
2655 << "ProcessUdpPacket must not be called while processing a packet.";
2656 if (debug_visitor_ != nullptr) {
2657 debug_visitor_->OnPacketReceived(self_address, peer_address, packet);
2658 }
2659 last_received_packet_info_ =
2660 ReceivedPacketInfo(self_address, peer_address, packet.receipt_time(),
2661 packet.length(), packet.ecn_codepoint());
2662 current_packet_data_ = packet.data();
2663
2664 if (!default_path_.self_address.IsInitialized()) {
2665 default_path_.self_address = last_received_packet_info_.destination_address;
2666 } else if (default_path_.self_address != self_address &&
2667 sent_server_preferred_address_.IsInitialized() &&
2668 self_address.Normalized() ==
2669 sent_server_preferred_address_.Normalized()) {
2670 // If the packet is received at the preferred address, treat it as if it is
2671 // received on the original server address.
2672 last_received_packet_info_.destination_address = default_path_.self_address;
2673 last_received_packet_info_.actual_destination_address = self_address;
2674 }
2675
2676 if (!direct_peer_address_.IsInitialized()) {
2677 if (perspective_ == Perspective::IS_CLIENT) {
2678 AddKnownServerAddress(last_received_packet_info_.source_address);
2679 }
2680 UpdatePeerAddress(last_received_packet_info_.source_address);
2681 }
2682
2683 if (!default_path_.peer_address.IsInitialized()) {
2684 const QuicSocketAddress effective_peer_addr =
2685 GetEffectivePeerAddressFromCurrentPacket();
2686
2687 // The default path peer_address must be initialized at the beginning of the
2688 // first packet processed(here). If effective_peer_addr is uninitialized,
2689 // just set effective_peer_address_ to the direct peer address.
2690 default_path_.peer_address = effective_peer_addr.IsInitialized()
2691 ? effective_peer_addr
2692 : direct_peer_address_;
2693 }
2694
2695 stats_.bytes_received += packet.length();
2696 ++stats_.packets_received;
2697 if (IsDefaultPath(last_received_packet_info_.destination_address,
2698 last_received_packet_info_.source_address) &&
2699 EnforceAntiAmplificationLimit()) {
2700 last_received_packet_info_.received_bytes_counted = true;
2701 default_path_.bytes_received_before_address_validation +=
2702 last_received_packet_info_.length;
2703 }
2704
2705 // Ensure the time coming from the packet reader is within 2 minutes of now.
2706 if (std::abs((packet.receipt_time() - clock_->ApproximateNow()).ToSeconds()) >
2707 2 * 60) {
2708 QUIC_LOG(WARNING) << "(Formerly quic_bug_10511_21): Packet receipt time: "
2709 << packet.receipt_time().ToDebuggingValue()
2710 << " too far from current time: "
2711 << clock_->ApproximateNow().ToDebuggingValue();
2712 }
2713 QUIC_DVLOG(1) << ENDPOINT << "time of last received packet: "
2714 << packet.receipt_time().ToDebuggingValue() << " from peer "
2715 << last_received_packet_info_.source_address << ", to "
2716 << last_received_packet_info_.destination_address;
2717
2718 ScopedPacketFlusher flusher(this);
2719 if (!framer_.ProcessPacket(packet)) {
2720 // If we are unable to decrypt this packet, it might be
2721 // because the CHLO or SHLO packet was lost.
2722 QUIC_DVLOG(1) << ENDPOINT
2723 << "Unable to process packet. Last packet processed: "
2724 << last_received_packet_info_.header.packet_number;
2725 current_packet_data_ = nullptr;
2726 is_current_packet_connectivity_probing_ = false;
2727
2728 MaybeProcessCoalescedPackets();
2729 return;
2730 }
2731
2732 ++stats_.packets_processed;
2733
2734 QUIC_DLOG_IF(INFO, active_effective_peer_migration_type_ != NO_CHANGE)
2735 << "sent_packet_manager_.GetLargestObserved() = "
2736 << sent_packet_manager_.GetLargestObserved()
2737 << ", highest_packet_sent_before_effective_peer_migration_ = "
2738 << highest_packet_sent_before_effective_peer_migration_;
2739 if (!framer_.version().HasIetfQuicFrames() &&
2740 active_effective_peer_migration_type_ != NO_CHANGE &&
2741 sent_packet_manager_.GetLargestObserved().IsInitialized() &&
2742 (!highest_packet_sent_before_effective_peer_migration_.IsInitialized() ||
2743 sent_packet_manager_.GetLargestObserved() >
2744 highest_packet_sent_before_effective_peer_migration_)) {
2745 if (perspective_ == Perspective::IS_SERVER) {
2746 OnEffectivePeerMigrationValidated(/*is_migration_linkable=*/true);
2747 }
2748 }
2749
2750 if (!MaybeProcessCoalescedPackets()) {
2751 MaybeProcessUndecryptablePackets();
2752 MaybeSendInResponseToPacket();
2753 }
2754 SetPingAlarm();
2755 RetirePeerIssuedConnectionIdsNoLongerOnPath();
2756 current_packet_data_ = nullptr;
2757 is_current_packet_connectivity_probing_ = false;
2758 }
2759
OnBlockedWriterCanWrite()2760 void QuicConnection::OnBlockedWriterCanWrite() {
2761 writer_->SetWritable();
2762 OnCanWrite();
2763 }
2764
OnCanWrite()2765 void QuicConnection::OnCanWrite() {
2766 if (!connected_) {
2767 return;
2768 }
2769 if (writer_->IsWriteBlocked()) {
2770 const std::string error_details =
2771 "Writer is blocked while calling OnCanWrite.";
2772 QUIC_BUG(quic_bug_10511_22) << ENDPOINT << error_details;
2773 CloseConnection(QUIC_INTERNAL_ERROR, error_details,
2774 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
2775 return;
2776 }
2777
2778 ScopedPacketFlusher flusher(this);
2779
2780 WriteQueuedPackets();
2781 const QuicTime ack_timeout =
2782 uber_received_packet_manager_.GetEarliestAckTimeout();
2783 if (ack_timeout.IsInitialized() && ack_timeout <= clock_->ApproximateNow()) {
2784 // Send an ACK now because either 1) we were write blocked when we last
2785 // tried to send an ACK, or 2) both ack alarm and send alarm were set to
2786 // go off together.
2787 if (SupportsMultiplePacketNumberSpaces()) {
2788 SendAllPendingAcks();
2789 } else {
2790 SendAck();
2791 }
2792 }
2793
2794 // Sending queued packets may have caused the socket to become write blocked,
2795 // or the congestion manager to prohibit sending.
2796 if (!CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2797 return;
2798 }
2799
2800 // Tell the session it can write.
2801 visitor_->OnCanWrite();
2802
2803 // After the visitor writes, it may have caused the socket to become write
2804 // blocked or the congestion manager to prohibit sending, so check again.
2805 if (visitor_->WillingAndAbleToWrite() && !send_alarm_->IsSet() &&
2806 CanWrite(HAS_RETRANSMITTABLE_DATA)) {
2807 // We're not write blocked, but some data wasn't written. Register for
2808 // 'immediate' resumption so we'll keep writing after other connections.
2809 send_alarm_->Set(clock_->ApproximateNow());
2810 }
2811 }
2812
OnSendAlarm()2813 void QuicConnection::OnSendAlarm() { WriteIfNotBlocked(); }
2814
WriteIfNotBlocked()2815 void QuicConnection::WriteIfNotBlocked() {
2816 if (framer().is_processing_packet()) {
2817 QUIC_BUG(connection_write_mid_packet_processing)
2818 << ENDPOINT << "Tried to write in mid of packet processing";
2819 return;
2820 }
2821 if (IsMissingDestinationConnectionID()) {
2822 return;
2823 }
2824 if (!HandleWriteBlocked()) {
2825 OnCanWrite();
2826 }
2827 }
2828
MaybeClearQueuedPacketsOnPathChange()2829 void QuicConnection::MaybeClearQueuedPacketsOnPathChange() {
2830 if (version().HasIetfQuicFrames() && peer_issued_cid_manager_ != nullptr &&
2831 HasQueuedPackets()) {
2832 // Discard packets serialized with the connection ID on the old code path.
2833 // It is possible to clear queued packets only if connection ID changes.
2834 // However, the case where connection ID is unchanged and queued packets are
2835 // non-empty is quite rare.
2836 ClearQueuedPackets();
2837 }
2838 }
2839
ReplaceInitialServerConnectionId(const QuicConnectionId & new_server_connection_id)2840 void QuicConnection::ReplaceInitialServerConnectionId(
2841 const QuicConnectionId& new_server_connection_id) {
2842 QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT);
2843 if (version().HasIetfQuicFrames()) {
2844 if (new_server_connection_id.IsEmpty()) {
2845 peer_issued_cid_manager_ = nullptr;
2846 } else {
2847 if (peer_issued_cid_manager_ != nullptr) {
2848 QUIC_BUG_IF(quic_bug_12714_22,
2849 !peer_issued_cid_manager_->IsConnectionIdActive(
2850 default_path_.server_connection_id))
2851 << "Connection ID replaced header is no longer active. old id: "
2852 << default_path_.server_connection_id
2853 << " new_id: " << new_server_connection_id;
2854 peer_issued_cid_manager_->ReplaceConnectionId(
2855 default_path_.server_connection_id, new_server_connection_id);
2856 } else {
2857 peer_issued_cid_manager_ =
2858 std::make_unique<QuicPeerIssuedConnectionIdManager>(
2859 kMinNumOfActiveConnectionIds, new_server_connection_id, clock_,
2860 alarm_factory_, this, context());
2861 }
2862 }
2863 }
2864 default_path_.server_connection_id = new_server_connection_id;
2865 packet_creator_.SetServerConnectionId(default_path_.server_connection_id);
2866 }
2867
FindMatchingOrNewClientConnectionIdOrToken(const PathState & default_path,const PathState & alternative_path,const QuicConnectionId & server_connection_id,QuicConnectionId * client_connection_id,std::optional<StatelessResetToken> * stateless_reset_token)2868 void QuicConnection::FindMatchingOrNewClientConnectionIdOrToken(
2869 const PathState& default_path, const PathState& alternative_path,
2870 const QuicConnectionId& server_connection_id,
2871 QuicConnectionId* client_connection_id,
2872 std::optional<StatelessResetToken>* stateless_reset_token) {
2873 QUICHE_DCHECK(perspective_ == Perspective::IS_SERVER &&
2874 version().HasIetfQuicFrames());
2875 if (peer_issued_cid_manager_ == nullptr ||
2876 server_connection_id == default_path.server_connection_id) {
2877 *client_connection_id = default_path.client_connection_id;
2878 *stateless_reset_token = default_path.stateless_reset_token;
2879 return;
2880 }
2881 if (server_connection_id == alternative_path_.server_connection_id) {
2882 *client_connection_id = alternative_path.client_connection_id;
2883 *stateless_reset_token = alternative_path.stateless_reset_token;
2884 return;
2885 }
2886 auto* connection_id_data =
2887 peer_issued_cid_manager_->ConsumeOneUnusedConnectionId();
2888 if (connection_id_data == nullptr) {
2889 return;
2890 }
2891 *client_connection_id = connection_id_data->connection_id;
2892 *stateless_reset_token = connection_id_data->stateless_reset_token;
2893 }
2894
FindOnPathConnectionIds(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,QuicConnectionId * client_connection_id,QuicConnectionId * server_connection_id) const2895 bool QuicConnection::FindOnPathConnectionIds(
2896 const QuicSocketAddress& self_address,
2897 const QuicSocketAddress& peer_address,
2898 QuicConnectionId* client_connection_id,
2899 QuicConnectionId* server_connection_id) const {
2900 if (IsDefaultPath(self_address, peer_address)) {
2901 *client_connection_id = default_path_.client_connection_id,
2902 *server_connection_id = default_path_.server_connection_id;
2903 return true;
2904 }
2905 if (IsAlternativePath(self_address, peer_address)) {
2906 *client_connection_id = alternative_path_.client_connection_id,
2907 *server_connection_id = alternative_path_.server_connection_id;
2908 return true;
2909 }
2910 // Client should only send packets on either default or alternative path, so
2911 // it shouldn't fail here. If the server fail to find CID to use, no packet
2912 // will be generated on this path.
2913 // TODO(danzh) fix SendPathResponse() to respond to probes from a different
2914 // client port with non-Zero client CID.
2915 QUIC_BUG_IF(failed to find on path connection ids,
2916 perspective_ == Perspective::IS_CLIENT)
2917 << "Fails to find on path connection IDs";
2918 return false;
2919 }
2920
SetDefaultPathState(PathState new_path_state)2921 void QuicConnection::SetDefaultPathState(PathState new_path_state) {
2922 QUICHE_DCHECK(version().HasIetfQuicFrames());
2923 default_path_ = std::move(new_path_state);
2924 packet_creator_.SetClientConnectionId(default_path_.client_connection_id);
2925 packet_creator_.SetServerConnectionId(default_path_.server_connection_id);
2926 }
2927
ProcessValidatedPacket(const QuicPacketHeader & header)2928 bool QuicConnection::ProcessValidatedPacket(const QuicPacketHeader& header) {
2929 if (perspective_ == Perspective::IS_CLIENT && version().HasIetfQuicFrames() &&
2930 direct_peer_address_.IsInitialized() &&
2931 last_received_packet_info_.source_address.IsInitialized() &&
2932 direct_peer_address_ != last_received_packet_info_.source_address &&
2933 !IsKnownServerAddress(last_received_packet_info_.source_address)) {
2934 // Discard packets received from unseen server addresses.
2935 return false;
2936 }
2937
2938 if (perspective_ == Perspective::IS_SERVER &&
2939 default_path_.self_address.IsInitialized() &&
2940 last_received_packet_info_.destination_address.IsInitialized() &&
2941 default_path_.self_address !=
2942 last_received_packet_info_.destination_address) {
2943 // Allow change between pure IPv4 and equivalent mapped IPv4 address.
2944 if (default_path_.self_address.port() !=
2945 last_received_packet_info_.destination_address.port() ||
2946 default_path_.self_address.host().Normalized() !=
2947 last_received_packet_info_.destination_address.host()
2948 .Normalized()) {
2949 if (!visitor_->AllowSelfAddressChange()) {
2950 const std::string error_details = absl::StrCat(
2951 "Self address migration is not supported at the server, current "
2952 "address: ",
2953 default_path_.self_address.ToString(),
2954 ", server preferred address: ",
2955 sent_server_preferred_address_.ToString(),
2956 ", received packet address: ",
2957 last_received_packet_info_.destination_address.ToString(),
2958 ", size: ", last_received_packet_info_.length,
2959 ", packet number: ", header.packet_number.ToString(),
2960 ", encryption level: ",
2961 EncryptionLevelToString(
2962 last_received_packet_info_.decrypted_level));
2963 QUIC_LOG_EVERY_N_SEC(INFO, 100) << error_details;
2964 QUIC_CODE_COUNT(quic_dropped_packets_with_changed_server_address);
2965 return false;
2966 }
2967 }
2968 default_path_.self_address = last_received_packet_info_.destination_address;
2969 }
2970
2971 if (GetQuicReloadableFlag(quic_use_received_client_addresses_cache) &&
2972 perspective_ == Perspective::IS_SERVER &&
2973 !last_received_packet_info_.actual_destination_address.IsInitialized() &&
2974 last_received_packet_info_.source_address.IsInitialized()) {
2975 QUIC_RELOADABLE_FLAG_COUNT(quic_use_received_client_addresses_cache);
2976 // Record client address of packets received on server original address.
2977 received_client_addresses_cache_.Insert(
2978 last_received_packet_info_.source_address,
2979 std::make_unique<bool>(true));
2980 }
2981
2982 if (perspective_ == Perspective::IS_SERVER &&
2983 last_received_packet_info_.actual_destination_address.IsInitialized() &&
2984 !IsHandshakeConfirmed() &&
2985 GetEffectivePeerAddressFromCurrentPacket() !=
2986 default_path_.peer_address) {
2987 // Our client implementation has an optimization to spray packets from
2988 // different sockets to the server's preferred address before handshake
2989 // gets confirmed. In this case, do not kick off client address migration
2990 // detection.
2991 QUICHE_DCHECK(sent_server_preferred_address_.IsInitialized());
2992 last_received_packet_info_.source_address = direct_peer_address_;
2993 }
2994
2995 if (PacketCanReplaceServerConnectionId(header, perspective_) &&
2996 default_path_.server_connection_id != header.source_connection_id) {
2997 QUICHE_DCHECK_EQ(header.long_packet_type, INITIAL);
2998 if (server_connection_id_replaced_by_initial_) {
2999 QUIC_DLOG(ERROR) << ENDPOINT << "Refusing to replace connection ID "
3000 << default_path_.server_connection_id << " with "
3001 << header.source_connection_id;
3002 return false;
3003 }
3004 server_connection_id_replaced_by_initial_ = true;
3005 QUIC_DLOG(INFO) << ENDPOINT << "Replacing connection ID "
3006 << default_path_.server_connection_id << " with "
3007 << header.source_connection_id;
3008 if (!original_destination_connection_id_.has_value()) {
3009 original_destination_connection_id_ = default_path_.server_connection_id;
3010 }
3011 ReplaceInitialServerConnectionId(header.source_connection_id);
3012 }
3013
3014 if (!ValidateReceivedPacketNumber(header.packet_number)) {
3015 return false;
3016 }
3017
3018 if (!version_negotiated_) {
3019 if (perspective_ == Perspective::IS_CLIENT) {
3020 QUICHE_DCHECK(!header.version_flag || header.form != GOOGLE_QUIC_PACKET);
3021 version_negotiated_ = true;
3022 OnSuccessfulVersionNegotiation();
3023 }
3024 }
3025
3026 if (last_received_packet_info_.length > largest_received_packet_size_) {
3027 largest_received_packet_size_ = last_received_packet_info_.length;
3028 }
3029
3030 if (perspective_ == Perspective::IS_SERVER &&
3031 encryption_level_ == ENCRYPTION_INITIAL &&
3032 last_received_packet_info_.length > packet_creator_.max_packet_length()) {
3033 if (GetQuicFlag(quic_use_lower_server_response_mtu_for_test)) {
3034 SetMaxPacketLength(
3035 std::min(last_received_packet_info_.length, QuicByteCount(1250)));
3036 } else {
3037 SetMaxPacketLength(last_received_packet_info_.length);
3038 }
3039 }
3040 return true;
3041 }
3042
ValidateReceivedPacketNumber(QuicPacketNumber packet_number)3043 bool QuicConnection::ValidateReceivedPacketNumber(
3044 QuicPacketNumber packet_number) {
3045 // If this packet has already been seen, or the sender has told us that it
3046 // will not be retransmitted, then stop processing the packet.
3047 if (!uber_received_packet_manager_.IsAwaitingPacket(
3048 last_received_packet_info_.decrypted_level, packet_number)) {
3049 QUIC_DLOG(INFO) << ENDPOINT << "Packet " << packet_number
3050 << " no longer being waited for at level "
3051 << static_cast<int>(
3052 last_received_packet_info_.decrypted_level)
3053 << ". Discarding.";
3054 if (debug_visitor_ != nullptr) {
3055 debug_visitor_->OnDuplicatePacket(packet_number);
3056 }
3057 return false;
3058 }
3059
3060 return true;
3061 }
3062
WriteQueuedPackets()3063 void QuicConnection::WriteQueuedPackets() {
3064 QUICHE_DCHECK(!writer_->IsWriteBlocked());
3065 QUIC_CLIENT_HISTOGRAM_COUNTS("QuicSession.NumQueuedPacketsBeforeWrite",
3066 buffered_packets_.size(), 1, 1000, 50, "");
3067
3068 while (!buffered_packets_.empty()) {
3069 if (HandleWriteBlocked()) {
3070 break;
3071 }
3072 const BufferedPacket& packet = buffered_packets_.front();
3073 WriteResult result = SendPacketToWriter(
3074 packet.data.get(), packet.length, packet.self_address.host(),
3075 packet.peer_address, writer_, packet.ecn_codepoint);
3076 QUIC_DVLOG(1) << ENDPOINT << "Sending buffered packet, result: " << result;
3077 if (IsMsgTooBig(writer_, result) && packet.length > long_term_mtu_) {
3078 // When MSG_TOO_BIG is returned, the system typically knows what the
3079 // actual MTU is, so there is no need to probe further.
3080 // TODO(wub): Reduce max packet size to a safe default, or the actual MTU.
3081 mtu_discoverer_.Disable();
3082 mtu_discovery_alarm_->Cancel();
3083 buffered_packets_.pop_front();
3084 continue;
3085 }
3086 if (IsWriteError(result.status)) {
3087 OnWriteError(result.error_code);
3088 break;
3089 }
3090 if (result.status == WRITE_STATUS_OK ||
3091 result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
3092 buffered_packets_.pop_front();
3093 }
3094 if (IsWriteBlockedStatus(result.status)) {
3095 visitor_->OnWriteBlocked();
3096 break;
3097 }
3098 }
3099 }
3100
MarkZeroRttPacketsForRetransmission(int reject_reason)3101 void QuicConnection::MarkZeroRttPacketsForRetransmission(int reject_reason) {
3102 sent_packet_manager_.MarkZeroRttPacketsForRetransmission();
3103 if (debug_visitor_ != nullptr && version().UsesTls()) {
3104 debug_visitor_->OnZeroRttRejected(reject_reason);
3105 }
3106 }
3107
NeuterUnencryptedPackets()3108 void QuicConnection::NeuterUnencryptedPackets() {
3109 sent_packet_manager_.NeuterUnencryptedPackets();
3110 // This may have changed the retransmission timer, so re-arm it.
3111 SetRetransmissionAlarm();
3112 if (default_enable_5rto_blackhole_detection_) {
3113 QUIC_RELOADABLE_FLAG_COUNT_N(quic_default_enable_5rto_blackhole_detection2,
3114 1, 3);
3115 // Consider this as forward progress since this is called when initial key
3116 // gets discarded (or previous unencrypted data is not needed anymore).
3117 OnForwardProgressMade();
3118 }
3119 if (SupportsMultiplePacketNumberSpaces()) {
3120 // Stop sending ack of initial packet number space.
3121 uber_received_packet_manager_.ResetAckStates(ENCRYPTION_INITIAL);
3122 // Re-arm ack alarm.
3123 ack_alarm_->Update(uber_received_packet_manager_.GetEarliestAckTimeout(),
3124 kAlarmGranularity);
3125 }
3126 }
3127
IsMissingDestinationConnectionID() const3128 bool QuicConnection::IsMissingDestinationConnectionID() const {
3129 return peer_issued_cid_manager_ != nullptr &&
3130 packet_creator_.GetDestinationConnectionId().IsEmpty();
3131 }
3132
ShouldGeneratePacket(HasRetransmittableData retransmittable,IsHandshake handshake)3133 bool QuicConnection::ShouldGeneratePacket(
3134 HasRetransmittableData retransmittable, IsHandshake handshake) {
3135 QUICHE_DCHECK(handshake != IS_HANDSHAKE ||
3136 QuicVersionUsesCryptoFrames(transport_version()))
3137 << ENDPOINT
3138 << "Handshake in STREAM frames should not check ShouldGeneratePacket";
3139 if (IsMissingDestinationConnectionID()) {
3140 QUICHE_DCHECK(version().HasIetfQuicFrames());
3141 QUIC_CODE_COUNT(quic_generate_packet_blocked_by_no_connection_id);
3142 QUIC_BUG_IF(quic_bug_90265_1, perspective_ == Perspective::IS_CLIENT);
3143 QUIC_DLOG(INFO) << ENDPOINT
3144 << "There is no destination connection ID available to "
3145 "generate packet.";
3146 return false;
3147 }
3148 if (IsDefaultPath(default_path_.self_address,
3149 packet_creator_.peer_address())) {
3150 return CanWrite(retransmittable);
3151 }
3152 // This is checking on the alternative path with a different peer address. The
3153 // self address and the writer used are the same as the default path. In the
3154 // case of different self address and writer, writing packet would use a
3155 // differnt code path without checking the states of the default writer.
3156 return connected_ && !HandleWriteBlocked();
3157 }
3158
MaybeBundleOpportunistically()3159 void QuicConnection::MaybeBundleOpportunistically() {
3160 if (!ack_frequency_sent_ && sent_packet_manager_.CanSendAckFrequency()) {
3161 if (packet_creator_.NextSendingPacketNumber() >=
3162 FirstSendingPacketNumber() + kMinReceivedBeforeAckDecimation) {
3163 QUIC_RELOADABLE_FLAG_COUNT_N(quic_can_send_ack_frequency, 3, 3);
3164 ack_frequency_sent_ = true;
3165 auto frame = sent_packet_manager_.GetUpdatedAckFrequencyFrame();
3166 visitor_->SendAckFrequency(frame);
3167 }
3168 }
3169
3170 if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data2)) {
3171 QUIC_RESTART_FLAG_COUNT_N(quic_opport_bundle_qpack_decoder_data2, 1, 4);
3172 visitor_->MaybeBundleOpportunistically();
3173 }
3174
3175 if (packet_creator_.has_ack() || !CanWrite(NO_RETRANSMITTABLE_DATA)) {
3176 return;
3177 }
3178
3179 QuicFrames frames;
3180 const bool has_pending_ack =
3181 uber_received_packet_manager_
3182 .GetAckTimeout(QuicUtils::GetPacketNumberSpace(encryption_level_))
3183 .IsInitialized();
3184 if (!has_pending_ack) {
3185 // No need to send an ACK.
3186 return;
3187 }
3188 ResetAckStates();
3189
3190 QUIC_DVLOG(1) << ENDPOINT << "Bundle an ACK opportunistically";
3191 QuicFrame updated_ack_frame = GetUpdatedAckFrame();
3192 QUIC_BUG_IF(quic_bug_12714_23, updated_ack_frame.ack_frame->packets.Empty())
3193 << ENDPOINT << "Attempted to opportunistically bundle an empty "
3194 << encryption_level_ << " ACK, " << (has_pending_ack ? "" : "!")
3195 << "has_pending_ack";
3196 frames.push_back(updated_ack_frame);
3197
3198 const bool flushed = packet_creator_.FlushAckFrame(frames);
3199 QUIC_BUG_IF(failed_to_flush_ack, !flushed)
3200 << ENDPOINT << "Failed to flush ACK frame";
3201 }
3202
RecordLastCanWriteReason(LastCanWriteReason reason)3203 void QuicConnection::RecordLastCanWriteReason(LastCanWriteReason reason) {
3204 last_can_write_reason_ = reason;
3205 packets_sent_on_last_successful_can_write_ = stats_.packets_sent;
3206 }
3207
CanWrite(HasRetransmittableData retransmittable)3208 bool QuicConnection::CanWrite(HasRetransmittableData retransmittable) {
3209 if (!connected_) {
3210 return false;
3211 }
3212
3213 if (IsMissingDestinationConnectionID()) {
3214 return false;
3215 }
3216
3217 if (version().CanSendCoalescedPackets() &&
3218 framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL) &&
3219 framer_.is_processing_packet()) {
3220 // While we still have initial keys, suppress sending in mid of packet
3221 // processing.
3222 // TODO(fayang): always suppress sending while in the mid of packet
3223 // processing.
3224 QUIC_DVLOG(1) << ENDPOINT
3225 << "Suppress sending in the mid of packet processing";
3226 return false;
3227 }
3228
3229 if (fill_coalesced_packet_) {
3230 // Try to coalesce packet, only allow to write when creator is on soft max
3231 // packet length. Given the next created packet is going to fill current
3232 // coalesced packet, do not check amplification factor.
3233 if (packet_creator_.HasSoftMaxPacketLength()) {
3234 RecordLastCanWriteReason(LAST_CAN_WRITE_REASON_COALESCE_PACKET);
3235 }
3236 return packet_creator_.HasSoftMaxPacketLength();
3237 }
3238
3239 if (sent_packet_manager_.pending_timer_transmission_count() > 0) {
3240 // Allow sending if there are pending tokens, which occurs when:
3241 // 1) firing PTO,
3242 // 2) bundling CRYPTO data with ACKs,
3243 // 3) coalescing CRYPTO data of higher space.
3244 RecordLastCanWriteReason(LAST_CAN_WRITE_REASON_PENDING_TIMER);
3245 return true;
3246 }
3247
3248 if (LimitedByAmplificationFactor(packet_creator_.max_packet_length())) {
3249 // Server is constrained by the amplification restriction.
3250 QUIC_CODE_COUNT(quic_throttled_by_amplification_limit);
3251 QUIC_DVLOG(1) << ENDPOINT
3252 << "Constrained by amplification restriction to peer address "
3253 << default_path_.peer_address << " bytes received "
3254 << default_path_.bytes_received_before_address_validation
3255 << ", bytes sent"
3256 << default_path_.bytes_sent_before_address_validation;
3257 ++stats_.num_amplification_throttling;
3258 return false;
3259 }
3260
3261 if (HandleWriteBlocked()) {
3262 return false;
3263 }
3264
3265 // Allow acks and probing frames to be sent immediately.
3266 if (retransmittable == NO_RETRANSMITTABLE_DATA) {
3267 RecordLastCanWriteReason(LAST_CAN_WRITE_REASON_NO_RETRANSMITTABLE_DATA);
3268 return true;
3269 }
3270 // If the send alarm is set, wait for it to fire.
3271 if (send_alarm_->IsSet()) {
3272 return false;
3273 }
3274
3275 QuicTime now = clock_->Now();
3276 QuicTime::Delta delay = sent_packet_manager_.TimeUntilSend(now);
3277 if (delay.IsInfinite()) {
3278 send_alarm_->Cancel();
3279 return false;
3280 }
3281
3282 // Scheduler requires a delay.
3283 if (!delay.IsZero()) {
3284 if (delay <= release_time_into_future_) {
3285 // Required delay is within pace time into future, send now.
3286 RecordLastCanWriteReason(LAST_CAN_WRITE_REASON_DELAY_WITHIN_RELEASE_TIME);
3287 return true;
3288 }
3289 // Cannot send packet now because delay is too far in the future.
3290 send_alarm_->Update(now + delay, kAlarmGranularity);
3291 QUIC_DVLOG(1) << ENDPOINT << "Delaying sending " << delay.ToMilliseconds()
3292 << "ms";
3293 return false;
3294 }
3295
3296 RecordLastCanWriteReason(LAST_CAN_WRITE_REASON_NO_DELAY);
3297 return true;
3298 }
3299
CalculatePacketSentTime()3300 QuicTime QuicConnection::CalculatePacketSentTime() {
3301 const QuicTime now = clock_->Now();
3302 if (!supports_release_time_) {
3303 // Don't change the release delay.
3304 return now;
3305 }
3306
3307 auto next_release_time_result = sent_packet_manager_.GetNextReleaseTime();
3308
3309 // Release before |now| is impossible.
3310 QuicTime next_release_time =
3311 std::max(now, next_release_time_result.release_time);
3312 packet_writer_params_.release_time_delay = next_release_time - now;
3313 packet_writer_params_.allow_burst = next_release_time_result.allow_burst;
3314 return next_release_time;
3315 }
3316
WritePacket(SerializedPacket * packet)3317 bool QuicConnection::WritePacket(SerializedPacket* packet) {
3318 if (sent_packet_manager_.GetLargestSentPacket().IsInitialized() &&
3319 packet->packet_number < sent_packet_manager_.GetLargestSentPacket()) {
3320 QUIC_BUG(quic_bug_10511_23)
3321 << "Attempt to write packet:" << packet->packet_number
3322 << " after:" << sent_packet_manager_.GetLargestSentPacket();
3323 CloseConnection(QUIC_INTERNAL_ERROR, "Packet written out of order.",
3324 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
3325 return true;
3326 }
3327 const bool is_mtu_discovery = QuicUtils::ContainsFrameType(
3328 packet->nonretransmittable_frames, MTU_DISCOVERY_FRAME);
3329 const SerializedPacketFate fate = packet->fate;
3330 // Termination packets are encrypted and saved, so don't exit early.
3331 QuicErrorCode error_code = QUIC_NO_ERROR;
3332 const bool is_termination_packet = IsTerminationPacket(*packet, &error_code);
3333 QuicPacketNumber packet_number = packet->packet_number;
3334 QuicPacketLength encrypted_length = packet->encrypted_length;
3335 // Termination packets are eventually owned by TimeWaitListManager.
3336 // Others are deleted at the end of this call.
3337 if (is_termination_packet) {
3338 if (termination_packets_ == nullptr) {
3339 termination_packets_.reset(
3340 new std::vector<std::unique_ptr<QuicEncryptedPacket>>);
3341 }
3342 // Copy the buffer so it's owned in the future.
3343 char* buffer_copy = CopyBuffer(*packet);
3344 termination_packets_->emplace_back(
3345 new QuicEncryptedPacket(buffer_copy, encrypted_length, true));
3346 if (error_code == QUIC_SILENT_IDLE_TIMEOUT) {
3347 QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_);
3348 // TODO(fayang): populate histogram indicating the time elapsed from this
3349 // connection gets closed to following client packets get received.
3350 QUIC_DVLOG(1) << ENDPOINT
3351 << "Added silent connection close to termination packets, "
3352 "num of termination packets: "
3353 << termination_packets_->size();
3354 return true;
3355 }
3356 }
3357
3358 QUICHE_DCHECK_LE(encrypted_length, kMaxOutgoingPacketSize);
3359 QUICHE_DCHECK(is_mtu_discovery ||
3360 encrypted_length <= packet_creator_.max_packet_length())
3361 << " encrypted_length=" << encrypted_length
3362 << " > packet_creator max_packet_length="
3363 << packet_creator_.max_packet_length();
3364 QUIC_DVLOG(1) << ENDPOINT << "Sending packet " << packet_number << " : "
3365 << (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA
3366 ? "data bearing "
3367 : " ack or probing only ")
3368 << ", encryption level: " << packet->encryption_level
3369 << ", encrypted length:" << encrypted_length
3370 << ", fate: " << fate << " to peer " << packet->peer_address;
3371 QUIC_DVLOG(2) << ENDPOINT << packet->encryption_level << " packet number "
3372 << packet_number << " of length " << encrypted_length << ": "
3373 << std::endl
3374 << quiche::QuicheTextUtils::HexDump(absl::string_view(
3375 packet->encrypted_buffer, encrypted_length));
3376
3377 // Measure the RTT from before the write begins to avoid underestimating the
3378 // min_rtt_, especially in cases where the thread blocks or gets swapped out
3379 // during the WritePacket below.
3380 QuicTime packet_send_time = CalculatePacketSentTime();
3381 WriteResult result(WRITE_STATUS_OK, encrypted_length);
3382 QuicSocketAddress send_to_address = packet->peer_address;
3383 QuicSocketAddress send_from_address = self_address();
3384 if (perspective_ == Perspective::IS_SERVER &&
3385 sent_server_preferred_address_.IsInitialized() &&
3386 received_client_addresses_cache_.Lookup(send_to_address) ==
3387 received_client_addresses_cache_.end()) {
3388 // Given server has not received packets from send_to_address to
3389 // self_address(), most NATs do not allow packets from self_address() to
3390 // send_to_address to go through. Override packet's self address to
3391 // sent_server_preferred_address_.
3392 // TODO(b/262386897): server should validate reverse path before changing
3393 // self address of packets to send.
3394 send_from_address = sent_server_preferred_address_;
3395 }
3396 // Self address is always the default self address on this code path.
3397 const bool send_on_current_path = send_to_address == peer_address();
3398 if (!send_on_current_path) {
3399 QUIC_BUG_IF(quic_send_non_probing_frames_on_alternative_path,
3400 ContainsNonProbingFrame(*packet))
3401 << "Packet " << packet->packet_number
3402 << " with non-probing frames was sent on alternative path: "
3403 "nonretransmittable_frames: "
3404 << QuicFramesToString(packet->nonretransmittable_frames)
3405 << " retransmittable_frames: "
3406 << QuicFramesToString(packet->retransmittable_frames);
3407 }
3408 switch (fate) {
3409 case DISCARD:
3410 ++stats_.packets_discarded;
3411 if (debug_visitor_ != nullptr) {
3412 debug_visitor_->OnPacketDiscarded(*packet);
3413 }
3414 return true;
3415 case COALESCE:
3416 QUIC_BUG_IF(quic_bug_12714_24,
3417 !version().CanSendCoalescedPackets() || coalescing_done_);
3418 if (!coalesced_packet_.MaybeCoalescePacket(
3419 *packet, send_from_address, send_to_address,
3420 helper_->GetStreamSendBufferAllocator(),
3421 packet_creator_.max_packet_length(),
3422 GetEcnCodepointToSend(send_to_address))) {
3423 // Failed to coalesce packet, flush current coalesced packet.
3424 if (!FlushCoalescedPacket()) {
3425 QUIC_BUG_IF(quic_connection_connected_after_flush_coalesced_failure,
3426 connected_)
3427 << "QUIC connection is still connected after failing to flush "
3428 "coalesced packet.";
3429 // Failed to flush coalesced packet, write error has been handled.
3430 return false;
3431 }
3432 if (!coalesced_packet_.MaybeCoalescePacket(
3433 *packet, send_from_address, send_to_address,
3434 helper_->GetStreamSendBufferAllocator(),
3435 packet_creator_.max_packet_length(),
3436 GetEcnCodepointToSend(send_to_address))) {
3437 // Failed to coalesce packet even it is the only packet, raise a write
3438 // error.
3439 QUIC_DLOG(ERROR) << ENDPOINT << "Failed to coalesce packet";
3440 result.error_code = WRITE_STATUS_FAILED_TO_COALESCE_PACKET;
3441 break;
3442 }
3443 }
3444 if (coalesced_packet_.length() < coalesced_packet_.max_packet_length()) {
3445 QUIC_DVLOG(1) << ENDPOINT << "Trying to set soft max packet length to "
3446 << coalesced_packet_.max_packet_length() -
3447 coalesced_packet_.length();
3448 packet_creator_.SetSoftMaxPacketLength(
3449 coalesced_packet_.max_packet_length() - coalesced_packet_.length());
3450 }
3451 last_ecn_codepoint_sent_ = coalesced_packet_.ecn_codepoint();
3452 break;
3453 case BUFFER:
3454 QUIC_DVLOG(1) << ENDPOINT << "Adding packet: " << packet->packet_number
3455 << " to buffered packets";
3456 last_ecn_codepoint_sent_ = GetEcnCodepointToSend(send_to_address);
3457 buffered_packets_.emplace_back(*packet, send_from_address,
3458 send_to_address, last_ecn_codepoint_sent_);
3459 break;
3460 case SEND_TO_WRITER:
3461 // Stop using coalescer from now on.
3462 coalescing_done_ = true;
3463 // At this point, packet->release_encrypted_buffer is either nullptr,
3464 // meaning |packet->encrypted_buffer| is a stack buffer, or not-nullptr,
3465 /// meaning it's a writer-allocated buffer. Note that connectivity probing
3466 // packets do not use this function, so setting release_encrypted_buffer
3467 // to nullptr will not cause probing packets to be leaked.
3468 //
3469 // writer_->WritePacket transfers buffer ownership back to the writer.
3470 packet->release_encrypted_buffer = nullptr;
3471 result = SendPacketToWriter(
3472 packet->encrypted_buffer, encrypted_length, send_from_address.host(),
3473 send_to_address, writer_, GetEcnCodepointToSend(send_to_address));
3474 // This is a work around for an issue with linux UDP GSO batch writers.
3475 // When sending a GSO packet with 2 segments, if the first segment is
3476 // larger than the path MTU, instead of EMSGSIZE, the linux kernel returns
3477 // EINVAL, which translates to WRITE_STATUS_ERROR and causes conneciton to
3478 // be closed. By manually flush the writer here, the MTU probe is sent in
3479 // a normal(non-GSO) packet, so the kernel can return EMSGSIZE and we will
3480 // not close the connection.
3481 if (is_mtu_discovery && writer_->IsBatchMode()) {
3482 result = writer_->Flush();
3483 }
3484 break;
3485 default:
3486 QUICHE_DCHECK(false);
3487 break;
3488 }
3489
3490 QUIC_HISTOGRAM_ENUM(
3491 "QuicConnection.WritePacketStatus", result.status,
3492 WRITE_STATUS_NUM_VALUES,
3493 "Status code returned by writer_->WritePacket() in QuicConnection.");
3494
3495 if (IsWriteBlockedStatus(result.status)) {
3496 // Ensure the writer is still write blocked, otherwise QUIC may continue
3497 // trying to write when it will not be able to.
3498 QUICHE_DCHECK(writer_->IsWriteBlocked());
3499 visitor_->OnWriteBlocked();
3500 // If the socket buffers the data, then the packet should not
3501 // be queued and sent again, which would result in an unnecessary
3502 // duplicate packet being sent. The helper must call OnCanWrite
3503 // when the write completes, and OnWriteError if an error occurs.
3504 if (result.status != WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
3505 QUIC_DVLOG(1) << ENDPOINT << "Adding packet: " << packet->packet_number
3506 << " to buffered packets";
3507 buffered_packets_.emplace_back(*packet, send_from_address,
3508 send_to_address, last_ecn_codepoint_sent_);
3509 }
3510 }
3511
3512 // In some cases, an MTU probe can cause EMSGSIZE. This indicates that the
3513 // MTU discovery is permanently unsuccessful.
3514 if (IsMsgTooBig(writer_, result)) {
3515 if (is_mtu_discovery) {
3516 // When MSG_TOO_BIG is returned, the system typically knows what the
3517 // actual MTU is, so there is no need to probe further.
3518 // TODO(wub): Reduce max packet size to a safe default, or the actual MTU.
3519 QUIC_DVLOG(1) << ENDPOINT
3520 << " MTU probe packet too big, size:" << encrypted_length
3521 << ", long_term_mtu_:" << long_term_mtu_;
3522 mtu_discoverer_.Disable();
3523 mtu_discovery_alarm_->Cancel();
3524 // The write failed, but the writer is not blocked, so return true.
3525 return true;
3526 }
3527 if (!send_on_current_path) {
3528 // Only handle MSG_TOO_BIG as error on current path.
3529 return true;
3530 }
3531 }
3532
3533 if (IsWriteError(result.status)) {
3534 QUIC_LOG_FIRST_N(ERROR, 10)
3535 << ENDPOINT << "Failed writing packet " << packet_number << " of "
3536 << encrypted_length << " bytes from " << send_from_address.host()
3537 << " to " << send_to_address << ", with error code "
3538 << result.error_code << ". long_term_mtu_:" << long_term_mtu_
3539 << ", previous_validated_mtu_:" << previous_validated_mtu_
3540 << ", max_packet_length():" << max_packet_length()
3541 << ", is_mtu_discovery:" << is_mtu_discovery;
3542 if (MaybeRevertToPreviousMtu()) {
3543 return true;
3544 }
3545
3546 OnWriteError(result.error_code);
3547 return false;
3548 }
3549
3550 if (result.status == WRITE_STATUS_OK) {
3551 // packet_send_time is the ideal send time, if allow_burst is true, writer
3552 // may have sent it earlier than that.
3553 packet_send_time = packet_send_time + result.send_time_offset;
3554 }
3555
3556 if (IsRetransmittable(*packet) == HAS_RETRANSMITTABLE_DATA &&
3557 !is_termination_packet) {
3558 // Start blackhole/path degrading detections if the sent packet is not
3559 // termination packet and contains retransmittable data.
3560 // Do not restart detection if detection is in progress indicating no
3561 // forward progress has been made since last event (i.e., packet was sent
3562 // or new packets were acknowledged).
3563 if (!blackhole_detector_.IsDetectionInProgress()) {
3564 // Try to start detections if no detection in progress. This could
3565 // because either both detections are inactive when sending last packet
3566 // or this connection just gets out of quiescence.
3567 blackhole_detector_.RestartDetection(GetPathDegradingDeadline(),
3568 GetNetworkBlackholeDeadline(),
3569 GetPathMtuReductionDeadline());
3570 }
3571 idle_network_detector_.OnPacketSent(packet_send_time,
3572 sent_packet_manager_.GetPtoDelay());
3573 }
3574
3575 MaybeSetMtuAlarm(packet_number);
3576 QUIC_DVLOG(1) << ENDPOINT << "time we began writing last sent packet: "
3577 << packet_send_time.ToDebuggingValue();
3578
3579 if (IsDefaultPath(default_path_.self_address, send_to_address)) {
3580 if (EnforceAntiAmplificationLimit()) {
3581 // Include bytes sent even if they are not in flight.
3582 default_path_.bytes_sent_before_address_validation += encrypted_length;
3583 }
3584 } else {
3585 MaybeUpdateBytesSentToAlternativeAddress(send_to_address, encrypted_length);
3586 }
3587
3588 // Do not measure rtt of this packet if it's not sent on current path.
3589 QUIC_DLOG_IF(INFO, !send_on_current_path)
3590 << ENDPOINT << " Sent packet " << packet->packet_number
3591 << " on a different path with remote address " << send_to_address
3592 << " while current path has peer address " << peer_address();
3593 const bool in_flight = sent_packet_manager_.OnPacketSent(
3594 packet, packet_send_time, packet->transmission_type,
3595 IsRetransmittable(*packet), /*measure_rtt=*/send_on_current_path,
3596 last_ecn_codepoint_sent_);
3597 QUIC_BUG_IF(quic_bug_12714_25,
3598 perspective_ == Perspective::IS_SERVER &&
3599 default_enable_5rto_blackhole_detection_ &&
3600 blackhole_detector_.IsDetectionInProgress() &&
3601 !sent_packet_manager_.HasInFlightPackets())
3602 << ENDPOINT
3603 << "Trying to start blackhole detection without no bytes in flight";
3604
3605 if (debug_visitor_ != nullptr) {
3606 if (sent_packet_manager_.unacked_packets().empty()) {
3607 QUIC_BUG(quic_bug_10511_25)
3608 << "Unacked map is empty right after packet is sent";
3609 } else {
3610 debug_visitor_->OnPacketSent(
3611 packet->packet_number, packet->encrypted_length,
3612 packet->has_crypto_handshake, packet->transmission_type,
3613 packet->encryption_level,
3614 sent_packet_manager_.unacked_packets()
3615 .rbegin()
3616 ->retransmittable_frames,
3617 packet->nonretransmittable_frames, packet_send_time, result.batch_id);
3618 }
3619 }
3620 if (packet->encryption_level == ENCRYPTION_HANDSHAKE) {
3621 handshake_packet_sent_ = true;
3622 }
3623
3624 if (packet->encryption_level == ENCRYPTION_FORWARD_SECURE) {
3625 if (!lowest_packet_sent_in_current_key_phase_.IsInitialized()) {
3626 QUIC_DLOG(INFO) << ENDPOINT
3627 << "lowest_packet_sent_in_current_key_phase_ = "
3628 << packet_number;
3629 lowest_packet_sent_in_current_key_phase_ = packet_number;
3630 }
3631 if (!is_termination_packet &&
3632 MaybeHandleAeadConfidentialityLimits(*packet)) {
3633 return true;
3634 }
3635 }
3636 if (in_flight || !retransmission_alarm_->IsSet()) {
3637 SetRetransmissionAlarm();
3638 }
3639 SetPingAlarm();
3640 RetirePeerIssuedConnectionIdsNoLongerOnPath();
3641
3642 // The packet number length must be updated after OnPacketSent, because it
3643 // may change the packet number length in packet.
3644 packet_creator_.UpdatePacketNumberLength(
3645 sent_packet_manager_.GetLeastPacketAwaitedByPeer(encryption_level_),
3646 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
3647
3648 stats_.bytes_sent += encrypted_length;
3649 ++stats_.packets_sent;
3650 if (packet->has_ack_ecn) {
3651 stats_.num_ack_frames_sent_with_ecn++;
3652 }
3653
3654 QuicByteCount bytes_not_retransmitted =
3655 packet->bytes_not_retransmitted.value_or(0);
3656 if (packet->transmission_type != NOT_RETRANSMISSION) {
3657 if (static_cast<uint64_t>(encrypted_length) < bytes_not_retransmitted) {
3658 QUIC_BUG(quic_packet_bytes_written_lt_bytes_not_retransmitted)
3659 << "Total bytes written to the packet should be larger than the "
3660 "bytes in not-retransmitted frames. Bytes written: "
3661 << encrypted_length
3662 << ", bytes not retransmitted: " << bytes_not_retransmitted;
3663 } else {
3664 // bytes_retransmitted includes packet's headers and encryption
3665 // overhead.
3666 stats_.bytes_retransmitted +=
3667 (encrypted_length - bytes_not_retransmitted);
3668 }
3669 ++stats_.packets_retransmitted;
3670 }
3671
3672 return true;
3673 }
3674
MaybeHandleAeadConfidentialityLimits(const SerializedPacket & packet)3675 bool QuicConnection::MaybeHandleAeadConfidentialityLimits(
3676 const SerializedPacket& packet) {
3677 if (!version().UsesTls()) {
3678 return false;
3679 }
3680
3681 if (packet.encryption_level != ENCRYPTION_FORWARD_SECURE) {
3682 QUIC_BUG(quic_bug_12714_26)
3683 << "MaybeHandleAeadConfidentialityLimits called on non 1-RTT packet";
3684 return false;
3685 }
3686 if (!lowest_packet_sent_in_current_key_phase_.IsInitialized()) {
3687 QUIC_BUG(quic_bug_10511_26)
3688 << "lowest_packet_sent_in_current_key_phase_ must be initialized "
3689 "before calling MaybeHandleAeadConfidentialityLimits";
3690 return false;
3691 }
3692
3693 // Calculate the number of packets encrypted from the packet number, which is
3694 // simpler than keeping another counter. The packet number space may be
3695 // sparse, so this might overcount, but doing a key update earlier than
3696 // necessary would only improve security and has negligible cost.
3697 if (packet.packet_number < lowest_packet_sent_in_current_key_phase_) {
3698 const std::string error_details =
3699 absl::StrCat("packet_number(", packet.packet_number.ToString(),
3700 ") < lowest_packet_sent_in_current_key_phase_ (",
3701 lowest_packet_sent_in_current_key_phase_.ToString(), ")");
3702 QUIC_BUG(quic_bug_10511_27) << error_details;
3703 CloseConnection(QUIC_INTERNAL_ERROR, error_details,
3704 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
3705 return true;
3706 }
3707 const QuicPacketCount num_packets_encrypted_in_current_key_phase =
3708 packet.packet_number - lowest_packet_sent_in_current_key_phase_ + 1;
3709
3710 const QuicPacketCount confidentiality_limit =
3711 framer_.GetOneRttEncrypterConfidentialityLimit();
3712
3713 // Attempt to initiate a key update before reaching the AEAD
3714 // confidentiality limit when the number of packets sent in the current
3715 // key phase gets within |kKeyUpdateConfidentialityLimitOffset| packets of
3716 // the limit, unless overridden by
3717 // FLAGS_quic_key_update_confidentiality_limit.
3718 constexpr QuicPacketCount kKeyUpdateConfidentialityLimitOffset = 1000;
3719 QuicPacketCount key_update_limit = 0;
3720 if (confidentiality_limit > kKeyUpdateConfidentialityLimitOffset) {
3721 key_update_limit =
3722 confidentiality_limit - kKeyUpdateConfidentialityLimitOffset;
3723 }
3724 const QuicPacketCount key_update_limit_override =
3725 GetQuicFlag(quic_key_update_confidentiality_limit);
3726 if (key_update_limit_override) {
3727 key_update_limit = key_update_limit_override;
3728 }
3729
3730 QUIC_DVLOG(2) << ENDPOINT << "Checking AEAD confidentiality limits: "
3731 << "num_packets_encrypted_in_current_key_phase="
3732 << num_packets_encrypted_in_current_key_phase
3733 << " key_update_limit=" << key_update_limit
3734 << " confidentiality_limit=" << confidentiality_limit
3735 << " IsKeyUpdateAllowed()=" << IsKeyUpdateAllowed();
3736
3737 if (num_packets_encrypted_in_current_key_phase >= confidentiality_limit) {
3738 // Reached the confidentiality limit without initiating a key update,
3739 // must close the connection.
3740 const std::string error_details = absl::StrCat(
3741 "encrypter confidentiality limit reached: "
3742 "num_packets_encrypted_in_current_key_phase=",
3743 num_packets_encrypted_in_current_key_phase,
3744 " key_update_limit=", key_update_limit,
3745 " confidentiality_limit=", confidentiality_limit,
3746 " IsKeyUpdateAllowed()=", IsKeyUpdateAllowed());
3747 CloseConnection(QUIC_AEAD_LIMIT_REACHED, error_details,
3748 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
3749 return true;
3750 }
3751
3752 if (IsKeyUpdateAllowed() &&
3753 num_packets_encrypted_in_current_key_phase >= key_update_limit) {
3754 // Approaching the confidentiality limit, initiate key update so that
3755 // the next set of keys will be ready for the next packet before the
3756 // limit is reached.
3757 KeyUpdateReason reason = KeyUpdateReason::kLocalAeadConfidentialityLimit;
3758 if (key_update_limit_override) {
3759 QUIC_DLOG(INFO) << ENDPOINT
3760 << "reached FLAGS_quic_key_update_confidentiality_limit, "
3761 "initiating key update: "
3762 << "num_packets_encrypted_in_current_key_phase="
3763 << num_packets_encrypted_in_current_key_phase
3764 << " key_update_limit=" << key_update_limit
3765 << " confidentiality_limit=" << confidentiality_limit;
3766 reason = KeyUpdateReason::kLocalKeyUpdateLimitOverride;
3767 } else {
3768 QUIC_DLOG(INFO) << ENDPOINT
3769 << "approaching AEAD confidentiality limit, "
3770 "initiating key update: "
3771 << "num_packets_encrypted_in_current_key_phase="
3772 << num_packets_encrypted_in_current_key_phase
3773 << " key_update_limit=" << key_update_limit
3774 << " confidentiality_limit=" << confidentiality_limit;
3775 }
3776 InitiateKeyUpdate(reason);
3777 }
3778
3779 return false;
3780 }
3781
FlushPackets()3782 void QuicConnection::FlushPackets() {
3783 if (!connected_) {
3784 return;
3785 }
3786
3787 if (!writer_->IsBatchMode()) {
3788 return;
3789 }
3790
3791 if (HandleWriteBlocked()) {
3792 QUIC_DLOG(INFO) << ENDPOINT << "FlushPackets called while blocked.";
3793 return;
3794 }
3795
3796 WriteResult result = writer_->Flush();
3797
3798 QUIC_HISTOGRAM_ENUM("QuicConnection.FlushPacketStatus", result.status,
3799 WRITE_STATUS_NUM_VALUES,
3800 "Status code returned by writer_->Flush() in "
3801 "QuicConnection::FlushPackets.");
3802
3803 if (HandleWriteBlocked()) {
3804 QUICHE_DCHECK_EQ(WRITE_STATUS_BLOCKED, result.status)
3805 << "Unexpected flush result:" << result;
3806 QUIC_DLOG(INFO) << ENDPOINT << "Write blocked in FlushPackets.";
3807 return;
3808 }
3809
3810 if (IsWriteError(result.status) && !MaybeRevertToPreviousMtu()) {
3811 OnWriteError(result.error_code);
3812 }
3813 }
3814
IsMsgTooBig(const QuicPacketWriter * writer,const WriteResult & result)3815 bool QuicConnection::IsMsgTooBig(const QuicPacketWriter* writer,
3816 const WriteResult& result) {
3817 std::optional<int> writer_error_code = writer->MessageTooBigErrorCode();
3818 return (result.status == WRITE_STATUS_MSG_TOO_BIG) ||
3819 (writer_error_code.has_value() && IsWriteError(result.status) &&
3820 result.error_code == *writer_error_code);
3821 }
3822
ShouldDiscardPacket(EncryptionLevel encryption_level)3823 bool QuicConnection::ShouldDiscardPacket(EncryptionLevel encryption_level) {
3824 if (!connected_) {
3825 QUIC_DLOG(INFO) << ENDPOINT
3826 << "Not sending packet as connection is disconnected.";
3827 return true;
3828 }
3829
3830 if (encryption_level_ == ENCRYPTION_FORWARD_SECURE &&
3831 encryption_level == ENCRYPTION_INITIAL) {
3832 // Drop packets that are NULL encrypted since the peer won't accept them
3833 // anymore.
3834 QUIC_DLOG(INFO) << ENDPOINT
3835 << "Dropping NULL encrypted packet since the connection is "
3836 "forward secure.";
3837 return true;
3838 }
3839
3840 return false;
3841 }
3842
GetPathMtuReductionDeadline() const3843 QuicTime QuicConnection::GetPathMtuReductionDeadline() const {
3844 if (previous_validated_mtu_ == 0) {
3845 return QuicTime::Zero();
3846 }
3847 QuicTime::Delta delay = sent_packet_manager_.GetMtuReductionDelay(
3848 num_rtos_for_blackhole_detection_);
3849 if (delay.IsZero()) {
3850 return QuicTime::Zero();
3851 }
3852 return clock_->ApproximateNow() + delay;
3853 }
3854
MaybeRevertToPreviousMtu()3855 bool QuicConnection::MaybeRevertToPreviousMtu() {
3856 if (previous_validated_mtu_ == 0) {
3857 return false;
3858 }
3859
3860 SetMaxPacketLength(previous_validated_mtu_);
3861 mtu_discoverer_.Disable();
3862 mtu_discovery_alarm_->Cancel();
3863 previous_validated_mtu_ = 0;
3864 return true;
3865 }
3866
OnWriteError(int error_code)3867 void QuicConnection::OnWriteError(int error_code) {
3868 if (write_error_occurred_) {
3869 // A write error already occurred. The connection is being closed.
3870 return;
3871 }
3872 write_error_occurred_ = true;
3873
3874 const std::string error_details = absl::StrCat(
3875 "Write failed with error: ", error_code, " (", strerror(error_code), ")");
3876 QUIC_LOG_FIRST_N(ERROR, 2) << ENDPOINT << error_details;
3877 std::optional<int> writer_error_code = writer_->MessageTooBigErrorCode();
3878 if (writer_error_code.has_value() && error_code == *writer_error_code) {
3879 CloseConnection(QUIC_PACKET_WRITE_ERROR, error_details,
3880 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
3881 return;
3882 }
3883 // We can't send an error as the socket is presumably borked.
3884 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_write_error_ietf);
3885 CloseConnection(QUIC_PACKET_WRITE_ERROR, error_details,
3886 ConnectionCloseBehavior::SILENT_CLOSE);
3887 }
3888
GetPacketBuffer()3889 QuicPacketBuffer QuicConnection::GetPacketBuffer() {
3890 if (version().CanSendCoalescedPackets() && !coalescing_done_) {
3891 // Do not use writer's packet buffer for coalesced packets which may
3892 // contain multiple QUIC packets.
3893 return {nullptr, nullptr};
3894 }
3895 return writer_->GetNextWriteLocation(self_address().host(), peer_address());
3896 }
3897
OnSerializedPacket(SerializedPacket serialized_packet)3898 void QuicConnection::OnSerializedPacket(SerializedPacket serialized_packet) {
3899 if (serialized_packet.encrypted_buffer == nullptr) {
3900 // We failed to serialize the packet, so close the connection.
3901 // Specify that the close is silent, that no packet be sent, so no infinite
3902 // loop here.
3903 // TODO(ianswett): This is actually an internal error, not an
3904 // encryption failure.
3905 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_serialized_packet_ietf);
3906 CloseConnection(QUIC_ENCRYPTION_FAILURE,
3907 "Serialized packet does not have an encrypted buffer.",
3908 ConnectionCloseBehavior::SILENT_CLOSE);
3909 return;
3910 }
3911
3912 if (serialized_packet.retransmittable_frames.empty()) {
3913 // Increment consecutive_num_packets_with_no_retransmittable_frames_ if
3914 // this packet is a new transmission with no retransmittable frames.
3915 ++consecutive_num_packets_with_no_retransmittable_frames_;
3916 } else {
3917 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
3918 }
3919 if (retransmittable_on_wire_behavior_ == SEND_FIRST_FORWARD_SECURE_PACKET &&
3920 first_serialized_one_rtt_packet_ == nullptr &&
3921 serialized_packet.encryption_level == ENCRYPTION_FORWARD_SECURE) {
3922 first_serialized_one_rtt_packet_ = std::make_unique<BufferedPacket>(
3923 serialized_packet, self_address(), peer_address(),
3924 GetEcnCodepointToSend(peer_address()));
3925 }
3926 SendOrQueuePacket(std::move(serialized_packet));
3927 }
3928
OnUnrecoverableError(QuicErrorCode error,const std::string & error_details)3929 void QuicConnection::OnUnrecoverableError(QuicErrorCode error,
3930 const std::string& error_details) {
3931 // The packet creator or generator encountered an unrecoverable error: tear
3932 // down local connection state immediately.
3933 QUIC_CODE_COUNT(quic_tear_down_local_connection_on_unrecoverable_error_ietf);
3934 CloseConnection(error, error_details, ConnectionCloseBehavior::SILENT_CLOSE);
3935 }
3936
OnCongestionChange()3937 void QuicConnection::OnCongestionChange() {
3938 visitor_->OnCongestionWindowChange(clock_->ApproximateNow());
3939
3940 // Uses the connection's smoothed RTT. If zero, uses initial_rtt.
3941 QuicTime::Delta rtt = sent_packet_manager_.GetRttStats()->smoothed_rtt();
3942 if (rtt.IsZero()) {
3943 rtt = sent_packet_manager_.GetRttStats()->initial_rtt();
3944 }
3945
3946 if (debug_visitor_ != nullptr) {
3947 debug_visitor_->OnRttChanged(rtt);
3948 }
3949 }
3950
OnPathMtuIncreased(QuicPacketLength packet_size)3951 void QuicConnection::OnPathMtuIncreased(QuicPacketLength packet_size) {
3952 if (packet_size > max_packet_length()) {
3953 previous_validated_mtu_ = max_packet_length();
3954 SetMaxPacketLength(packet_size);
3955 mtu_discoverer_.OnMaxPacketLengthUpdated(previous_validated_mtu_,
3956 max_packet_length());
3957 }
3958 }
3959
OnInFlightEcnPacketAcked()3960 void QuicConnection::OnInFlightEcnPacketAcked() {
3961 QUIC_BUG_IF(quic_bug_518619343_01, !GetQuicReloadableFlag(quic_send_ect1))
3962 << "Unexpected call to OnInFlightEcnPacketAcked()";
3963 // Only packets on the default path are in-flight.
3964 if (!default_path_.ecn_marked_packet_acked) {
3965 QUIC_DVLOG(1) << ENDPOINT << "First ECT packet acked on active path.";
3966 QUIC_RELOADABLE_FLAG_COUNT_N(quic_send_ect1, 2, 8);
3967 default_path_.ecn_marked_packet_acked = true;
3968 }
3969 }
3970
OnInvalidEcnFeedback()3971 void QuicConnection::OnInvalidEcnFeedback() {
3972 QUIC_BUG_IF(quic_bug_518619343_02, !GetQuicReloadableFlag(quic_send_ect1))
3973 << "Unexpected call to OnInvalidEcnFeedback().";
3974 if (disable_ecn_codepoint_validation_) {
3975 // In some tests, senders may send ECN marks in patterns that are not
3976 // in accordance with the spec, and should not fail validation as a result.
3977 return;
3978 }
3979 QUIC_DVLOG(1) << ENDPOINT << "ECN feedback is invalid, stop marking.";
3980 packet_writer_params_.ecn_codepoint = ECN_NOT_ECT;
3981 }
3982
3983 std::unique_ptr<QuicSelfIssuedConnectionIdManager>
MakeSelfIssuedConnectionIdManager()3984 QuicConnection::MakeSelfIssuedConnectionIdManager() {
3985 QUICHE_DCHECK((perspective_ == Perspective::IS_CLIENT &&
3986 !default_path_.client_connection_id.IsEmpty()) ||
3987 (perspective_ == Perspective::IS_SERVER &&
3988 !default_path_.server_connection_id.IsEmpty()));
3989 return std::make_unique<QuicSelfIssuedConnectionIdManager>(
3990 kMinNumOfActiveConnectionIds,
3991 perspective_ == Perspective::IS_CLIENT
3992 ? default_path_.client_connection_id
3993 : default_path_.server_connection_id,
3994 clock_, alarm_factory_, this, context(), connection_id_generator_);
3995 }
3996
MaybeSendConnectionIdToClient()3997 void QuicConnection::MaybeSendConnectionIdToClient() {
3998 if (perspective_ == Perspective::IS_CLIENT) {
3999 return;
4000 }
4001 QUICHE_DCHECK(self_issued_cid_manager_ != nullptr);
4002 self_issued_cid_manager_->MaybeSendNewConnectionIds();
4003 }
4004
OnHandshakeComplete()4005 void QuicConnection::OnHandshakeComplete() {
4006 sent_packet_manager_.SetHandshakeConfirmed();
4007 if (version().HasIetfQuicFrames() && perspective_ == Perspective::IS_SERVER &&
4008 self_issued_cid_manager_ != nullptr) {
4009 self_issued_cid_manager_->MaybeSendNewConnectionIds();
4010 }
4011 if (send_ack_frequency_on_handshake_completion_ &&
4012 sent_packet_manager_.CanSendAckFrequency()) {
4013 QUIC_RELOADABLE_FLAG_COUNT_N(quic_can_send_ack_frequency, 2, 3);
4014 auto ack_frequency_frame =
4015 sent_packet_manager_.GetUpdatedAckFrequencyFrame();
4016 // This AckFrequencyFrame is meant to only update the max_ack_delay. Set
4017 // packet tolerance to the default value for now.
4018 ack_frequency_frame.packet_tolerance =
4019 kDefaultRetransmittablePacketsBeforeAck;
4020 visitor_->SendAckFrequency(ack_frequency_frame);
4021 if (!connected_) {
4022 return;
4023 }
4024 }
4025 // This may have changed the retransmission timer, so re-arm it.
4026 SetRetransmissionAlarm();
4027 if (default_enable_5rto_blackhole_detection_) {
4028 QUIC_RELOADABLE_FLAG_COUNT_N(quic_default_enable_5rto_blackhole_detection2,
4029 2, 3);
4030 OnForwardProgressMade();
4031 }
4032 if (!SupportsMultiplePacketNumberSpaces()) {
4033 // The client should immediately ack the SHLO to confirm the handshake is
4034 // complete with the server.
4035 if (perspective_ == Perspective::IS_CLIENT && ack_frame_updated()) {
4036 ack_alarm_->Update(clock_->ApproximateNow(), QuicTime::Delta::Zero());
4037 }
4038 return;
4039 }
4040 // Stop sending ack of handshake packet number space.
4041 uber_received_packet_manager_.ResetAckStates(ENCRYPTION_HANDSHAKE);
4042 // Re-arm ack alarm.
4043 ack_alarm_->Update(uber_received_packet_manager_.GetEarliestAckTimeout(),
4044 kAlarmGranularity);
4045 if (!accelerated_server_preferred_address_ &&
4046 received_server_preferred_address_.IsInitialized()) {
4047 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
4048 visitor_->OnServerPreferredAddressAvailable(
4049 received_server_preferred_address_);
4050 }
4051 }
4052
MaybeCreateMultiPortPath()4053 void QuicConnection::MaybeCreateMultiPortPath() {
4054 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
4055 QUIC_CLIENT_HISTOGRAM_BOOL(
4056 "QuicConnection.ServerAllowsActiveMigrationForMultiPort",
4057 !active_migration_disabled_,
4058 "Whether the server allows active migration that's required for "
4059 "multi-port");
4060 if (active_migration_disabled_) {
4061 return;
4062 }
4063 if (path_validator_.HasPendingPathValidation()) {
4064 QUIC_CLIENT_HISTOGRAM_ENUM("QuicConnection.MultiPortPathCreationCancelled",
4065 path_validator_.GetPathValidationReason(),
4066 PathValidationReason::kMaxValue,
4067 "Reason for cancelled multi port path creation");
4068 return;
4069 }
4070 if (multi_port_stats_->num_multi_port_paths_created >=
4071 kMaxNumMultiPortPaths) {
4072 return;
4073 }
4074
4075 auto context_observer = std::make_unique<ContextObserver>(this);
4076 visitor_->CreateContextForMultiPortPath(std::move(context_observer));
4077 }
4078
SendOrQueuePacket(SerializedPacket packet)4079 void QuicConnection::SendOrQueuePacket(SerializedPacket packet) {
4080 // The caller of this function is responsible for checking CanWrite().
4081 WritePacket(&packet);
4082 }
4083
SendAck()4084 void QuicConnection::SendAck() {
4085 QUICHE_DCHECK(!SupportsMultiplePacketNumberSpaces());
4086 QUIC_DVLOG(1) << ENDPOINT << "Sending an ACK proactively";
4087 QuicFrames frames;
4088 frames.push_back(GetUpdatedAckFrame());
4089 if (!packet_creator_.FlushAckFrame(frames)) {
4090 return;
4091 }
4092 ResetAckStates();
4093 if (!ShouldBundleRetransmittableFrameWithAck()) {
4094 return;
4095 }
4096 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
4097 if (packet_creator_.HasPendingRetransmittableFrames() ||
4098 visitor_->WillingAndAbleToWrite()) {
4099 // There are pending retransmittable frames.
4100 return;
4101 }
4102
4103 visitor_->OnAckNeedsRetransmittableFrame();
4104 }
4105
GetEncryptionLevelToSendPingForSpace(PacketNumberSpace space) const4106 EncryptionLevel QuicConnection::GetEncryptionLevelToSendPingForSpace(
4107 PacketNumberSpace space) const {
4108 switch (space) {
4109 case INITIAL_DATA:
4110 return ENCRYPTION_INITIAL;
4111 case HANDSHAKE_DATA:
4112 return ENCRYPTION_HANDSHAKE;
4113 case APPLICATION_DATA:
4114 return framer_.GetEncryptionLevelToSendApplicationData();
4115 default:
4116 QUICHE_DCHECK(false);
4117 return NUM_ENCRYPTION_LEVELS;
4118 }
4119 }
4120
IsKnownServerAddress(const QuicSocketAddress & address) const4121 bool QuicConnection::IsKnownServerAddress(
4122 const QuicSocketAddress& address) const {
4123 QUICHE_DCHECK(address.IsInitialized());
4124 return std::find(known_server_addresses_.cbegin(),
4125 known_server_addresses_.cend(),
4126 address) != known_server_addresses_.cend();
4127 }
4128
GetEcnCodepointToSend(const QuicSocketAddress & destination_address) const4129 QuicEcnCodepoint QuicConnection::GetEcnCodepointToSend(
4130 const QuicSocketAddress& destination_address) const {
4131 // Don't send ECN marks on alternate paths. Sending ECN marks might
4132 // cause the connectivity check to fail on some networks.
4133 if (destination_address != peer_address()) {
4134 return ECN_NOT_ECT;
4135 }
4136 // If the path might drop ECN marked packets, send retransmission without
4137 // them.
4138 if (in_probe_time_out_ && !default_path_.ecn_marked_packet_acked) {
4139 return ECN_NOT_ECT;
4140 }
4141 return packet_writer_params_.ecn_codepoint;
4142 }
4143
SendPacketToWriter(const char * buffer,size_t buf_len,const QuicIpAddress & self_address,const QuicSocketAddress & destination_address,QuicPacketWriter * writer,const QuicEcnCodepoint ecn_codepoint)4144 WriteResult QuicConnection::SendPacketToWriter(
4145 const char* buffer, size_t buf_len, const QuicIpAddress& self_address,
4146 const QuicSocketAddress& destination_address, QuicPacketWriter* writer,
4147 const QuicEcnCodepoint ecn_codepoint) {
4148 QuicPacketWriterParams params = packet_writer_params_;
4149 params.ecn_codepoint = ecn_codepoint;
4150 last_ecn_codepoint_sent_ = ecn_codepoint;
4151 WriteResult result =
4152 writer->WritePacket(buffer, buf_len, self_address, destination_address,
4153 per_packet_options_, params);
4154 return result;
4155 }
4156
OnRetransmissionTimeout()4157 void QuicConnection::OnRetransmissionTimeout() {
4158 ScopedRetransmissionTimeoutIndicator indicator(this);
4159 #ifndef NDEBUG
4160 if (sent_packet_manager_.unacked_packets().empty()) {
4161 QUICHE_DCHECK(sent_packet_manager_.handshake_mode_disabled());
4162 QUICHE_DCHECK(!IsHandshakeConfirmed());
4163 }
4164 #endif
4165 if (!connected_) {
4166 return;
4167 }
4168
4169 QuicPacketNumber previous_created_packet_number =
4170 packet_creator_.packet_number();
4171 const auto retransmission_mode =
4172 sent_packet_manager_.OnRetransmissionTimeout();
4173 if (retransmission_mode == QuicSentPacketManager::PTO_MODE) {
4174 // Skip a packet number when PTO fires to elicit an immediate ACK.
4175 const QuicPacketCount num_packet_numbers_to_skip = 1;
4176 packet_creator_.SkipNPacketNumbers(
4177 num_packet_numbers_to_skip,
4178 sent_packet_manager_.GetLeastPacketAwaitedByPeer(encryption_level_),
4179 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
4180 previous_created_packet_number += num_packet_numbers_to_skip;
4181 if (debug_visitor_ != nullptr) {
4182 debug_visitor_->OnNPacketNumbersSkipped(num_packet_numbers_to_skip,
4183 clock_->Now());
4184 }
4185 }
4186 if (default_enable_5rto_blackhole_detection_ &&
4187 !sent_packet_manager_.HasInFlightPackets() &&
4188 blackhole_detector_.IsDetectionInProgress()) {
4189 // Stop detection in quiescence.
4190 QUICHE_DCHECK_EQ(QuicSentPacketManager::LOSS_MODE, retransmission_mode);
4191 blackhole_detector_.StopDetection(/*permanent=*/false);
4192 }
4193 WriteIfNotBlocked();
4194
4195 // A write failure can result in the connection being closed, don't attempt to
4196 // write further packets, or to set alarms.
4197 if (!connected_) {
4198 return;
4199 }
4200 // When PTO fires, the SentPacketManager gives the connection the opportunity
4201 // to send new data before retransmitting.
4202 sent_packet_manager_.MaybeSendProbePacket();
4203
4204 if (packet_creator_.packet_number() == previous_created_packet_number &&
4205 retransmission_mode == QuicSentPacketManager::PTO_MODE &&
4206 !visitor_->WillingAndAbleToWrite()) {
4207 // Send PING if timer fires in PTO mode but there is no data to send.
4208 QUIC_DLOG(INFO) << ENDPOINT
4209 << "No packet gets sent when timer fires in mode "
4210 << retransmission_mode << ", send PING";
4211 QUICHE_DCHECK_LT(0u,
4212 sent_packet_manager_.pending_timer_transmission_count());
4213 if (SupportsMultiplePacketNumberSpaces()) {
4214 // Based on https://datatracker.ietf.org/doc/html/rfc9002#appendix-A.9
4215 PacketNumberSpace packet_number_space;
4216 if (sent_packet_manager_
4217 .GetEarliestPacketSentTimeForPto(&packet_number_space)
4218 .IsInitialized()) {
4219 SendPingAtLevel(
4220 GetEncryptionLevelToSendPingForSpace(packet_number_space));
4221 } else {
4222 // The client must PTO when there is nothing in flight if the server
4223 // could be blocked from sending by the amplification limit
4224 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
4225 if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_HANDSHAKE)) {
4226 SendPingAtLevel(ENCRYPTION_HANDSHAKE);
4227 } else if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL)) {
4228 SendPingAtLevel(ENCRYPTION_INITIAL);
4229 } else {
4230 QUIC_BUG(quic_bug_no_pto) << "PTO fired but nothing was sent.";
4231 }
4232 }
4233 } else {
4234 SendPingAtLevel(encryption_level_);
4235 }
4236 }
4237 if (retransmission_mode == QuicSentPacketManager::PTO_MODE) {
4238 // When timer fires in PTO mode, ensure 1) at least one packet is created,
4239 // or there is data to send and available credit (such that packets will be
4240 // sent eventually).
4241 QUIC_BUG_IF(
4242 quic_bug_12714_27,
4243 packet_creator_.packet_number() == previous_created_packet_number &&
4244 (!visitor_->WillingAndAbleToWrite() ||
4245 sent_packet_manager_.pending_timer_transmission_count() == 0u))
4246 << "retransmission_mode: " << retransmission_mode
4247 << ", packet_number: " << packet_creator_.packet_number()
4248 << ", session has data to write: " << visitor_->WillingAndAbleToWrite()
4249 << ", writer is blocked: " << writer_->IsWriteBlocked()
4250 << ", pending_timer_transmission_count: "
4251 << sent_packet_manager_.pending_timer_transmission_count();
4252 }
4253
4254 // Ensure the retransmission alarm is always set if there are unacked packets
4255 // and nothing waiting to be sent.
4256 // This happens if the loss algorithm invokes a timer based loss, but the
4257 // packet doesn't need to be retransmitted.
4258 if (!HasQueuedData() && !retransmission_alarm_->IsSet()) {
4259 SetRetransmissionAlarm();
4260 }
4261 if (packet_writer_params_.ecn_codepoint == ECN_NOT_ECT ||
4262 default_path_.ecn_marked_packet_acked) {
4263 return;
4264 }
4265 ++default_path_.ecn_pto_count;
4266 if (default_path_.ecn_pto_count == kEcnPtoLimit) {
4267 // Give up on ECN. There are two scenarios:
4268 // 1. All packets are suffering PTO. In this case, the connection
4269 // abandons ECN after 1 failed ECT(1) flight and one failed Not-ECT
4270 // flight.
4271 // 2. Only ECN packets are suffering PTO. In that case, alternating
4272 // flights will have ECT(1). On the second ECT(1) failure, the
4273 // connection will abandon.
4274 // This behavior is in the range of acceptable choices in S13.4.2 of RFC
4275 // 9000.
4276 QUIC_DVLOG(1) << ENDPOINT << "ECN packets PTO 3 times.";
4277 OnInvalidEcnFeedback();
4278 }
4279 }
4280
SetEncrypter(EncryptionLevel level,std::unique_ptr<QuicEncrypter> encrypter)4281 void QuicConnection::SetEncrypter(EncryptionLevel level,
4282 std::unique_ptr<QuicEncrypter> encrypter) {
4283 packet_creator_.SetEncrypter(level, std::move(encrypter));
4284 }
4285
RemoveEncrypter(EncryptionLevel level)4286 void QuicConnection::RemoveEncrypter(EncryptionLevel level) {
4287 framer_.RemoveEncrypter(level);
4288 }
4289
SetDiversificationNonce(const DiversificationNonce & nonce)4290 void QuicConnection::SetDiversificationNonce(
4291 const DiversificationNonce& nonce) {
4292 QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_);
4293 packet_creator_.SetDiversificationNonce(nonce);
4294 }
4295
SetDefaultEncryptionLevel(EncryptionLevel level)4296 void QuicConnection::SetDefaultEncryptionLevel(EncryptionLevel level) {
4297 QUIC_DVLOG(1) << ENDPOINT << "Setting default encryption level from "
4298 << encryption_level_ << " to " << level;
4299 const bool changing_level = level != encryption_level_;
4300 if (changing_level && packet_creator_.HasPendingFrames()) {
4301 // Flush all queued frames when encryption level changes.
4302 ScopedPacketFlusher flusher(this);
4303 packet_creator_.FlushCurrentPacket();
4304 }
4305 encryption_level_ = level;
4306 packet_creator_.set_encryption_level(level);
4307 QUIC_BUG_IF(quic_bug_12714_28, !framer_.HasEncrypterOfEncryptionLevel(level))
4308 << ENDPOINT << "Trying to set encryption level to "
4309 << EncryptionLevelToString(level) << " while the key is missing";
4310
4311 if (!changing_level) {
4312 return;
4313 }
4314 // The least packet awaited by the peer depends on the encryption level so
4315 // we recalculate it here.
4316 packet_creator_.UpdatePacketNumberLength(
4317 sent_packet_manager_.GetLeastPacketAwaitedByPeer(encryption_level_),
4318 sent_packet_manager_.EstimateMaxPacketsInFlight(max_packet_length()));
4319 }
4320
SetDecrypter(EncryptionLevel level,std::unique_ptr<QuicDecrypter> decrypter)4321 void QuicConnection::SetDecrypter(EncryptionLevel level,
4322 std::unique_ptr<QuicDecrypter> decrypter) {
4323 framer_.SetDecrypter(level, std::move(decrypter));
4324
4325 if (!undecryptable_packets_.empty() &&
4326 !process_undecryptable_packets_alarm_->IsSet()) {
4327 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
4328 }
4329 }
4330
SetAlternativeDecrypter(EncryptionLevel level,std::unique_ptr<QuicDecrypter> decrypter,bool latch_once_used)4331 void QuicConnection::SetAlternativeDecrypter(
4332 EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter,
4333 bool latch_once_used) {
4334 framer_.SetAlternativeDecrypter(level, std::move(decrypter), latch_once_used);
4335
4336 if (!undecryptable_packets_.empty() &&
4337 !process_undecryptable_packets_alarm_->IsSet()) {
4338 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
4339 }
4340 }
4341
InstallDecrypter(EncryptionLevel level,std::unique_ptr<QuicDecrypter> decrypter)4342 void QuicConnection::InstallDecrypter(
4343 EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) {
4344 if (level == ENCRYPTION_ZERO_RTT) {
4345 had_zero_rtt_decrypter_ = true;
4346 }
4347 framer_.InstallDecrypter(level, std::move(decrypter));
4348 if (!undecryptable_packets_.empty() &&
4349 !process_undecryptable_packets_alarm_->IsSet()) {
4350 process_undecryptable_packets_alarm_->Set(clock_->ApproximateNow());
4351 }
4352 }
4353
RemoveDecrypter(EncryptionLevel level)4354 void QuicConnection::RemoveDecrypter(EncryptionLevel level) {
4355 framer_.RemoveDecrypter(level);
4356 }
4357
DiscardPreviousOneRttKeys()4358 void QuicConnection::DiscardPreviousOneRttKeys() {
4359 framer_.DiscardPreviousOneRttKeys();
4360 }
4361
IsKeyUpdateAllowed() const4362 bool QuicConnection::IsKeyUpdateAllowed() const {
4363 return support_key_update_for_connection_ &&
4364 GetLargestAckedPacket().IsInitialized() &&
4365 lowest_packet_sent_in_current_key_phase_.IsInitialized() &&
4366 GetLargestAckedPacket() >= lowest_packet_sent_in_current_key_phase_;
4367 }
4368
HaveSentPacketsInCurrentKeyPhaseButNoneAcked() const4369 bool QuicConnection::HaveSentPacketsInCurrentKeyPhaseButNoneAcked() const {
4370 return lowest_packet_sent_in_current_key_phase_.IsInitialized() &&
4371 (!GetLargestAckedPacket().IsInitialized() ||
4372 GetLargestAckedPacket() < lowest_packet_sent_in_current_key_phase_);
4373 }
4374
PotentialPeerKeyUpdateAttemptCount() const4375 QuicPacketCount QuicConnection::PotentialPeerKeyUpdateAttemptCount() const {
4376 return framer_.PotentialPeerKeyUpdateAttemptCount();
4377 }
4378
InitiateKeyUpdate(KeyUpdateReason reason)4379 bool QuicConnection::InitiateKeyUpdate(KeyUpdateReason reason) {
4380 QUIC_DLOG(INFO) << ENDPOINT << "InitiateKeyUpdate";
4381 if (!IsKeyUpdateAllowed()) {
4382 QUIC_BUG(quic_bug_10511_28) << "key update not allowed";
4383 return false;
4384 }
4385 return framer_.DoKeyUpdate(reason);
4386 }
4387
decrypter() const4388 const QuicDecrypter* QuicConnection::decrypter() const {
4389 return framer_.decrypter();
4390 }
4391
alternative_decrypter() const4392 const QuicDecrypter* QuicConnection::alternative_decrypter() const {
4393 return framer_.alternative_decrypter();
4394 }
4395
QueueUndecryptablePacket(const QuicEncryptedPacket & packet,EncryptionLevel decryption_level)4396 void QuicConnection::QueueUndecryptablePacket(
4397 const QuicEncryptedPacket& packet, EncryptionLevel decryption_level) {
4398 for (const auto& saved_packet : undecryptable_packets_) {
4399 if (packet.data() == saved_packet.packet->data() &&
4400 packet.length() == saved_packet.packet->length()) {
4401 QUIC_DVLOG(1) << ENDPOINT << "Not queueing known undecryptable packet";
4402 return;
4403 }
4404 }
4405 QUIC_DVLOG(1) << ENDPOINT << "Queueing undecryptable packet.";
4406 undecryptable_packets_.emplace_back(packet, decryption_level,
4407 last_received_packet_info_);
4408 if (perspective_ == Perspective::IS_CLIENT) {
4409 SetRetransmissionAlarm();
4410 }
4411 }
4412
MaybeProcessUndecryptablePackets()4413 void QuicConnection::MaybeProcessUndecryptablePackets() {
4414 process_undecryptable_packets_alarm_->Cancel();
4415
4416 if (undecryptable_packets_.empty() ||
4417 encryption_level_ == ENCRYPTION_INITIAL) {
4418 return;
4419 }
4420
4421 auto iter = undecryptable_packets_.begin();
4422 while (connected_ && iter != undecryptable_packets_.end()) {
4423 // Making sure there is no pending frames when processing next undecrypted
4424 // packet because the queued ack frame may change.
4425 packet_creator_.FlushCurrentPacket();
4426 if (!connected_) {
4427 return;
4428 }
4429 UndecryptablePacket* undecryptable_packet = &*iter;
4430 QUIC_DVLOG(1) << ENDPOINT << "Attempting to process undecryptable packet";
4431 if (debug_visitor_ != nullptr) {
4432 debug_visitor_->OnAttemptingToProcessUndecryptablePacket(
4433 undecryptable_packet->encryption_level);
4434 }
4435 last_received_packet_info_ = undecryptable_packet->packet_info;
4436 current_packet_data_ = undecryptable_packet->packet->data();
4437 const bool processed = framer_.ProcessPacket(*undecryptable_packet->packet);
4438 current_packet_data_ = nullptr;
4439
4440 if (processed) {
4441 QUIC_DVLOG(1) << ENDPOINT << "Processed undecryptable packet!";
4442 iter = undecryptable_packets_.erase(iter);
4443 ++stats_.packets_processed;
4444 continue;
4445 }
4446 const bool has_decryption_key = version().KnowsWhichDecrypterToUse() &&
4447 framer_.HasDecrypterOfEncryptionLevel(
4448 undecryptable_packet->encryption_level);
4449 if (framer_.error() == QUIC_DECRYPTION_FAILURE &&
4450 ShouldEnqueueUnDecryptablePacket(undecryptable_packet->encryption_level,
4451 has_decryption_key)) {
4452 QUIC_DVLOG(1)
4453 << ENDPOINT
4454 << "Need to attempt to process this undecryptable packet later";
4455 ++iter;
4456 continue;
4457 }
4458 iter = undecryptable_packets_.erase(iter);
4459 }
4460
4461 // Once handshake is complete, there will be no new keys installed and hence
4462 // any undecryptable packets will never be able to be decrypted.
4463 if (IsHandshakeComplete()) {
4464 if (debug_visitor_ != nullptr) {
4465 for (const auto& undecryptable_packet : undecryptable_packets_) {
4466 debug_visitor_->OnUndecryptablePacket(
4467 undecryptable_packet.encryption_level, /*dropped=*/true);
4468 }
4469 }
4470 undecryptable_packets_.clear();
4471 }
4472 if (perspective_ == Perspective::IS_CLIENT) {
4473 SetRetransmissionAlarm();
4474 }
4475 }
4476
QueueCoalescedPacket(const QuicEncryptedPacket & packet)4477 void QuicConnection::QueueCoalescedPacket(const QuicEncryptedPacket& packet) {
4478 QUIC_DVLOG(1) << ENDPOINT << "Queueing coalesced packet.";
4479 received_coalesced_packets_.push_back(packet.Clone());
4480 ++stats_.num_coalesced_packets_received;
4481 }
4482
MaybeProcessCoalescedPackets()4483 bool QuicConnection::MaybeProcessCoalescedPackets() {
4484 bool processed = false;
4485 while (connected_ && !received_coalesced_packets_.empty()) {
4486 // Making sure there are no pending frames when processing the next
4487 // coalesced packet because the queued ack frame may change.
4488 packet_creator_.FlushCurrentPacket();
4489 if (!connected_) {
4490 return processed;
4491 }
4492
4493 std::unique_ptr<QuicEncryptedPacket> packet =
4494 std::move(received_coalesced_packets_.front());
4495 received_coalesced_packets_.pop_front();
4496
4497 QUIC_DVLOG(1) << ENDPOINT << "Processing coalesced packet";
4498 if (framer_.ProcessPacket(*packet)) {
4499 processed = true;
4500 ++stats_.num_coalesced_packets_processed;
4501 } else {
4502 // If we are unable to decrypt this packet, it might be
4503 // because the CHLO or SHLO packet was lost.
4504 }
4505 }
4506 if (processed) {
4507 MaybeProcessUndecryptablePackets();
4508 MaybeSendInResponseToPacket();
4509 }
4510 return processed;
4511 }
4512
CloseConnection(QuicErrorCode error,const std::string & details,ConnectionCloseBehavior connection_close_behavior)4513 void QuicConnection::CloseConnection(
4514 QuicErrorCode error, const std::string& details,
4515 ConnectionCloseBehavior connection_close_behavior) {
4516 CloseConnection(error, NO_IETF_QUIC_ERROR, details,
4517 connection_close_behavior);
4518 }
4519
CloseConnection(QuicErrorCode error,QuicIetfTransportErrorCodes ietf_error,const std::string & error_details,ConnectionCloseBehavior connection_close_behavior)4520 void QuicConnection::CloseConnection(
4521 QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error,
4522 const std::string& error_details,
4523 ConnectionCloseBehavior connection_close_behavior) {
4524 QUICHE_DCHECK(!error_details.empty());
4525 if (!connected_) {
4526 QUIC_DLOG(INFO) << "Connection is already closed.";
4527 return;
4528 }
4529
4530 if (ietf_error != NO_IETF_QUIC_ERROR) {
4531 QUIC_DLOG(INFO) << ENDPOINT << "Closing connection: " << connection_id()
4532 << ", with wire error: " << ietf_error
4533 << ", error: " << QuicErrorCodeToString(error)
4534 << ", and details: " << error_details;
4535 } else {
4536 QUIC_DLOG(INFO) << ENDPOINT << "Closing connection: " << connection_id()
4537 << ", with error: " << QuicErrorCodeToString(error) << " ("
4538 << error << "), and details: " << error_details;
4539 }
4540
4541 if (connection_close_behavior != ConnectionCloseBehavior::SILENT_CLOSE) {
4542 SendConnectionClosePacket(error, ietf_error, error_details);
4543 }
4544
4545 TearDownLocalConnectionState(error, ietf_error, error_details,
4546 ConnectionCloseSource::FROM_SELF);
4547 }
4548
SendConnectionClosePacket(QuicErrorCode error,QuicIetfTransportErrorCodes ietf_error,const std::string & details)4549 void QuicConnection::SendConnectionClosePacket(
4550 QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error,
4551 const std::string& details) {
4552 // Always use the current path to send CONNECTION_CLOSE.
4553 QuicPacketCreator::ScopedPeerAddressContext context(
4554 &packet_creator_, peer_address(), default_path_.client_connection_id,
4555 default_path_.server_connection_id);
4556 if (!SupportsMultiplePacketNumberSpaces()) {
4557 QUIC_DLOG(INFO) << ENDPOINT << "Sending connection close packet.";
4558 ScopedEncryptionLevelContext context(this,
4559 GetConnectionCloseEncryptionLevel());
4560 if (version().CanSendCoalescedPackets()) {
4561 coalesced_packet_.Clear();
4562 }
4563 ClearQueuedPackets();
4564 // If there was a packet write error, write the smallest close possible.
4565 ScopedPacketFlusher flusher(this);
4566 // Always bundle an ACK with connection close for debugging purpose.
4567 if (error != QUIC_PACKET_WRITE_ERROR &&
4568 !uber_received_packet_manager_.IsAckFrameEmpty(
4569 QuicUtils::GetPacketNumberSpace(encryption_level_)) &&
4570 !packet_creator_.has_ack()) {
4571 SendAck();
4572 }
4573 QuicConnectionCloseFrame* frame;
4574
4575 frame = new QuicConnectionCloseFrame(transport_version(), error, ietf_error,
4576 details,
4577 framer_.current_received_frame_type());
4578 packet_creator_.ConsumeRetransmittableControlFrame(QuicFrame(frame));
4579 packet_creator_.FlushCurrentPacket();
4580 if (version().CanSendCoalescedPackets()) {
4581 FlushCoalescedPacket();
4582 }
4583 ClearQueuedPackets();
4584 return;
4585 }
4586 ScopedPacketFlusher flusher(this);
4587
4588 // Now that the connection is being closed, discard any unsent packets
4589 // so the only packets to be sent will be connection close packets.
4590 if (version().CanSendCoalescedPackets()) {
4591 coalesced_packet_.Clear();
4592 }
4593 ClearQueuedPackets();
4594
4595 for (EncryptionLevel level :
4596 {ENCRYPTION_INITIAL, ENCRYPTION_HANDSHAKE, ENCRYPTION_ZERO_RTT,
4597 ENCRYPTION_FORWARD_SECURE}) {
4598 if (!framer_.HasEncrypterOfEncryptionLevel(level)) {
4599 continue;
4600 }
4601 QUIC_DLOG(INFO) << ENDPOINT
4602 << "Sending connection close packet at level: " << level;
4603 ScopedEncryptionLevelContext context(this, level);
4604 // Bundle an ACK of the corresponding packet number space for debugging
4605 // purpose.
4606 if (error != QUIC_PACKET_WRITE_ERROR &&
4607 !uber_received_packet_manager_.IsAckFrameEmpty(
4608 QuicUtils::GetPacketNumberSpace(encryption_level_)) &&
4609 !packet_creator_.has_ack()) {
4610 QuicFrames frames;
4611 frames.push_back(GetUpdatedAckFrame());
4612 packet_creator_.FlushAckFrame(frames);
4613 }
4614
4615 if (level == ENCRYPTION_FORWARD_SECURE &&
4616 perspective_ == Perspective::IS_SERVER) {
4617 visitor_->BeforeConnectionCloseSent();
4618 }
4619
4620 auto* frame = new QuicConnectionCloseFrame(
4621 transport_version(), error, ietf_error, details,
4622 framer_.current_received_frame_type());
4623 packet_creator_.ConsumeRetransmittableControlFrame(QuicFrame(frame));
4624 packet_creator_.FlushCurrentPacket();
4625 }
4626 if (version().CanSendCoalescedPackets()) {
4627 FlushCoalescedPacket();
4628 }
4629 // Since the connection is closing, if the connection close packets were not
4630 // sent, then they should be discarded.
4631 ClearQueuedPackets();
4632 }
4633
TearDownLocalConnectionState(QuicErrorCode error,QuicIetfTransportErrorCodes ietf_error,const std::string & error_details,ConnectionCloseSource source)4634 void QuicConnection::TearDownLocalConnectionState(
4635 QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error,
4636 const std::string& error_details, ConnectionCloseSource source) {
4637 QuicConnectionCloseFrame frame(transport_version(), error, ietf_error,
4638 error_details,
4639 framer_.current_received_frame_type());
4640 return TearDownLocalConnectionState(frame, source);
4641 }
4642
TearDownLocalConnectionState(const QuicConnectionCloseFrame & frame,ConnectionCloseSource source)4643 void QuicConnection::TearDownLocalConnectionState(
4644 const QuicConnectionCloseFrame& frame, ConnectionCloseSource source) {
4645 if (!connected_) {
4646 QUIC_DLOG(INFO) << "Connection is already closed.";
4647 return;
4648 }
4649
4650 // If we are using a batch writer, flush packets queued in it, if any.
4651 FlushPackets();
4652 connected_ = false;
4653 QUICHE_DCHECK(visitor_ != nullptr);
4654 visitor_->OnConnectionClosed(frame, source);
4655 // LossDetectionTunerInterface::Finish() may be called from
4656 // sent_packet_manager_.OnConnectionClosed. Which may require the session to
4657 // finish its business first.
4658 sent_packet_manager_.OnConnectionClosed();
4659 if (debug_visitor_ != nullptr) {
4660 debug_visitor_->OnConnectionClosed(frame, source);
4661 }
4662 // Cancel the alarms so they don't trigger any action now that the
4663 // connection is closed.
4664 CancelAllAlarms();
4665 CancelPathValidation();
4666
4667 peer_issued_cid_manager_.reset();
4668 self_issued_cid_manager_.reset();
4669 }
4670
CancelAllAlarms()4671 void QuicConnection::CancelAllAlarms() {
4672 QUIC_DVLOG(1) << "Cancelling all QuicConnection alarms.";
4673
4674 ack_alarm_->PermanentCancel();
4675 ping_manager_.Stop();
4676 retransmission_alarm_->PermanentCancel();
4677 send_alarm_->PermanentCancel();
4678 mtu_discovery_alarm_->PermanentCancel();
4679 process_undecryptable_packets_alarm_->PermanentCancel();
4680 discard_previous_one_rtt_keys_alarm_->PermanentCancel();
4681 discard_zero_rtt_decryption_keys_alarm_->PermanentCancel();
4682 multi_port_probing_alarm_->PermanentCancel();
4683 blackhole_detector_.StopDetection(/*permanent=*/true);
4684 idle_network_detector_.StopDetection();
4685 }
4686
max_packet_length() const4687 QuicByteCount QuicConnection::max_packet_length() const {
4688 return packet_creator_.max_packet_length();
4689 }
4690
SetMaxPacketLength(QuicByteCount length)4691 void QuicConnection::SetMaxPacketLength(QuicByteCount length) {
4692 long_term_mtu_ = length;
4693 stats_.max_egress_mtu = std::max(stats_.max_egress_mtu, long_term_mtu_);
4694 packet_creator_.SetMaxPacketLength(GetLimitedMaxPacketSize(length));
4695 }
4696
HasQueuedData() const4697 bool QuicConnection::HasQueuedData() const {
4698 return packet_creator_.HasPendingFrames() || !buffered_packets_.empty();
4699 }
4700
SetNetworkTimeouts(QuicTime::Delta handshake_timeout,QuicTime::Delta idle_timeout)4701 void QuicConnection::SetNetworkTimeouts(QuicTime::Delta handshake_timeout,
4702 QuicTime::Delta idle_timeout) {
4703 QUIC_BUG_IF(quic_bug_12714_29, idle_timeout > handshake_timeout)
4704 << "idle_timeout:" << idle_timeout.ToMilliseconds()
4705 << " handshake_timeout:" << handshake_timeout.ToMilliseconds();
4706 // Adjust the idle timeout on client and server to prevent clients from
4707 // sending requests to servers which have already closed the connection.
4708 if (perspective_ == Perspective::IS_SERVER) {
4709 idle_timeout = idle_timeout + QuicTime::Delta::FromSeconds(3);
4710 } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) {
4711 idle_timeout = idle_timeout - QuicTime::Delta::FromSeconds(1);
4712 }
4713 idle_network_detector_.SetTimeouts(handshake_timeout, idle_timeout);
4714 }
4715
SetPingAlarm()4716 void QuicConnection::SetPingAlarm() {
4717 if (!connected_) {
4718 return;
4719 }
4720 ping_manager_.SetAlarm(clock_->ApproximateNow(),
4721 visitor_->ShouldKeepConnectionAlive(),
4722 sent_packet_manager_.HasInFlightPackets());
4723 }
4724
SetRetransmissionAlarm()4725 void QuicConnection::SetRetransmissionAlarm() {
4726 if (!connected_) {
4727 if (retransmission_alarm_->IsSet()) {
4728 QUIC_BUG(quic_bug_10511_29)
4729 << ENDPOINT << "Retransmission alarm is set while disconnected";
4730 retransmission_alarm_->Cancel();
4731 }
4732 return;
4733 }
4734 if (packet_creator_.PacketFlusherAttached()) {
4735 pending_retransmission_alarm_ = true;
4736 return;
4737 }
4738 if (LimitedByAmplificationFactor(packet_creator_.max_packet_length())) {
4739 // Do not set retransmission timer if connection is anti-amplification limit
4740 // throttled. Otherwise, nothing can be sent when timer fires.
4741 retransmission_alarm_->Cancel();
4742 return;
4743 }
4744 PacketNumberSpace packet_number_space;
4745 if (SupportsMultiplePacketNumberSpaces() && !IsHandshakeConfirmed() &&
4746 !sent_packet_manager_
4747 .GetEarliestPacketSentTimeForPto(&packet_number_space)
4748 .IsInitialized()) {
4749 // Before handshake gets confirmed, GetEarliestPacketSentTimeForPto
4750 // returning 0 indicates no packets are in flight or only application data
4751 // is in flight.
4752 if (perspective_ == Perspective::IS_SERVER) {
4753 // No need to arm PTO on server side.
4754 retransmission_alarm_->Cancel();
4755 return;
4756 }
4757 if (retransmission_alarm_->IsSet() &&
4758 GetRetransmissionDeadline() > retransmission_alarm_->deadline()) {
4759 // Do not postpone armed PTO on the client side.
4760 return;
4761 }
4762 }
4763
4764 retransmission_alarm_->Update(GetRetransmissionDeadline(), kAlarmGranularity);
4765 }
4766
MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number)4767 void QuicConnection::MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number) {
4768 if (mtu_discovery_alarm_->IsSet() ||
4769 !mtu_discoverer_.ShouldProbeMtu(sent_packet_number)) {
4770 return;
4771 }
4772 mtu_discovery_alarm_->Set(clock_->ApproximateNow());
4773 }
4774
ScopedPacketFlusher(QuicConnection * connection)4775 QuicConnection::ScopedPacketFlusher::ScopedPacketFlusher(
4776 QuicConnection* connection)
4777 : connection_(connection),
4778 flush_and_set_pending_retransmission_alarm_on_delete_(false),
4779 handshake_packet_sent_(connection != nullptr &&
4780 connection->handshake_packet_sent_) {
4781 if (connection_ == nullptr) {
4782 return;
4783 }
4784
4785 if (!connection_->packet_creator_.PacketFlusherAttached()) {
4786 flush_and_set_pending_retransmission_alarm_on_delete_ = true;
4787 connection->packet_creator_.AttachPacketFlusher();
4788 }
4789 }
4790
~ScopedPacketFlusher()4791 QuicConnection::ScopedPacketFlusher::~ScopedPacketFlusher() {
4792 if (connection_ == nullptr || !connection_->connected()) {
4793 return;
4794 }
4795
4796 if (flush_and_set_pending_retransmission_alarm_on_delete_) {
4797 const QuicTime ack_timeout =
4798 connection_->uber_received_packet_manager_.GetEarliestAckTimeout();
4799 if (ack_timeout.IsInitialized()) {
4800 if (ack_timeout <= connection_->clock_->ApproximateNow() &&
4801 !connection_->CanWrite(NO_RETRANSMITTABLE_DATA)) {
4802 // Cancel ACK alarm if connection is write blocked, and ACK will be
4803 // sent when connection gets unblocked.
4804 connection_->ack_alarm_->Cancel();
4805 } else if (!connection_->ack_alarm_->IsSet() ||
4806 connection_->ack_alarm_->deadline() > ack_timeout) {
4807 connection_->ack_alarm_->Update(ack_timeout, QuicTime::Delta::Zero());
4808 }
4809 }
4810 if (connection_->ack_alarm_->IsSet() &&
4811 connection_->ack_alarm_->deadline() <=
4812 connection_->clock_->ApproximateNow()) {
4813 // An ACK needs to be sent right now. This ACK did not get bundled
4814 // because either there was no data to write or packets were marked as
4815 // received after frames were queued in the generator.
4816 if (connection_->send_alarm_->IsSet() &&
4817 connection_->send_alarm_->deadline() <=
4818 connection_->clock_->ApproximateNow()) {
4819 // If send alarm will go off soon, let send alarm send the ACK.
4820 connection_->ack_alarm_->Cancel();
4821 } else if (connection_->SupportsMultiplePacketNumberSpaces()) {
4822 connection_->SendAllPendingAcks();
4823 } else {
4824 connection_->SendAck();
4825 }
4826 }
4827
4828 // INITIAL or HANDSHAKE retransmission could cause peer to derive new
4829 // keys, such that the buffered undecryptable packets may be processed.
4830 // This endpoint would derive an inflated RTT sample when receiving ACKs
4831 // of those undecryptable packets. To mitigate this, tries to coalesce as
4832 // many higher space packets as possible (via for loop inside
4833 // MaybeCoalescePacketOfHigherSpace) to fill the remaining space in the
4834 // coalescer.
4835 if (connection_->version().CanSendCoalescedPackets()) {
4836 connection_->MaybeCoalescePacketOfHigherSpace();
4837 }
4838 connection_->packet_creator_.Flush();
4839 if (connection_->version().CanSendCoalescedPackets()) {
4840 connection_->FlushCoalescedPacket();
4841 }
4842 connection_->FlushPackets();
4843
4844 if (!connection_->connected()) {
4845 return;
4846 }
4847
4848 if (!handshake_packet_sent_ && connection_->handshake_packet_sent_) {
4849 // This would cause INITIAL key to be dropped. Drop keys here to avoid
4850 // missing the write keys in the middle of writing.
4851 connection_->visitor_->OnHandshakePacketSent();
4852 }
4853 // Reset transmission type.
4854 connection_->SetTransmissionType(NOT_RETRANSMISSION);
4855
4856 // Once all transmissions are done, check if there is any outstanding data
4857 // to send and notify the congestion controller if not.
4858 //
4859 // Note that this means that the application limited check will happen as
4860 // soon as the last flusher gets destroyed, which is typically after a
4861 // single stream write is finished. This means that if all the data from a
4862 // single write goes through the connection, the application-limited signal
4863 // will fire even if the caller does a write operation immediately after.
4864 // There are two important approaches to remedy this situation:
4865 // (1) Instantiate ScopedPacketFlusher before performing multiple subsequent
4866 // writes, thus deferring this check until all writes are done.
4867 // (2) Write data in chunks sufficiently large so that they cause the
4868 // connection to be limited by the congestion control. Typically, this
4869 // would mean writing chunks larger than the product of the current
4870 // pacing rate and the pacer granularity. So, for instance, if the
4871 // pacing rate of the connection is 1 Gbps, and the pacer granularity is
4872 // 1 ms, the caller should send at least 125k bytes in order to not
4873 // be marked as application-limited.
4874 connection_->CheckIfApplicationLimited();
4875
4876 if (connection_->pending_retransmission_alarm_) {
4877 connection_->SetRetransmissionAlarm();
4878 connection_->pending_retransmission_alarm_ = false;
4879 }
4880 }
4881 QUICHE_DCHECK_EQ(flush_and_set_pending_retransmission_alarm_on_delete_,
4882 !connection_->packet_creator_.PacketFlusherAttached());
4883 }
4884
ScopedEncryptionLevelContext(QuicConnection * connection,EncryptionLevel encryption_level)4885 QuicConnection::ScopedEncryptionLevelContext::ScopedEncryptionLevelContext(
4886 QuicConnection* connection, EncryptionLevel encryption_level)
4887 : connection_(connection), latched_encryption_level_(ENCRYPTION_INITIAL) {
4888 if (connection_ == nullptr) {
4889 return;
4890 }
4891 latched_encryption_level_ = connection_->encryption_level_;
4892 connection_->SetDefaultEncryptionLevel(encryption_level);
4893 }
4894
~ScopedEncryptionLevelContext()4895 QuicConnection::ScopedEncryptionLevelContext::~ScopedEncryptionLevelContext() {
4896 if (connection_ == nullptr || !connection_->connected_) {
4897 return;
4898 }
4899 connection_->SetDefaultEncryptionLevel(latched_encryption_level_);
4900 }
4901
BufferedPacket(const SerializedPacket & packet,const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,const QuicEcnCodepoint ecn_codepoint)4902 QuicConnection::BufferedPacket::BufferedPacket(
4903 const SerializedPacket& packet, const QuicSocketAddress& self_address,
4904 const QuicSocketAddress& peer_address, const QuicEcnCodepoint ecn_codepoint)
4905 : BufferedPacket(packet.encrypted_buffer, packet.encrypted_length,
4906 self_address, peer_address, ecn_codepoint) {}
4907
BufferedPacket(const char * encrypted_buffer,QuicPacketLength encrypted_length,const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,const QuicEcnCodepoint ecn_codepoint)4908 QuicConnection::BufferedPacket::BufferedPacket(
4909 const char* encrypted_buffer, QuicPacketLength encrypted_length,
4910 const QuicSocketAddress& self_address,
4911 const QuicSocketAddress& peer_address, const QuicEcnCodepoint ecn_codepoint)
4912 : length(encrypted_length),
4913 self_address(self_address),
4914 peer_address(peer_address),
4915 ecn_codepoint(ecn_codepoint) {
4916 data = std::make_unique<char[]>(encrypted_length);
4917 memcpy(data.get(), encrypted_buffer, encrypted_length);
4918 }
4919
BufferedPacket(QuicRandom & random,QuicPacketLength encrypted_length,const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address)4920 QuicConnection::BufferedPacket::BufferedPacket(
4921 QuicRandom& random, QuicPacketLength encrypted_length,
4922 const QuicSocketAddress& self_address,
4923 const QuicSocketAddress& peer_address)
4924 : length(encrypted_length),
4925 self_address(self_address),
4926 peer_address(peer_address) {
4927 data = std::make_unique<char[]>(encrypted_length);
4928 random.RandBytes(data.get(), encrypted_length);
4929 }
4930
ReceivedPacketInfo(QuicTime receipt_time)4931 QuicConnection::ReceivedPacketInfo::ReceivedPacketInfo(QuicTime receipt_time)
4932 : receipt_time(receipt_time) {}
ReceivedPacketInfo(const QuicSocketAddress & destination_address,const QuicSocketAddress & source_address,QuicTime receipt_time,QuicByteCount length,QuicEcnCodepoint ecn_codepoint)4933 QuicConnection::ReceivedPacketInfo::ReceivedPacketInfo(
4934 const QuicSocketAddress& destination_address,
4935 const QuicSocketAddress& source_address, QuicTime receipt_time,
4936 QuicByteCount length, QuicEcnCodepoint ecn_codepoint)
4937 : destination_address(destination_address),
4938 source_address(source_address),
4939 receipt_time(receipt_time),
4940 length(length),
4941 ecn_codepoint(ecn_codepoint) {}
4942
operator <<(std::ostream & os,const QuicConnection::ReceivedPacketInfo & info)4943 std::ostream& operator<<(std::ostream& os,
4944 const QuicConnection::ReceivedPacketInfo& info) {
4945 os << " { destination_address: " << info.destination_address.ToString()
4946 << ", source_address: " << info.source_address.ToString()
4947 << ", received_bytes_counted: " << info.received_bytes_counted
4948 << ", length: " << info.length
4949 << ", destination_connection_id: " << info.destination_connection_id;
4950 if (!info.decrypted) {
4951 os << " }\n";
4952 return os;
4953 }
4954 os << ", decrypted: " << info.decrypted
4955 << ", decrypted_level: " << EncryptionLevelToString(info.decrypted_level)
4956 << ", header: " << info.header << ", frames: ";
4957 for (const auto frame : info.frames) {
4958 os << frame;
4959 }
4960 os << " }\n";
4961 return os;
4962 }
4963
IsRetransmittable(const SerializedPacket & packet)4964 HasRetransmittableData QuicConnection::IsRetransmittable(
4965 const SerializedPacket& packet) {
4966 // Retransmitted packets retransmittable frames are owned by the unacked
4967 // packet map, but are not present in the serialized packet.
4968 if (packet.transmission_type != NOT_RETRANSMISSION ||
4969 !packet.retransmittable_frames.empty()) {
4970 return HAS_RETRANSMITTABLE_DATA;
4971 } else {
4972 return NO_RETRANSMITTABLE_DATA;
4973 }
4974 }
4975
IsTerminationPacket(const SerializedPacket & packet,QuicErrorCode * error_code)4976 bool QuicConnection::IsTerminationPacket(const SerializedPacket& packet,
4977 QuicErrorCode* error_code) {
4978 if (packet.retransmittable_frames.empty()) {
4979 return false;
4980 }
4981 for (const QuicFrame& frame : packet.retransmittable_frames) {
4982 if (frame.type == CONNECTION_CLOSE_FRAME) {
4983 *error_code = frame.connection_close_frame->quic_error_code;
4984 return true;
4985 }
4986 }
4987 return false;
4988 }
4989
SetMtuDiscoveryTarget(QuicByteCount target)4990 void QuicConnection::SetMtuDiscoveryTarget(QuicByteCount target) {
4991 QUIC_DVLOG(2) << ENDPOINT << "SetMtuDiscoveryTarget: " << target;
4992 mtu_discoverer_.Disable();
4993 mtu_discoverer_.Enable(max_packet_length(), GetLimitedMaxPacketSize(target));
4994 }
4995
GetLimitedMaxPacketSize(QuicByteCount suggested_max_packet_size)4996 QuicByteCount QuicConnection::GetLimitedMaxPacketSize(
4997 QuicByteCount suggested_max_packet_size) {
4998 if (!peer_address().IsInitialized()) {
4999 QUIC_BUG(quic_bug_10511_30)
5000 << "Attempted to use a connection without a valid peer address";
5001 return suggested_max_packet_size;
5002 }
5003
5004 const QuicByteCount writer_limit = writer_->GetMaxPacketSize(peer_address());
5005
5006 QuicByteCount max_packet_size = suggested_max_packet_size;
5007 if (max_packet_size > writer_limit) {
5008 max_packet_size = writer_limit;
5009 }
5010 if (max_packet_size > peer_max_packet_size_) {
5011 max_packet_size = peer_max_packet_size_;
5012 }
5013 if (max_packet_size > kMaxOutgoingPacketSize) {
5014 max_packet_size = kMaxOutgoingPacketSize;
5015 }
5016 return max_packet_size;
5017 }
5018
SendMtuDiscoveryPacket(QuicByteCount target_mtu)5019 void QuicConnection::SendMtuDiscoveryPacket(QuicByteCount target_mtu) {
5020 // Currently, this limit is ensured by the caller.
5021 QUICHE_DCHECK_EQ(target_mtu, GetLimitedMaxPacketSize(target_mtu));
5022
5023 // Send the probe.
5024 packet_creator_.GenerateMtuDiscoveryPacket(target_mtu);
5025 }
5026
5027 // TODO(zhongyi): change this method to generate a connectivity probing packet
5028 // and let the caller to call writer to write the packet and handle write
5029 // status.
SendConnectivityProbingPacket(QuicPacketWriter * probing_writer,const QuicSocketAddress & peer_address)5030 bool QuicConnection::SendConnectivityProbingPacket(
5031 QuicPacketWriter* probing_writer, const QuicSocketAddress& peer_address) {
5032 QUICHE_DCHECK(peer_address.IsInitialized());
5033 if (!connected_) {
5034 QUIC_BUG(quic_bug_10511_31)
5035 << "Not sending connectivity probing packet as connection is "
5036 << "disconnected.";
5037 return false;
5038 }
5039 if (perspective_ == Perspective::IS_SERVER && probing_writer == nullptr) {
5040 // Server can use default packet writer to write packet.
5041 probing_writer = writer_;
5042 }
5043 QUICHE_DCHECK(probing_writer);
5044
5045 if (probing_writer->IsWriteBlocked()) {
5046 QUIC_DLOG(INFO)
5047 << ENDPOINT
5048 << "Writer blocked when sending connectivity probing packet.";
5049 if (probing_writer == writer_) {
5050 // Visitor should not be write blocked if the probing writer is not the
5051 // default packet writer.
5052 visitor_->OnWriteBlocked();
5053 }
5054 return true;
5055 }
5056
5057 QUIC_DLOG(INFO) << ENDPOINT
5058 << "Sending path probe packet for connection_id = "
5059 << default_path_.server_connection_id;
5060
5061 std::unique_ptr<SerializedPacket> probing_packet;
5062 if (!version().HasIetfQuicFrames()) {
5063 // Non-IETF QUIC, generate a padded ping regardless of whether this is a
5064 // request or a response.
5065 probing_packet = packet_creator_.SerializeConnectivityProbingPacket();
5066 } else {
5067 // IETF QUIC path challenge.
5068 // Send a path probe request using IETF QUIC PATH_CHALLENGE frame.
5069 QuicPathFrameBuffer transmitted_connectivity_probe_payload;
5070 random_generator_->RandBytes(&transmitted_connectivity_probe_payload,
5071 sizeof(QuicPathFrameBuffer));
5072 probing_packet =
5073 packet_creator_.SerializePathChallengeConnectivityProbingPacket(
5074 transmitted_connectivity_probe_payload);
5075 }
5076 QUICHE_DCHECK_EQ(IsRetransmittable(*probing_packet), NO_RETRANSMITTABLE_DATA);
5077 return WritePacketUsingWriter(std::move(probing_packet), probing_writer,
5078 self_address(), peer_address,
5079 /*measure_rtt=*/true);
5080 }
5081
WritePacketUsingWriter(std::unique_ptr<SerializedPacket> packet,QuicPacketWriter * writer,const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,bool measure_rtt)5082 bool QuicConnection::WritePacketUsingWriter(
5083 std::unique_ptr<SerializedPacket> packet, QuicPacketWriter* writer,
5084 const QuicSocketAddress& self_address,
5085 const QuicSocketAddress& peer_address, bool measure_rtt) {
5086 const QuicTime packet_send_time = clock_->Now();
5087 QUIC_BUG_IF(write using blocked writer, writer->IsWriteBlocked());
5088 QUIC_DVLOG(2) << ENDPOINT
5089 << "Sending path probe packet for server connection ID "
5090 << default_path_.server_connection_id << std::endl
5091 << quiche::QuicheTextUtils::HexDump(absl::string_view(
5092 packet->encrypted_buffer, packet->encrypted_length));
5093 WriteResult result = SendPacketToWriter(
5094 packet->encrypted_buffer, packet->encrypted_length, self_address.host(),
5095 peer_address, writer, GetEcnCodepointToSend(peer_address));
5096
5097 const uint32_t writer_batch_id = result.batch_id;
5098
5099 // If using a batch writer and the probing packet is buffered, flush it.
5100 if (writer->IsBatchMode() && result.status == WRITE_STATUS_OK &&
5101 result.bytes_written == 0) {
5102 result = writer->Flush();
5103 }
5104
5105 if (IsWriteError(result.status)) {
5106 // Write error for any connectivity probe should not affect the connection
5107 // as it is sent on a different path.
5108 QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet failed with error = "
5109 << result.error_code;
5110 return false;
5111 }
5112
5113 // Send in currrent path. Call OnPacketSent regardless of the write result.
5114 sent_packet_manager_.OnPacketSent(
5115 packet.get(), packet_send_time, packet->transmission_type,
5116 NO_RETRANSMITTABLE_DATA, measure_rtt, last_ecn_codepoint_sent_);
5117
5118 if (debug_visitor_ != nullptr) {
5119 if (sent_packet_manager_.unacked_packets().empty()) {
5120 QUIC_BUG(quic_bug_10511_32)
5121 << "Unacked map is empty right after packet is sent";
5122 } else {
5123 debug_visitor_->OnPacketSent(
5124 packet->packet_number, packet->encrypted_length,
5125 packet->has_crypto_handshake, packet->transmission_type,
5126 packet->encryption_level,
5127 sent_packet_manager_.unacked_packets()
5128 .rbegin()
5129 ->retransmittable_frames,
5130 packet->nonretransmittable_frames, packet_send_time, writer_batch_id);
5131 }
5132 }
5133
5134 if (IsWriteBlockedStatus(result.status)) {
5135 if (writer == writer_) {
5136 // Visitor should not be write blocked if the probing writer is not the
5137 // default packet writer.
5138 visitor_->OnWriteBlocked();
5139 }
5140 if (result.status == WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
5141 QUIC_DLOG(INFO) << ENDPOINT << "Write probing packet blocked";
5142 }
5143 }
5144
5145 return true;
5146 }
5147
DisableMtuDiscovery()5148 void QuicConnection::DisableMtuDiscovery() {
5149 mtu_discoverer_.Disable();
5150 mtu_discovery_alarm_->Cancel();
5151 }
5152
DiscoverMtu()5153 void QuicConnection::DiscoverMtu() {
5154 QUICHE_DCHECK(!mtu_discovery_alarm_->IsSet());
5155
5156 const QuicPacketNumber largest_sent_packet =
5157 sent_packet_manager_.GetLargestSentPacket();
5158 if (mtu_discoverer_.ShouldProbeMtu(largest_sent_packet)) {
5159 ++mtu_probe_count_;
5160 SendMtuDiscoveryPacket(
5161 mtu_discoverer_.GetUpdatedMtuProbeSize(largest_sent_packet));
5162 }
5163 QUICHE_DCHECK(!mtu_discovery_alarm_->IsSet());
5164 }
5165
OnEffectivePeerMigrationValidated(bool)5166 void QuicConnection::OnEffectivePeerMigrationValidated(
5167 bool /*is_migration_linkable*/) {
5168 if (active_effective_peer_migration_type_ == NO_CHANGE) {
5169 QUIC_BUG(quic_bug_10511_33) << "No migration underway.";
5170 return;
5171 }
5172 highest_packet_sent_before_effective_peer_migration_.Clear();
5173 const bool send_address_token =
5174 active_effective_peer_migration_type_ != PORT_CHANGE;
5175 active_effective_peer_migration_type_ = NO_CHANGE;
5176 ++stats_.num_validated_peer_migration;
5177 if (!framer_.version().HasIetfQuicFrames()) {
5178 return;
5179 }
5180 if (debug_visitor_ != nullptr) {
5181 const QuicTime now = clock_->ApproximateNow();
5182 if (now >= stats_.handshake_completion_time) {
5183 debug_visitor_->OnPeerMigrationValidated(
5184 now - stats_.handshake_completion_time);
5185 } else {
5186 QUIC_BUG(quic_bug_10511_34)
5187 << "Handshake completion time is larger than current time.";
5188 }
5189 }
5190
5191 // Lift anti-amplification limit.
5192 default_path_.validated = true;
5193 alternative_path_.Clear();
5194 if (send_address_token) {
5195 visitor_->MaybeSendAddressToken();
5196 }
5197 }
5198
StartEffectivePeerMigration(AddressChangeType type)5199 void QuicConnection::StartEffectivePeerMigration(AddressChangeType type) {
5200 // TODO(fayang): Currently, all peer address change type are allowed. Need to
5201 // add a method ShouldAllowPeerAddressChange(PeerAddressChangeType type) to
5202 // determine whether |type| is allowed.
5203 if (!framer_.version().HasIetfQuicFrames()) {
5204 if (type == NO_CHANGE) {
5205 QUIC_BUG(quic_bug_10511_35)
5206 << "EffectivePeerMigration started without address change.";
5207 return;
5208 }
5209 QUIC_DLOG(INFO)
5210 << ENDPOINT << "Effective peer's ip:port changed from "
5211 << default_path_.peer_address.ToString() << " to "
5212 << GetEffectivePeerAddressFromCurrentPacket().ToString()
5213 << ", address change type is " << type
5214 << ", migrating connection without validating new client address.";
5215
5216 highest_packet_sent_before_effective_peer_migration_ =
5217 sent_packet_manager_.GetLargestSentPacket();
5218 default_path_.peer_address = GetEffectivePeerAddressFromCurrentPacket();
5219 active_effective_peer_migration_type_ = type;
5220
5221 OnConnectionMigration();
5222 return;
5223 }
5224
5225 if (type == NO_CHANGE) {
5226 UpdatePeerAddress(last_received_packet_info_.source_address);
5227 QUIC_BUG(quic_bug_10511_36)
5228 << "EffectivePeerMigration started without address change.";
5229 return;
5230 }
5231 // There could be pending NEW_TOKEN_FRAME triggered by non-probing
5232 // PATH_RESPONSE_FRAME in the same packet or pending padding bytes in the
5233 // packet creator.
5234 packet_creator_.FlushCurrentPacket();
5235 packet_creator_.SendRemainingPendingPadding();
5236 if (!connected_) {
5237 return;
5238 }
5239
5240 // Action items:
5241 // 1. Switch congestion controller;
5242 // 2. Update default_path_ (addresses, validation and bytes accounting);
5243 // 3. Save previous default path if needed;
5244 // 4. Kick off reverse path validation if needed.
5245 // Items 1 and 2 are must-to-do. Items 3 and 4 depends on if the new address
5246 // is validated or not and which path the incoming packet is on.
5247
5248 const QuicSocketAddress current_effective_peer_address =
5249 GetEffectivePeerAddressFromCurrentPacket();
5250 QUIC_DLOG(INFO) << ENDPOINT << "Effective peer's ip:port changed from "
5251 << default_path_.peer_address.ToString() << " to "
5252 << current_effective_peer_address.ToString()
5253 << ", address change type is " << type
5254 << ", migrating connection.";
5255
5256 const QuicSocketAddress previous_direct_peer_address = direct_peer_address_;
5257 PathState previous_default_path = std::move(default_path_);
5258 active_effective_peer_migration_type_ = type;
5259 MaybeClearQueuedPacketsOnPathChange();
5260 OnConnectionMigration();
5261
5262 // Update congestion controller if the address change type is not PORT_CHANGE.
5263 if (type == PORT_CHANGE) {
5264 QUICHE_DCHECK(previous_default_path.validated ||
5265 (alternative_path_.validated &&
5266 alternative_path_.send_algorithm != nullptr));
5267 // No need to store previous congestion controller because either the new
5268 // default path is validated or the alternative path is validated and
5269 // already has associated congestion controller.
5270 } else {
5271 previous_default_path.rtt_stats.emplace();
5272 previous_default_path.rtt_stats->CloneFrom(
5273 *sent_packet_manager_.GetRttStats());
5274 // If the new peer address share the same IP with the alternative path, the
5275 // connection should switch to the congestion controller of the alternative
5276 // path. Otherwise, the connection should use a brand new one.
5277 // In order to re-use existing code in sent_packet_manager_, reset
5278 // congestion controller to initial state first and then change to the one
5279 // on alternative path.
5280 // TODO(danzh) combine these two steps into one after deprecating gQUIC.
5281 previous_default_path.send_algorithm = OnPeerIpAddressChanged();
5282
5283 if (alternative_path_.peer_address.host() ==
5284 current_effective_peer_address.host() &&
5285 alternative_path_.send_algorithm != nullptr &&
5286 alternative_path_.rtt_stats.has_value()) {
5287 // Update the default path with the congestion controller of the
5288 // alternative path.
5289 sent_packet_manager_.SetSendAlgorithm(
5290 alternative_path_.send_algorithm.release());
5291 sent_packet_manager_.SetRttStats(*alternative_path_.rtt_stats);
5292
5293 // Explicitly clear alternative_path_.rtt_stats
5294 alternative_path_.rtt_stats = std::nullopt;
5295 }
5296 }
5297 // Update to the new peer address.
5298 UpdatePeerAddress(last_received_packet_info_.source_address);
5299 // Update the default path.
5300 if (IsAlternativePath(last_received_packet_info_.destination_address,
5301 current_effective_peer_address)) {
5302 SetDefaultPathState(std::move(alternative_path_));
5303 } else {
5304 QuicConnectionId client_connection_id;
5305 std::optional<StatelessResetToken> stateless_reset_token;
5306 FindMatchingOrNewClientConnectionIdOrToken(
5307 previous_default_path, alternative_path_,
5308 last_received_packet_info_.destination_connection_id,
5309 &client_connection_id, &stateless_reset_token);
5310 SetDefaultPathState(
5311 PathState(last_received_packet_info_.destination_address,
5312 current_effective_peer_address, client_connection_id,
5313 last_received_packet_info_.destination_connection_id,
5314 stateless_reset_token));
5315 // The path is considered validated if its peer IP address matches any
5316 // validated path's peer IP address.
5317 default_path_.validated =
5318 (alternative_path_.peer_address.host() ==
5319 current_effective_peer_address.host() &&
5320 alternative_path_.validated) ||
5321 (previous_default_path.validated && type == PORT_CHANGE);
5322 }
5323 if (!last_received_packet_info_.received_bytes_counted) {
5324 // Increment bytes counting on the new default path.
5325 default_path_.bytes_received_before_address_validation +=
5326 last_received_packet_info_.length;
5327 last_received_packet_info_.received_bytes_counted = true;
5328 }
5329
5330 if (!previous_default_path.validated) {
5331 // If the old address is under validation, cancel and fail it. Failing to
5332 // validate the old path shouldn't take any effect.
5333 QUIC_DVLOG(1) << "Cancel validation of previous peer address change to "
5334 << previous_default_path.peer_address
5335 << " upon peer migration to " << default_path_.peer_address;
5336 path_validator_.CancelPathValidation();
5337 ++stats_.num_peer_migration_while_validating_default_path;
5338 }
5339
5340 // Clear alternative path if the new default path shares the same IP as the
5341 // alternative path.
5342 if (alternative_path_.peer_address.host() ==
5343 default_path_.peer_address.host()) {
5344 alternative_path_.Clear();
5345 }
5346
5347 if (default_path_.validated) {
5348 QUIC_DVLOG(1) << "Peer migrated to a validated address.";
5349 // No need to save previous default path, validate new peer address or
5350 // update bytes sent/received.
5351 if (!(previous_default_path.validated && type == PORT_CHANGE)) {
5352 // The alternative path was validated because of proactive reverse path
5353 // validation.
5354 ++stats_.num_peer_migration_to_proactively_validated_address;
5355 }
5356 OnEffectivePeerMigrationValidated(
5357 default_path_.server_connection_id ==
5358 previous_default_path.server_connection_id);
5359 return;
5360 }
5361
5362 // The new default address is not validated yet. Anti-amplification limit is
5363 // enforced.
5364 QUICHE_DCHECK(EnforceAntiAmplificationLimit());
5365 QUIC_DVLOG(1) << "Apply anti-amplification limit to effective peer address "
5366 << default_path_.peer_address << " with "
5367 << default_path_.bytes_sent_before_address_validation
5368 << " bytes sent and "
5369 << default_path_.bytes_received_before_address_validation
5370 << " bytes received.";
5371
5372 QUICHE_DCHECK(!alternative_path_.peer_address.IsInitialized() ||
5373 alternative_path_.peer_address.host() !=
5374 default_path_.peer_address.host());
5375
5376 // Save previous default path to the altenative path.
5377 if (previous_default_path.validated) {
5378 // The old path is a validated path which the connection might revert back
5379 // to later. Store it as the alternative path.
5380 alternative_path_ = std::move(previous_default_path);
5381 QUICHE_DCHECK(alternative_path_.send_algorithm != nullptr);
5382 }
5383
5384 // If the new address is not validated and the connection is not already
5385 // validating that address, a new reverse path validation is needed.
5386 if (!path_validator_.IsValidatingPeerAddress(
5387 current_effective_peer_address)) {
5388 ++stats_.num_reverse_path_validtion_upon_migration;
5389 ValidatePath(std::make_unique<ReversePathValidationContext>(
5390 default_path_.self_address, peer_address(),
5391 default_path_.peer_address, this),
5392 std::make_unique<ReversePathValidationResultDelegate>(
5393 this, previous_direct_peer_address),
5394 PathValidationReason::kReversePathValidation);
5395 } else {
5396 QUIC_DVLOG(1) << "Peer address " << default_path_.peer_address
5397 << " is already under validation, wait for result.";
5398 ++stats_.num_peer_migration_to_proactively_validated_address;
5399 }
5400 }
5401
OnConnectionMigration()5402 void QuicConnection::OnConnectionMigration() {
5403 if (debug_visitor_ != nullptr) {
5404 const QuicTime now = clock_->ApproximateNow();
5405 if (now >= stats_.handshake_completion_time) {
5406 debug_visitor_->OnPeerAddressChange(
5407 active_effective_peer_migration_type_,
5408 now - stats_.handshake_completion_time);
5409 }
5410 }
5411 visitor_->OnConnectionMigration(active_effective_peer_migration_type_);
5412 if (active_effective_peer_migration_type_ != PORT_CHANGE &&
5413 active_effective_peer_migration_type_ != IPV4_SUBNET_CHANGE &&
5414 !framer_.version().HasIetfQuicFrames()) {
5415 sent_packet_manager_.OnConnectionMigration(/*reset_send_algorithm=*/false);
5416 }
5417 }
5418
IsCurrentPacketConnectivityProbing() const5419 bool QuicConnection::IsCurrentPacketConnectivityProbing() const {
5420 return is_current_packet_connectivity_probing_;
5421 }
5422
ack_frame_updated() const5423 bool QuicConnection::ack_frame_updated() const {
5424 return uber_received_packet_manager_.IsAckFrameUpdated();
5425 }
5426
GetCurrentPacket()5427 absl::string_view QuicConnection::GetCurrentPacket() {
5428 if (current_packet_data_ == nullptr) {
5429 return absl::string_view();
5430 }
5431 return absl::string_view(current_packet_data_,
5432 last_received_packet_info_.length);
5433 }
5434
MaybeConsiderAsMemoryCorruption(const QuicStreamFrame & frame)5435 bool QuicConnection::MaybeConsiderAsMemoryCorruption(
5436 const QuicStreamFrame& frame) {
5437 if (QuicUtils::IsCryptoStreamId(transport_version(), frame.stream_id) ||
5438 last_received_packet_info_.decrypted_level != ENCRYPTION_INITIAL) {
5439 return false;
5440 }
5441
5442 if (perspective_ == Perspective::IS_SERVER &&
5443 frame.data_length >= sizeof(kCHLO) &&
5444 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kCHLO),
5445 sizeof(kCHLO)) == 0) {
5446 return true;
5447 }
5448
5449 if (perspective_ == Perspective::IS_CLIENT &&
5450 frame.data_length >= sizeof(kREJ) &&
5451 strncmp(frame.data_buffer, reinterpret_cast<const char*>(&kREJ),
5452 sizeof(kREJ)) == 0) {
5453 return true;
5454 }
5455
5456 return false;
5457 }
5458
CheckIfApplicationLimited()5459 void QuicConnection::CheckIfApplicationLimited() {
5460 if (!connected_) {
5461 return;
5462 }
5463
5464 bool application_limited =
5465 buffered_packets_.empty() && !visitor_->WillingAndAbleToWrite();
5466
5467 if (!application_limited) {
5468 return;
5469 }
5470
5471 sent_packet_manager_.OnApplicationLimited();
5472 }
5473
UpdatePacketContent(QuicFrameType type)5474 bool QuicConnection::UpdatePacketContent(QuicFrameType type) {
5475 last_received_packet_info_.frames.push_back(type);
5476 if (version().HasIetfQuicFrames()) {
5477 if (perspective_ == Perspective::IS_CLIENT) {
5478 return connected_;
5479 }
5480 if (!QuicUtils::IsProbingFrame(type)) {
5481 MaybeStartIetfPeerMigration();
5482 return connected_;
5483 }
5484 QuicSocketAddress current_effective_peer_address =
5485 GetEffectivePeerAddressFromCurrentPacket();
5486 if (IsDefaultPath(last_received_packet_info_.destination_address,
5487 last_received_packet_info_.source_address)) {
5488 return connected_;
5489 }
5490 if (type == PATH_CHALLENGE_FRAME &&
5491 !IsAlternativePath(last_received_packet_info_.destination_address,
5492 current_effective_peer_address)) {
5493 QUIC_DVLOG(1)
5494 << "The peer is probing a new path with effective peer address "
5495 << current_effective_peer_address << ", self address "
5496 << last_received_packet_info_.destination_address;
5497 if (!default_path_.validated) {
5498 // Skip reverse path validation because either handshake hasn't
5499 // completed or the connection is validating the default path. Using
5500 // PATH_CHALLENGE to validate alternative client address before
5501 // handshake gets comfirmed is meaningless because anyone can respond to
5502 // it. If the connection is validating the default path, this
5503 // alternative path is currently the only validated path which shouldn't
5504 // be overridden.
5505 QUIC_DVLOG(1) << "The connection hasn't finished handshake or is "
5506 "validating a recent peer address change.";
5507 QUIC_BUG_IF(quic_bug_12714_30,
5508 IsHandshakeConfirmed() && !alternative_path_.validated)
5509 << "No validated peer address to send after handshake comfirmed.";
5510 } else if (!IsReceivedPeerAddressValidated()) {
5511 QuicConnectionId client_connection_id;
5512 std::optional<StatelessResetToken> stateless_reset_token;
5513 FindMatchingOrNewClientConnectionIdOrToken(
5514 default_path_, alternative_path_,
5515 last_received_packet_info_.destination_connection_id,
5516 &client_connection_id, &stateless_reset_token);
5517 // Only override alternative path state upon receiving a PATH_CHALLENGE
5518 // from an unvalidated peer address, and the connection isn't validating
5519 // a recent peer migration.
5520 alternative_path_ =
5521 PathState(last_received_packet_info_.destination_address,
5522 current_effective_peer_address, client_connection_id,
5523 last_received_packet_info_.destination_connection_id,
5524 stateless_reset_token);
5525 should_proactively_validate_peer_address_on_path_challenge_ = true;
5526 }
5527 }
5528 MaybeUpdateBytesReceivedFromAlternativeAddress(
5529 last_received_packet_info_.length);
5530 return connected_;
5531 }
5532
5533 if (!ignore_gquic_probing_) {
5534 // Packet content is tracked to identify connectivity probe in non-IETF
5535 // version, where a connectivity probe is defined as
5536 // - a padded PING packet with peer address change received by server,
5537 // - a padded PING packet on new path received by client.
5538
5539 if (current_packet_content_ == NOT_PADDED_PING) {
5540 // We have already learned the current packet is not a connectivity
5541 // probing packet. Peer migration should have already been started earlier
5542 // if needed.
5543 return connected_;
5544 }
5545
5546 if (type == PING_FRAME) {
5547 if (current_packet_content_ == NO_FRAMES_RECEIVED) {
5548 current_packet_content_ = FIRST_FRAME_IS_PING;
5549 return connected_;
5550 }
5551 }
5552
5553 // In Google QUIC, we look for a packet with just a PING and PADDING.
5554 // If the condition is met, mark things as connectivity-probing, causing
5555 // later processing to generate the correct response.
5556 if (type == PADDING_FRAME &&
5557 current_packet_content_ == FIRST_FRAME_IS_PING) {
5558 current_packet_content_ = SECOND_FRAME_IS_PADDING;
5559 QUIC_CODE_COUNT_N(gquic_padded_ping_received, 1, 2);
5560 if (perspective_ == Perspective::IS_SERVER) {
5561 is_current_packet_connectivity_probing_ =
5562 current_effective_peer_migration_type_ != NO_CHANGE;
5563 if (is_current_packet_connectivity_probing_) {
5564 QUIC_CODE_COUNT_N(gquic_padded_ping_received, 2, 2);
5565 }
5566 QUIC_DLOG_IF(INFO, is_current_packet_connectivity_probing_)
5567 << ENDPOINT
5568 << "Detected connectivity probing packet. "
5569 "current_effective_peer_migration_type_:"
5570 << current_effective_peer_migration_type_;
5571 } else {
5572 is_current_packet_connectivity_probing_ =
5573 (last_received_packet_info_.source_address != peer_address()) ||
5574 (last_received_packet_info_.destination_address !=
5575 default_path_.self_address);
5576 QUIC_DLOG_IF(INFO, is_current_packet_connectivity_probing_)
5577 << ENDPOINT
5578 << "Detected connectivity probing packet. "
5579 "last_packet_source_address:"
5580 << last_received_packet_info_.source_address
5581 << ", peer_address_:" << peer_address()
5582 << ", last_packet_destination_address:"
5583 << last_received_packet_info_.destination_address
5584 << ", default path self_address :" << default_path_.self_address;
5585 }
5586 return connected_;
5587 }
5588
5589 current_packet_content_ = NOT_PADDED_PING;
5590 } else {
5591 QUIC_RELOADABLE_FLAG_COUNT(quic_ignore_gquic_probing);
5592 QUICHE_DCHECK_EQ(current_packet_content_, NO_FRAMES_RECEIVED);
5593 }
5594
5595 if (GetLargestReceivedPacket().IsInitialized() &&
5596 last_received_packet_info_.header.packet_number ==
5597 GetLargestReceivedPacket()) {
5598 UpdatePeerAddress(last_received_packet_info_.source_address);
5599 if (current_effective_peer_migration_type_ != NO_CHANGE) {
5600 // Start effective peer migration immediately when the current packet is
5601 // confirmed not a connectivity probing packet.
5602 StartEffectivePeerMigration(current_effective_peer_migration_type_);
5603 }
5604 }
5605 current_effective_peer_migration_type_ = NO_CHANGE;
5606 return connected_;
5607 }
5608
MaybeStartIetfPeerMigration()5609 void QuicConnection::MaybeStartIetfPeerMigration() {
5610 QUICHE_DCHECK(version().HasIetfQuicFrames());
5611 if (current_effective_peer_migration_type_ != NO_CHANGE &&
5612 !IsHandshakeConfirmed()) {
5613 QUIC_LOG_EVERY_N_SEC(INFO, 60)
5614 << ENDPOINT << "Effective peer's ip:port changed from "
5615 << default_path_.peer_address.ToString() << " to "
5616 << GetEffectivePeerAddressFromCurrentPacket().ToString()
5617 << " before handshake confirmed, "
5618 "current_effective_peer_migration_type_: "
5619 << current_effective_peer_migration_type_;
5620 // Peer migrated before handshake gets confirmed.
5621 CloseConnection((current_effective_peer_migration_type_ == PORT_CHANGE
5622 ? QUIC_PEER_PORT_CHANGE_HANDSHAKE_UNCONFIRMED
5623 : QUIC_CONNECTION_MIGRATION_HANDSHAKE_UNCONFIRMED),
5624 "Peer address changed before handshake is confirmed.",
5625 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
5626 return;
5627 }
5628
5629 if (GetLargestReceivedPacket().IsInitialized() &&
5630 last_received_packet_info_.header.packet_number ==
5631 GetLargestReceivedPacket()) {
5632 if (current_effective_peer_migration_type_ != NO_CHANGE) {
5633 // Start effective peer migration when the current packet contains a
5634 // non-probing frame.
5635 // TODO(fayang): When multiple packet number spaces is supported, only
5636 // start peer migration for the application data.
5637 StartEffectivePeerMigration(current_effective_peer_migration_type_);
5638 } else {
5639 UpdatePeerAddress(last_received_packet_info_.source_address);
5640 }
5641 }
5642 current_effective_peer_migration_type_ = NO_CHANGE;
5643 }
5644
PostProcessAfterAckFrame(bool acked_new_packet)5645 void QuicConnection::PostProcessAfterAckFrame(bool acked_new_packet) {
5646 if (!packet_creator_.has_ack()) {
5647 uber_received_packet_manager_.DontWaitForPacketsBefore(
5648 last_received_packet_info_.decrypted_level,
5649 SupportsMultiplePacketNumberSpaces()
5650 ? sent_packet_manager_.GetLargestPacketPeerKnowsIsAcked(
5651 last_received_packet_info_.decrypted_level)
5652 : sent_packet_manager_.largest_packet_peer_knows_is_acked());
5653 }
5654 // Always reset the retransmission alarm when an ack comes in, since we now
5655 // have a better estimate of the current rtt than when it was set.
5656 SetRetransmissionAlarm();
5657 if (acked_new_packet) {
5658 OnForwardProgressMade();
5659 } else if (default_enable_5rto_blackhole_detection_ &&
5660 !sent_packet_manager_.HasInFlightPackets() &&
5661 blackhole_detector_.IsDetectionInProgress()) {
5662 // In case no new packets get acknowledged, it is possible packets are
5663 // detected lost because of time based loss detection. Cancel blackhole
5664 // detection if there is no packets in flight.
5665 blackhole_detector_.StopDetection(/*permanent=*/false);
5666 }
5667 }
5668
SetSessionNotifier(SessionNotifierInterface * session_notifier)5669 void QuicConnection::SetSessionNotifier(
5670 SessionNotifierInterface* session_notifier) {
5671 sent_packet_manager_.SetSessionNotifier(session_notifier);
5672 }
5673
SetDataProducer(QuicStreamFrameDataProducer * data_producer)5674 void QuicConnection::SetDataProducer(
5675 QuicStreamFrameDataProducer* data_producer) {
5676 framer_.set_data_producer(data_producer);
5677 }
5678
SetTransmissionType(TransmissionType type)5679 void QuicConnection::SetTransmissionType(TransmissionType type) {
5680 packet_creator_.SetTransmissionType(type);
5681 }
5682
UpdateReleaseTimeIntoFuture()5683 void QuicConnection::UpdateReleaseTimeIntoFuture() {
5684 QUICHE_DCHECK(supports_release_time_);
5685
5686 const QuicTime::Delta prior_max_release_time = release_time_into_future_;
5687 release_time_into_future_ = std::max(
5688 QuicTime::Delta::FromMilliseconds(kMinReleaseTimeIntoFutureMs),
5689 std::min(QuicTime::Delta::FromMilliseconds(
5690 GetQuicFlag(quic_max_pace_time_into_future_ms)),
5691 sent_packet_manager_.GetRttStats()->SmoothedOrInitialRtt() *
5692 GetQuicFlag(quic_pace_time_into_future_srtt_fraction)));
5693 QUIC_DVLOG(3) << "Updated max release time delay from "
5694 << prior_max_release_time << " to "
5695 << release_time_into_future_;
5696 }
5697
ResetAckStates()5698 void QuicConnection::ResetAckStates() {
5699 ack_alarm_->Cancel();
5700 uber_received_packet_manager_.ResetAckStates(encryption_level_);
5701 }
5702
SendMessage(QuicMessageId message_id,absl::Span<quiche::QuicheMemSlice> message,bool flush)5703 MessageStatus QuicConnection::SendMessage(
5704 QuicMessageId message_id, absl::Span<quiche::QuicheMemSlice> message,
5705 bool flush) {
5706 if (MemSliceSpanTotalSize(message) > GetCurrentLargestMessagePayload()) {
5707 return MESSAGE_STATUS_TOO_LARGE;
5708 }
5709 if (!connected_ || (!flush && !CanWrite(HAS_RETRANSMITTABLE_DATA))) {
5710 return MESSAGE_STATUS_BLOCKED;
5711 }
5712 ScopedPacketFlusher flusher(this);
5713 return packet_creator_.AddMessageFrame(message_id, message);
5714 }
5715
GetCurrentLargestMessagePayload() const5716 QuicPacketLength QuicConnection::GetCurrentLargestMessagePayload() const {
5717 return packet_creator_.GetCurrentLargestMessagePayload();
5718 }
5719
GetGuaranteedLargestMessagePayload() const5720 QuicPacketLength QuicConnection::GetGuaranteedLargestMessagePayload() const {
5721 return packet_creator_.GetGuaranteedLargestMessagePayload();
5722 }
5723
cipher_id() const5724 uint32_t QuicConnection::cipher_id() const {
5725 if (version().KnowsWhichDecrypterToUse()) {
5726 return framer_.GetDecrypter(last_received_packet_info_.decrypted_level)
5727 ->cipher_id();
5728 }
5729 return framer_.decrypter()->cipher_id();
5730 }
5731
GetConnectionCloseEncryptionLevel() const5732 EncryptionLevel QuicConnection::GetConnectionCloseEncryptionLevel() const {
5733 if (perspective_ == Perspective::IS_CLIENT) {
5734 return encryption_level_;
5735 }
5736 if (IsHandshakeComplete()) {
5737 // A forward secure packet has been received.
5738 QUIC_BUG_IF(quic_bug_12714_31,
5739 encryption_level_ != ENCRYPTION_FORWARD_SECURE)
5740 << ENDPOINT << "Unexpected connection close encryption level "
5741 << encryption_level_;
5742 return ENCRYPTION_FORWARD_SECURE;
5743 }
5744 if (framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_ZERO_RTT)) {
5745 if (encryption_level_ != ENCRYPTION_ZERO_RTT) {
5746 QUIC_CODE_COUNT(quic_wrong_encryption_level_connection_close_ietf);
5747 }
5748 return ENCRYPTION_ZERO_RTT;
5749 }
5750 return ENCRYPTION_INITIAL;
5751 }
5752
MaybeBundleCryptoDataWithAcks()5753 void QuicConnection::MaybeBundleCryptoDataWithAcks() {
5754 QUICHE_DCHECK(SupportsMultiplePacketNumberSpaces());
5755 if (IsHandshakeConfirmed()) {
5756 return;
5757 }
5758 PacketNumberSpace space = HANDSHAKE_DATA;
5759 if (perspective() == Perspective::IS_SERVER &&
5760 framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL)) {
5761 // On the server side, sends INITIAL data with INITIAL ACK if initial key is
5762 // available.
5763 space = INITIAL_DATA;
5764 }
5765 const QuicTime ack_timeout =
5766 uber_received_packet_manager_.GetAckTimeout(space);
5767 if (!ack_timeout.IsInitialized() ||
5768 (ack_timeout > clock_->ApproximateNow() &&
5769 ack_timeout > uber_received_packet_manager_.GetEarliestAckTimeout())) {
5770 // No pending ACK of space.
5771 return;
5772 }
5773 if (coalesced_packet_.length() > 0) {
5774 // Do not bundle CRYPTO data if the ACK could be coalesced with other
5775 // packets.
5776 return;
5777 }
5778
5779 if (!framer_.HasAnEncrypterForSpace(space)) {
5780 QUIC_BUG(quic_bug_10511_39)
5781 << ENDPOINT
5782 << "Try to bundle crypto with ACK with missing key of space "
5783 << PacketNumberSpaceToString(space);
5784 return;
5785 }
5786
5787 sent_packet_manager_.RetransmitDataOfSpaceIfAny(space);
5788 }
5789
SendAllPendingAcks()5790 void QuicConnection::SendAllPendingAcks() {
5791 QUICHE_DCHECK(SupportsMultiplePacketNumberSpaces());
5792 QUIC_DVLOG(1) << ENDPOINT << "Trying to send all pending ACKs";
5793 ack_alarm_->Cancel();
5794 QuicTime earliest_ack_timeout =
5795 uber_received_packet_manager_.GetEarliestAckTimeout();
5796 QUIC_BUG_IF(quic_bug_12714_32, !earliest_ack_timeout.IsInitialized());
5797 MaybeBundleCryptoDataWithAcks();
5798 if (GetQuicRestartFlag(quic_opport_bundle_qpack_decoder_data2)) {
5799 QUIC_RESTART_FLAG_COUNT_N(quic_opport_bundle_qpack_decoder_data2, 2, 4);
5800 visitor_->MaybeBundleOpportunistically();
5801 }
5802 earliest_ack_timeout = uber_received_packet_manager_.GetEarliestAckTimeout();
5803 if (!earliest_ack_timeout.IsInitialized()) {
5804 return;
5805 }
5806 for (int8_t i = INITIAL_DATA; i <= APPLICATION_DATA; ++i) {
5807 const QuicTime ack_timeout = uber_received_packet_manager_.GetAckTimeout(
5808 static_cast<PacketNumberSpace>(i));
5809 if (!ack_timeout.IsInitialized()) {
5810 continue;
5811 }
5812 if (!framer_.HasAnEncrypterForSpace(static_cast<PacketNumberSpace>(i))) {
5813 // The key has been dropped.
5814 continue;
5815 }
5816 if (ack_timeout > clock_->ApproximateNow() &&
5817 ack_timeout > earliest_ack_timeout) {
5818 // Always send the earliest ACK to make forward progress in case alarm
5819 // fires early.
5820 continue;
5821 }
5822 QUIC_DVLOG(1) << ENDPOINT << "Sending ACK of packet number space "
5823 << PacketNumberSpaceToString(
5824 static_cast<PacketNumberSpace>(i));
5825 ScopedEncryptionLevelContext context(
5826 this, QuicUtils::GetEncryptionLevelToSendAckofSpace(
5827 static_cast<PacketNumberSpace>(i)));
5828 QuicFrames frames;
5829 frames.push_back(uber_received_packet_manager_.GetUpdatedAckFrame(
5830 static_cast<PacketNumberSpace>(i), clock_->ApproximateNow()));
5831 const bool flushed = packet_creator_.FlushAckFrame(frames);
5832 // Consider reset ack states even when flush is not successful.
5833 if (!flushed) {
5834 // Connection is write blocked.
5835 QUIC_BUG_IF(quic_bug_12714_33,
5836 !writer_->IsWriteBlocked() &&
5837 !LimitedByAmplificationFactor(
5838 packet_creator_.max_packet_length()) &&
5839 !IsMissingDestinationConnectionID())
5840 << "Writer not blocked and not throttled by amplification factor, "
5841 "but ACK not flushed for packet space:"
5842 << PacketNumberSpaceToString(static_cast<PacketNumberSpace>(i))
5843 << ", connected: " << connected_
5844 << ", fill_coalesced_packet: " << fill_coalesced_packet_
5845 << ", blocked_by_no_connection_id: "
5846 << (peer_issued_cid_manager_ != nullptr &&
5847 packet_creator_.GetDestinationConnectionId().IsEmpty())
5848 << ", has_soft_max_packet_length: "
5849 << packet_creator_.HasSoftMaxPacketLength()
5850 << ", max_packet_length: " << packet_creator_.max_packet_length()
5851 << ", pending frames: " << packet_creator_.GetPendingFramesInfo();
5852 break;
5853 }
5854 ResetAckStates();
5855 }
5856
5857 const QuicTime timeout =
5858 uber_received_packet_manager_.GetEarliestAckTimeout();
5859 if (timeout.IsInitialized()) {
5860 // If there are ACKs pending, re-arm ack alarm.
5861 ack_alarm_->Update(timeout, kAlarmGranularity);
5862 }
5863 // Only try to bundle retransmittable data with ACK frame if default
5864 // encryption level is forward secure.
5865 if (encryption_level_ != ENCRYPTION_FORWARD_SECURE ||
5866 !ShouldBundleRetransmittableFrameWithAck()) {
5867 return;
5868 }
5869 consecutive_num_packets_with_no_retransmittable_frames_ = 0;
5870 if (packet_creator_.HasPendingRetransmittableFrames() ||
5871 visitor_->WillingAndAbleToWrite()) {
5872 // There are pending retransmittable frames.
5873 return;
5874 }
5875
5876 visitor_->OnAckNeedsRetransmittableFrame();
5877 }
5878
ShouldBundleRetransmittableFrameWithAck() const5879 bool QuicConnection::ShouldBundleRetransmittableFrameWithAck() const {
5880 if (consecutive_num_packets_with_no_retransmittable_frames_ >=
5881 max_consecutive_num_packets_with_no_retransmittable_frames_) {
5882 return true;
5883 }
5884 if (bundle_retransmittable_with_pto_ack_ &&
5885 sent_packet_manager_.GetConsecutivePtoCount() > 0) {
5886 // Bundle a retransmittable frame with an ACK if PTO has fired in order to
5887 // recover more quickly in cases of temporary network outage.
5888 return true;
5889 }
5890 return false;
5891 }
5892
MaybeCoalescePacketOfHigherSpace()5893 void QuicConnection::MaybeCoalescePacketOfHigherSpace() {
5894 if (!connected() || !packet_creator_.HasSoftMaxPacketLength()) {
5895 return;
5896 }
5897 if (fill_coalesced_packet_) {
5898 // Make sure MaybeCoalescePacketOfHigherSpace is not re-entrant.
5899 QUIC_BUG(quic_coalesce_packet_reentrant);
5900 return;
5901 }
5902 for (EncryptionLevel retransmission_level :
5903 {ENCRYPTION_INITIAL, ENCRYPTION_HANDSHAKE}) {
5904 // Coalesce HANDSHAKE with INITIAL retransmission, and coalesce 1-RTT with
5905 // HANDSHAKE retransmission.
5906 const EncryptionLevel coalesced_level =
5907 retransmission_level == ENCRYPTION_INITIAL ? ENCRYPTION_HANDSHAKE
5908 : ENCRYPTION_FORWARD_SECURE;
5909 if (coalesced_packet_.ContainsPacketOfEncryptionLevel(
5910 retransmission_level) &&
5911 coalesced_packet_.TransmissionTypeOfPacket(retransmission_level) !=
5912 NOT_RETRANSMISSION &&
5913 framer_.HasEncrypterOfEncryptionLevel(coalesced_level) &&
5914 !coalesced_packet_.ContainsPacketOfEncryptionLevel(coalesced_level)) {
5915 QUIC_DVLOG(1) << ENDPOINT
5916 << "Trying to coalesce packet of encryption level: "
5917 << EncryptionLevelToString(coalesced_level);
5918 fill_coalesced_packet_ = true;
5919 sent_packet_manager_.RetransmitDataOfSpaceIfAny(
5920 QuicUtils::GetPacketNumberSpace(coalesced_level));
5921 fill_coalesced_packet_ = false;
5922 }
5923 }
5924 }
5925
FlushCoalescedPacket()5926 bool QuicConnection::FlushCoalescedPacket() {
5927 ScopedCoalescedPacketClearer clearer(&coalesced_packet_);
5928 if (!connected_) {
5929 return false;
5930 }
5931 if (!version().CanSendCoalescedPackets()) {
5932 QUIC_BUG_IF(quic_bug_12714_34, coalesced_packet_.length() > 0);
5933 return true;
5934 }
5935 if (coalesced_packet_.ContainsPacketOfEncryptionLevel(ENCRYPTION_INITIAL) &&
5936 !framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_INITIAL)) {
5937 // Initial packet will be re-serialized. Neuter it in case initial key has
5938 // been dropped.
5939 QUIC_BUG(quic_bug_10511_40)
5940 << ENDPOINT
5941 << "Coalescer contains initial packet while initial key has "
5942 "been dropped.";
5943 coalesced_packet_.NeuterInitialPacket();
5944 }
5945 if (coalesced_packet_.length() == 0) {
5946 return true;
5947 }
5948
5949 char buffer[kMaxOutgoingPacketSize];
5950 const size_t length = packet_creator_.SerializeCoalescedPacket(
5951 coalesced_packet_, buffer, coalesced_packet_.max_packet_length());
5952 if (length == 0) {
5953 if (connected_) {
5954 CloseConnection(QUIC_FAILED_TO_SERIALIZE_PACKET,
5955 "Failed to serialize coalesced packet.",
5956 ConnectionCloseBehavior::SILENT_CLOSE);
5957 }
5958 return false;
5959 }
5960 if (debug_visitor_ != nullptr) {
5961 debug_visitor_->OnCoalescedPacketSent(coalesced_packet_, length);
5962 }
5963 QUIC_DVLOG(1) << ENDPOINT << "Sending coalesced packet "
5964 << coalesced_packet_.ToString(length);
5965 const size_t padding_size =
5966 length - std::min<size_t>(length, coalesced_packet_.length());
5967 // Buffer coalesced packet if padding + bytes_sent exceeds amplifcation limit.
5968 if (!buffered_packets_.empty() || HandleWriteBlocked() ||
5969 (enforce_strict_amplification_factor_ &&
5970 LimitedByAmplificationFactor(padding_size))) {
5971 QUIC_DVLOG(1) << ENDPOINT
5972 << "Buffering coalesced packet of len: " << length;
5973 buffered_packets_.emplace_back(
5974 buffer, static_cast<QuicPacketLength>(length),
5975 coalesced_packet_.self_address(), coalesced_packet_.peer_address(),
5976 coalesced_packet_.ecn_codepoint());
5977 } else {
5978 WriteResult result = SendPacketToWriter(
5979 buffer, length, coalesced_packet_.self_address().host(),
5980 coalesced_packet_.peer_address(), writer_,
5981 coalesced_packet_.ecn_codepoint());
5982 if (IsWriteError(result.status)) {
5983 OnWriteError(result.error_code);
5984 return false;
5985 }
5986 if (IsWriteBlockedStatus(result.status)) {
5987 visitor_->OnWriteBlocked();
5988 if (result.status != WRITE_STATUS_BLOCKED_DATA_BUFFERED) {
5989 QUIC_DVLOG(1) << ENDPOINT
5990 << "Buffering coalesced packet of len: " << length;
5991 buffered_packets_.emplace_back(
5992 buffer, static_cast<QuicPacketLength>(length),
5993 coalesced_packet_.self_address(), coalesced_packet_.peer_address(),
5994 coalesced_packet_.ecn_codepoint());
5995 }
5996 }
5997 }
5998 if (accelerated_server_preferred_address_ &&
5999 stats_.num_duplicated_packets_sent_to_server_preferred_address <
6000 kMaxDuplicatedPacketsSentToServerPreferredAddress) {
6001 // Send coalesced packets to both addresses while the server preferred
6002 // address validation is pending.
6003 QUICHE_DCHECK(received_server_preferred_address_.IsInitialized());
6004 path_validator_.MaybeWritePacketToAddress(
6005 buffer, length, received_server_preferred_address_);
6006 ++stats_.num_duplicated_packets_sent_to_server_preferred_address;
6007 }
6008 // Account for added padding.
6009 if (length > coalesced_packet_.length()) {
6010 if (IsDefaultPath(coalesced_packet_.self_address(),
6011 coalesced_packet_.peer_address())) {
6012 if (EnforceAntiAmplificationLimit()) {
6013 // Include bytes sent even if they are not in flight.
6014 default_path_.bytes_sent_before_address_validation += padding_size;
6015 }
6016 } else {
6017 MaybeUpdateBytesSentToAlternativeAddress(coalesced_packet_.peer_address(),
6018 padding_size);
6019 }
6020 stats_.bytes_sent += padding_size;
6021 if (coalesced_packet_.initial_packet() != nullptr &&
6022 coalesced_packet_.initial_packet()->transmission_type !=
6023 NOT_RETRANSMISSION) {
6024 stats_.bytes_retransmitted += padding_size;
6025 }
6026 }
6027 return true;
6028 }
6029
MaybeEnableMultiplePacketNumberSpacesSupport()6030 void QuicConnection::MaybeEnableMultiplePacketNumberSpacesSupport() {
6031 if (version().handshake_protocol != PROTOCOL_TLS1_3) {
6032 return;
6033 }
6034 QUIC_DVLOG(1) << ENDPOINT << "connection " << connection_id()
6035 << " supports multiple packet number spaces";
6036 framer_.EnableMultiplePacketNumberSpacesSupport();
6037 sent_packet_manager_.EnableMultiplePacketNumberSpacesSupport();
6038 uber_received_packet_manager_.EnableMultiplePacketNumberSpacesSupport(
6039 perspective_);
6040 }
6041
SupportsMultiplePacketNumberSpaces() const6042 bool QuicConnection::SupportsMultiplePacketNumberSpaces() const {
6043 return sent_packet_manager_.supports_multiple_packet_number_spaces();
6044 }
6045
SetLargestReceivedPacketWithAck(QuicPacketNumber new_value)6046 void QuicConnection::SetLargestReceivedPacketWithAck(
6047 QuicPacketNumber new_value) {
6048 if (SupportsMultiplePacketNumberSpaces()) {
6049 largest_seen_packets_with_ack_[QuicUtils::GetPacketNumberSpace(
6050 last_received_packet_info_.decrypted_level)] = new_value;
6051 } else {
6052 largest_seen_packet_with_ack_ = new_value;
6053 }
6054 }
6055
OnForwardProgressMade()6056 void QuicConnection::OnForwardProgressMade() {
6057 if (!connected_) {
6058 return;
6059 }
6060 if (is_path_degrading_) {
6061 visitor_->OnForwardProgressMadeAfterPathDegrading();
6062 stats_.num_forward_progress_after_path_degrading++;
6063 is_path_degrading_ = false;
6064 }
6065 if (sent_packet_manager_.HasInFlightPackets()) {
6066 // Restart detections if forward progress has been made.
6067 blackhole_detector_.RestartDetection(GetPathDegradingDeadline(),
6068 GetNetworkBlackholeDeadline(),
6069 GetPathMtuReductionDeadline());
6070 } else {
6071 // Stop detections in quiecense.
6072 blackhole_detector_.StopDetection(/*permanent=*/false);
6073 }
6074 QUIC_BUG_IF(quic_bug_12714_35,
6075 perspective_ == Perspective::IS_SERVER &&
6076 default_enable_5rto_blackhole_detection_ &&
6077 blackhole_detector_.IsDetectionInProgress() &&
6078 !sent_packet_manager_.HasInFlightPackets())
6079 << ENDPOINT
6080 << "Trying to start blackhole detection without no bytes in flight";
6081 }
6082
GetLargestReceivedPacketWithAck() const6083 QuicPacketNumber QuicConnection::GetLargestReceivedPacketWithAck() const {
6084 if (SupportsMultiplePacketNumberSpaces()) {
6085 return largest_seen_packets_with_ack_[QuicUtils::GetPacketNumberSpace(
6086 last_received_packet_info_.decrypted_level)];
6087 }
6088 return largest_seen_packet_with_ack_;
6089 }
6090
GetLargestAckedPacket() const6091 QuicPacketNumber QuicConnection::GetLargestAckedPacket() const {
6092 if (SupportsMultiplePacketNumberSpaces()) {
6093 return sent_packet_manager_.GetLargestAckedPacket(
6094 last_received_packet_info_.decrypted_level);
6095 }
6096 return sent_packet_manager_.GetLargestObserved();
6097 }
6098
GetLargestReceivedPacket() const6099 QuicPacketNumber QuicConnection::GetLargestReceivedPacket() const {
6100 return uber_received_packet_manager_.GetLargestObserved(
6101 last_received_packet_info_.decrypted_level);
6102 }
6103
EnforceAntiAmplificationLimit() const6104 bool QuicConnection::EnforceAntiAmplificationLimit() const {
6105 return version().SupportsAntiAmplificationLimit() &&
6106 perspective_ == Perspective::IS_SERVER && !default_path_.validated;
6107 }
6108
6109 // TODO(danzh) Pass in path object or its reference of some sort to use this
6110 // method to check anti-amplification limit on non-default path.
LimitedByAmplificationFactor(QuicByteCount bytes) const6111 bool QuicConnection::LimitedByAmplificationFactor(QuicByteCount bytes) const {
6112 return EnforceAntiAmplificationLimit() &&
6113 (default_path_.bytes_sent_before_address_validation +
6114 (enforce_strict_amplification_factor_ ? bytes : 0)) >=
6115 anti_amplification_factor_ *
6116 default_path_.bytes_received_before_address_validation;
6117 }
6118
GetSerializedPacketFate(bool is_mtu_discovery,EncryptionLevel encryption_level)6119 SerializedPacketFate QuicConnection::GetSerializedPacketFate(
6120 bool is_mtu_discovery, EncryptionLevel encryption_level) {
6121 if (ShouldDiscardPacket(encryption_level)) {
6122 return DISCARD;
6123 }
6124 if (version().CanSendCoalescedPackets() && !coalescing_done_ &&
6125 !is_mtu_discovery) {
6126 if (!IsHandshakeConfirmed()) {
6127 // Before receiving ACK for any 1-RTT packets, always try to coalesce
6128 // packet (except MTU discovery packet).
6129 return COALESCE;
6130 }
6131 if (coalesced_packet_.length() > 0) {
6132 // If the coalescer is not empty, let this packet go through coalescer
6133 // to avoid potential out of order sending.
6134 return COALESCE;
6135 }
6136 }
6137 if (!buffered_packets_.empty() || HandleWriteBlocked()) {
6138 return BUFFER;
6139 }
6140 return SEND_TO_WRITER;
6141 }
6142
IsHandshakeComplete() const6143 bool QuicConnection::IsHandshakeComplete() const {
6144 return visitor_->GetHandshakeState() >= HANDSHAKE_COMPLETE;
6145 }
6146
IsHandshakeConfirmed() const6147 bool QuicConnection::IsHandshakeConfirmed() const {
6148 QUICHE_DCHECK_EQ(PROTOCOL_TLS1_3, version().handshake_protocol);
6149 return visitor_->GetHandshakeState() == HANDSHAKE_CONFIRMED;
6150 }
6151
min_received_before_ack_decimation() const6152 size_t QuicConnection::min_received_before_ack_decimation() const {
6153 return uber_received_packet_manager_.min_received_before_ack_decimation();
6154 }
6155
set_min_received_before_ack_decimation(size_t new_value)6156 void QuicConnection::set_min_received_before_ack_decimation(size_t new_value) {
6157 uber_received_packet_manager_.set_min_received_before_ack_decimation(
6158 new_value);
6159 }
6160
ack_frame() const6161 const QuicAckFrame& QuicConnection::ack_frame() const {
6162 if (SupportsMultiplePacketNumberSpaces()) {
6163 return uber_received_packet_manager_.GetAckFrame(
6164 QuicUtils::GetPacketNumberSpace(
6165 last_received_packet_info_.decrypted_level));
6166 }
6167 return uber_received_packet_manager_.ack_frame();
6168 }
6169
set_client_connection_id(QuicConnectionId client_connection_id)6170 void QuicConnection::set_client_connection_id(
6171 QuicConnectionId client_connection_id) {
6172 if (!version().SupportsClientConnectionIds()) {
6173 QUIC_BUG_IF(quic_bug_12714_36, !client_connection_id.IsEmpty())
6174 << ENDPOINT << "Attempted to use client connection ID "
6175 << client_connection_id << " with unsupported version " << version();
6176 return;
6177 }
6178 default_path_.client_connection_id = client_connection_id;
6179
6180 client_connection_id_is_set_ = true;
6181 if (version().HasIetfQuicFrames() && !client_connection_id.IsEmpty()) {
6182 if (perspective_ == Perspective::IS_SERVER) {
6183 QUICHE_DCHECK(peer_issued_cid_manager_ == nullptr);
6184 peer_issued_cid_manager_ =
6185 std::make_unique<QuicPeerIssuedConnectionIdManager>(
6186 kMinNumOfActiveConnectionIds, client_connection_id, clock_,
6187 alarm_factory_, this, context());
6188 } else {
6189 bool create_client_self_issued_cid_manager = true;
6190 quiche::AdjustTestValue(
6191 "quic::QuicConnection::create_cid_manager_when_set_client_cid",
6192 &create_client_self_issued_cid_manager);
6193 // Note in Chromium client, set_client_connection_id is not called and
6194 // thus self_issued_cid_manager_ should be null.
6195 if (create_client_self_issued_cid_manager) {
6196 self_issued_cid_manager_ = MakeSelfIssuedConnectionIdManager();
6197 }
6198 }
6199 }
6200 QUIC_DLOG(INFO) << ENDPOINT << "setting client connection ID to "
6201 << default_path_.client_connection_id
6202 << " for connection with server connection ID "
6203 << default_path_.server_connection_id;
6204 packet_creator_.SetClientConnectionId(default_path_.client_connection_id);
6205 framer_.SetExpectedClientConnectionIdLength(
6206 default_path_.client_connection_id.length());
6207 }
6208
OnPathDegradingDetected()6209 void QuicConnection::OnPathDegradingDetected() {
6210 is_path_degrading_ = true;
6211 visitor_->OnPathDegrading();
6212 stats_.num_path_degrading++;
6213 if (multi_port_stats_ && multi_port_migration_enabled_) {
6214 MaybeMigrateToMultiPortPath();
6215 }
6216 }
6217
MaybeMigrateToMultiPortPath()6218 void QuicConnection::MaybeMigrateToMultiPortPath() {
6219 if (!alternative_path_.validated) {
6220 QUIC_CLIENT_HISTOGRAM_ENUM(
6221 "QuicConnection.MultiPortPathStatusWhenMigrating",
6222 MultiPortStatusOnMigration::kNotValidated,
6223 MultiPortStatusOnMigration::kMaxValue,
6224 "Status of the multi port path upon migration");
6225 return;
6226 }
6227 std::unique_ptr<QuicPathValidationContext> context;
6228 const bool has_pending_validation =
6229 path_validator_.HasPendingPathValidation();
6230 if (!has_pending_validation) {
6231 // The multi-port path should have just finished the recent probe and
6232 // waiting for the next one.
6233 context = std::move(multi_port_path_context_);
6234 multi_port_probing_alarm_->Cancel();
6235 QUIC_CLIENT_HISTOGRAM_ENUM(
6236 "QuicConnection.MultiPortPathStatusWhenMigrating",
6237 MultiPortStatusOnMigration::kWaitingForRefreshValidation,
6238 MultiPortStatusOnMigration::kMaxValue,
6239 "Status of the multi port path upon migration");
6240 } else {
6241 // The multi-port path is currently under probing.
6242 context = path_validator_.ReleaseContext();
6243 QUIC_CLIENT_HISTOGRAM_ENUM(
6244 "QuicConnection.MultiPortPathStatusWhenMigrating",
6245 MultiPortStatusOnMigration::kPendingRefreshValidation,
6246 MultiPortStatusOnMigration::kMaxValue,
6247 "Status of the multi port path upon migration");
6248 }
6249 if (context == nullptr) {
6250 QUICHE_BUG(quic_bug_12714_90) << "No multi-port context to migrate to";
6251 return;
6252 }
6253 visitor_->MigrateToMultiPortPath(std::move(context));
6254 }
6255
OnBlackholeDetected()6256 void QuicConnection::OnBlackholeDetected() {
6257 if (default_enable_5rto_blackhole_detection_ &&
6258 !sent_packet_manager_.HasInFlightPackets()) {
6259 QUIC_BUG(quic_bug_10511_41)
6260 << ENDPOINT
6261 << "Blackhole detected, but there is no bytes in flight, version: "
6262 << version();
6263 // Do not close connection if there is no bytes in flight.
6264 return;
6265 }
6266 CloseConnection(QUIC_TOO_MANY_RTOS, "Network blackhole detected",
6267 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
6268 }
6269
OnPathMtuReductionDetected()6270 void QuicConnection::OnPathMtuReductionDetected() {
6271 MaybeRevertToPreviousMtu();
6272 }
6273
OnHandshakeTimeout()6274 void QuicConnection::OnHandshakeTimeout() {
6275 const QuicTime::Delta duration =
6276 clock_->ApproximateNow() - stats_.connection_creation_time;
6277 std::string error_details = absl::StrCat(
6278 "Handshake timeout expired after ", duration.ToDebuggingValue(),
6279 ". Timeout:",
6280 idle_network_detector_.handshake_timeout().ToDebuggingValue());
6281 if (perspective() == Perspective::IS_CLIENT && version().UsesTls()) {
6282 absl::StrAppend(&error_details, " ", UndecryptablePacketsInfo());
6283 }
6284 QUIC_DVLOG(1) << ENDPOINT << error_details;
6285 CloseConnection(QUIC_HANDSHAKE_TIMEOUT, error_details,
6286 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
6287 }
6288
OnIdleNetworkDetected()6289 void QuicConnection::OnIdleNetworkDetected() {
6290 const QuicTime::Delta duration =
6291 clock_->ApproximateNow() -
6292 idle_network_detector_.last_network_activity_time();
6293 std::string error_details = absl::StrCat(
6294 "No recent network activity after ", duration.ToDebuggingValue(),
6295 ". Timeout:",
6296 idle_network_detector_.idle_network_timeout().ToDebuggingValue());
6297 if (perspective() == Perspective::IS_CLIENT && version().UsesTls() &&
6298 !IsHandshakeComplete()) {
6299 absl::StrAppend(&error_details, " ", UndecryptablePacketsInfo());
6300 }
6301 QUIC_DVLOG(1) << ENDPOINT << error_details;
6302 const bool has_consecutive_pto =
6303 sent_packet_manager_.GetConsecutivePtoCount() > 0;
6304 if (has_consecutive_pto || visitor_->ShouldKeepConnectionAlive()) {
6305 if (GetQuicReloadableFlag(quic_add_stream_info_to_idle_close_detail) &&
6306 !has_consecutive_pto) {
6307 // Include stream information in error detail if there are open streams.
6308 QUIC_RELOADABLE_FLAG_COUNT(quic_add_stream_info_to_idle_close_detail);
6309 absl::StrAppend(&error_details, ", ",
6310 visitor_->GetStreamsInfoForLogging());
6311 }
6312 CloseConnection(QUIC_NETWORK_IDLE_TIMEOUT, error_details,
6313 ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
6314 return;
6315 }
6316 QuicErrorCode error_code = QUIC_NETWORK_IDLE_TIMEOUT;
6317 if (idle_timeout_connection_close_behavior_ ==
6318 ConnectionCloseBehavior::
6319 SILENT_CLOSE_WITH_CONNECTION_CLOSE_PACKET_SERIALIZED) {
6320 error_code = QUIC_SILENT_IDLE_TIMEOUT;
6321 }
6322 CloseConnection(error_code, error_details,
6323 idle_timeout_connection_close_behavior_);
6324 }
6325
OnKeepAliveTimeout()6326 void QuicConnection::OnKeepAliveTimeout() {
6327 if (retransmission_alarm_->IsSet() ||
6328 !visitor_->ShouldKeepConnectionAlive()) {
6329 return;
6330 }
6331 SendPingAtLevel(framer().GetEncryptionLevelToSendApplicationData());
6332 }
6333
OnRetransmittableOnWireTimeout()6334 void QuicConnection::OnRetransmittableOnWireTimeout() {
6335 if (retransmission_alarm_->IsSet() ||
6336 !visitor_->ShouldKeepConnectionAlive()) {
6337 return;
6338 }
6339 bool packet_buffered = false;
6340 switch (retransmittable_on_wire_behavior_) {
6341 case DEFAULT:
6342 break;
6343 case SEND_FIRST_FORWARD_SECURE_PACKET:
6344 if (first_serialized_one_rtt_packet_ != nullptr) {
6345 buffered_packets_.emplace_back(
6346 first_serialized_one_rtt_packet_->data.get(),
6347 first_serialized_one_rtt_packet_->length, self_address(),
6348 peer_address(), first_serialized_one_rtt_packet_->ecn_codepoint);
6349 packet_buffered = true;
6350 }
6351 break;
6352 case SEND_RANDOM_BYTES:
6353 const QuicPacketLength random_bytes_length = std::max<QuicPacketLength>(
6354 QuicFramer::GetMinStatelessResetPacketLength() + 1,
6355 random_generator_->RandUint64() %
6356 packet_creator_.max_packet_length());
6357 buffered_packets_.emplace_back(*random_generator_, random_bytes_length,
6358 self_address(), peer_address());
6359 packet_buffered = true;
6360 break;
6361 }
6362 if (packet_buffered) {
6363 if (!writer_->IsWriteBlocked()) {
6364 WriteQueuedPackets();
6365 }
6366 if (connected_) {
6367 // Always reset PING alarm with has_in_flight_packets=true. This is used
6368 // to avoid re-arming the alarm in retransmittable-on-wire mode.
6369 ping_manager_.SetAlarm(clock_->ApproximateNow(),
6370 visitor_->ShouldKeepConnectionAlive(),
6371 /*has_in_flight_packets=*/true);
6372 }
6373 return;
6374 }
6375 SendPingAtLevel(framer().GetEncryptionLevelToSendApplicationData());
6376 }
6377
OnPeerIssuedConnectionIdRetired()6378 void QuicConnection::OnPeerIssuedConnectionIdRetired() {
6379 QUICHE_DCHECK(peer_issued_cid_manager_ != nullptr);
6380 QuicConnectionId* default_path_cid =
6381 perspective_ == Perspective::IS_CLIENT
6382 ? &default_path_.server_connection_id
6383 : &default_path_.client_connection_id;
6384 QuicConnectionId* alternative_path_cid =
6385 perspective_ == Perspective::IS_CLIENT
6386 ? &alternative_path_.server_connection_id
6387 : &alternative_path_.client_connection_id;
6388 bool default_path_and_alternative_path_use_the_same_peer_connection_id =
6389 *default_path_cid == *alternative_path_cid;
6390 if (!default_path_cid->IsEmpty() &&
6391 !peer_issued_cid_manager_->IsConnectionIdActive(*default_path_cid)) {
6392 *default_path_cid = QuicConnectionId();
6393 }
6394 // TODO(haoyuewang) Handle the change for default_path_ & alternatvie_path_
6395 // via the same helper function.
6396 if (default_path_cid->IsEmpty()) {
6397 // Try setting a new connection ID now such that subsequent
6398 // RetireConnectionId frames can be sent on the default path.
6399 const QuicConnectionIdData* unused_connection_id_data =
6400 peer_issued_cid_manager_->ConsumeOneUnusedConnectionId();
6401 if (unused_connection_id_data != nullptr) {
6402 *default_path_cid = unused_connection_id_data->connection_id;
6403 default_path_.stateless_reset_token =
6404 unused_connection_id_data->stateless_reset_token;
6405 if (perspective_ == Perspective::IS_CLIENT) {
6406 packet_creator_.SetServerConnectionId(
6407 unused_connection_id_data->connection_id);
6408 } else {
6409 packet_creator_.SetClientConnectionId(
6410 unused_connection_id_data->connection_id);
6411 }
6412 }
6413 }
6414 if (default_path_and_alternative_path_use_the_same_peer_connection_id) {
6415 *alternative_path_cid = *default_path_cid;
6416 alternative_path_.stateless_reset_token =
6417 default_path_.stateless_reset_token;
6418 } else if (!alternative_path_cid->IsEmpty() &&
6419 !peer_issued_cid_manager_->IsConnectionIdActive(
6420 *alternative_path_cid)) {
6421 *alternative_path_cid = EmptyQuicConnectionId();
6422 const QuicConnectionIdData* unused_connection_id_data =
6423 peer_issued_cid_manager_->ConsumeOneUnusedConnectionId();
6424 if (unused_connection_id_data != nullptr) {
6425 *alternative_path_cid = unused_connection_id_data->connection_id;
6426 alternative_path_.stateless_reset_token =
6427 unused_connection_id_data->stateless_reset_token;
6428 }
6429 }
6430
6431 std::vector<uint64_t> retired_cid_sequence_numbers =
6432 peer_issued_cid_manager_->ConsumeToBeRetiredConnectionIdSequenceNumbers();
6433 QUICHE_DCHECK(!retired_cid_sequence_numbers.empty());
6434 for (const auto& sequence_number : retired_cid_sequence_numbers) {
6435 ++stats_.num_retire_connection_id_sent;
6436 visitor_->SendRetireConnectionId(sequence_number);
6437 }
6438 }
6439
SendNewConnectionId(const QuicNewConnectionIdFrame & frame)6440 bool QuicConnection::SendNewConnectionId(
6441 const QuicNewConnectionIdFrame& frame) {
6442 visitor_->SendNewConnectionId(frame);
6443 ++stats_.num_new_connection_id_sent;
6444 return connected_;
6445 }
6446
MaybeReserveConnectionId(const QuicConnectionId & connection_id)6447 bool QuicConnection::MaybeReserveConnectionId(
6448 const QuicConnectionId& connection_id) {
6449 if (perspective_ == Perspective::IS_SERVER) {
6450 return visitor_->MaybeReserveConnectionId(connection_id);
6451 }
6452 return true;
6453 }
6454
OnSelfIssuedConnectionIdRetired(const QuicConnectionId & connection_id)6455 void QuicConnection::OnSelfIssuedConnectionIdRetired(
6456 const QuicConnectionId& connection_id) {
6457 if (perspective_ == Perspective::IS_SERVER) {
6458 visitor_->OnServerConnectionIdRetired(connection_id);
6459 }
6460 }
6461
MaybeUpdateAckTimeout()6462 void QuicConnection::MaybeUpdateAckTimeout() {
6463 if (should_last_packet_instigate_acks_) {
6464 return;
6465 }
6466 should_last_packet_instigate_acks_ = true;
6467 uber_received_packet_manager_.MaybeUpdateAckTimeout(
6468 /*should_last_packet_instigate_acks=*/true,
6469 last_received_packet_info_.decrypted_level,
6470 last_received_packet_info_.header.packet_number,
6471 last_received_packet_info_.receipt_time, clock_->ApproximateNow(),
6472 sent_packet_manager_.GetRttStats());
6473 }
6474
GetPathDegradingDeadline() const6475 QuicTime QuicConnection::GetPathDegradingDeadline() const {
6476 if (!ShouldDetectPathDegrading()) {
6477 return QuicTime::Zero();
6478 }
6479 return clock_->ApproximateNow() +
6480 sent_packet_manager_.GetPathDegradingDelay();
6481 }
6482
ShouldDetectPathDegrading() const6483 bool QuicConnection::ShouldDetectPathDegrading() const {
6484 if (!connected_) {
6485 return false;
6486 }
6487 if (GetQuicReloadableFlag(
6488 quic_no_path_degrading_before_handshake_confirmed) &&
6489 SupportsMultiplePacketNumberSpaces()) {
6490 QUIC_RELOADABLE_FLAG_COUNT_N(
6491 quic_no_path_degrading_before_handshake_confirmed, 1, 2);
6492 // No path degrading detection before handshake confirmed.
6493 return perspective_ == Perspective::IS_CLIENT && IsHandshakeConfirmed() &&
6494 !is_path_degrading_;
6495 }
6496 // No path degrading detection before handshake completes.
6497 if (!idle_network_detector_.handshake_timeout().IsInfinite()) {
6498 return false;
6499 }
6500 return perspective_ == Perspective::IS_CLIENT && !is_path_degrading_;
6501 }
6502
GetNetworkBlackholeDeadline() const6503 QuicTime QuicConnection::GetNetworkBlackholeDeadline() const {
6504 if (!ShouldDetectBlackhole()) {
6505 return QuicTime::Zero();
6506 }
6507 QUICHE_DCHECK_LT(0u, num_rtos_for_blackhole_detection_);
6508
6509 const QuicTime::Delta blackhole_delay =
6510 sent_packet_manager_.GetNetworkBlackholeDelay(
6511 num_rtos_for_blackhole_detection_);
6512 if (!ShouldDetectPathDegrading()) {
6513 return clock_->ApproximateNow() + blackhole_delay;
6514 }
6515 return clock_->ApproximateNow() +
6516 CalculateNetworkBlackholeDelay(
6517 blackhole_delay, sent_packet_manager_.GetPathDegradingDelay(),
6518 sent_packet_manager_.GetPtoDelay());
6519 }
6520
6521 // static
CalculateNetworkBlackholeDelay(QuicTime::Delta blackhole_delay,QuicTime::Delta path_degrading_delay,QuicTime::Delta pto_delay)6522 QuicTime::Delta QuicConnection::CalculateNetworkBlackholeDelay(
6523 QuicTime::Delta blackhole_delay, QuicTime::Delta path_degrading_delay,
6524 QuicTime::Delta pto_delay) {
6525 const QuicTime::Delta min_delay = path_degrading_delay + pto_delay * 2;
6526 if (blackhole_delay < min_delay) {
6527 QUIC_CODE_COUNT(quic_extending_short_blackhole_delay);
6528 }
6529 return std::max(min_delay, blackhole_delay);
6530 }
6531
AddKnownServerAddress(const QuicSocketAddress & address)6532 void QuicConnection::AddKnownServerAddress(const QuicSocketAddress& address) {
6533 QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT);
6534 if (!address.IsInitialized() || IsKnownServerAddress(address)) {
6535 return;
6536 }
6537 known_server_addresses_.push_back(address);
6538 }
6539
6540 std::optional<QuicNewConnectionIdFrame>
MaybeIssueNewConnectionIdForPreferredAddress()6541 QuicConnection::MaybeIssueNewConnectionIdForPreferredAddress() {
6542 if (self_issued_cid_manager_ == nullptr) {
6543 return std::nullopt;
6544 }
6545 return self_issued_cid_manager_
6546 ->MaybeIssueNewConnectionIdForPreferredAddress();
6547 }
6548
ShouldDetectBlackhole() const6549 bool QuicConnection::ShouldDetectBlackhole() const {
6550 if (!connected_ || blackhole_detection_disabled_) {
6551 return false;
6552 }
6553 if (GetQuicReloadableFlag(
6554 quic_no_path_degrading_before_handshake_confirmed) &&
6555 SupportsMultiplePacketNumberSpaces() && !IsHandshakeConfirmed()) {
6556 QUIC_RELOADABLE_FLAG_COUNT_N(
6557 quic_no_path_degrading_before_handshake_confirmed, 2, 2);
6558 return false;
6559 }
6560 // No blackhole detection before handshake completes.
6561 if (default_enable_5rto_blackhole_detection_) {
6562 QUIC_RELOADABLE_FLAG_COUNT_N(quic_default_enable_5rto_blackhole_detection2,
6563 3, 3);
6564 return IsHandshakeComplete();
6565 }
6566
6567 if (!idle_network_detector_.handshake_timeout().IsInfinite()) {
6568 return false;
6569 }
6570 return num_rtos_for_blackhole_detection_ > 0;
6571 }
6572
GetRetransmissionDeadline() const6573 QuicTime QuicConnection::GetRetransmissionDeadline() const {
6574 if (perspective_ == Perspective::IS_CLIENT &&
6575 SupportsMultiplePacketNumberSpaces() && !IsHandshakeConfirmed() &&
6576 stats_.pto_count == 0 &&
6577 !framer_.HasDecrypterOfEncryptionLevel(ENCRYPTION_HANDSHAKE) &&
6578 !undecryptable_packets_.empty()) {
6579 // Retransmits ClientHello quickly when a Handshake or 1-RTT packet is
6580 // received prior to having Handshake keys. Adding kAlarmGranulary will
6581 // avoid spurious retransmissions in the case of small-scale reordering.
6582 return clock_->ApproximateNow() + kAlarmGranularity;
6583 }
6584 return sent_packet_manager_.GetRetransmissionTime();
6585 }
6586
SendPathChallenge(const QuicPathFrameBuffer & data_buffer,const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,const QuicSocketAddress & effective_peer_address,QuicPacketWriter * writer)6587 bool QuicConnection::SendPathChallenge(
6588 const QuicPathFrameBuffer& data_buffer,
6589 const QuicSocketAddress& self_address,
6590 const QuicSocketAddress& peer_address,
6591 const QuicSocketAddress& effective_peer_address, QuicPacketWriter* writer) {
6592 if (!framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_FORWARD_SECURE)) {
6593 return connected_;
6594 }
6595
6596 QuicConnectionId client_cid, server_cid;
6597 FindOnPathConnectionIds(self_address, effective_peer_address, &client_cid,
6598 &server_cid);
6599 if (writer == writer_) {
6600 ScopedPacketFlusher flusher(this);
6601 {
6602 QuicPacketCreator::ScopedPeerAddressContext context(
6603 &packet_creator_, peer_address, client_cid, server_cid);
6604 // It's using the default writer, add the PATH_CHALLENGE the same way as
6605 // other frames. This may cause connection to be closed.
6606 packet_creator_.AddPathChallengeFrame(data_buffer);
6607 }
6608 } else if (!writer->IsWriteBlocked()) {
6609 // Switch to the right CID and source/peer addresses.
6610 QuicPacketCreator::ScopedPeerAddressContext context(
6611 &packet_creator_, peer_address, client_cid, server_cid);
6612 std::unique_ptr<SerializedPacket> probing_packet =
6613 packet_creator_.SerializePathChallengeConnectivityProbingPacket(
6614 data_buffer);
6615 QUICHE_DCHECK_EQ(IsRetransmittable(*probing_packet),
6616 NO_RETRANSMITTABLE_DATA)
6617 << ENDPOINT << "Probing Packet contains retransmittable frames";
6618 QUICHE_DCHECK_EQ(self_address, alternative_path_.self_address)
6619 << ENDPOINT
6620 << "Send PATH_CHALLENGE from self_address: " << self_address.ToString()
6621 << " which is different from alt_path self address: "
6622 << alternative_path_.self_address.ToString();
6623 WritePacketUsingWriter(std::move(probing_packet), writer, self_address,
6624 peer_address, /*measure_rtt=*/false);
6625 } else {
6626 QUIC_DLOG(INFO) << ENDPOINT
6627 << "Writer blocked when sending PATH_CHALLENGE.";
6628 }
6629 return connected_;
6630 }
6631
GetRetryTimeout(const QuicSocketAddress & peer_address_to_use,QuicPacketWriter * writer_to_use) const6632 QuicTime QuicConnection::GetRetryTimeout(
6633 const QuicSocketAddress& peer_address_to_use,
6634 QuicPacketWriter* writer_to_use) const {
6635 if (writer_to_use == writer_ && peer_address_to_use == peer_address()) {
6636 return clock_->ApproximateNow() + sent_packet_manager_.GetPtoDelay();
6637 }
6638 return clock_->ApproximateNow() +
6639 QuicTime::Delta::FromMilliseconds(3 * kInitialRttMs);
6640 }
6641
ValidatePath(std::unique_ptr<QuicPathValidationContext> context,std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate,PathValidationReason reason)6642 void QuicConnection::ValidatePath(
6643 std::unique_ptr<QuicPathValidationContext> context,
6644 std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate,
6645 PathValidationReason reason) {
6646 QUICHE_DCHECK(version().HasIetfQuicFrames());
6647 if (path_validator_.HasPendingPathValidation()) {
6648 if (perspective_ == Perspective::IS_CLIENT &&
6649 IsValidatingServerPreferredAddress()) {
6650 QUIC_CLIENT_HISTOGRAM_BOOL(
6651 "QuicSession.ServerPreferredAddressValidationCancelled", true,
6652 "How often the caller kicked off another validation while there is "
6653 "an on-going server preferred address validation.");
6654 }
6655 // Cancel and fail any earlier validation.
6656 path_validator_.CancelPathValidation();
6657 }
6658 if (perspective_ == Perspective::IS_CLIENT &&
6659 !IsDefaultPath(context->self_address(), context->peer_address())) {
6660 if (self_issued_cid_manager_ != nullptr) {
6661 self_issued_cid_manager_->MaybeSendNewConnectionIds();
6662 if (!connected_) {
6663 return;
6664 }
6665 }
6666 if ((self_issued_cid_manager_ != nullptr &&
6667 !self_issued_cid_manager_->HasConnectionIdToConsume()) ||
6668 (peer_issued_cid_manager_ != nullptr &&
6669 !peer_issued_cid_manager_->HasUnusedConnectionId())) {
6670 QUIC_DVLOG(1) << "Client cannot start new path validation as there is no "
6671 "requried connection ID is available.";
6672 result_delegate->OnPathValidationFailure(std::move(context));
6673 return;
6674 }
6675 QuicConnectionId client_connection_id, server_connection_id;
6676 std::optional<StatelessResetToken> stateless_reset_token;
6677 if (self_issued_cid_manager_ != nullptr) {
6678 client_connection_id =
6679 *self_issued_cid_manager_->ConsumeOneConnectionId();
6680 }
6681 if (peer_issued_cid_manager_ != nullptr) {
6682 const auto* connection_id_data =
6683 peer_issued_cid_manager_->ConsumeOneUnusedConnectionId();
6684 server_connection_id = connection_id_data->connection_id;
6685 stateless_reset_token = connection_id_data->stateless_reset_token;
6686 }
6687 alternative_path_ = PathState(context->self_address(),
6688 context->peer_address(), client_connection_id,
6689 server_connection_id, stateless_reset_token);
6690 }
6691 path_validator_.StartPathValidation(std::move(context),
6692 std::move(result_delegate), reason);
6693 if (perspective_ == Perspective::IS_CLIENT &&
6694 IsValidatingServerPreferredAddress()) {
6695 AddKnownServerAddress(received_server_preferred_address_);
6696 }
6697 }
6698
SendPathResponse(const QuicPathFrameBuffer & data_buffer,const QuicSocketAddress & peer_address_to_send,const QuicSocketAddress & effective_peer_address)6699 bool QuicConnection::SendPathResponse(
6700 const QuicPathFrameBuffer& data_buffer,
6701 const QuicSocketAddress& peer_address_to_send,
6702 const QuicSocketAddress& effective_peer_address) {
6703 if (!framer_.HasEncrypterOfEncryptionLevel(ENCRYPTION_FORWARD_SECURE)) {
6704 return false;
6705 }
6706 QuicConnectionId client_cid, server_cid;
6707 FindOnPathConnectionIds(last_received_packet_info_.destination_address,
6708 effective_peer_address, &client_cid, &server_cid);
6709 // Send PATH_RESPONSE using the provided peer address. If the creator has been
6710 // using a different peer address, it will flush before and after serializing
6711 // the current PATH_RESPONSE.
6712 QuicPacketCreator::ScopedPeerAddressContext context(
6713 &packet_creator_, peer_address_to_send, client_cid, server_cid);
6714 QUIC_DVLOG(1) << ENDPOINT << "Send PATH_RESPONSE to " << peer_address_to_send;
6715 if (default_path_.self_address ==
6716 last_received_packet_info_.destination_address) {
6717 // The PATH_CHALLENGE is received on the default socket. Respond on the same
6718 // socket.
6719 return packet_creator_.AddPathResponseFrame(data_buffer);
6720 }
6721
6722 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_);
6723 // This PATH_CHALLENGE is received on an alternative socket which should be
6724 // used to send PATH_RESPONSE.
6725 if (!path_validator_.HasPendingPathValidation() ||
6726 path_validator_.GetContext()->self_address() !=
6727 last_received_packet_info_.destination_address) {
6728 // Ignore this PATH_CHALLENGE if it's received from an uninteresting
6729 // socket.
6730 return true;
6731 }
6732 QuicPacketWriter* writer = path_validator_.GetContext()->WriterToUse();
6733 if (writer->IsWriteBlocked()) {
6734 QUIC_DLOG(INFO) << ENDPOINT << "Writer blocked when sending PATH_RESPONSE.";
6735 return true;
6736 }
6737
6738 std::unique_ptr<SerializedPacket> probing_packet =
6739 packet_creator_.SerializePathResponseConnectivityProbingPacket(
6740 {data_buffer}, /*is_padded=*/true);
6741 QUICHE_DCHECK_EQ(IsRetransmittable(*probing_packet), NO_RETRANSMITTABLE_DATA);
6742 QUIC_DVLOG(1) << ENDPOINT
6743 << "Send PATH_RESPONSE from alternative socket with address "
6744 << last_received_packet_info_.destination_address;
6745 // Ignore the return value to treat write error on the alternative writer as
6746 // part of network error. If the writer becomes blocked, wait for the peer to
6747 // send another PATH_CHALLENGE.
6748 WritePacketUsingWriter(std::move(probing_packet), writer,
6749 last_received_packet_info_.destination_address,
6750 peer_address_to_send,
6751 /*measure_rtt=*/false);
6752 return true;
6753 }
6754
UpdatePeerAddress(QuicSocketAddress peer_address)6755 void QuicConnection::UpdatePeerAddress(QuicSocketAddress peer_address) {
6756 direct_peer_address_ = peer_address;
6757 packet_creator_.SetDefaultPeerAddress(peer_address);
6758 }
6759
SendPingAtLevel(EncryptionLevel level)6760 void QuicConnection::SendPingAtLevel(EncryptionLevel level) {
6761 ScopedEncryptionLevelContext context(this, level);
6762 SendControlFrame(QuicFrame(QuicPingFrame()));
6763 }
6764
HasPendingPathValidation() const6765 bool QuicConnection::HasPendingPathValidation() const {
6766 return path_validator_.HasPendingPathValidation();
6767 }
6768
GetPathValidationContext() const6769 QuicPathValidationContext* QuicConnection::GetPathValidationContext() const {
6770 return path_validator_.GetContext();
6771 }
6772
CancelPathValidation()6773 void QuicConnection::CancelPathValidation() {
6774 path_validator_.CancelPathValidation();
6775 }
6776
UpdateConnectionIdsOnMigration(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address)6777 bool QuicConnection::UpdateConnectionIdsOnMigration(
6778 const QuicSocketAddress& self_address,
6779 const QuicSocketAddress& peer_address) {
6780 QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT);
6781 if (IsAlternativePath(self_address, peer_address)) {
6782 // Client migration is after path validation.
6783 default_path_.client_connection_id = alternative_path_.client_connection_id;
6784 default_path_.server_connection_id = alternative_path_.server_connection_id;
6785 default_path_.stateless_reset_token =
6786 alternative_path_.stateless_reset_token;
6787 return true;
6788 }
6789 // Client migration is without path validation.
6790 if (self_issued_cid_manager_ != nullptr) {
6791 self_issued_cid_manager_->MaybeSendNewConnectionIds();
6792 if (!connected_) {
6793 return false;
6794 }
6795 }
6796 if ((self_issued_cid_manager_ != nullptr &&
6797 !self_issued_cid_manager_->HasConnectionIdToConsume()) ||
6798 (peer_issued_cid_manager_ != nullptr &&
6799 !peer_issued_cid_manager_->HasUnusedConnectionId())) {
6800 return false;
6801 }
6802 if (self_issued_cid_manager_ != nullptr) {
6803 default_path_.client_connection_id =
6804 *self_issued_cid_manager_->ConsumeOneConnectionId();
6805 }
6806 if (peer_issued_cid_manager_ != nullptr) {
6807 const auto* connection_id_data =
6808 peer_issued_cid_manager_->ConsumeOneUnusedConnectionId();
6809 default_path_.server_connection_id = connection_id_data->connection_id;
6810 default_path_.stateless_reset_token =
6811 connection_id_data->stateless_reset_token;
6812 }
6813 return true;
6814 }
6815
RetirePeerIssuedConnectionIdsNoLongerOnPath()6816 void QuicConnection::RetirePeerIssuedConnectionIdsNoLongerOnPath() {
6817 if (!version().HasIetfQuicFrames() || peer_issued_cid_manager_ == nullptr) {
6818 return;
6819 }
6820 if (perspective_ == Perspective::IS_CLIENT) {
6821 peer_issued_cid_manager_->MaybeRetireUnusedConnectionIds(
6822 {default_path_.server_connection_id,
6823 alternative_path_.server_connection_id});
6824 } else {
6825 peer_issued_cid_manager_->MaybeRetireUnusedConnectionIds(
6826 {default_path_.client_connection_id,
6827 alternative_path_.client_connection_id});
6828 }
6829 }
6830
MigratePath(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,QuicPacketWriter * writer,bool owns_writer)6831 bool QuicConnection::MigratePath(const QuicSocketAddress& self_address,
6832 const QuicSocketAddress& peer_address,
6833 QuicPacketWriter* writer, bool owns_writer) {
6834 QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT);
6835 if (!connected_) {
6836 if (owns_writer) {
6837 delete writer;
6838 }
6839 return false;
6840 }
6841 QUICHE_DCHECK(!version().UsesHttp3() || IsHandshakeConfirmed() ||
6842 accelerated_server_preferred_address_);
6843
6844 if (version().UsesHttp3()) {
6845 if (!UpdateConnectionIdsOnMigration(self_address, peer_address)) {
6846 if (owns_writer) {
6847 delete writer;
6848 }
6849 return false;
6850 }
6851 if (packet_creator_.GetServerConnectionId().length() !=
6852 default_path_.server_connection_id.length()) {
6853 packet_creator_.FlushCurrentPacket();
6854 }
6855 packet_creator_.SetClientConnectionId(default_path_.client_connection_id);
6856 packet_creator_.SetServerConnectionId(default_path_.server_connection_id);
6857 }
6858
6859 const auto self_address_change_type = QuicUtils::DetermineAddressChangeType(
6860 default_path_.self_address, self_address);
6861 const auto peer_address_change_type = QuicUtils::DetermineAddressChangeType(
6862 default_path_.peer_address, peer_address);
6863 QUICHE_DCHECK(self_address_change_type != NO_CHANGE ||
6864 peer_address_change_type != NO_CHANGE);
6865 const bool is_port_change = (self_address_change_type == PORT_CHANGE ||
6866 self_address_change_type == NO_CHANGE) &&
6867 (peer_address_change_type == PORT_CHANGE ||
6868 peer_address_change_type == NO_CHANGE);
6869 SetSelfAddress(self_address);
6870 UpdatePeerAddress(peer_address);
6871 default_path_.peer_address = peer_address;
6872 if (writer_ != writer) {
6873 SetQuicPacketWriter(writer, owns_writer);
6874 }
6875 MaybeClearQueuedPacketsOnPathChange();
6876 OnSuccessfulMigration(is_port_change);
6877 return true;
6878 }
6879
OnPathValidationFailureAtClient(bool is_multi_port,const QuicPathValidationContext & context)6880 void QuicConnection::OnPathValidationFailureAtClient(
6881 bool is_multi_port, const QuicPathValidationContext& context) {
6882 QUICHE_DCHECK(perspective_ == Perspective::IS_CLIENT &&
6883 version().HasIetfQuicFrames());
6884 alternative_path_.Clear();
6885
6886 if (is_multi_port && multi_port_stats_ != nullptr) {
6887 if (is_path_degrading_) {
6888 multi_port_stats_->num_multi_port_probe_failures_when_path_degrading++;
6889 } else {
6890 multi_port_stats_
6891 ->num_multi_port_probe_failures_when_path_not_degrading++;
6892 }
6893 }
6894
6895 if (context.peer_address() == received_server_preferred_address_ &&
6896 received_server_preferred_address_ != default_path_.peer_address) {
6897 QUIC_DLOG(INFO) << "Failed to validate server preferred address : "
6898 << received_server_preferred_address_;
6899 mutable_stats().failed_to_validate_server_preferred_address = true;
6900 }
6901
6902 RetirePeerIssuedConnectionIdsNoLongerOnPath();
6903 }
6904
GetOneActiveServerConnectionId() const6905 QuicConnectionId QuicConnection::GetOneActiveServerConnectionId() const {
6906 if (perspective_ == Perspective::IS_CLIENT ||
6907 self_issued_cid_manager_ == nullptr) {
6908 return connection_id();
6909 }
6910 auto active_connection_ids = GetActiveServerConnectionIds();
6911 QUIC_BUG_IF(quic_bug_6944, active_connection_ids.empty());
6912 if (active_connection_ids.empty() ||
6913 std::find(active_connection_ids.begin(), active_connection_ids.end(),
6914 connection_id()) != active_connection_ids.end()) {
6915 return connection_id();
6916 }
6917 QUICHE_CODE_COUNT(connection_id_on_default_path_has_been_retired);
6918 auto active_connection_id =
6919 self_issued_cid_manager_->GetOneActiveConnectionId();
6920 return active_connection_id;
6921 }
6922
GetActiveServerConnectionIds() const6923 std::vector<QuicConnectionId> QuicConnection::GetActiveServerConnectionIds()
6924 const {
6925 QUICHE_DCHECK_EQ(Perspective::IS_SERVER, perspective_);
6926 std::vector<QuicConnectionId> result;
6927 if (self_issued_cid_manager_ == nullptr) {
6928 result.push_back(default_path_.server_connection_id);
6929 } else {
6930 QUICHE_DCHECK(version().HasIetfQuicFrames());
6931 result = self_issued_cid_manager_->GetUnretiredConnectionIds();
6932 }
6933 if (!original_destination_connection_id_.has_value()) {
6934 return result;
6935 }
6936 // Add the original connection ID
6937 if (std::find(result.begin(), result.end(),
6938 *original_destination_connection_id_) != result.end()) {
6939 QUIC_BUG(quic_unexpected_original_destination_connection_id)
6940 << "original_destination_connection_id: "
6941 << *original_destination_connection_id_
6942 << " is unexpectedly in active list";
6943 } else {
6944 result.insert(result.end(), *original_destination_connection_id_);
6945 }
6946 return result;
6947 }
6948
CreateConnectionIdManager()6949 void QuicConnection::CreateConnectionIdManager() {
6950 if (!version().HasIetfQuicFrames()) {
6951 return;
6952 }
6953
6954 if (perspective_ == Perspective::IS_CLIENT) {
6955 if (!default_path_.server_connection_id.IsEmpty()) {
6956 peer_issued_cid_manager_ =
6957 std::make_unique<QuicPeerIssuedConnectionIdManager>(
6958 kMinNumOfActiveConnectionIds, default_path_.server_connection_id,
6959 clock_, alarm_factory_, this, context());
6960 }
6961 } else {
6962 if (!default_path_.server_connection_id.IsEmpty()) {
6963 self_issued_cid_manager_ = MakeSelfIssuedConnectionIdManager();
6964 }
6965 }
6966 }
6967
QuicBugIfHasPendingFrames(QuicStreamId id) const6968 void QuicConnection::QuicBugIfHasPendingFrames(QuicStreamId id) const {
6969 QUIC_BUG_IF(quic_has_pending_frames_unexpectedly,
6970 connected_ && packet_creator_.HasPendingStreamFramesOfStream(id))
6971 << "Stream " << id
6972 << " has pending frames unexpectedly. Received packet info: "
6973 << last_received_packet_info_;
6974 }
6975
SetUnackedMapInitialCapacity()6976 void QuicConnection::SetUnackedMapInitialCapacity() {
6977 sent_packet_manager_.ReserveUnackedPacketsInitialCapacity(
6978 GetUnackedMapInitialCapacity());
6979 }
6980
SetSourceAddressTokenToSend(absl::string_view token)6981 void QuicConnection::SetSourceAddressTokenToSend(absl::string_view token) {
6982 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
6983 if (!packet_creator_.HasRetryToken()) {
6984 // Ignore received tokens (via NEW_TOKEN frame) from previous connections
6985 // when a RETRY token has been received.
6986 packet_creator_.SetRetryToken(std::string(token.data(), token.length()));
6987 }
6988 }
6989
MaybeUpdateBytesSentToAlternativeAddress(const QuicSocketAddress & peer_address,QuicByteCount sent_packet_size)6990 void QuicConnection::MaybeUpdateBytesSentToAlternativeAddress(
6991 const QuicSocketAddress& peer_address, QuicByteCount sent_packet_size) {
6992 if (!version().SupportsAntiAmplificationLimit() ||
6993 perspective_ != Perspective::IS_SERVER) {
6994 return;
6995 }
6996 QUICHE_DCHECK(!IsDefaultPath(default_path_.self_address, peer_address));
6997 if (!IsAlternativePath(default_path_.self_address, peer_address)) {
6998 QUIC_DLOG(INFO) << "Wrote to uninteresting peer address: " << peer_address
6999 << " default direct_peer_address_ " << direct_peer_address_
7000 << " alternative path peer address "
7001 << alternative_path_.peer_address;
7002 return;
7003 }
7004 if (alternative_path_.validated) {
7005 return;
7006 }
7007 if (alternative_path_.bytes_sent_before_address_validation >=
7008 anti_amplification_factor_ *
7009 alternative_path_.bytes_received_before_address_validation) {
7010 QUIC_LOG_FIRST_N(WARNING, 100)
7011 << "Server sent more data than allowed to unverified alternative "
7012 "peer address "
7013 << peer_address << " bytes sent "
7014 << alternative_path_.bytes_sent_before_address_validation
7015 << ", bytes received "
7016 << alternative_path_.bytes_received_before_address_validation;
7017 }
7018 alternative_path_.bytes_sent_before_address_validation += sent_packet_size;
7019 }
7020
MaybeUpdateBytesReceivedFromAlternativeAddress(QuicByteCount received_packet_size)7021 void QuicConnection::MaybeUpdateBytesReceivedFromAlternativeAddress(
7022 QuicByteCount received_packet_size) {
7023 if (!version().SupportsAntiAmplificationLimit() ||
7024 perspective_ != Perspective::IS_SERVER ||
7025 !IsAlternativePath(last_received_packet_info_.destination_address,
7026 GetEffectivePeerAddressFromCurrentPacket()) ||
7027 last_received_packet_info_.received_bytes_counted) {
7028 return;
7029 }
7030 // Only update bytes received if this probing frame is received on the most
7031 // recent alternative path.
7032 QUICHE_DCHECK(!IsDefaultPath(last_received_packet_info_.destination_address,
7033 GetEffectivePeerAddressFromCurrentPacket()));
7034 if (!alternative_path_.validated) {
7035 alternative_path_.bytes_received_before_address_validation +=
7036 received_packet_size;
7037 }
7038 last_received_packet_info_.received_bytes_counted = true;
7039 }
7040
IsDefaultPath(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address) const7041 bool QuicConnection::IsDefaultPath(
7042 const QuicSocketAddress& self_address,
7043 const QuicSocketAddress& peer_address) const {
7044 return direct_peer_address_ == peer_address &&
7045 default_path_.self_address == self_address;
7046 }
7047
IsAlternativePath(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address) const7048 bool QuicConnection::IsAlternativePath(
7049 const QuicSocketAddress& self_address,
7050 const QuicSocketAddress& peer_address) const {
7051 return alternative_path_.peer_address == peer_address &&
7052 alternative_path_.self_address == self_address;
7053 }
7054
Clear()7055 void QuicConnection::PathState::Clear() {
7056 self_address = QuicSocketAddress();
7057 peer_address = QuicSocketAddress();
7058 client_connection_id = {};
7059 server_connection_id = {};
7060 validated = false;
7061 bytes_received_before_address_validation = 0;
7062 bytes_sent_before_address_validation = 0;
7063 send_algorithm = nullptr;
7064 rtt_stats = std::nullopt;
7065 stateless_reset_token.reset();
7066 ecn_marked_packet_acked = false;
7067 ecn_pto_count = 0;
7068 }
7069
PathState(PathState && other)7070 QuicConnection::PathState::PathState(PathState&& other) {
7071 *this = std::move(other);
7072 }
7073
operator =(QuicConnection::PathState && other)7074 QuicConnection::PathState& QuicConnection::PathState::operator=(
7075 QuicConnection::PathState&& other) {
7076 if (this != &other) {
7077 self_address = other.self_address;
7078 peer_address = other.peer_address;
7079 client_connection_id = other.client_connection_id;
7080 server_connection_id = other.server_connection_id;
7081 stateless_reset_token = other.stateless_reset_token;
7082 validated = other.validated;
7083 bytes_received_before_address_validation =
7084 other.bytes_received_before_address_validation;
7085 bytes_sent_before_address_validation =
7086 other.bytes_sent_before_address_validation;
7087 send_algorithm = std::move(other.send_algorithm);
7088 if (other.rtt_stats.has_value()) {
7089 rtt_stats.emplace();
7090 rtt_stats->CloneFrom(*other.rtt_stats);
7091 } else {
7092 rtt_stats.reset();
7093 }
7094 other.Clear();
7095 }
7096 return *this;
7097 }
7098
IsReceivedPeerAddressValidated() const7099 bool QuicConnection::IsReceivedPeerAddressValidated() const {
7100 QuicSocketAddress current_effective_peer_address =
7101 GetEffectivePeerAddressFromCurrentPacket();
7102 QUICHE_DCHECK(current_effective_peer_address.IsInitialized());
7103 return (alternative_path_.peer_address.host() ==
7104 current_effective_peer_address.host() &&
7105 alternative_path_.validated) ||
7106 (default_path_.validated && default_path_.peer_address.host() ==
7107 current_effective_peer_address.host());
7108 }
7109
OnMultiPortPathProbingSuccess(std::unique_ptr<QuicPathValidationContext> context,QuicTime start_time)7110 void QuicConnection::OnMultiPortPathProbingSuccess(
7111 std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time) {
7112 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective());
7113 alternative_path_.validated = true;
7114 multi_port_path_context_ = std::move(context);
7115 multi_port_probing_alarm_->Set(clock_->ApproximateNow() +
7116 multi_port_probing_interval_);
7117 if (multi_port_stats_ != nullptr) {
7118 auto now = clock_->Now();
7119 auto time_delta = now - start_time;
7120 multi_port_stats_->rtt_stats.UpdateRtt(time_delta, QuicTime::Delta::Zero(),
7121 now);
7122 if (is_path_degrading_) {
7123 multi_port_stats_->rtt_stats_when_default_path_degrading.UpdateRtt(
7124 time_delta, QuicTime::Delta::Zero(), now);
7125 }
7126 }
7127 }
7128
MaybeProbeMultiPortPath()7129 void QuicConnection::MaybeProbeMultiPortPath() {
7130 if (!connected_ || path_validator_.HasPendingPathValidation() ||
7131 !multi_port_path_context_ ||
7132 alternative_path_.self_address !=
7133 multi_port_path_context_->self_address() ||
7134 alternative_path_.peer_address !=
7135 multi_port_path_context_->peer_address() ||
7136 !visitor_->ShouldKeepConnectionAlive() ||
7137 multi_port_probing_alarm_->IsSet()) {
7138 return;
7139 }
7140 auto multi_port_validation_result_delegate =
7141 std::make_unique<MultiPortPathValidationResultDelegate>(this);
7142 path_validator_.StartPathValidation(
7143 std::move(multi_port_path_context_),
7144 std::move(multi_port_validation_result_delegate),
7145 PathValidationReason::kMultiPort);
7146 }
7147
OnMultiPortPathContextAvailable(std::unique_ptr<QuicPathValidationContext> path_context)7148 void QuicConnection::ContextObserver::OnMultiPortPathContextAvailable(
7149 std::unique_ptr<QuicPathValidationContext> path_context) {
7150 if (!path_context) {
7151 return;
7152 }
7153 auto multi_port_validation_result_delegate =
7154 std::make_unique<MultiPortPathValidationResultDelegate>(connection_);
7155 connection_->multi_port_probing_alarm_->Cancel();
7156 connection_->multi_port_path_context_ = nullptr;
7157 connection_->multi_port_stats_->num_multi_port_paths_created++;
7158 connection_->ValidatePath(std::move(path_context),
7159 std::move(multi_port_validation_result_delegate),
7160 PathValidationReason::kMultiPort);
7161 }
7162
7163 QuicConnection::MultiPortPathValidationResultDelegate::
MultiPortPathValidationResultDelegate(QuicConnection * connection)7164 MultiPortPathValidationResultDelegate(QuicConnection* connection)
7165 : connection_(connection) {
7166 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, connection->perspective());
7167 }
7168
7169 void QuicConnection::MultiPortPathValidationResultDelegate::
OnPathValidationSuccess(std::unique_ptr<QuicPathValidationContext> context,QuicTime start_time)7170 OnPathValidationSuccess(std::unique_ptr<QuicPathValidationContext> context,
7171 QuicTime start_time) {
7172 connection_->OnMultiPortPathProbingSuccess(std::move(context), start_time);
7173 }
7174
7175 void QuicConnection::MultiPortPathValidationResultDelegate::
OnPathValidationFailure(std::unique_ptr<QuicPathValidationContext> context)7176 OnPathValidationFailure(
7177 std::unique_ptr<QuicPathValidationContext> context) {
7178 connection_->OnPathValidationFailureAtClient(/*is_multi_port=*/true,
7179 *context);
7180 }
7181
7182 QuicConnection::ReversePathValidationResultDelegate::
ReversePathValidationResultDelegate(QuicConnection * connection,const QuicSocketAddress & direct_peer_address)7183 ReversePathValidationResultDelegate(
7184 QuicConnection* connection,
7185 const QuicSocketAddress& direct_peer_address)
7186 : QuicPathValidator::ResultDelegate(),
7187 connection_(connection),
7188 original_direct_peer_address_(direct_peer_address),
7189 peer_address_default_path_(connection->direct_peer_address_),
7190 peer_address_alternative_path_(
7191 connection_->alternative_path_.peer_address),
7192 active_effective_peer_migration_type_(
7193 connection_->active_effective_peer_migration_type_) {}
7194
7195 void QuicConnection::ReversePathValidationResultDelegate::
OnPathValidationSuccess(std::unique_ptr<QuicPathValidationContext> context,QuicTime start_time)7196 OnPathValidationSuccess(std::unique_ptr<QuicPathValidationContext> context,
7197 QuicTime start_time) {
7198 QUIC_DLOG(INFO) << "Successfully validated new path " << *context
7199 << ", validation started at " << start_time;
7200 if (connection_->IsDefaultPath(context->self_address(),
7201 context->peer_address())) {
7202 QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 3, 6);
7203 if (connection_->active_effective_peer_migration_type_ == NO_CHANGE) {
7204 std::string error_detail = absl::StrCat(
7205 "Reverse path validation on default path from ",
7206 context->self_address().ToString(), " to ",
7207 context->peer_address().ToString(),
7208 " completed without active peer address change: current "
7209 "peer address on default path ",
7210 connection_->direct_peer_address_.ToString(),
7211 ", peer address on default path when the reverse path "
7212 "validation was kicked off ",
7213 peer_address_default_path_.ToString(),
7214 ", peer address on alternative path when the reverse "
7215 "path validation was kicked off ",
7216 peer_address_alternative_path_.ToString(),
7217 ", with active_effective_peer_migration_type_ = ",
7218 AddressChangeTypeToString(active_effective_peer_migration_type_),
7219 ". The last received packet number ",
7220 connection_->last_received_packet_info_.header.packet_number
7221 .ToString(),
7222 " Connection is connected: ", connection_->connected_);
7223 QUIC_BUG(quic_bug_10511_43) << error_detail;
7224 }
7225 connection_->OnEffectivePeerMigrationValidated(
7226 connection_->alternative_path_.server_connection_id ==
7227 connection_->default_path_.server_connection_id);
7228 } else {
7229 QUICHE_DCHECK(connection_->IsAlternativePath(
7230 context->self_address(), context->effective_peer_address()));
7231 QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 4, 6);
7232 QUIC_DVLOG(1) << "Mark alternative peer address "
7233 << context->effective_peer_address() << " validated.";
7234 connection_->alternative_path_.validated = true;
7235 }
7236 }
7237
7238 void QuicConnection::ReversePathValidationResultDelegate::
OnPathValidationFailure(std::unique_ptr<QuicPathValidationContext> context)7239 OnPathValidationFailure(
7240 std::unique_ptr<QuicPathValidationContext> context) {
7241 if (!connection_->connected()) {
7242 return;
7243 }
7244 QUIC_DLOG(INFO) << "Fail to validate new path " << *context;
7245 if (connection_->IsDefaultPath(context->self_address(),
7246 context->peer_address())) {
7247 // Only act upon validation failure on the default path.
7248 QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 5, 6);
7249 connection_->RestoreToLastValidatedPath(original_direct_peer_address_);
7250 } else if (connection_->IsAlternativePath(
7251 context->self_address(), context->effective_peer_address())) {
7252 QUIC_CODE_COUNT_N(quic_kick_off_client_address_validation, 6, 6);
7253 connection_->alternative_path_.Clear();
7254 }
7255 connection_->RetirePeerIssuedConnectionIdsNoLongerOnPath();
7256 }
7257
7258 QuicConnection::ScopedRetransmissionTimeoutIndicator::
ScopedRetransmissionTimeoutIndicator(QuicConnection * connection)7259 ScopedRetransmissionTimeoutIndicator(QuicConnection* connection)
7260 : connection_(connection) {
7261 QUICHE_DCHECK(!connection_->in_probe_time_out_)
7262 << "ScopedRetransmissionTimeoutIndicator is not supposed to be nested";
7263 connection_->in_probe_time_out_ = true;
7264 }
7265
7266 QuicConnection::ScopedRetransmissionTimeoutIndicator::
~ScopedRetransmissionTimeoutIndicator()7267 ~ScopedRetransmissionTimeoutIndicator() {
7268 QUICHE_DCHECK(connection_->in_probe_time_out_);
7269 connection_->in_probe_time_out_ = false;
7270 }
7271
RestoreToLastValidatedPath(QuicSocketAddress original_direct_peer_address)7272 void QuicConnection::RestoreToLastValidatedPath(
7273 QuicSocketAddress original_direct_peer_address) {
7274 QUIC_DLOG(INFO) << "Switch back to use the old peer address "
7275 << alternative_path_.peer_address;
7276 if (!alternative_path_.validated) {
7277 // If not validated by now, close connection silently so that the following
7278 // packets received will be rejected.
7279 CloseConnection(QUIC_INTERNAL_ERROR,
7280 "No validated peer address to use after reverse path "
7281 "validation failure.",
7282 ConnectionCloseBehavior::SILENT_CLOSE);
7283 return;
7284 }
7285 MaybeClearQueuedPacketsOnPathChange();
7286
7287 // Revert congestion control context to old state.
7288 OnPeerIpAddressChanged();
7289
7290 if (alternative_path_.send_algorithm != nullptr) {
7291 sent_packet_manager_.SetSendAlgorithm(
7292 alternative_path_.send_algorithm.release());
7293 } else {
7294 QUIC_BUG(quic_bug_10511_42)
7295 << "Fail to store congestion controller before migration.";
7296 }
7297
7298 if (alternative_path_.rtt_stats.has_value()) {
7299 sent_packet_manager_.SetRttStats(*alternative_path_.rtt_stats);
7300 }
7301
7302 UpdatePeerAddress(original_direct_peer_address);
7303 SetDefaultPathState(std::move(alternative_path_));
7304
7305 active_effective_peer_migration_type_ = NO_CHANGE;
7306 ++stats_.num_invalid_peer_migration;
7307 // The reverse path validation failed because of alarm firing, flush all the
7308 // pending writes previously throttled by anti-amplification limit.
7309 WriteIfNotBlocked();
7310 }
7311
7312 std::unique_ptr<SendAlgorithmInterface>
OnPeerIpAddressChanged()7313 QuicConnection::OnPeerIpAddressChanged() {
7314 QUICHE_DCHECK(framer_.version().HasIetfQuicFrames());
7315 std::unique_ptr<SendAlgorithmInterface> old_send_algorithm =
7316 sent_packet_manager_.OnConnectionMigration(
7317 /*reset_send_algorithm=*/true);
7318 // OnConnectionMigration() should have marked in-flight packets to be
7319 // retransmitted if there is any.
7320 QUICHE_DCHECK(!sent_packet_manager_.HasInFlightPackets());
7321 // OnConnectionMigration() may have changed the retransmission timer, so
7322 // re-arm it.
7323 SetRetransmissionAlarm();
7324 // Stop detections in quiecense.
7325 blackhole_detector_.StopDetection(/*permanent=*/false);
7326 return old_send_algorithm;
7327 }
7328
set_keep_alive_ping_timeout(QuicTime::Delta keep_alive_ping_timeout)7329 void QuicConnection::set_keep_alive_ping_timeout(
7330 QuicTime::Delta keep_alive_ping_timeout) {
7331 ping_manager_.set_keep_alive_timeout(keep_alive_ping_timeout);
7332 }
7333
set_initial_retransmittable_on_wire_timeout(QuicTime::Delta retransmittable_on_wire_timeout)7334 void QuicConnection::set_initial_retransmittable_on_wire_timeout(
7335 QuicTime::Delta retransmittable_on_wire_timeout) {
7336 ping_manager_.set_initial_retransmittable_on_wire_timeout(
7337 retransmittable_on_wire_timeout);
7338 }
7339
IsValidatingServerPreferredAddress() const7340 bool QuicConnection::IsValidatingServerPreferredAddress() const {
7341 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT);
7342 return received_server_preferred_address_.IsInitialized() &&
7343 received_server_preferred_address_ != default_path_.peer_address &&
7344 path_validator_.HasPendingPathValidation() &&
7345 path_validator_.GetContext()->peer_address() ==
7346 received_server_preferred_address_;
7347 }
7348
OnServerPreferredAddressValidated(QuicPathValidationContext & context,bool owns_writer)7349 void QuicConnection::OnServerPreferredAddressValidated(
7350 QuicPathValidationContext& context, bool owns_writer) {
7351 QUIC_DLOG(INFO) << "Server preferred address: " << context.peer_address()
7352 << " validated. Migrating path, self_address: "
7353 << context.self_address()
7354 << ", peer_address: " << context.peer_address();
7355 mutable_stats().server_preferred_address_validated = true;
7356 const bool success =
7357 MigratePath(context.self_address(), context.peer_address(),
7358 context.WriterToUse(), owns_writer);
7359 QUIC_BUG_IF(failed to migrate to server preferred address, !success)
7360 << "Failed to migrate to server preferred address: "
7361 << context.peer_address() << " after successful validation";
7362 }
7363
set_ecn_codepoint(QuicEcnCodepoint ecn_codepoint)7364 bool QuicConnection::set_ecn_codepoint(QuicEcnCodepoint ecn_codepoint) {
7365 if (!GetQuicReloadableFlag(quic_send_ect1)) {
7366 return false;
7367 }
7368 QUIC_RELOADABLE_FLAG_COUNT_N(quic_send_ect1, 3, 8);
7369 if (disable_ecn_codepoint_validation_ || ecn_codepoint == ECN_NOT_ECT) {
7370 packet_writer_params_.ecn_codepoint = ecn_codepoint;
7371 return true;
7372 }
7373 if (!writer_->SupportsEcn()) {
7374 return false;
7375 }
7376 switch (ecn_codepoint) {
7377 case ECN_NOT_ECT:
7378 QUICHE_DCHECK(false);
7379 break;
7380 case ECN_ECT0:
7381 if (!sent_packet_manager_.GetSendAlgorithm()->SupportsECT0()) {
7382 return false;
7383 }
7384 break;
7385 case ECN_ECT1:
7386 if (!sent_packet_manager_.GetSendAlgorithm()->SupportsECT1()) {
7387 return false;
7388 }
7389 break;
7390 case ECN_CE:
7391 return false;
7392 }
7393 packet_writer_params_.ecn_codepoint = ecn_codepoint;
7394 return true;
7395 }
7396
7397 #undef ENDPOINT // undef for jumbo builds
7398 } // namespace quic
7399