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