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 // The entity that handles framing writes for a Quic client or server. 6 // Each QuicSession will have a connection associated with it. 7 // 8 // On the server side, the Dispatcher handles the raw reads, and hands off 9 // packets via ProcessUdpPacket for framing and processing. 10 // 11 // On the client side, the Connection handles the raw reads, as well as the 12 // processing. 13 // 14 // Note: this class is not thread-safe. 15 16 #ifndef QUICHE_QUIC_CORE_QUIC_CONNECTION_H_ 17 #define QUICHE_QUIC_CORE_QUIC_CONNECTION_H_ 18 19 #include <cstddef> 20 #include <cstdint> 21 #include <list> 22 #include <map> 23 #include <memory> 24 #include <optional> 25 #include <string> 26 #include <vector> 27 28 #include "absl/strings/string_view.h" 29 #include "quiche/quic/core/congestion_control/rtt_stats.h" 30 #include "quiche/quic/core/crypto/quic_decrypter.h" 31 #include "quiche/quic/core/crypto/quic_encrypter.h" 32 #include "quiche/quic/core/crypto/quic_random.h" 33 #include "quiche/quic/core/crypto/transport_parameters.h" 34 #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" 35 #include "quiche/quic/core/frames/quic_max_streams_frame.h" 36 #include "quiche/quic/core/frames/quic_new_connection_id_frame.h" 37 #include "quiche/quic/core/quic_alarm.h" 38 #include "quiche/quic/core/quic_alarm_factory.h" 39 #include "quiche/quic/core/quic_blocked_writer_interface.h" 40 #include "quiche/quic/core/quic_connection_context.h" 41 #include "quiche/quic/core/quic_connection_id.h" 42 #include "quiche/quic/core/quic_connection_id_manager.h" 43 #include "quiche/quic/core/quic_connection_stats.h" 44 #include "quiche/quic/core/quic_constants.h" 45 #include "quiche/quic/core/quic_framer.h" 46 #include "quiche/quic/core/quic_idle_network_detector.h" 47 #include "quiche/quic/core/quic_lru_cache.h" 48 #include "quiche/quic/core/quic_mtu_discovery.h" 49 #include "quiche/quic/core/quic_network_blackhole_detector.h" 50 #include "quiche/quic/core/quic_one_block_arena.h" 51 #include "quiche/quic/core/quic_packet_creator.h" 52 #include "quiche/quic/core/quic_packet_writer.h" 53 #include "quiche/quic/core/quic_packets.h" 54 #include "quiche/quic/core/quic_path_validator.h" 55 #include "quiche/quic/core/quic_ping_manager.h" 56 #include "quiche/quic/core/quic_sent_packet_manager.h" 57 #include "quiche/quic/core/quic_time.h" 58 #include "quiche/quic/core/quic_types.h" 59 #include "quiche/quic/core/uber_received_packet_manager.h" 60 #include "quiche/quic/platform/api/quic_export.h" 61 #include "quiche/quic/platform/api/quic_flags.h" 62 #include "quiche/quic/platform/api/quic_socket_address.h" 63 #include "quiche/common/platform/api/quiche_mem_slice.h" 64 #include "quiche/common/quiche_circular_deque.h" 65 66 namespace quic { 67 68 class QuicClock; 69 class QuicConfig; 70 class QuicConnection; 71 72 namespace test { 73 class QuicConnectionPeer; 74 } // namespace test 75 76 // Class that receives callbacks from the connection when the path context is 77 // available. 78 class QUICHE_EXPORT MultiPortPathContextObserver { 79 public: 80 virtual void OnMultiPortPathContextAvailable( 81 std::unique_ptr<QuicPathValidationContext>) = 0; 82 83 virtual ~MultiPortPathContextObserver() = default; 84 }; 85 86 // Class that receives callbacks from the connection when frames are received 87 // and when other interesting events happen. 88 class QUICHE_EXPORT QuicConnectionVisitorInterface { 89 public: ~QuicConnectionVisitorInterface()90 virtual ~QuicConnectionVisitorInterface() {} 91 92 // A simple visitor interface for dealing with a data frame. 93 virtual void OnStreamFrame(const QuicStreamFrame& frame) = 0; 94 95 // Called when a CRYPTO frame containing handshake data is received. 96 virtual void OnCryptoFrame(const QuicCryptoFrame& frame) = 0; 97 98 // The session should process the WINDOW_UPDATE frame, adjusting both stream 99 // and connection level flow control windows. 100 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0; 101 102 // A BLOCKED frame indicates the peer is flow control blocked 103 // on a specified stream. 104 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) = 0; 105 106 // Called when the stream is reset by the peer. 107 virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0; 108 109 // Called when the connection is going away according to the peer. 110 virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0; 111 112 // Called when |message| has been received. 113 virtual void OnMessageReceived(absl::string_view message) = 0; 114 115 // Called when a HANDSHAKE_DONE frame has been received. 116 virtual void OnHandshakeDoneReceived() = 0; 117 118 // Called when a NEW_TOKEN frame has been received. 119 virtual void OnNewTokenReceived(absl::string_view token) = 0; 120 121 // Called when a MAX_STREAMS frame has been received from the peer. 122 virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0; 123 124 // Called when a STREAMS_BLOCKED frame has been received from the peer. 125 virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0; 126 127 // Called when the connection is closed either locally by the framer, or 128 // remotely by the peer. 129 virtual void OnConnectionClosed(const QuicConnectionCloseFrame& frame, 130 ConnectionCloseSource source) = 0; 131 132 // Called when the connection failed to write because the socket was blocked. 133 virtual void OnWriteBlocked() = 0; 134 135 // Called once a specific QUIC version is agreed by both endpoints. 136 virtual void OnSuccessfulVersionNegotiation( 137 const ParsedQuicVersion& version) = 0; 138 139 // Called when a packet has been received by the connection, after being 140 // validated and parsed. Only called when the client receives a valid packet 141 // or the server receives a connectivity probing packet. 142 // |is_connectivity_probe| is true if the received packet is a connectivity 143 // probe. 144 virtual void OnPacketReceived(const QuicSocketAddress& self_address, 145 const QuicSocketAddress& peer_address, 146 bool is_connectivity_probe) = 0; 147 148 // Called when a blocked socket becomes writable. 149 virtual void OnCanWrite() = 0; 150 151 // Called when the connection experiences a change in congestion window. 152 virtual void OnCongestionWindowChange(QuicTime now) = 0; 153 154 // Called when the connection receives a packet from a migrated client. 155 virtual void OnConnectionMigration(AddressChangeType type) = 0; 156 157 // Called when the peer seems unreachable over the current path. 158 virtual void OnPathDegrading() = 0; 159 160 // Called when forward progress made after path degrading. 161 virtual void OnForwardProgressMadeAfterPathDegrading() = 0; 162 163 // Called when the connection sends ack after 164 // max_consecutive_num_packets_with_no_retransmittable_frames_ consecutive not 165 // retransmittable packets sent. To instigate an ack from peer, a 166 // retransmittable frame needs to be added. 167 virtual void OnAckNeedsRetransmittableFrame() = 0; 168 169 // Called when an AckFrequency frame need to be sent. 170 virtual void SendAckFrequency(const QuicAckFrequencyFrame& frame) = 0; 171 172 // Called to send a NEW_CONNECTION_ID frame. 173 virtual void SendNewConnectionId(const QuicNewConnectionIdFrame& frame) = 0; 174 175 // Called to send a RETIRE_CONNECTION_ID frame. 176 virtual void SendRetireConnectionId(uint64_t sequence_number) = 0; 177 178 // Called when server starts to use a server issued connection ID. Returns 179 // true if this connection ID hasn't been used by another connection. 180 virtual bool MaybeReserveConnectionId( 181 const QuicConnectionId& server_connection_id) = 0; 182 183 // Called when server stops to use a server issued connection ID. 184 virtual void OnServerConnectionIdRetired( 185 const QuicConnectionId& server_connection_id) = 0; 186 187 // Called to ask if the visitor wants to schedule write resumption as it both 188 // has pending data to write, and is able to write (e.g. based on flow control 189 // limits). 190 // Writes may be pending because they were write-blocked, congestion-throttled 191 // or yielded to other connections. 192 virtual bool WillingAndAbleToWrite() const = 0; 193 194 // Called to ask if the connection should be kept alive and prevented 195 // from timing out, for example if there are outstanding application 196 // transactions expecting a response. 197 virtual bool ShouldKeepConnectionAlive() const = 0; 198 199 // Called to retrieve streams information for logging purpose. 200 virtual std::string GetStreamsInfoForLogging() const = 0; 201 202 // Called when a self address change is observed. Returns true if self address 203 // change is allowed. 204 virtual bool AllowSelfAddressChange() const = 0; 205 206 // Called to get current handshake state. 207 virtual HandshakeState GetHandshakeState() const = 0; 208 209 // Called when a STOP_SENDING frame has been received. 210 virtual void OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0; 211 212 // Called when a packet of encryption |level| has been successfully decrypted. 213 virtual void OnPacketDecrypted(EncryptionLevel level) = 0; 214 215 // Called when a 1RTT packet has been acknowledged. 216 virtual void OnOneRttPacketAcknowledged() = 0; 217 218 // Called when a packet of ENCRYPTION_HANDSHAKE gets sent. 219 virtual void OnHandshakePacketSent() = 0; 220 221 // Called when a key update has occurred. 222 virtual void OnKeyUpdate(KeyUpdateReason reason) = 0; 223 224 // Called to generate a decrypter for the next key phase. Each call should 225 // generate the key for phase n+1. 226 virtual std::unique_ptr<QuicDecrypter> 227 AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0; 228 229 // Called to generate an encrypter for the same key phase of the last 230 // decrypter returned by AdvanceKeysAndCreateCurrentOneRttDecrypter(). 231 virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0; 232 233 // Called when connection is being closed right before a CONNECTION_CLOSE 234 // frame is serialized, but only on the server and only if forward secure 235 // encryption has already been established. 236 virtual void BeforeConnectionCloseSent() = 0; 237 238 // Called by the server to validate |token| in received INITIAL packets. 239 // Consider the client address gets validated (and therefore remove 240 // amplification factor) once the |token| gets successfully validated. 241 virtual bool ValidateToken(absl::string_view token) = 0; 242 243 // Called by the server to send another token. 244 // Return false if the crypto stream fail to generate one. 245 virtual bool MaybeSendAddressToken() = 0; 246 247 // Runs OnMultiPortPathContextAvailable() from |context_observer| with context 248 // needed for the connection to probe on the alternative path. The callback 249 // must be called exactly once. May run OnMultiPortPathContextAvailable() 250 // synchronously or asynchronously. If OnMultiPortPathContextAvailable() is 251 // run asynchronously, it must be called on the same thread as QuicConnection 252 // is not thread safe. 253 virtual void CreateContextForMultiPortPath( 254 std::unique_ptr<MultiPortPathContextObserver> context_observer) = 0; 255 256 // Migrate to the multi-port path which is identified by |context|. 257 virtual void MigrateToMultiPortPath( 258 std::unique_ptr<QuicPathValidationContext> context) = 0; 259 260 // Called when the client receives a preferred address from its peer. 261 virtual void OnServerPreferredAddressAvailable( 262 const QuicSocketAddress& server_preferred_address) = 0; 263 264 // Asks session to bundle data opportunistically with outgoing data. 265 virtual void MaybeBundleOpportunistically() = 0; 266 267 // Get from session the flow control send window for stream |id|. 268 virtual QuicByteCount GetFlowControlSendWindowSize(QuicStreamId id) = 0; 269 }; 270 271 // Interface which gets callbacks from the QuicConnection at interesting 272 // points. Implementations must not mutate the state of the connection 273 // as a result of these callbacks. 274 class QUICHE_EXPORT QuicConnectionDebugVisitor 275 : public QuicSentPacketManager::DebugDelegate { 276 public: ~QuicConnectionDebugVisitor()277 ~QuicConnectionDebugVisitor() override {} 278 279 // Called when a packet has been sent. OnPacketSent(QuicPacketNumber,QuicPacketLength,bool,TransmissionType,EncryptionLevel,const QuicFrames &,const QuicFrames &,QuicTime,uint32_t)280 virtual void OnPacketSent(QuicPacketNumber /*packet_number*/, 281 QuicPacketLength /*packet_length*/, 282 bool /*has_crypto_handshake*/, 283 TransmissionType /*transmission_type*/, 284 EncryptionLevel /*encryption_level*/, 285 const QuicFrames& /*retransmittable_frames*/, 286 const QuicFrames& /*nonretransmittable_frames*/, 287 QuicTime /*sent_time*/, uint32_t /*batch_id*/) {} 288 289 // Called when a coalesced packet is successfully serialized. OnCoalescedPacketSent(const QuicCoalescedPacket &,size_t)290 virtual void OnCoalescedPacketSent( 291 const QuicCoalescedPacket& /*coalesced_packet*/, size_t /*length*/) {} 292 293 // Called when a PING frame has been sent. OnPingSent()294 virtual void OnPingSent() {} 295 296 // Called when a packet has been received, but before it is 297 // validated or parsed. OnPacketReceived(const QuicSocketAddress &,const QuicSocketAddress &,const QuicEncryptedPacket &)298 virtual void OnPacketReceived(const QuicSocketAddress& /*self_address*/, 299 const QuicSocketAddress& /*peer_address*/, 300 const QuicEncryptedPacket& /*packet*/) {} 301 302 // Called when the unauthenticated portion of the header has been parsed. OnUnauthenticatedHeader(const QuicPacketHeader &)303 virtual void OnUnauthenticatedHeader(const QuicPacketHeader& /*header*/) {} 304 305 // Called when a packet is received with a connection id that does not 306 // match the ID of this connection. OnIncorrectConnectionId(QuicConnectionId)307 virtual void OnIncorrectConnectionId(QuicConnectionId /*connection_id*/) {} 308 309 // Called when an undecryptable packet has been received. If |dropped| is 310 // true, the packet has been dropped. Otherwise, the packet will be queued and 311 // connection will attempt to process it later. OnUndecryptablePacket(EncryptionLevel,bool)312 virtual void OnUndecryptablePacket(EncryptionLevel /*decryption_level*/, 313 bool /*dropped*/) {} 314 315 // Called when attempting to process a previously undecryptable packet. OnAttemptingToProcessUndecryptablePacket(EncryptionLevel)316 virtual void OnAttemptingToProcessUndecryptablePacket( 317 EncryptionLevel /*decryption_level*/) {} 318 319 // Called when a duplicate packet has been received. OnDuplicatePacket(QuicPacketNumber)320 virtual void OnDuplicatePacket(QuicPacketNumber /*packet_number*/) {} 321 322 // Called when the protocol version on the received packet doensn't match 323 // current protocol version of the connection. OnProtocolVersionMismatch(ParsedQuicVersion)324 virtual void OnProtocolVersionMismatch(ParsedQuicVersion /*version*/) {} 325 326 // Called when the complete header of a packet has been parsed. OnPacketHeader(const QuicPacketHeader &,QuicTime,EncryptionLevel)327 virtual void OnPacketHeader(const QuicPacketHeader& /*header*/, 328 QuicTime /*receive_time*/, 329 EncryptionLevel /*level*/) {} 330 331 // Called when a StreamFrame has been parsed. OnStreamFrame(const QuicStreamFrame &)332 virtual void OnStreamFrame(const QuicStreamFrame& /*frame*/) {} 333 334 // Called when a CRYPTO frame containing handshake data is received. OnCryptoFrame(const QuicCryptoFrame &)335 virtual void OnCryptoFrame(const QuicCryptoFrame& /*frame*/) {} 336 337 // Called when a QuicPaddingFrame has been parsed. OnPaddingFrame(const QuicPaddingFrame &)338 virtual void OnPaddingFrame(const QuicPaddingFrame& /*frame*/) {} 339 340 // Called when a Ping has been parsed. OnPingFrame(const QuicPingFrame &,QuicTime::Delta)341 virtual void OnPingFrame(const QuicPingFrame& /*frame*/, 342 QuicTime::Delta /*ping_received_delay*/) {} 343 344 // Called when a GoAway has been parsed. OnGoAwayFrame(const QuicGoAwayFrame &)345 virtual void OnGoAwayFrame(const QuicGoAwayFrame& /*frame*/) {} 346 347 // Called when a RstStreamFrame has been parsed. OnRstStreamFrame(const QuicRstStreamFrame &)348 virtual void OnRstStreamFrame(const QuicRstStreamFrame& /*frame*/) {} 349 350 // Called when a ConnectionCloseFrame has been parsed. All forms 351 // of CONNECTION CLOSE are handled, Google QUIC, IETF QUIC 352 // CONNECTION CLOSE/Transport and IETF QUIC CONNECTION CLOSE/Application OnConnectionCloseFrame(const QuicConnectionCloseFrame &)353 virtual void OnConnectionCloseFrame( 354 const QuicConnectionCloseFrame& /*frame*/) {} 355 356 // Called when a WindowUpdate has been parsed. OnWindowUpdateFrame(const QuicWindowUpdateFrame &,const QuicTime &)357 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& /*frame*/, 358 const QuicTime& /*receive_time*/) {} 359 360 // Called when a BlockedFrame has been parsed. OnBlockedFrame(const QuicBlockedFrame &)361 virtual void OnBlockedFrame(const QuicBlockedFrame& /*frame*/) {} 362 363 // Called when a NewConnectionIdFrame has been parsed. OnNewConnectionIdFrame(const QuicNewConnectionIdFrame &)364 virtual void OnNewConnectionIdFrame( 365 const QuicNewConnectionIdFrame& /*frame*/) {} 366 367 // Called when a RetireConnectionIdFrame has been parsed. OnRetireConnectionIdFrame(const QuicRetireConnectionIdFrame &)368 virtual void OnRetireConnectionIdFrame( 369 const QuicRetireConnectionIdFrame& /*frame*/) {} 370 371 // Called when a NewTokenFrame has been parsed. OnNewTokenFrame(const QuicNewTokenFrame &)372 virtual void OnNewTokenFrame(const QuicNewTokenFrame& /*frame*/) {} 373 374 // Called when a MessageFrame has been parsed. OnMessageFrame(const QuicMessageFrame &)375 virtual void OnMessageFrame(const QuicMessageFrame& /*frame*/) {} 376 377 // Called when a HandshakeDoneFrame has been parsed. OnHandshakeDoneFrame(const QuicHandshakeDoneFrame &)378 virtual void OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& /*frame*/) {} 379 380 // Called when a version negotiation packet has been received. OnVersionNegotiationPacket(const QuicVersionNegotiationPacket &)381 virtual void OnVersionNegotiationPacket( 382 const QuicVersionNegotiationPacket& /*packet*/) {} 383 384 // Called when the connection is closed. OnConnectionClosed(const QuicConnectionCloseFrame &,ConnectionCloseSource)385 virtual void OnConnectionClosed(const QuicConnectionCloseFrame& /*frame*/, 386 ConnectionCloseSource /*source*/) {} 387 388 // Called when the version negotiation is successful. OnSuccessfulVersionNegotiation(const ParsedQuicVersion &)389 virtual void OnSuccessfulVersionNegotiation( 390 const ParsedQuicVersion& /*version*/) {} 391 392 // Called when a CachedNetworkParameters is sent to the client. OnSendConnectionState(const CachedNetworkParameters &)393 virtual void OnSendConnectionState( 394 const CachedNetworkParameters& /*cached_network_params*/) {} 395 396 // Called when a CachedNetworkParameters are received from the client. OnReceiveConnectionState(const CachedNetworkParameters &)397 virtual void OnReceiveConnectionState( 398 const CachedNetworkParameters& /*cached_network_params*/) {} 399 400 // Called when the connection parameters are set from the supplied 401 // |config|. OnSetFromConfig(const QuicConfig &)402 virtual void OnSetFromConfig(const QuicConfig& /*config*/) {} 403 404 // Called when RTT may have changed, including when an RTT is read from 405 // the config. OnRttChanged(QuicTime::Delta)406 virtual void OnRttChanged(QuicTime::Delta /*rtt*/) const {} 407 408 // Called when a StopSendingFrame has been parsed. OnStopSendingFrame(const QuicStopSendingFrame &)409 virtual void OnStopSendingFrame(const QuicStopSendingFrame& /*frame*/) {} 410 411 // Called when a PathChallengeFrame has been parsed. OnPathChallengeFrame(const QuicPathChallengeFrame &)412 virtual void OnPathChallengeFrame(const QuicPathChallengeFrame& /*frame*/) {} 413 414 // Called when a PathResponseFrame has been parsed. OnPathResponseFrame(const QuicPathResponseFrame &)415 virtual void OnPathResponseFrame(const QuicPathResponseFrame& /*frame*/) {} 416 417 // Called when a StreamsBlockedFrame has been parsed. OnStreamsBlockedFrame(const QuicStreamsBlockedFrame &)418 virtual void OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& /*frame*/) { 419 } 420 421 // Called when a MaxStreamsFrame has been parsed. OnMaxStreamsFrame(const QuicMaxStreamsFrame &)422 virtual void OnMaxStreamsFrame(const QuicMaxStreamsFrame& /*frame*/) {} 423 424 // Called when an AckFrequencyFrame has been parsed. OnAckFrequencyFrame(const QuicAckFrequencyFrame &)425 virtual void OnAckFrequencyFrame(const QuicAckFrequencyFrame& /*frame*/) {} 426 427 // Called when |count| packet numbers have been skipped. OnNPacketNumbersSkipped(QuicPacketCount,QuicTime)428 virtual void OnNPacketNumbersSkipped(QuicPacketCount /*count*/, 429 QuicTime /*now*/) {} 430 431 // Called when a packet is serialized but discarded (i.e. not sent). OnPacketDiscarded(const SerializedPacket &)432 virtual void OnPacketDiscarded(const SerializedPacket& /*packet*/) {} 433 434 // Called for QUIC+TLS versions when we send transport parameters. OnTransportParametersSent(const TransportParameters &)435 virtual void OnTransportParametersSent( 436 const TransportParameters& /*transport_parameters*/) {} 437 438 // Called for QUIC+TLS versions when we receive transport parameters. OnTransportParametersReceived(const TransportParameters &)439 virtual void OnTransportParametersReceived( 440 const TransportParameters& /*transport_parameters*/) {} 441 442 // Called for QUIC+TLS versions when we resume cached transport parameters for 443 // 0-RTT. OnTransportParametersResumed(const TransportParameters &)444 virtual void OnTransportParametersResumed( 445 const TransportParameters& /*transport_parameters*/) {} 446 447 // Called for QUIC+TLS versions when 0-RTT is rejected. OnZeroRttRejected(int)448 virtual void OnZeroRttRejected(int /*reject_reason*/) {} 449 450 // Called for QUIC+TLS versions when 0-RTT packet gets acked. OnZeroRttPacketAcked()451 virtual void OnZeroRttPacketAcked() {} 452 453 // Called on peer address change. OnPeerAddressChange(AddressChangeType,QuicTime::Delta)454 virtual void OnPeerAddressChange(AddressChangeType /*type*/, 455 QuicTime::Delta /*connection_time*/) {} 456 457 // Called after peer migration is validated. OnPeerMigrationValidated(QuicTime::Delta)458 virtual void OnPeerMigrationValidated(QuicTime::Delta /*connection_time*/) {} 459 460 // Called after an ClientHelloInner is encrypted and sent as a client. OnEncryptedClientHelloSent(absl::string_view)461 virtual void OnEncryptedClientHelloSent(absl::string_view /*client_hello*/) {} 462 463 // Called after an ClientHelloInner is received and decrypted as a server. OnEncryptedClientHelloReceived(absl::string_view)464 virtual void OnEncryptedClientHelloReceived( 465 absl::string_view /*client_hello*/) {} 466 }; 467 468 class QUICHE_EXPORT QuicConnectionHelperInterface { 469 public: ~QuicConnectionHelperInterface()470 virtual ~QuicConnectionHelperInterface() {} 471 472 // Returns a QuicClock to be used for all time related functions. 473 virtual const QuicClock* GetClock() const = 0; 474 475 // Returns a QuicRandom to be used for all random number related functions. 476 virtual QuicRandom* GetRandomGenerator() = 0; 477 478 // Returns a QuicheBufferAllocator to be used for stream send buffers. 479 virtual quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() = 0; 480 }; 481 482 class QUICHE_EXPORT QuicConnection 483 : public QuicFramerVisitorInterface, 484 public QuicBlockedWriterInterface, 485 public QuicPacketCreator::DelegateInterface, 486 public QuicSentPacketManager::NetworkChangeVisitor, 487 public QuicNetworkBlackholeDetector::Delegate, 488 public QuicIdleNetworkDetector::Delegate, 489 public QuicPathValidator::SendDelegate, 490 public QuicConnectionIdManagerVisitorInterface, 491 public QuicPingManager::Delegate { 492 public: 493 // Constructs a new QuicConnection for |connection_id| and 494 // |initial_peer_address| using |writer| to write packets. |owns_writer| 495 // specifies whether the connection takes ownership of |writer|. |helper| must 496 // outlive this connection. 497 QuicConnection(QuicConnectionId server_connection_id, 498 QuicSocketAddress initial_self_address, 499 QuicSocketAddress initial_peer_address, 500 QuicConnectionHelperInterface* helper, 501 QuicAlarmFactory* alarm_factory, QuicPacketWriter* writer, 502 bool owns_writer, Perspective perspective, 503 const ParsedQuicVersionVector& supported_versions, 504 ConnectionIdGeneratorInterface& generator); 505 QuicConnection(const QuicConnection&) = delete; 506 QuicConnection& operator=(const QuicConnection&) = delete; 507 ~QuicConnection() override; 508 509 struct MultiPortStats { 510 // general rtt stats of the multi-port path. 511 RttStats rtt_stats; 512 // rtt stats for the multi-port path when the default path is degrading. 513 RttStats rtt_stats_when_default_path_degrading; 514 // number of multi-port probe failures when path is not degrading 515 size_t num_multi_port_probe_failures_when_path_not_degrading = 0; 516 // number of multi-port probe failure when path is degrading 517 size_t num_multi_port_probe_failures_when_path_degrading = 0; 518 // number of total multi-port path creations in a connection 519 size_t num_multi_port_paths_created = 0; 520 }; 521 522 // Sets connection parameters from the supplied |config|. 523 void SetFromConfig(const QuicConfig& config); 524 525 // Apply |connection_options| for this connection. Unlike SetFromConfig, this 526 // can happen at anytime in the life of a connection. 527 // Note there is no guarantee that all options can be applied. Components will 528 // only apply cherrypicked options that make sense at the time of the call. 529 void ApplyConnectionOptions(const QuicTagVector& connection_options); 530 531 // Called by the session when sending connection state to the client. 532 virtual void OnSendConnectionState( 533 const CachedNetworkParameters& cached_network_params); 534 535 // Called by the session when receiving connection state from the client. 536 virtual void OnReceiveConnectionState( 537 const CachedNetworkParameters& cached_network_params); 538 539 // Called by the Session when the client has provided CachedNetworkParameters. 540 virtual void ResumeConnectionState( 541 const CachedNetworkParameters& cached_network_params, 542 bool max_bandwidth_resumption); 543 544 // Called by the Session when a max pacing rate for the connection is needed. 545 virtual void SetMaxPacingRate(QuicBandwidth max_pacing_rate); 546 547 // Allows the client to adjust network parameters based on external 548 // information. 549 void AdjustNetworkParameters( 550 const SendAlgorithmInterface::NetworkParams& params); 551 void AdjustNetworkParameters(QuicBandwidth bandwidth, QuicTime::Delta rtt, 552 bool allow_cwnd_to_decrease); 553 554 // Install a loss detection tuner. Must be called before OnConfigNegotiated. 555 void SetLossDetectionTuner( 556 std::unique_ptr<LossDetectionTunerInterface> tuner); 557 // Called by the session when session->is_configured() becomes true. 558 void OnConfigNegotiated(); 559 560 // Returns the max pacing rate for the connection. 561 virtual QuicBandwidth MaxPacingRate() const; 562 563 // Sends crypto handshake messages of length |write_length| to the peer in as 564 // few packets as possible. Returns the number of bytes consumed from the 565 // data. 566 virtual size_t SendCryptoData(EncryptionLevel level, size_t write_length, 567 QuicStreamOffset offset); 568 569 // Send the data of length |write_length| to the peer in as few packets as 570 // possible. Returns the number of bytes consumed from data, and a boolean 571 // indicating if the fin bit was consumed. This does not indicate the data 572 // has been sent on the wire: it may have been turned into a packet and queued 573 // if the socket was unexpectedly blocked. 574 virtual QuicConsumedData SendStreamData(QuicStreamId id, size_t write_length, 575 QuicStreamOffset offset, 576 StreamSendingState state); 577 578 // Send |frame| to the peer. Returns true if frame is consumed, false 579 // otherwise. 580 virtual bool SendControlFrame(const QuicFrame& frame); 581 582 // Called when stream |id| is reset because of |error|. 583 virtual void OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error); 584 585 // Closes the connection. 586 // |connection_close_behavior| determines whether or not a connection close 587 // packet is sent to the peer. 588 virtual void CloseConnection( 589 QuicErrorCode error, const std::string& details, 590 ConnectionCloseBehavior connection_close_behavior); 591 // Closes the connection, specifying the wire error code |ietf_error| 592 // explicitly. 593 virtual void CloseConnection( 594 QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error, 595 const std::string& details, 596 ConnectionCloseBehavior connection_close_behavior); 597 mutable_stats()598 QuicConnectionStats& mutable_stats() { return stats_; } 599 600 // Returns statistics tracked for this connection. 601 const QuicConnectionStats& GetStats(); 602 603 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from 604 // the peer. 605 // In a client, the packet may be "stray" and have a different connection ID 606 // than that of this connection. 607 virtual void ProcessUdpPacket(const QuicSocketAddress& self_address, 608 const QuicSocketAddress& peer_address, 609 const QuicReceivedPacket& packet); 610 611 // QuicBlockedWriterInterface 612 // Called when the underlying connection becomes writable to allow queued 613 // writes to happen. 614 void OnBlockedWriterCanWrite() override; 615 IsWriterBlocked()616 bool IsWriterBlocked() const override { 617 return writer_ != nullptr && writer_->IsWriteBlocked(); 618 } 619 620 // Called when the caller thinks it's worth a try to write. 621 // TODO(fayang): consider unifying this with QuicSession::OnCanWrite. 622 virtual void OnCanWrite(); 623 624 // Called when an error occurs while attempting to write a packet to the 625 // network. 626 void OnWriteError(int error_code); 627 628 // Whether |result| represents a MSG TOO BIG write error. 629 bool IsMsgTooBig(const QuicPacketWriter* writer, const WriteResult& result); 630 631 // Called from the SendAlarmDelegate to initiate writing data. 632 virtual void OnSendAlarm(); 633 634 // If the socket is not blocked, writes queued packets. 635 void WriteIfNotBlocked(); 636 637 // Set the packet writer. SetQuicPacketWriter(QuicPacketWriter * writer,bool owns_writer)638 void SetQuicPacketWriter(QuicPacketWriter* writer, bool owns_writer) { 639 QUICHE_DCHECK(writer != nullptr); 640 if (writer_ != nullptr && owns_writer_) { 641 delete writer_; 642 } 643 writer_ = writer; 644 owns_writer_ = owns_writer; 645 } 646 647 // Set self address. SetSelfAddress(QuicSocketAddress address)648 void SetSelfAddress(QuicSocketAddress address) { 649 default_path_.self_address = address; 650 } 651 652 // The version of the protocol this connection is using. transport_version()653 QuicTransportVersion transport_version() const { 654 return framer_.transport_version(); 655 } 656 version()657 ParsedQuicVersion version() const { return framer_.version(); } 658 659 // The versions of the protocol that this connection supports. supported_versions()660 const ParsedQuicVersionVector& supported_versions() const { 661 return framer_.supported_versions(); 662 } 663 664 // Mark version negotiated for this connection. Once called, the connection 665 // will ignore received version negotiation packets. SetVersionNegotiated()666 void SetVersionNegotiated() { version_negotiated_ = true; } 667 668 // From QuicFramerVisitorInterface 669 void OnError(QuicFramer* framer) override; 670 bool OnProtocolVersionMismatch(ParsedQuicVersion received_version) override; 671 void OnPacket() override; 672 void OnVersionNegotiationPacket( 673 const QuicVersionNegotiationPacket& packet) override; 674 void OnRetryPacket(QuicConnectionId original_connection_id, 675 QuicConnectionId new_connection_id, 676 absl::string_view retry_token, 677 absl::string_view retry_integrity_tag, 678 absl::string_view retry_without_tag) override; 679 bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override; 680 bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override; 681 void OnDecryptedPacket(size_t length, EncryptionLevel level) override; 682 bool OnPacketHeader(const QuicPacketHeader& header) override; 683 void OnCoalescedPacket(const QuicEncryptedPacket& packet) override; 684 void OnUndecryptablePacket(const QuicEncryptedPacket& packet, 685 EncryptionLevel decryption_level, 686 bool has_decryption_key) override; 687 bool OnStreamFrame(const QuicStreamFrame& frame) override; 688 bool OnCryptoFrame(const QuicCryptoFrame& frame) override; 689 bool OnAckFrameStart(QuicPacketNumber largest_acked, 690 QuicTime::Delta ack_delay_time) override; 691 bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override; 692 bool OnAckTimestamp(QuicPacketNumber packet_number, 693 QuicTime timestamp) override; 694 bool OnAckFrameEnd(QuicPacketNumber start, 695 const std::optional<QuicEcnCounts>& ecn_counts) override; 696 bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override; 697 bool OnPaddingFrame(const QuicPaddingFrame& frame) override; 698 bool OnPingFrame(const QuicPingFrame& frame) override; 699 bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override; 700 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override; 701 bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override; 702 bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override; 703 bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override; 704 bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override; 705 bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; 706 bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; 707 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; 708 bool OnBlockedFrame(const QuicBlockedFrame& frame) override; 709 bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override; 710 bool OnRetireConnectionIdFrame( 711 const QuicRetireConnectionIdFrame& frame) override; 712 bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override; 713 bool OnMessageFrame(const QuicMessageFrame& frame) override; 714 bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override; 715 bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override; 716 void OnPacketComplete() override; 717 bool IsValidStatelessResetToken( 718 const StatelessResetToken& token) const override; 719 void OnAuthenticatedIetfStatelessResetPacket( 720 const QuicIetfStatelessResetPacket& packet) override; 721 void OnKeyUpdate(KeyUpdateReason reason) override; 722 void OnDecryptedFirstPacketInKeyPhase() override; 723 std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() 724 override; 725 std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; 726 727 // Whether destination connection ID is required but missing in the packet 728 // creator. 729 bool IsMissingDestinationConnectionID() const; 730 // QuicPacketCreator::DelegateInterface 731 bool ShouldGeneratePacket(HasRetransmittableData retransmittable, 732 IsHandshake handshake) override; 733 void MaybeBundleOpportunistically() override; GetFlowControlSendWindowSize(QuicStreamId id)734 QuicByteCount GetFlowControlSendWindowSize(QuicStreamId id) override { 735 return visitor_->GetFlowControlSendWindowSize(id); 736 } 737 QuicPacketBuffer GetPacketBuffer() override; 738 void OnSerializedPacket(SerializedPacket packet) override; 739 void OnUnrecoverableError(QuicErrorCode error, 740 const std::string& error_details) override; 741 SerializedPacketFate GetSerializedPacketFate( 742 bool is_mtu_discovery, EncryptionLevel encryption_level) override; 743 744 // QuicSentPacketManager::NetworkChangeVisitor 745 void OnCongestionChange() override; 746 void OnPathMtuIncreased(QuicPacketLength packet_size) override; 747 void OnInFlightEcnPacketAcked() override; 748 void OnInvalidEcnFeedback() override; 749 750 // QuicNetworkBlackholeDetector::Delegate 751 void OnPathDegradingDetected() override; 752 void OnBlackholeDetected() override; 753 void OnPathMtuReductionDetected() override; 754 755 // QuicIdleNetworkDetector::Delegate 756 void OnHandshakeTimeout() override; 757 void OnIdleNetworkDetected() override; 758 759 // QuicPingManager::Delegate 760 void OnKeepAliveTimeout() override; 761 void OnRetransmittableOnWireTimeout() override; 762 763 // QuicConnectionIdManagerVisitorInterface 764 void OnPeerIssuedConnectionIdRetired() override; 765 bool SendNewConnectionId(const QuicNewConnectionIdFrame& frame) override; 766 bool MaybeReserveConnectionId(const QuicConnectionId& connection_id) override; 767 void OnSelfIssuedConnectionIdRetired( 768 const QuicConnectionId& connection_id) override; 769 770 // Please note, this is not a const function. For logging purpose, please use 771 // ack_frame(). 772 const QuicFrame GetUpdatedAckFrame(); 773 774 // Called to send a new connection ID to client if the # of connection ID has 775 // not exceeded the active connection ID limits. 776 void MaybeSendConnectionIdToClient(); 777 778 // Called when the handshake completes. On the client side, handshake 779 // completes on receipt of SHLO. On the server side, handshake completes when 780 // SHLO gets ACKed (or a forward secure packet gets decrypted successfully). 781 // TODO(fayang): Add a guard that this only gets called once. 782 void OnHandshakeComplete(); 783 784 // Creates and probes an multi-port path if none exists. 785 void MaybeCreateMultiPortPath(); 786 787 // Called in multi-port QUIC when the alternative path validation succeeds. 788 // Stores the path validation context and prepares for the next validation. 789 void OnMultiPortPathProbingSuccess( 790 std::unique_ptr<QuicPathValidationContext> context, QuicTime start_time); 791 792 // Probe the existing alternative path. Does not create a new alternative 793 // path. This method is the callback for |multi_port_probing_alarm_|. 794 virtual void MaybeProbeMultiPortPath(); 795 796 // Accessors set_visitor(QuicConnectionVisitorInterface * visitor)797 void set_visitor(QuicConnectionVisitorInterface* visitor) { 798 visitor_ = visitor; 799 } set_debug_visitor(QuicConnectionDebugVisitor * debug_visitor)800 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) { 801 debug_visitor_ = debug_visitor; 802 sent_packet_manager_.SetDebugDelegate(debug_visitor); 803 } 804 // Used in Chromium, but not internally. 805 // Must only be called before ping_alarm_ is set. 806 void set_keep_alive_ping_timeout(QuicTime::Delta keep_alive_ping_timeout); 807 // Sets an initial timeout for the ping alarm when there is no retransmittable 808 // data in flight, allowing for a more aggressive ping alarm in that case. 809 void set_initial_retransmittable_on_wire_timeout( 810 QuicTime::Delta retransmittable_on_wire_timeout); 811 // Used in Chromium, but not internally. set_creator_debug_delegate(QuicPacketCreator::DebugDelegate * visitor)812 void set_creator_debug_delegate(QuicPacketCreator::DebugDelegate* visitor) { 813 packet_creator_.set_debug_delegate(visitor); 814 } self_address()815 const QuicSocketAddress& self_address() const { 816 return default_path_.self_address; 817 } peer_address()818 const QuicSocketAddress& peer_address() const { return direct_peer_address_; } effective_peer_address()819 const QuicSocketAddress& effective_peer_address() const { 820 return default_path_.peer_address; 821 } 822 823 // Returns the server connection ID used on the default path. connection_id()824 const QuicConnectionId& connection_id() const { 825 return default_path_.server_connection_id; 826 } 827 client_connection_id()828 const QuicConnectionId& client_connection_id() const { 829 return default_path_.client_connection_id; 830 } 831 void set_client_connection_id(QuicConnectionId client_connection_id); clock()832 const QuicClock* clock() const { return clock_; } random_generator()833 QuicRandom* random_generator() const { return random_generator_; } 834 QuicByteCount max_packet_length() const; 835 void SetMaxPacketLength(QuicByteCount length); 836 mtu_probe_count()837 size_t mtu_probe_count() const { return mtu_probe_count_; } 838 connected()839 bool connected() const { return connected_; } 840 841 // Must only be called on client connections. server_supported_versions()842 const ParsedQuicVersionVector& server_supported_versions() const { 843 QUICHE_DCHECK_EQ(Perspective::IS_CLIENT, perspective_); 844 return server_supported_versions_; 845 } 846 HasQueuedPackets()847 bool HasQueuedPackets() const { return !buffered_packets_.empty(); } 848 // Testing only. TODO(ianswett): Use a peer instead. NumQueuedPackets()849 size_t NumQueuedPackets() const { return buffered_packets_.size(); } 850 851 // Returns true if the connection has queued packets or frames. 852 bool HasQueuedData() const; 853 854 // Sets the handshake and idle state connection timeouts. 855 void SetNetworkTimeouts(QuicTime::Delta handshake_timeout, 856 QuicTime::Delta idle_timeout); 857 SetMultiPortProbingInterval(QuicTime::Delta probing_interval)858 void SetMultiPortProbingInterval(QuicTime::Delta probing_interval) { 859 multi_port_probing_interval_ = probing_interval; 860 } 861 multi_port_stats()862 const MultiPortStats* multi_port_stats() const { 863 return multi_port_stats_.get(); 864 } 865 866 // Sets up a packet with an QuicAckFrame and sends it out. 867 void SendAck(); 868 869 // Called when an RTO fires. Resets the retransmission alarm if there are 870 // remaining unacked packets. 871 void OnRetransmissionTimeout(); 872 873 // Mark all sent 0-RTT encrypted packets for retransmission. Called when new 874 // 0-RTT or 1-RTT key is available in gQUIC, or when 0-RTT is rejected in IETF 875 // QUIC. |reject_reason| is used in TLS-QUIC to log why 0-RTT was rejected. 876 void MarkZeroRttPacketsForRetransmission(int reject_reason); 877 878 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the 879 // connection becomes forward secure and hasn't received acks for all packets. 880 void NeuterUnencryptedPackets(); 881 882 // Changes the encrypter used for level |level| to |encrypter|. 883 void SetEncrypter(EncryptionLevel level, 884 std::unique_ptr<QuicEncrypter> encrypter); 885 886 // Called to remove encrypter of encryption |level|. 887 void RemoveEncrypter(EncryptionLevel level); 888 889 // SetNonceForPublicHeader sets the nonce that will be transmitted in the 890 // header of each packet encrypted at the initial encryption level decrypted. 891 // This should only be called on the server side. 892 void SetDiversificationNonce(const DiversificationNonce& nonce); 893 894 // SetDefaultEncryptionLevel sets the encryption level that will be applied 895 // to new packets. 896 void SetDefaultEncryptionLevel(EncryptionLevel level); 897 898 // SetDecrypter sets the primary decrypter, replacing any that already exists. 899 // If an alternative decrypter is in place then the function QUICHE_DCHECKs. 900 // This is intended for cases where one knows that future packets will be 901 // using the new decrypter and the previous decrypter is now obsolete. |level| 902 // indicates the encryption level of the new decrypter. 903 void SetDecrypter(EncryptionLevel level, 904 std::unique_ptr<QuicDecrypter> decrypter); 905 906 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt 907 // future packets. |level| indicates the encryption level of the decrypter. If 908 // |latch_once_used| is true, then the first time that the decrypter is 909 // successful it will replace the primary decrypter. Otherwise both 910 // decrypters will remain active and the primary decrypter will be the one 911 // last used. 912 void SetAlternativeDecrypter(EncryptionLevel level, 913 std::unique_ptr<QuicDecrypter> decrypter, 914 bool latch_once_used); 915 916 void InstallDecrypter(EncryptionLevel level, 917 std::unique_ptr<QuicDecrypter> decrypter); 918 void RemoveDecrypter(EncryptionLevel level); 919 920 // Discard keys for the previous key phase. 921 void DiscardPreviousOneRttKeys(); 922 923 // Returns true if it is currently allowed to initiate a key update. 924 bool IsKeyUpdateAllowed() const; 925 926 // Returns true if packets have been sent in the current 1-RTT key phase but 927 // none of these packets have been acked. 928 bool HaveSentPacketsInCurrentKeyPhaseButNoneAcked() const; 929 930 // Returns the count of packets received that appeared to attempt a key 931 // update but failed decryption that have been received since the last 932 // successfully decrypted packet. 933 QuicPacketCount PotentialPeerKeyUpdateAttemptCount() const; 934 935 // Increment the key phase. It is a bug to call this when IsKeyUpdateAllowed() 936 // is false. Returns false on error. 937 bool InitiateKeyUpdate(KeyUpdateReason reason); 938 939 const QuicDecrypter* decrypter() const; 940 const QuicDecrypter* alternative_decrypter() const; 941 perspective()942 Perspective perspective() const { return perspective_; } 943 944 // Allow easy overriding of truncated connection IDs. set_can_truncate_connection_ids(bool can)945 void set_can_truncate_connection_ids(bool can) { 946 can_truncate_connection_ids_ = can; 947 } 948 949 // Returns the underlying sent packet manager. sent_packet_manager()950 const QuicSentPacketManager& sent_packet_manager() const { 951 return sent_packet_manager_; 952 } 953 954 // Returns the underlying sent packet manager. sent_packet_manager()955 QuicSentPacketManager& sent_packet_manager() { return sent_packet_manager_; } 956 received_packet_manager()957 UberReceivedPacketManager& received_packet_manager() { 958 return uber_received_packet_manager_; 959 } 960 961 bool CanWrite(HasRetransmittableData retransmittable); 962 963 // When the flusher is out of scope, only the outermost flusher will cause a 964 // flush of the connection and set the retransmission alarm if there is one 965 // pending. In addition, this flusher can be configured to ensure that an ACK 966 // frame is included in the first packet created, if there's new ack 967 // information to be sent. 968 class QUICHE_EXPORT ScopedPacketFlusher { 969 public: 970 explicit ScopedPacketFlusher(QuicConnection* connection); 971 ~ScopedPacketFlusher(); 972 973 private: 974 QuicConnection* connection_; 975 // If true, when this flusher goes out of scope, flush connection and set 976 // retransmission alarm if there is one pending. 977 bool flush_and_set_pending_retransmission_alarm_on_delete_; 978 // Latched connection's handshake_packet_sent_ on creation of this flusher. 979 const bool handshake_packet_sent_; 980 }; 981 982 class QUICHE_EXPORT ScopedEncryptionLevelContext { 983 public: 984 ScopedEncryptionLevelContext(QuicConnection* connection, 985 EncryptionLevel level); 986 ~ScopedEncryptionLevelContext(); 987 988 private: 989 QuicConnection* connection_; 990 // Latched current write encryption level on creation of this context. 991 EncryptionLevel latched_encryption_level_; 992 }; 993 writer()994 QuicPacketWriter* writer() { return writer_; } writer()995 const QuicPacketWriter* writer() const { return writer_; } 996 997 // Sends an MTU discovery packet of size |target_mtu|. If the packet is 998 // acknowledged by the peer, the maximum packet size will be increased to 999 // |target_mtu|. 1000 void SendMtuDiscoveryPacket(QuicByteCount target_mtu); 1001 1002 // Sends a connectivity probing packet to |peer_address| with 1003 // |probing_writer|. If |probing_writer| is nullptr, will use default 1004 // packet writer to write the packet. Returns true if subsequent packets can 1005 // be written to the probing writer. If connection is V99, a padded IETF QUIC 1006 // PATH_CHALLENGE packet is transmitted; if not V99, a Google QUIC padded PING 1007 // packet is transmitted. 1008 virtual bool SendConnectivityProbingPacket( 1009 QuicPacketWriter* probing_writer, const QuicSocketAddress& peer_address); 1010 1011 // Disable MTU discovery on this connection. 1012 void DisableMtuDiscovery(); 1013 1014 // Sends an MTU discovery packet and updates the MTU discovery alarm. 1015 void DiscoverMtu(); 1016 1017 // Sets the session notifier on the SentPacketManager. 1018 void SetSessionNotifier(SessionNotifierInterface* session_notifier); 1019 1020 // Set data producer in framer. 1021 void SetDataProducer(QuicStreamFrameDataProducer* data_producer); 1022 1023 // Set transmission type of next sending packets. 1024 void SetTransmissionType(TransmissionType type); 1025 1026 // Tries to send |message| and returns the message status. 1027 // If |flush| is false, this will return a MESSAGE_STATUS_BLOCKED 1028 // when the connection is deemed unwritable. 1029 virtual MessageStatus SendMessage(QuicMessageId message_id, 1030 absl::Span<quiche::QuicheMemSlice> message, 1031 bool flush); 1032 1033 // Returns the largest payload that will fit into a single MESSAGE frame. 1034 // Because overhead can vary during a connection, this method should be 1035 // checked for every message. 1036 QuicPacketLength GetCurrentLargestMessagePayload() const; 1037 // Returns the largest payload that will fit into a single MESSAGE frame at 1038 // any point during the connection. This assumes the version and 1039 // connection ID lengths do not change. 1040 QuicPacketLength GetGuaranteedLargestMessagePayload() const; 1041 1042 void SetUnackedMapInitialCapacity(); 1043 GetUnackedMapInitialCapacity()1044 virtual int GetUnackedMapInitialCapacity() const { 1045 return kDefaultUnackedPacketsInitialCapacity; 1046 } 1047 1048 // Returns the id of the cipher last used for decrypting packets. 1049 uint32_t cipher_id() const; 1050 termination_packets()1051 std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets() { 1052 return termination_packets_.get(); 1053 } 1054 1055 bool ack_frame_updated() const; 1056 helper()1057 QuicConnectionHelperInterface* helper() { return helper_; } helper()1058 const QuicConnectionHelperInterface* helper() const { return helper_; } alarm_factory()1059 QuicAlarmFactory* alarm_factory() { return alarm_factory_; } 1060 1061 absl::string_view GetCurrentPacket(); 1062 framer()1063 const QuicFramer& framer() const { return framer_; } 1064 packet_creator()1065 const QuicPacketCreator& packet_creator() const { return packet_creator_; } 1066 encryption_level()1067 EncryptionLevel encryption_level() const { return encryption_level_; } last_decrypted_level()1068 EncryptionLevel last_decrypted_level() const { 1069 return last_received_packet_info_.decrypted_level; 1070 } 1071 last_packet_source_address()1072 const QuicSocketAddress& last_packet_source_address() const { 1073 return last_received_packet_info_.source_address; 1074 } 1075 1076 // This setting may be changed during the crypto handshake in order to 1077 // enable/disable padding of different packets in the crypto handshake. 1078 // 1079 // This setting should never be set to false in public facing endpoints. It 1080 // can only be set to false if there is some other mechanism of preventing 1081 // amplification attacks, such as ICE (plus its a non-standard quic). set_fully_pad_crypto_handshake_packets(bool new_value)1082 void set_fully_pad_crypto_handshake_packets(bool new_value) { 1083 packet_creator_.set_fully_pad_crypto_handshake_packets(new_value); 1084 } 1085 fully_pad_during_crypto_handshake()1086 bool fully_pad_during_crypto_handshake() const { 1087 return packet_creator_.fully_pad_crypto_handshake_packets(); 1088 } 1089 1090 size_t min_received_before_ack_decimation() const; 1091 void set_min_received_before_ack_decimation(size_t new_value); 1092 1093 // If |defer| is true, configures the connection to defer sending packets in 1094 // response to an ACK to the SendAlarm. If |defer| is false, packets may be 1095 // sent immediately after receiving an ACK. set_defer_send_in_response_to_packets(bool defer)1096 void set_defer_send_in_response_to_packets(bool defer) { 1097 defer_send_in_response_to_packets_ = defer; 1098 } 1099 1100 // Sets the current per-packet options for the connection. The QuicConnection 1101 // does not take ownership of |options|; |options| must live for as long as 1102 // the QuicConnection is in use. set_per_packet_options(PerPacketOptions * options)1103 void set_per_packet_options(PerPacketOptions* options) { 1104 per_packet_options_ = options; 1105 } 1106 IsPathDegrading()1107 bool IsPathDegrading() const { return is_path_degrading_; } 1108 1109 // Attempts to process any queued undecryptable packets. 1110 void MaybeProcessUndecryptablePackets(); 1111 1112 // Queue a coalesced packet. 1113 void QueueCoalescedPacket(const QuicEncryptedPacket& packet); 1114 1115 // Process previously queued coalesced packets. Returns true if any coalesced 1116 // packets have been successfully processed. 1117 bool MaybeProcessCoalescedPackets(); 1118 1119 enum PacketContent : uint8_t { 1120 NO_FRAMES_RECEIVED, 1121 // TODO(fkastenholz): Change name when we get rid of padded ping/ 1122 // pre-version-99. 1123 // Also PATH CHALLENGE and PATH RESPONSE. 1124 FIRST_FRAME_IS_PING, 1125 SECOND_FRAME_IS_PADDING, 1126 NOT_PADDED_PING, // Set if the packet is not {PING, PADDING}. 1127 }; 1128 1129 // Whether the handshake completes from this connection's perspective. 1130 bool IsHandshakeComplete() const; 1131 1132 // Whether peer completes handshake. Only used with TLS handshake. 1133 bool IsHandshakeConfirmed() const; 1134 1135 // Returns the largest received packet number sent by peer. 1136 QuicPacketNumber GetLargestReceivedPacket() const; 1137 1138 // Sets the original destination connection ID on the connection. 1139 // This is called by QuicDispatcher when it has replaced the connection ID. 1140 void SetOriginalDestinationConnectionId( 1141 const QuicConnectionId& original_destination_connection_id); 1142 1143 // Returns the original destination connection ID used for this connection. 1144 QuicConnectionId GetOriginalDestinationConnectionId() const; 1145 1146 // Tells the visitor the serverside connection is no longer expecting packets 1147 // with the client-generated destination connection ID. 1148 void RetireOriginalDestinationConnectionId(); 1149 1150 // Called when ACK alarm goes off. Sends ACKs of those packet number spaces 1151 // which have expired ACK timeout. Only used when this connection supports 1152 // multiple packet number spaces. 1153 void SendAllPendingAcks(); 1154 1155 // Returns true if this connection supports multiple packet number spaces. 1156 bool SupportsMultiplePacketNumberSpaces() const; 1157 1158 // For logging purpose. 1159 const QuicAckFrame& ack_frame() const; 1160 1161 // Install encrypter and decrypter for ENCRYPTION_INITIAL using 1162 // |connection_id| as the first client-sent destination connection ID, 1163 // or the one sent after an IETF Retry. 1164 void InstallInitialCrypters(QuicConnectionId connection_id); 1165 1166 // Called when version is considered negotiated. 1167 void OnSuccessfulVersionNegotiation(); 1168 1169 // Called when self migration succeeds after probing. 1170 void OnSuccessfulMigration(bool is_port_change); 1171 1172 // Called for QUIC+TLS versions when we send transport parameters. 1173 void OnTransportParametersSent( 1174 const TransportParameters& transport_parameters) const; 1175 1176 // Called for QUIC+TLS versions when we receive transport parameters. 1177 void OnTransportParametersReceived( 1178 const TransportParameters& transport_parameters) const; 1179 1180 // Called for QUIC+TLS versions when we resume cached transport parameters for 1181 // 0-RTT. 1182 void OnTransportParametersResumed( 1183 const TransportParameters& transport_parameters) const; 1184 1185 // Called after an ClientHelloInner is encrypted and sent as a client. 1186 void OnEncryptedClientHelloSent(absl::string_view client_hello) const; 1187 1188 // Called after an ClientHelloInner is received and decrypted as a server. 1189 void OnEncryptedClientHelloReceived(absl::string_view client_hello) const; 1190 1191 // Returns true if ack_alarm_ is set. 1192 bool HasPendingAcks() const; 1193 1194 virtual void OnUserAgentIdKnown(const std::string& user_agent_id); 1195 1196 // If now is close to idle timeout, returns true and sends a connectivity 1197 // probing packet to test the connection for liveness. Otherwise, returns 1198 // false. 1199 bool MaybeTestLiveness(); 1200 1201 // QuicPathValidator::SendDelegate 1202 // Send PATH_CHALLENGE using the given path information. If |writer| is the 1203 // default writer, PATH_CHALLENGE can be bundled with other frames, and the 1204 // containing packet can be buffered if the writer is blocked. Otherwise, 1205 // PATH_CHALLENGE will be written in an individual packet and it will be 1206 // dropped if write fails. |data_buffer| will be populated with the payload 1207 // for future validation. 1208 // Return false if the connection is closed thus the caller will not continue 1209 // the validation, otherwise return true. 1210 bool SendPathChallenge(const QuicPathFrameBuffer& data_buffer, 1211 const QuicSocketAddress& self_address, 1212 const QuicSocketAddress& peer_address, 1213 const QuicSocketAddress& effective_peer_address, 1214 QuicPacketWriter* writer) override; 1215 // If |writer| is the default writer and |peer_address| is the same as 1216 // peer_address(), return the PTO of this connection. Otherwise, return 3 * 1217 // kInitialRtt. 1218 QuicTime GetRetryTimeout(const QuicSocketAddress& peer_address_to_use, 1219 QuicPacketWriter* writer_to_use) const override; 1220 1221 // Start vaildating the path defined by |context| asynchronously and call the 1222 // |result_delegate| after validation finishes. If the connection is 1223 // validating another path, cancel and fail that validation before starting 1224 // this one. 1225 void ValidatePath( 1226 std::unique_ptr<QuicPathValidationContext> context, 1227 std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate, 1228 PathValidationReason reason); 1229 can_receive_ack_frequency_frame()1230 bool can_receive_ack_frequency_frame() const { 1231 return can_receive_ack_frequency_frame_; 1232 } 1233 set_can_receive_ack_frequency_frame()1234 void set_can_receive_ack_frequency_frame() { 1235 can_receive_ack_frequency_frame_ = true; 1236 } 1237 is_processing_packet()1238 bool is_processing_packet() const { return framer_.is_processing_packet(); } 1239 1240 bool HasPendingPathValidation() const; 1241 1242 QuicPathValidationContext* GetPathValidationContext() const; 1243 1244 void CancelPathValidation(); 1245 1246 // Returns true if the migration succeeds, otherwise returns false (e.g., no 1247 // available CIDs, connection disconnected, etc). 1248 bool MigratePath(const QuicSocketAddress& self_address, 1249 const QuicSocketAddress& peer_address, 1250 QuicPacketWriter* writer, bool owns_writer); 1251 1252 // Called to clear the alternative_path_ when path validation failed on the 1253 // client side. 1254 void OnPathValidationFailureAtClient( 1255 bool is_multi_port, const QuicPathValidationContext& context); 1256 1257 void SetSourceAddressTokenToSend(absl::string_view token); 1258 SendPing()1259 void SendPing() { 1260 SendPingAtLevel(framer().GetEncryptionLevelToSendApplicationData()); 1261 } 1262 1263 // Returns one server connection ID that associates the current session in the 1264 // session map. 1265 virtual QuicConnectionId GetOneActiveServerConnectionId() const; 1266 1267 // Returns all server connection IDs that have not been removed from the 1268 // session map. 1269 virtual std::vector<QuicConnectionId> GetActiveServerConnectionIds() const; 1270 1271 // Instantiates connection ID manager. 1272 void CreateConnectionIdManager(); 1273 1274 // Log QUIC_BUG if there is pending frames for the stream with |id|. 1275 void QuicBugIfHasPendingFrames(QuicStreamId id) const; 1276 context()1277 QuicConnectionContext* context() { return &context_; } context()1278 const QuicConnectionContext* context() const { return &context_; } 1279 set_tracer(std::unique_ptr<QuicConnectionTracer> tracer)1280 void set_tracer(std::unique_ptr<QuicConnectionTracer> tracer) { 1281 context_.tracer.swap(tracer); 1282 } 1283 set_bug_listener(std::unique_ptr<QuicBugListener> bug_listener)1284 void set_bug_listener(std::unique_ptr<QuicBugListener> bug_listener) { 1285 context_.bug_listener.swap(bug_listener); 1286 } 1287 in_probe_time_out()1288 bool in_probe_time_out() const { return in_probe_time_out_; } 1289 blackhole_detector()1290 QuicNetworkBlackholeDetector& blackhole_detector() { 1291 return blackhole_detector_; 1292 } 1293 1294 // Ensures the network blackhole delay is longer than path degrading delay. 1295 static QuicTime::Delta CalculateNetworkBlackholeDelay( 1296 QuicTime::Delta blackhole_delay, QuicTime::Delta path_degrading_delay, 1297 QuicTime::Delta pto_delay); 1298 DisableLivenessTesting()1299 void DisableLivenessTesting() { liveness_testing_disabled_ = true; } 1300 1301 void AddKnownServerAddress(const QuicSocketAddress& address); 1302 1303 std::optional<QuicNewConnectionIdFrame> 1304 MaybeIssueNewConnectionIdForPreferredAddress(); 1305 1306 // Kicks off validation of received server preferred address. 1307 void ValidateServerPreferredAddress(); 1308 1309 // Returns true if the client is validating the server preferred address which 1310 // hasn't been used before. 1311 bool IsValidatingServerPreferredAddress() const; 1312 1313 // Called by client to start sending packets to the preferred address. 1314 // If |owns_writer| is true, the ownership of the writer in the |context| is 1315 // also passed in. 1316 void OnServerPreferredAddressValidated(QuicPathValidationContext& context, 1317 bool owns_writer); 1318 set_sent_server_preferred_address(const QuicSocketAddress & sent_server_preferred_address)1319 void set_sent_server_preferred_address( 1320 const QuicSocketAddress& sent_server_preferred_address) { 1321 sent_server_preferred_address_ = sent_server_preferred_address; 1322 } 1323 sent_server_preferred_address()1324 const QuicSocketAddress& sent_server_preferred_address() const { 1325 return sent_server_preferred_address_; 1326 } 1327 1328 // True if received long packet header contains source connection ID. PeerIssuesConnectionIds()1329 bool PeerIssuesConnectionIds() const { 1330 return peer_issued_cid_manager_ != nullptr; 1331 } 1332 ignore_gquic_probing()1333 bool ignore_gquic_probing() const { return ignore_gquic_probing_; } 1334 1335 // Sets the ECN marking for all outgoing packets, assuming that the congestion 1336 // control supports that codepoint. QuicConnection will revert to sending 1337 // ECN_NOT_ECT if there is evidence the path is dropping ECN-marked packets, 1338 // or if the peer provides invalid ECN feedback. Returns false if the current 1339 // configuration prevents setting the desired codepoint. 1340 bool set_ecn_codepoint(QuicEcnCodepoint ecn_codepoint); 1341 ecn_codepoint()1342 QuicEcnCodepoint ecn_codepoint() const { 1343 return packet_writer_params_.ecn_codepoint; 1344 } 1345 1346 protected: 1347 // Calls cancel() on all the alarms owned by this connection. 1348 void CancelAllAlarms(); 1349 1350 // Send a packet to the peer, and takes ownership of the packet if the packet 1351 // cannot be written immediately. 1352 virtual void SendOrQueuePacket(SerializedPacket packet); 1353 1354 // Called after a packet is received from a new effective peer address and is 1355 // decrypted. Starts validation of effective peer's address change. Calls 1356 // OnConnectionMigration as soon as the address changed. 1357 void StartEffectivePeerMigration(AddressChangeType type); 1358 1359 // Called when a effective peer address migration is validated. 1360 virtual void OnEffectivePeerMigrationValidated(bool is_migration_linkable); 1361 1362 // Get the effective peer address from the packet being processed. For proxied 1363 // connections, effective peer address is the address of the endpoint behind 1364 // the proxy. For non-proxied connections, effective peer address is the same 1365 // as peer address. 1366 // 1367 // Notes for implementations in subclasses: 1368 // - If the connection is not proxied, the overridden method should use the 1369 // base implementation: 1370 // 1371 // return QuicConnection::GetEffectivePeerAddressFromCurrentPacket(); 1372 // 1373 // - If the connection is proxied, the overridden method may return either of 1374 // the following: 1375 // a) The address of the endpoint behind the proxy. The address is used to 1376 // drive effective peer migration. 1377 // b) An uninitialized address, meaning the effective peer address does not 1378 // change. 1379 virtual QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const; 1380 1381 // Selects and updates the version of the protocol being used by selecting a 1382 // version from |available_versions| which is also supported. Returns true if 1383 // such a version exists, false otherwise. 1384 bool SelectMutualVersion(const ParsedQuicVersionVector& available_versions); 1385 1386 // Returns the current per-packet options for the connection. per_packet_options()1387 PerPacketOptions* per_packet_options() { return per_packet_options_; } 1388 active_effective_peer_migration_type()1389 AddressChangeType active_effective_peer_migration_type() const { 1390 return active_effective_peer_migration_type_; 1391 } 1392 1393 // Sends a connection close packet to the peer and includes an ACK if the ACK 1394 // is not empty, the |error| is not PACKET_WRITE_ERROR, and it fits. 1395 // |ietf_error| may optionally be be used to directly specify the wire 1396 // error code. Otherwise if |ietf_error| is NO_IETF_QUIC_ERROR, the 1397 // QuicErrorCodeToTransportErrorCode mapping of |error| will be used. 1398 // Caller may choose to call SendConnectionClosePacket() directly instead of 1399 // CloseConnection() to notify peer that the connection is going to be closed, 1400 // for example, when the server is tearing down. Given 1401 // SendConnectionClosePacket() does not close connection, multiple connection 1402 // close packets could be sent to the peer. 1403 virtual void SendConnectionClosePacket(QuicErrorCode error, 1404 QuicIetfTransportErrorCodes ietf_error, 1405 const std::string& details); 1406 1407 // Returns true if the packet should be discarded and not sent. 1408 virtual bool ShouldDiscardPacket(EncryptionLevel encryption_level); 1409 1410 // Notify various components(Session etc.) that this connection has been 1411 // migrated. 1412 virtual void OnConnectionMigration(); 1413 1414 // Return whether the packet being processed is a connectivity probing. 1415 // A packet is a connectivity probing if it is a padded ping packet with self 1416 // and/or peer address changes. 1417 bool IsCurrentPacketConnectivityProbing() const; 1418 1419 // Return true iff the writer is blocked, if blocked, call 1420 // visitor_->OnWriteBlocked() to add the connection into the write blocked 1421 // list. 1422 bool HandleWriteBlocked(); 1423 1424 // Whether connection enforces anti-amplification limit. 1425 bool EnforceAntiAmplificationLimit() const; 1426 AddBytesReceivedBeforeAddressValidation(size_t length)1427 void AddBytesReceivedBeforeAddressValidation(size_t length) { 1428 default_path_.bytes_received_before_address_validation += length; 1429 } 1430 defer_send_in_response_to_packets()1431 bool defer_send_in_response_to_packets() const { 1432 return defer_send_in_response_to_packets_; 1433 } 1434 connection_id_generator()1435 ConnectionIdGeneratorInterface& connection_id_generator() const { 1436 return connection_id_generator_; 1437 } 1438 1439 private: 1440 friend class test::QuicConnectionPeer; 1441 1442 enum RetransmittableOnWireBehavior { 1443 DEFAULT, // Send packet containing a PING frame. 1444 SEND_FIRST_FORWARD_SECURE_PACKET, // Send 1st 1-RTT packet. 1445 SEND_RANDOM_BYTES // Send random bytes which is an unprocessable packet. 1446 }; 1447 1448 enum class MultiPortStatusOnMigration { 1449 kNotValidated, 1450 kPendingRefreshValidation, 1451 kWaitingForRefreshValidation, 1452 kMaxValue, 1453 }; 1454 1455 struct QUICHE_EXPORT PendingPathChallenge { 1456 QuicPathFrameBuffer received_path_challenge; 1457 QuicSocketAddress peer_address; 1458 }; 1459 1460 struct QUICHE_EXPORT PathState { 1461 PathState() = default; 1462 PathStatePathState1463 PathState(const QuicSocketAddress& alternative_self_address, 1464 const QuicSocketAddress& alternative_peer_address, 1465 const QuicConnectionId& client_connection_id, 1466 const QuicConnectionId& server_connection_id, 1467 std::optional<StatelessResetToken> stateless_reset_token) 1468 : self_address(alternative_self_address), 1469 peer_address(alternative_peer_address), 1470 client_connection_id(client_connection_id), 1471 server_connection_id(server_connection_id), 1472 stateless_reset_token(stateless_reset_token) {} 1473 1474 PathState(PathState&& other); 1475 1476 PathState& operator=(PathState&& other); 1477 1478 // Reset all the members. 1479 void Clear(); 1480 1481 QuicSocketAddress self_address; 1482 // The actual peer address behind the proxy if there is any. 1483 QuicSocketAddress peer_address; 1484 QuicConnectionId client_connection_id; 1485 QuicConnectionId server_connection_id; 1486 std::optional<StatelessResetToken> stateless_reset_token; 1487 // True if the peer address has been validated. Address is considered 1488 // validated when 1) an address token of the peer address is received and 1489 // validated, or 2) a HANDSHAKE packet has been successfully processed on 1490 // this path, or 3) a path validation on this path has succeeded. 1491 bool validated = false; 1492 // Used by the sever to apply anti-amplification limit after this path 1493 // becomes the default path if |peer_address| hasn't been validated. 1494 QuicByteCount bytes_received_before_address_validation = 0; 1495 QuicByteCount bytes_sent_before_address_validation = 0; 1496 // Points to the send algorithm on the old default path while connection is 1497 // validating migrated peer address. Nullptr otherwise. 1498 std::unique_ptr<SendAlgorithmInterface> send_algorithm; 1499 std::optional<RttStats> rtt_stats; 1500 // If true, an ECN packet was acked on this path, so the path probably isn't 1501 // dropping ECN-marked packets. 1502 bool ecn_marked_packet_acked = false; 1503 // How many total PTOs have fired since the connection started sending ECN 1504 // on this path, but before an ECN-marked packet has been acked. 1505 uint8_t ecn_pto_count = 0; 1506 }; 1507 1508 using QueuedPacketList = std::list<SerializedPacket>; 1509 1510 // BufferedPacket stores necessary information (encrypted buffer and self/peer 1511 // addresses) of those packets which are serialized but failed to send because 1512 // socket is blocked. From unacked packet map and send algorithm's 1513 // perspective, buffered packets are treated as sent. 1514 struct QUICHE_EXPORT BufferedPacket { 1515 BufferedPacket(const SerializedPacket& packet, 1516 const QuicSocketAddress& self_address, 1517 const QuicSocketAddress& peer_address, 1518 QuicEcnCodepoint ecn_codepoint); 1519 BufferedPacket(const char* encrypted_buffer, 1520 QuicPacketLength encrypted_length, 1521 const QuicSocketAddress& self_address, 1522 const QuicSocketAddress& peer_address, 1523 QuicEcnCodepoint ecn_codepoint); 1524 // Please note, this buffered packet contains random bytes (and is not 1525 // *actually* a QUIC packet). 1526 BufferedPacket(QuicRandom& random, QuicPacketLength encrypted_length, 1527 const QuicSocketAddress& self_address, 1528 const QuicSocketAddress& peer_address); 1529 BufferedPacket(const BufferedPacket& other) = delete; 1530 BufferedPacket(const BufferedPacket&& other) = delete; 1531 1532 ~BufferedPacket() = default; 1533 1534 std::unique_ptr<char[]> data; 1535 const QuicPacketLength length; 1536 // Self and peer addresses when the packet is serialized. 1537 const QuicSocketAddress self_address; 1538 const QuicSocketAddress peer_address; 1539 QuicEcnCodepoint ecn_codepoint = ECN_NOT_ECT; 1540 }; 1541 1542 // ReceivedPacketInfo comprises the received packet information. 1543 // TODO(fayang): move more fields to ReceivedPacketInfo. 1544 struct QUICHE_EXPORT ReceivedPacketInfo { 1545 explicit ReceivedPacketInfo(QuicTime receipt_time); 1546 ReceivedPacketInfo(const QuicSocketAddress& destination_address, 1547 const QuicSocketAddress& source_address, 1548 QuicTime receipt_time, QuicByteCount length, 1549 QuicEcnCodepoint ecn_codepoint); 1550 1551 QuicSocketAddress destination_address; 1552 QuicSocketAddress source_address; 1553 QuicTime receipt_time = QuicTime::Zero(); 1554 bool received_bytes_counted = false; 1555 QuicByteCount length = 0; 1556 QuicConnectionId destination_connection_id; 1557 // Fields below are only populated if packet gets decrypted successfully. 1558 // TODO(fayang): consider using std::optional for following fields. 1559 bool decrypted = false; 1560 EncryptionLevel decrypted_level = ENCRYPTION_INITIAL; 1561 QuicPacketHeader header; 1562 absl::InlinedVector<QuicFrameType, 1> frames; 1563 QuicEcnCodepoint ecn_codepoint = ECN_NOT_ECT; 1564 // Stores the actual address this packet is received on when it is received 1565 // on the preferred address. In this case, |destination_address| will 1566 // be overridden to the current default self address. 1567 QuicSocketAddress actual_destination_address; 1568 }; 1569 1570 QUICHE_EXPORT friend std::ostream& operator<<( 1571 std::ostream& os, const QuicConnection::ReceivedPacketInfo& info); 1572 1573 // UndecrytablePacket comprises a undecryptable packet and related 1574 // information. 1575 struct QUICHE_EXPORT UndecryptablePacket { UndecryptablePacketUndecryptablePacket1576 UndecryptablePacket(const QuicEncryptedPacket& packet, 1577 EncryptionLevel encryption_level, 1578 const ReceivedPacketInfo& packet_info) 1579 : packet(packet.Clone()), 1580 encryption_level(encryption_level), 1581 packet_info(packet_info) {} 1582 1583 std::unique_ptr<QuicEncryptedPacket> packet; 1584 EncryptionLevel encryption_level; 1585 ReceivedPacketInfo packet_info; 1586 }; 1587 1588 // Handles the reverse path validation result depending on connection state: 1589 // whether the connection is validating a migrated peer address or is 1590 // validating an alternative path. 1591 class ReversePathValidationResultDelegate 1592 : public QuicPathValidator::ResultDelegate { 1593 public: 1594 ReversePathValidationResultDelegate( 1595 QuicConnection* connection, 1596 const QuicSocketAddress& direct_peer_address); 1597 1598 void OnPathValidationSuccess( 1599 std::unique_ptr<QuicPathValidationContext> context, 1600 QuicTime start_time) override; 1601 1602 void OnPathValidationFailure( 1603 std::unique_ptr<QuicPathValidationContext> context) override; 1604 1605 private: 1606 QuicConnection* connection_; 1607 QuicSocketAddress original_direct_peer_address_; 1608 // TODO(b/205023946) Debug-only fields, to be deprecated after the bug is 1609 // fixed. 1610 QuicSocketAddress peer_address_default_path_; 1611 QuicSocketAddress peer_address_alternative_path_; 1612 AddressChangeType active_effective_peer_migration_type_; 1613 }; 1614 1615 class ContextObserver final : public MultiPortPathContextObserver { 1616 public: ContextObserver(QuicConnection * connection)1617 explicit ContextObserver(QuicConnection* connection) 1618 : connection_(connection) {} 1619 1620 void OnMultiPortPathContextAvailable( 1621 std::unique_ptr<QuicPathValidationContext> path_context) override; 1622 1623 private: 1624 QuicConnection* connection_; 1625 }; 1626 1627 // Keeps an ongoing alternative path. The connection will not migrate upon 1628 // validation success. 1629 class MultiPortPathValidationResultDelegate 1630 : public QuicPathValidator::ResultDelegate { 1631 public: 1632 MultiPortPathValidationResultDelegate(QuicConnection* connection); 1633 1634 void OnPathValidationSuccess( 1635 std::unique_ptr<QuicPathValidationContext> context, 1636 QuicTime start_time) override; 1637 1638 void OnPathValidationFailure( 1639 std::unique_ptr<QuicPathValidationContext> context) override; 1640 1641 private: 1642 QuicConnection* connection_; 1643 }; 1644 1645 // A class which sets and clears in_probe_time_out_ when entering 1646 // and exiting OnRetransmissionTimeout, respectively. 1647 class QUICHE_EXPORT ScopedRetransmissionTimeoutIndicator { 1648 public: 1649 // |connection| must outlive this indicator. 1650 explicit ScopedRetransmissionTimeoutIndicator(QuicConnection* connection); 1651 1652 ~ScopedRetransmissionTimeoutIndicator(); 1653 1654 private: 1655 QuicConnection* connection_; // Not owned. 1656 }; 1657 1658 // If peer uses non-empty connection ID, discards any buffered packets on path 1659 // change in IETF QUIC. 1660 void MaybeClearQueuedPacketsOnPathChange(); 1661 1662 // Notifies the visitor of the close and marks the connection as disconnected. 1663 // Does not send a connection close frame to the peer. It should only be 1664 // called by CloseConnection or OnConnectionCloseFrame, and 1665 // OnAuthenticatedIetfStatelessResetPacket. |ietf_error| may optionally be be 1666 // used to directly specify the wire error code. Otherwise if |ietf_error| is 1667 // NO_IETF_QUIC_ERROR, the QuicErrorCodeToTransportErrorCode mapping of 1668 // |error| will be used. 1669 void TearDownLocalConnectionState(QuicErrorCode error, 1670 QuicIetfTransportErrorCodes ietf_error, 1671 const std::string& details, 1672 ConnectionCloseSource source); 1673 void TearDownLocalConnectionState(const QuicConnectionCloseFrame& frame, 1674 ConnectionCloseSource source); 1675 1676 // Replace server connection ID on the client side from retry packet or 1677 // initial packets with a different source connection ID. 1678 void ReplaceInitialServerConnectionId( 1679 const QuicConnectionId& new_server_connection_id); 1680 1681 // Given the server_connection_id find if there is already a corresponding 1682 // client connection ID used on default/alternative path. If not, find if 1683 // there is an unused connection ID. 1684 void FindMatchingOrNewClientConnectionIdOrToken( 1685 const PathState& default_path, const PathState& alternative_path, 1686 const QuicConnectionId& server_connection_id, 1687 QuicConnectionId* client_connection_id, 1688 std::optional<StatelessResetToken>* stateless_reset_token); 1689 1690 // Returns true and sets connection IDs if (self_address, peer_address) 1691 // corresponds to either the default path or alternative path. Returns false 1692 // otherwise. 1693 bool FindOnPathConnectionIds(const QuicSocketAddress& self_address, 1694 const QuicSocketAddress& peer_address, 1695 QuicConnectionId* client_connection_id, 1696 QuicConnectionId* server_connection_id) const; 1697 1698 // Set default_path_ to the new_path_state and update the connection IDs in 1699 // packet creator accordingly. 1700 void SetDefaultPathState(PathState new_path_state); 1701 1702 // Returns true if header contains valid server connection ID. 1703 bool ValidateServerConnectionId(const QuicPacketHeader& header) const; 1704 1705 // Update the connection IDs when client migrates its own address 1706 // (with/without validation) or switches to server preferred address. 1707 // Returns false if required connection ID is not available. 1708 bool UpdateConnectionIdsOnMigration(const QuicSocketAddress& self_address, 1709 const QuicSocketAddress& peer_address); 1710 1711 // Retire active peer issued connection IDs after they are no longer used on 1712 // any path. 1713 void RetirePeerIssuedConnectionIdsNoLongerOnPath(); 1714 1715 // Writes the given packet to socket, encrypted with packet's 1716 // encryption_level. Returns true on successful write, and false if the writer 1717 // was blocked and the write needs to be tried again. Notifies the 1718 // SentPacketManager when the write is successful and sets 1719 // retransmittable frames to nullptr. 1720 // Saves the connection close packet for later transmission, even if the 1721 // writer is write blocked. 1722 bool WritePacket(SerializedPacket* packet); 1723 1724 // Enforce AEAD Confidentiality limits by iniating key update or closing 1725 // connection if too many packets have been encrypted with the current key. 1726 // Returns true if the connection was closed. Should not be called for 1727 // termination packets. 1728 bool MaybeHandleAeadConfidentialityLimits(const SerializedPacket& packet); 1729 1730 // Flush packets buffered in the writer, if any. 1731 void FlushPackets(); 1732 1733 // Clears any accumulated frames from the last received packet. 1734 void ClearLastFrames(); 1735 1736 // Deletes and clears any queued packets. 1737 void ClearQueuedPackets(); 1738 1739 // Closes the connection if the sent packet manager is tracking too many 1740 // outstanding packets. 1741 void CloseIfTooManyOutstandingSentPackets(); 1742 1743 // Writes as many queued packets as possible. The connection must not be 1744 // blocked when this is called. 1745 void WriteQueuedPackets(); 1746 1747 // Queues |packet| in the hopes that it can be decrypted in the 1748 // future, when a new key is installed. 1749 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet, 1750 EncryptionLevel decryption_level); 1751 1752 // Sends any packets which are a response to the last packet, including both 1753 // acks and pending writes if an ack opened the congestion window. 1754 void MaybeSendInResponseToPacket(); 1755 1756 // Gets the least unacked packet number, which is the next packet number to be 1757 // sent if there are no outstanding packets. 1758 QuicPacketNumber GetLeastUnacked() const; 1759 1760 // Sets the ping alarm to the appropriate value, if any. 1761 void SetPingAlarm(); 1762 1763 // Sets the retransmission alarm based on SentPacketManager. 1764 void SetRetransmissionAlarm(); 1765 1766 // Sets the MTU discovery alarm if necessary. 1767 // |sent_packet_number| is the recently sent packet number. 1768 void MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number); 1769 1770 HasRetransmittableData IsRetransmittable(const SerializedPacket& packet); 1771 bool IsTerminationPacket(const SerializedPacket& packet, 1772 QuicErrorCode* error_code); 1773 1774 // Set the size of the packet we are targeting while doing path MTU discovery. 1775 void SetMtuDiscoveryTarget(QuicByteCount target); 1776 1777 // Returns |suggested_max_packet_size| clamped to any limits set by the 1778 // underlying writer, connection, or protocol. 1779 QuicByteCount GetLimitedMaxPacketSize( 1780 QuicByteCount suggested_max_packet_size); 1781 1782 // Do any work which logically would be done in OnPacket but can not be 1783 // safely done until the packet is validated. Returns true if packet can be 1784 // handled, false otherwise. 1785 bool ProcessValidatedPacket(const QuicPacketHeader& header); 1786 1787 // Returns true if received |packet_number| can be processed. Please note, 1788 // this is called after packet got decrypted successfully. 1789 bool ValidateReceivedPacketNumber(QuicPacketNumber packet_number); 1790 1791 // Consider receiving crypto frame on non crypto stream as memory corruption. 1792 bool MaybeConsiderAsMemoryCorruption(const QuicStreamFrame& frame); 1793 1794 // Check if the connection has no outstanding data to send and notify 1795 // congestion controller if it is the case. 1796 void CheckIfApplicationLimited(); 1797 1798 // Sets |current_packet_content_| to |type| if applicable. And 1799 // starts effective peer migration if current packet is confirmed not a 1800 // connectivity probe and |current_effective_peer_migration_type_| indicates 1801 // effective peer address change. 1802 // Returns true if connection is still alive. 1803 ABSL_MUST_USE_RESULT bool UpdatePacketContent(QuicFrameType type); 1804 1805 // Called when last received ack frame has been processed. 1806 // |acked_new_packet| is true if a previously-unacked packet was acked. 1807 void PostProcessAfterAckFrame(bool acked_new_packet); 1808 1809 // Updates the release time into the future. 1810 void UpdateReleaseTimeIntoFuture(); 1811 1812 // Sends generic path probe packet to the peer. If we are not IETF QUIC, will 1813 // always send a padded ping, regardless of whether this is a request or not. 1814 bool SendGenericPathProbePacket(QuicPacketWriter* probing_writer, 1815 const QuicSocketAddress& peer_address); 1816 1817 // Called when an ACK is about to send. Resets ACK related internal states, 1818 // e.g., cancels ack_alarm_, resets 1819 // num_retransmittable_packets_received_since_last_ack_sent_ etc. 1820 void ResetAckStates(); 1821 1822 // Returns true if the ACK frame should be bundled with ACK-eliciting frame. 1823 bool ShouldBundleRetransmittableFrameWithAck() const; 1824 1825 // Enables multiple packet number spaces support based on handshake protocol 1826 // and flags. 1827 void MaybeEnableMultiplePacketNumberSpacesSupport(); 1828 1829 // Called to update ACK timeout when an retransmittable frame has been parsed. 1830 void MaybeUpdateAckTimeout(); 1831 1832 // Tries to fill coalesced packet with data of higher packet space. 1833 void MaybeCoalescePacketOfHigherSpace(); 1834 1835 // Serialize and send coalesced_packet. Returns false if serialization fails 1836 // or the write causes errors, otherwise, returns true. 1837 bool FlushCoalescedPacket(); 1838 1839 // Returns the encryption level the connection close packet should be sent at, 1840 // which is the highest encryption level that peer can guarantee to process. 1841 EncryptionLevel GetConnectionCloseEncryptionLevel() const; 1842 1843 // Called after an ACK frame is successfully processed to update largest 1844 // received packet number which contains an ACK frame. 1845 void SetLargestReceivedPacketWithAck(QuicPacketNumber new_value); 1846 1847 // Called when new packets have been acknowledged or old keys have been 1848 // discarded. 1849 void OnForwardProgressMade(); 1850 1851 // Returns largest received packet number which contains an ACK frame. 1852 QuicPacketNumber GetLargestReceivedPacketWithAck() const; 1853 1854 // Returns the largest packet number that has been sent. 1855 QuicPacketNumber GetLargestSentPacket() const; 1856 1857 // Returns the largest sent packet number that has been ACKed by peer. 1858 QuicPacketNumber GetLargestAckedPacket() const; 1859 1860 // Whether connection is limited by amplification factor. 1861 // If enforce_strict_amplification_factor_ is true, this will return true if 1862 // connection is amplification limited after sending |bytes|. 1863 bool LimitedByAmplificationFactor(QuicByteCount bytes) const; 1864 1865 // Called before sending a packet to get packet send time and to set the 1866 // release time delay in |per_packet_options_|. Return the time when the 1867 // packet is scheduled to be released(a.k.a send time), which is NOW + delay. 1868 // Returns Now() and does not update release time delay if 1869 // |supports_release_time_| is false. 1870 QuicTime CalculatePacketSentTime(); 1871 1872 // If we have a previously validate MTU value, e.g. due to a write error, 1873 // revert to it and disable MTU discovery. 1874 // Return true iff we reverted to a previously validate MTU. 1875 bool MaybeRevertToPreviousMtu(); 1876 1877 QuicTime GetPathMtuReductionDeadline() const; 1878 1879 // Returns path degrading deadline. QuicTime::Zero() means no path degrading 1880 // detection is needed. 1881 QuicTime GetPathDegradingDeadline() const; 1882 1883 // Returns true if path degrading should be detected. 1884 bool ShouldDetectPathDegrading() const; 1885 1886 // Returns network blackhole deadline. QuicTime::Zero() means no blackhole 1887 // detection is needed. 1888 QuicTime GetNetworkBlackholeDeadline() const; 1889 1890 // Returns true if network blackhole should be detected. 1891 bool ShouldDetectBlackhole() const; 1892 1893 // Returns retransmission deadline. 1894 QuicTime GetRetransmissionDeadline() const; 1895 1896 // Validate connection IDs used during the handshake. Closes the connection 1897 // on validation failure. 1898 bool ValidateConfigConnectionIds(const QuicConfig& config); 1899 1900 // Called when ACK alarm goes off. Try to bundle crypto data with ACKs. 1901 void MaybeBundleCryptoDataWithAcks(); 1902 1903 // Returns true if an undecryptable packet of |decryption_level| should be 1904 // buffered (such that connection can try to decrypt it later). 1905 bool ShouldEnqueueUnDecryptablePacket(EncryptionLevel decryption_level, 1906 bool has_decryption_key) const; 1907 1908 // Returns string which contains undecryptable packets information. 1909 std::string UndecryptablePacketsInfo() const; 1910 1911 // For Google Quic, if the current packet is connectivity probing packet, call 1912 // session OnPacketReceived() which eventually sends connectivity probing 1913 // response on server side. And no-op on client side. And for both Google Quic 1914 // and IETF Quic, start migration if the current packet is a non-probing 1915 // packet. 1916 // TODO(danzh) remove it when deprecating ignore_gquic_probing_. 1917 void MaybeRespondToConnectivityProbingOrMigration(); 1918 1919 // Called in IETF QUIC. Start peer migration if a non-probing frame is 1920 // received and the current packet number is largest received so far. 1921 void MaybeStartIetfPeerMigration(); 1922 1923 // Send PATH_RESPONSE to the given peer address. 1924 bool SendPathResponse(const QuicPathFrameBuffer& data_buffer, 1925 const QuicSocketAddress& peer_address_to_send, 1926 const QuicSocketAddress& effective_peer_address); 1927 1928 // Update both connection's and packet creator's peer address. 1929 void UpdatePeerAddress(QuicSocketAddress peer_address); 1930 1931 // Send PING at encryption level. 1932 void SendPingAtLevel(EncryptionLevel level); 1933 1934 // Write the given packet with |self_address| and |peer_address| using 1935 // |writer|. 1936 bool WritePacketUsingWriter(std::unique_ptr<SerializedPacket> packet, 1937 QuicPacketWriter* writer, 1938 const QuicSocketAddress& self_address, 1939 const QuicSocketAddress& peer_address, 1940 bool measure_rtt); 1941 1942 // Increment bytes sent/received on the alternative path if the current packet 1943 // is sent/received on that path. 1944 void MaybeUpdateBytesSentToAlternativeAddress( 1945 const QuicSocketAddress& peer_address, QuicByteCount sent_packet_size); 1946 void MaybeUpdateBytesReceivedFromAlternativeAddress( 1947 QuicByteCount received_packet_size); 1948 1949 // TODO(danzh) pass in PathState of the incoming packet or the packet sent 1950 // once PathState is used in packet creator. Return true if the given self 1951 // address and peer address is the same as the self address and peer address 1952 // of the default path. 1953 bool IsDefaultPath(const QuicSocketAddress& self_address, 1954 const QuicSocketAddress& peer_address) const; 1955 1956 // Return true if the |self_address| and |peer_address| is the same as the 1957 // self address and peer address of the alternative path. 1958 bool IsAlternativePath(const QuicSocketAddress& self_address, 1959 const QuicSocketAddress& peer_address) const; 1960 1961 // Restore connection default path and congestion control state to the last 1962 // validated path and its state. Called after fail to validate peer address 1963 // upon detecting a peer migration. 1964 void RestoreToLastValidatedPath( 1965 QuicSocketAddress original_direct_peer_address); 1966 1967 // Return true if the current incoming packet is from a peer address that is 1968 // validated. 1969 bool IsReceivedPeerAddressValidated() const; 1970 1971 // Check the state of the multi-port alternative path and initiate path 1972 // migration. 1973 void MaybeMigrateToMultiPortPath(); 1974 1975 std::unique_ptr<QuicSelfIssuedConnectionIdManager> 1976 MakeSelfIssuedConnectionIdManager(); 1977 1978 // Called on peer IP change or restoring to previous address to reset 1979 // congestion window, RTT stats, retransmission timer, etc. Only used in IETF 1980 // QUIC. 1981 std::unique_ptr<SendAlgorithmInterface> OnPeerIpAddressChanged(); 1982 1983 // Process NewConnectionIdFrame either sent from peer or synsthesized from 1984 // preferred_address transport parameter. 1985 NewConnectionIdResult OnNewConnectionIdFrameInner( 1986 const QuicNewConnectionIdFrame& frame); 1987 1988 // Called to patch missing client connection ID on default/alternative paths 1989 // when a new client connection ID is received. 1990 void OnClientConnectionIdAvailable(); 1991 1992 // Determines encryption level to send ping in `packet_number_space`. 1993 EncryptionLevel GetEncryptionLevelToSendPingForSpace( 1994 PacketNumberSpace space) const; 1995 1996 // Returns true if |address| is known server address. 1997 bool IsKnownServerAddress(const QuicSocketAddress& address) const; 1998 1999 // Retrieves the ECN codepoint to be sent on the next packet. 2000 QuicEcnCodepoint GetEcnCodepointToSend( 2001 const QuicSocketAddress& destination_address) const; 2002 2003 // Writes the packet to |writer| with the ECN mark specified in 2004 // |ecn_codepoint|. Will also set last_ecn_sent_ appropriately. 2005 WriteResult SendPacketToWriter(const char* buffer, size_t buf_len, 2006 const QuicIpAddress& self_address, 2007 const QuicSocketAddress& destination_address, 2008 QuicPacketWriter* writer, 2009 const QuicEcnCodepoint ecn_codepoint); 2010 2011 QuicConnectionContext context_; 2012 2013 QuicFramer framer_; 2014 2015 // TODO(danzh) remove below fields once quic_ignore_gquic_probing_ gets 2016 // deprecated. Contents received in the current packet, especially used to 2017 // identify whether the current packet is a padded PING packet. 2018 PacketContent current_packet_content_; 2019 // Set to true as soon as the packet currently being processed has been 2020 // detected as a connectivity probing. 2021 // Always false outside the context of ProcessUdpPacket(). 2022 bool is_current_packet_connectivity_probing_; 2023 2024 bool has_path_challenge_in_current_packet_; 2025 2026 // Caches the current effective peer migration type if a effective peer 2027 // migration might be initiated. As soon as the current packet is confirmed 2028 // not a connectivity probe, effective peer migration will start. 2029 AddressChangeType current_effective_peer_migration_type_; 2030 QuicConnectionHelperInterface* helper_; // Not owned. 2031 QuicAlarmFactory* alarm_factory_; // Not owned. 2032 PerPacketOptions* per_packet_options_; // Not owned. 2033 QuicPacketWriterParams packet_writer_params_; 2034 QuicPacketWriter* writer_; // Owned or not depending on |owns_writer_|. 2035 bool owns_writer_; 2036 // Encryption level for new packets. Should only be changed via 2037 // SetDefaultEncryptionLevel(). 2038 EncryptionLevel encryption_level_; 2039 const QuicClock* clock_; 2040 QuicRandom* random_generator_; 2041 2042 // On the server, the connection ID is set when receiving the first packet. 2043 // This variable ensures we only set it this way once. 2044 bool client_connection_id_is_set_; 2045 2046 // Whether we've already replaced our server connection ID due to receiving an 2047 // INITIAL packet with a different source connection ID. Only used on client. 2048 bool server_connection_id_replaced_by_initial_ = false; 2049 // Address on the last successfully processed packet received from the 2050 // direct peer. 2051 2052 // Other than initialization, do not modify it directly, use 2053 // UpdatePeerAddress() instead. 2054 QuicSocketAddress direct_peer_address_; 2055 // The default path on which the endpoint sends non-probing packets. 2056 // The send algorithm and RTT stats of this path are stored in 2057 // |sent_packet_manager_| instead of in this object. 2058 PathState default_path_; 2059 2060 // Records change type when the effective peer initiates migration to a new 2061 // address. Reset to NO_CHANGE after effective peer migration is validated. 2062 AddressChangeType active_effective_peer_migration_type_; 2063 2064 // Records highest sent packet number when effective peer migration is 2065 // started. 2066 QuicPacketNumber highest_packet_sent_before_effective_peer_migration_; 2067 2068 // True if Key Update is supported on this connection. 2069 bool support_key_update_for_connection_; 2070 2071 // Tracks the lowest packet sent in the current key phase. Will be 2072 // uninitialized before the first one-RTT packet has been sent or after a 2073 // key update but before the first packet has been sent. 2074 QuicPacketNumber lowest_packet_sent_in_current_key_phase_; 2075 2076 // TODO(rch): remove this when b/27221014 is fixed. 2077 const char* current_packet_data_; // UDP payload of packet currently being 2078 // parsed or nullptr. 2079 bool should_last_packet_instigate_acks_; 2080 2081 // Track some peer state so we can do less bookkeeping 2082 // Largest sequence sent by the peer which had an ack frame (latest ack info). 2083 // Do not read or write directly, use GetLargestReceivedPacketWithAck() and 2084 // SetLargestReceivedPacketWithAck() instead. 2085 QuicPacketNumber largest_seen_packet_with_ack_; 2086 // Largest packet number sent by the peer which had an ACK frame per packet 2087 // number space. Only used when this connection supports multiple packet 2088 // number spaces. 2089 QuicPacketNumber largest_seen_packets_with_ack_[NUM_PACKET_NUMBER_SPACES]; 2090 2091 // Largest packet number sent by the peer which had a stop waiting frame. 2092 QuicPacketNumber largest_seen_packet_with_stop_waiting_; 2093 2094 // Collection of packets which were received before encryption was 2095 // established, but which could not be decrypted. We buffer these on 2096 // the assumption that they could not be processed because they were 2097 // sent with the INITIAL encryption and the CHLO message was lost. 2098 std::deque<UndecryptablePacket> undecryptable_packets_; 2099 2100 // Collection of coalesced packets which were received while processing 2101 // the current packet. 2102 quiche::QuicheCircularDeque<std::unique_ptr<QuicEncryptedPacket>> 2103 received_coalesced_packets_; 2104 2105 // Maximum number of undecryptable packets the connection will store. 2106 size_t max_undecryptable_packets_; 2107 2108 // Maximum number of tracked packets. 2109 QuicPacketCount max_tracked_packets_; 2110 2111 // Contains the connection close packets if the connection has been closed. 2112 std::unique_ptr<std::vector<std::unique_ptr<QuicEncryptedPacket>>> 2113 termination_packets_; 2114 2115 // Determines whether or not a connection close packet is sent to the peer 2116 // after idle timeout due to lack of network activity. During the handshake, 2117 // a connection close packet is sent, but not after. 2118 ConnectionCloseBehavior idle_timeout_connection_close_behavior_; 2119 2120 // When > 0, close the QUIC connection after this number of RTOs. 2121 size_t num_rtos_for_blackhole_detection_; 2122 2123 // Statistics for this session. 2124 QuicConnectionStats stats_; 2125 2126 UberReceivedPacketManager uber_received_packet_manager_; 2127 2128 // Indicates the retransmission alarm needs to be set. 2129 bool pending_retransmission_alarm_; 2130 2131 // If true, defer sending data in response to received packets to the 2132 // SendAlarm. 2133 bool defer_send_in_response_to_packets_; 2134 2135 // Arena to store class implementations within the QuicConnection. 2136 QuicConnectionArena arena_; 2137 2138 // An alarm that fires when an ACK should be sent to the peer. 2139 QuicArenaScopedPtr<QuicAlarm> ack_alarm_; 2140 // An alarm that fires when a packet needs to be retransmitted. 2141 QuicArenaScopedPtr<QuicAlarm> retransmission_alarm_; 2142 // An alarm that is scheduled when the SentPacketManager requires a delay 2143 // before sending packets and fires when the packet may be sent. 2144 QuicArenaScopedPtr<QuicAlarm> send_alarm_; 2145 // An alarm that fires when an MTU probe should be sent. 2146 QuicArenaScopedPtr<QuicAlarm> mtu_discovery_alarm_; 2147 // An alarm that fires to process undecryptable packets when new decyrption 2148 // keys are available. 2149 QuicArenaScopedPtr<QuicAlarm> process_undecryptable_packets_alarm_; 2150 // An alarm that fires to discard keys for the previous key phase some time 2151 // after a key update has completed. 2152 QuicArenaScopedPtr<QuicAlarm> discard_previous_one_rtt_keys_alarm_; 2153 // An alarm that fires to discard 0-RTT decryption keys some time after the 2154 // first 1-RTT packet has been decrypted. Only used on server connections with 2155 // TLS handshaker. 2156 QuicArenaScopedPtr<QuicAlarm> discard_zero_rtt_decryption_keys_alarm_; 2157 // An alarm that fires to keep probing the multi-port path. 2158 QuicArenaScopedPtr<QuicAlarm> multi_port_probing_alarm_; 2159 // Neither visitor is owned by this class. 2160 QuicConnectionVisitorInterface* visitor_; 2161 QuicConnectionDebugVisitor* debug_visitor_; 2162 2163 QuicPacketCreator packet_creator_; 2164 2165 // Information about the last received QUIC packet, which may not have been 2166 // successfully decrypted and processed. 2167 ReceivedPacketInfo last_received_packet_info_; 2168 2169 // Sent packet manager which tracks the status of packets sent by this 2170 // connection and contains the send and receive algorithms to determine when 2171 // to send packets. 2172 QuicSentPacketManager sent_packet_manager_; 2173 2174 // Indicates whether connection version has been negotiated. 2175 // Always true for server connections. 2176 bool version_negotiated_; 2177 2178 // Tracks if the connection was created by the server or the client. 2179 Perspective perspective_; 2180 2181 // True by default. False if we've received or sent an explicit connection 2182 // close. 2183 bool connected_; 2184 2185 // Set to false if the connection should not send truncated connection IDs to 2186 // the peer, even if the peer supports it. 2187 bool can_truncate_connection_ids_; 2188 2189 // If non-empty this contains the set of versions received in a 2190 // version negotiation packet. 2191 ParsedQuicVersionVector server_supported_versions_; 2192 2193 // The number of MTU probes already sent. 2194 size_t mtu_probe_count_; 2195 2196 // The value of |long_term_mtu_| prior to the last successful MTU increase. 2197 // 0 means either 2198 // - MTU discovery has never been enabled, or 2199 // - MTU discovery has been enabled, but the connection got a packet write 2200 // error with a new (successfully probed) MTU, so it reverted 2201 // |long_term_mtu_| to the value before the last increase. 2202 QuicPacketLength previous_validated_mtu_; 2203 // The value of the MTU regularly used by the connection. This is different 2204 // from the value returned by max_packet_size(), as max_packet_size() returns 2205 // the value of the MTU as currently used by the serializer, so if 2206 // serialization of an MTU probe is in progress, those two values will be 2207 // different. 2208 QuicByteCount long_term_mtu_; 2209 2210 // The maximum UDP payload size that our peer has advertised support for. 2211 // Defaults to kDefaultMaxPacketSizeTransportParam until received from peer. 2212 QuicByteCount peer_max_packet_size_; 2213 2214 // The size of the largest packet received from peer. 2215 QuicByteCount largest_received_packet_size_; 2216 2217 // Indicates whether a write error is encountered currently. This is used to 2218 // avoid infinite write errors. 2219 bool write_error_occurred_; 2220 2221 // Consecutive number of sent packets which have no retransmittable frames. 2222 size_t consecutive_num_packets_with_no_retransmittable_frames_; 2223 2224 // After this many packets sent without retransmittable frames, an artificial 2225 // retransmittable frame(a WINDOW_UPDATE) will be created to solicit an ack 2226 // from the peer. Default to kMaxConsecutiveNonRetransmittablePackets. 2227 size_t max_consecutive_num_packets_with_no_retransmittable_frames_; 2228 2229 // If true, bundle an ack-eliciting frame with an ACK if the PTO alarm have 2230 // previously fired. 2231 bool bundle_retransmittable_with_pto_ack_; 2232 2233 // Id of latest sent control frame. 0 if no control frame has been sent. 2234 QuicControlFrameId last_control_frame_id_; 2235 2236 // True if the peer is unreachable on the current path. 2237 bool is_path_degrading_; 2238 2239 // True if an ack frame is being processed. 2240 bool processing_ack_frame_; 2241 2242 // True if the writer supports release timestamp. 2243 bool supports_release_time_; 2244 2245 std::unique_ptr<QuicPeerIssuedConnectionIdManager> peer_issued_cid_manager_; 2246 std::unique_ptr<QuicSelfIssuedConnectionIdManager> self_issued_cid_manager_; 2247 2248 // Time this connection can release packets into the future. 2249 QuicTime::Delta release_time_into_future_; 2250 2251 // Payloads that were received in the most recent probe. This needs to be a 2252 // Deque because the peer might no be using this implementation, and others 2253 // might send a packet with more than one PATH_CHALLENGE, so all need to be 2254 // saved and responded to. 2255 // TODO(danzh) deprecate this field when deprecating 2256 // --quic_send_path_response. 2257 quiche::QuicheCircularDeque<QuicPathFrameBuffer> 2258 received_path_challenge_payloads_; 2259 2260 // When we receive a RETRY packet or some INITIAL packets, we replace 2261 // |server_connection_id_| with the value from that packet and save off the 2262 // original value of |server_connection_id_| into 2263 // |original_destination_connection_id_| for validation. 2264 std::optional<QuicConnectionId> original_destination_connection_id_; 2265 2266 // The connection ID that replaces original_destination_connection_id_. 2267 QuicConnectionId original_destination_connection_id_replacement_; 2268 2269 // After we receive a RETRY packet, |retry_source_connection_id_| contains 2270 // the source connection ID from that packet. 2271 std::optional<QuicConnectionId> retry_source_connection_id_; 2272 2273 // Used to store content of packets which cannot be sent because of write 2274 // blocked. Packets' encrypted buffers are copied and owned by 2275 // buffered_packets_. From unacked_packet_map (and congestion control)'s 2276 // perspective, those packets are considered sent. 2277 std::list<BufferedPacket> buffered_packets_; 2278 2279 // Used to coalesce packets of different encryption level into the same UDP 2280 // datagram. Connection stops trying to coalesce packets if a forward secure 2281 // packet gets acknowledged. 2282 QuicCoalescedPacket coalesced_packet_; 2283 2284 QuicConnectionMtuDiscoverer mtu_discoverer_; 2285 2286 QuicNetworkBlackholeDetector blackhole_detector_; 2287 2288 QuicIdleNetworkDetector idle_network_detector_; 2289 2290 bool blackhole_detection_disabled_ = false; 2291 2292 const bool default_enable_5rto_blackhole_detection_ = 2293 GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2); 2294 2295 // True if next packet is intended to consume remaining space in the 2296 // coalescer. 2297 bool fill_coalesced_packet_ = false; 2298 2299 size_t anti_amplification_factor_ = 2300 GetQuicFlag(quic_anti_amplification_factor); 2301 2302 // True if AckFrequencyFrame is supported. 2303 bool can_receive_ack_frequency_frame_ = false; 2304 2305 // Indicate whether coalescing is done. 2306 bool coalescing_done_ = false; 2307 2308 // Indicate whether any ENCRYPTION_HANDSHAKE packet has been sent. 2309 bool handshake_packet_sent_ = false; 2310 2311 // Indicate whether to send an AckFrequencyFrame upon handshake completion. 2312 // The AckFrequencyFrame sent will updates client's max_ack_delay, which if 2313 // chosen properly can reduce the CPU and bandwidth usage for ACK frames. 2314 bool send_ack_frequency_on_handshake_completion_ = false; 2315 2316 // Indicate whether AckFrequency frame has been sent. 2317 bool ack_frequency_sent_ = false; 2318 2319 // True if a 0-RTT decrypter was or is installed at some point in the 2320 // connection's lifetime. 2321 bool had_zero_rtt_decrypter_ = false; 2322 2323 // True after the first 1-RTT packet has successfully decrypted. 2324 bool have_decrypted_first_one_rtt_packet_ = false; 2325 2326 // True if we are currently processing OnRetransmissionTimeout. 2327 bool in_probe_time_out_ = false; 2328 2329 QuicPathValidator path_validator_; 2330 2331 // Stores information of a path which maybe used as default path in the 2332 // future. On the client side, it gets created when the client starts 2333 // validating a new path and gets cleared once it becomes the default path or 2334 // the path validation fails or replaced by a newer path of interest. On the 2335 // server side, alternative_path gets created when server: 1) receives 2336 // PATH_CHALLENGE on non-default path, or 2) switches to a not yet validated 2337 // default path such that it needs to store the previous validated default 2338 // path. 2339 // Note that if alternative_path_ stores a validated path information (case 2340 // 2), do not override it on receiving PATH_CHALLENGE (case 1). 2341 PathState alternative_path_; 2342 2343 // If true, upon seeing a new client address, validate the client address. 2344 bool validate_client_addresses_ = false; 2345 2346 // Indicates whether we should proactively validate peer address on a 2347 // PATH_CHALLENGE received. 2348 bool should_proactively_validate_peer_address_on_path_challenge_ = false; 2349 2350 // If true, send connection close packet on INVALID_VERSION. 2351 bool send_connection_close_for_invalid_version_ = false; 2352 2353 // If true, disable liveness testing. 2354 bool liveness_testing_disabled_ = false; 2355 2356 QuicPingManager ping_manager_; 2357 2358 // Records first serialized 1-RTT packet. 2359 std::unique_ptr<BufferedPacket> first_serialized_one_rtt_packet_; 2360 2361 std::unique_ptr<QuicPathValidationContext> multi_port_path_context_; 2362 2363 QuicTime::Delta multi_port_probing_interval_; 2364 2365 std::unique_ptr<MultiPortStats> multi_port_stats_; 2366 2367 // If true, connection will migrate to multi-port path upon path degrading. 2368 bool multi_port_migration_enabled_ = false; 2369 2370 // Client side only. 2371 bool active_migration_disabled_ = false; 2372 2373 const bool ignore_gquic_probing_ = 2374 GetQuicReloadableFlag(quic_ignore_gquic_probing); 2375 2376 RetransmittableOnWireBehavior retransmittable_on_wire_behavior_ = DEFAULT; 2377 2378 // Server addresses that are known to the client. 2379 std::vector<QuicSocketAddress> known_server_addresses_; 2380 2381 // Stores received server preferred address in transport param. Client side 2382 // only. 2383 QuicSocketAddress received_server_preferred_address_; 2384 2385 // Stores sent server preferred address in transport param. Server side only. 2386 QuicSocketAddress sent_server_preferred_address_; 2387 2388 // If true, kicks off validation of server_preferred_address_ once it is 2389 // received. Also, send all coalesced packets on both paths until handshake is 2390 // confirmed. 2391 bool accelerated_server_preferred_address_ = false; 2392 2393 // If true, throttle sending if next created packet will exceed amplification 2394 // limit. 2395 const bool enforce_strict_amplification_factor_ = 2396 GetQuicFlag(quic_enforce_strict_amplification_factor); 2397 2398 ConnectionIdGeneratorInterface& connection_id_generator_; 2399 2400 // This LRU cache records source addresses of packets received on server's 2401 // original address. 2402 QuicLRUCache<QuicSocketAddress, bool, QuicSocketAddressHash> 2403 received_client_addresses_cache_; 2404 2405 // Endpoints should never mark packets with Congestion Experienced (CE), as 2406 // this is only done by routers. Endpoints cannot send ECT(0) or ECT(1) if 2407 // their congestion control cannot respond to these signals in accordance with 2408 // the spec, or ECN feedback doesn't conform to the spec. When true, the 2409 // connection will not verify that the requested codepoint adheres to these 2410 // policies. This is only accessible through QuicConnectionPeer. 2411 bool disable_ecn_codepoint_validation_ = false; 2412 2413 // The ECN codepoint of the last packet to be sent to the writer, which 2414 // might be different from the next codepoint in per_packet_options_. 2415 QuicEcnCodepoint last_ecn_codepoint_sent_ = ECN_NOT_ECT; 2416 2417 // The reason for the last call to CanWrite with a true return value. 2418 enum LastCanWriteReason : uint8_t { 2419 LAST_CAN_WRITE_REASON_NONE = 0, 2420 LAST_CAN_WRITE_REASON_COALESCE_PACKET, 2421 LAST_CAN_WRITE_REASON_PENDING_TIMER, 2422 LAST_CAN_WRITE_REASON_NO_RETRANSMITTABLE_DATA, 2423 LAST_CAN_WRITE_REASON_DELAY_WITHIN_RELEASE_TIME, 2424 LAST_CAN_WRITE_REASON_NO_DELAY, 2425 }; 2426 void RecordLastCanWriteReason(LastCanWriteReason reason); 2427 // TODO(b/299071230): Delete |packets_sent_on_last_successful_can_write_| and 2428 // |last_can_write_reason_| after debugging. 2429 LastCanWriteReason last_can_write_reason_ = LAST_CAN_WRITE_REASON_NONE; 2430 QuicPacketCount packets_sent_on_last_successful_can_write_ = 0; 2431 }; 2432 2433 } // namespace quic 2434 2435 #endif // QUICHE_QUIC_CORE_QUIC_CONNECTION_H_ 2436