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