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 <string> 25 #include <vector> 26 27 #include "absl/strings/string_view.h" 28 #include "absl/types/optional.h" 29 #include "net/third_party/quiche/src/quic/core/crypto/quic_decrypter.h" 30 #include "net/third_party/quiche/src/quic/core/crypto/quic_encrypter.h" 31 #include "net/third_party/quiche/src/quic/core/crypto/transport_parameters.h" 32 #include "net/third_party/quiche/src/quic/core/frames/quic_ack_frequency_frame.h" 33 #include "net/third_party/quiche/src/quic/core/frames/quic_max_streams_frame.h" 34 #include "net/third_party/quiche/src/quic/core/proto/cached_network_parameters_proto.h" 35 #include "net/third_party/quiche/src/quic/core/quic_alarm.h" 36 #include "net/third_party/quiche/src/quic/core/quic_alarm_factory.h" 37 #include "net/third_party/quiche/src/quic/core/quic_blocked_writer_interface.h" 38 #include "net/third_party/quiche/src/quic/core/quic_circular_deque.h" 39 #include "net/third_party/quiche/src/quic/core/quic_connection_id.h" 40 #include "net/third_party/quiche/src/quic/core/quic_connection_stats.h" 41 #include "net/third_party/quiche/src/quic/core/quic_constants.h" 42 #include "net/third_party/quiche/src/quic/core/quic_framer.h" 43 #include "net/third_party/quiche/src/quic/core/quic_idle_network_detector.h" 44 #include "net/third_party/quiche/src/quic/core/quic_mtu_discovery.h" 45 #include "net/third_party/quiche/src/quic/core/quic_network_blackhole_detector.h" 46 #include "net/third_party/quiche/src/quic/core/quic_one_block_arena.h" 47 #include "net/third_party/quiche/src/quic/core/quic_packet_creator.h" 48 #include "net/third_party/quiche/src/quic/core/quic_packet_writer.h" 49 #include "net/third_party/quiche/src/quic/core/quic_packets.h" 50 #include "net/third_party/quiche/src/quic/core/quic_sent_packet_manager.h" 51 #include "net/third_party/quiche/src/quic/core/quic_time.h" 52 #include "net/third_party/quiche/src/quic/core/quic_types.h" 53 #include "net/third_party/quiche/src/quic/core/uber_received_packet_manager.h" 54 #include "net/third_party/quiche/src/quic/platform/api/quic_containers.h" 55 #include "net/third_party/quiche/src/quic/platform/api/quic_export.h" 56 #include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h" 57 #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" 58 59 namespace quic { 60 61 class QuicClock; 62 class QuicConfig; 63 class QuicConnection; 64 class QuicRandom; 65 66 namespace test { 67 class QuicConnectionPeer; 68 } // namespace test 69 70 // Class that receives callbacks from the connection when frames are received 71 // and when other interesting events happen. 72 class QUIC_EXPORT_PRIVATE QuicConnectionVisitorInterface { 73 public: ~QuicConnectionVisitorInterface()74 virtual ~QuicConnectionVisitorInterface() {} 75 76 // A simple visitor interface for dealing with a data frame. 77 virtual void OnStreamFrame(const QuicStreamFrame& frame) = 0; 78 79 // Called when a CRYPTO frame containing handshake data is received. 80 virtual void OnCryptoFrame(const QuicCryptoFrame& frame) = 0; 81 82 // The session should process the WINDOW_UPDATE frame, adjusting both stream 83 // and connection level flow control windows. 84 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0; 85 86 // A BLOCKED frame indicates the peer is flow control blocked 87 // on a specified stream. 88 virtual void OnBlockedFrame(const QuicBlockedFrame& frame) = 0; 89 90 // Called when the stream is reset by the peer. 91 virtual void OnRstStream(const QuicRstStreamFrame& frame) = 0; 92 93 // Called when the connection is going away according to the peer. 94 virtual void OnGoAway(const QuicGoAwayFrame& frame) = 0; 95 96 // Called when |message| has been received. 97 virtual void OnMessageReceived(absl::string_view message) = 0; 98 99 // Called when a HANDSHAKE_DONE frame has been received. 100 virtual void OnHandshakeDoneReceived() = 0; 101 102 // Called when a MAX_STREAMS frame has been received from the peer. 103 virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0; 104 105 // Called when a STREAMS_BLOCKED frame has been received from the peer. 106 virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0; 107 108 // Called when the connection is closed either locally by the framer, or 109 // remotely by the peer. 110 virtual void OnConnectionClosed(const QuicConnectionCloseFrame& frame, 111 ConnectionCloseSource source) = 0; 112 113 // Called when the connection failed to write because the socket was blocked. 114 virtual void OnWriteBlocked() = 0; 115 116 // Called once a specific QUIC version is agreed by both endpoints. 117 virtual void OnSuccessfulVersionNegotiation( 118 const ParsedQuicVersion& version) = 0; 119 120 // Called when a packet has been received by the connection, after being 121 // validated and parsed. Only called when the client receives a valid packet 122 // or the server receives a connectivity probing packet. 123 // |is_connectivity_probe| is true if the received packet is a connectivity 124 // probe. 125 virtual void OnPacketReceived(const QuicSocketAddress& self_address, 126 const QuicSocketAddress& peer_address, 127 bool is_connectivity_probe) = 0; 128 129 // Called when a blocked socket becomes writable. 130 virtual void OnCanWrite() = 0; 131 132 // Called when the connection needs more data to probe for additional 133 // bandwidth. Returns true if data was sent, false otherwise. 134 virtual bool SendProbingData() = 0; 135 136 // Called when stateless reset packet is received. Returns true if the 137 // connection needs to be closed. 138 virtual bool ValidateStatelessReset( 139 const quic::QuicSocketAddress& self_address, 140 const quic::QuicSocketAddress& peer_address) = 0; 141 142 // Called when the connection experiences a change in congestion window. 143 virtual void OnCongestionWindowChange(QuicTime now) = 0; 144 145 // Called when the connection receives a packet from a migrated client. 146 virtual void OnConnectionMigration(AddressChangeType type) = 0; 147 148 // Called when the peer seems unreachable over the current path. 149 virtual void OnPathDegrading() = 0; 150 151 // Called when forward progress made after path degrading. 152 virtual void OnForwardProgressMadeAfterPathDegrading() = 0; 153 154 // Called when the connection sends ack after 155 // max_consecutive_num_packets_with_no_retransmittable_frames_ consecutive not 156 // retransmittable packets sent. To instigate an ack from peer, a 157 // retransmittable frame needs to be added. 158 virtual void OnAckNeedsRetransmittableFrame() = 0; 159 160 // Called when a ping needs to be sent. 161 virtual void SendPing() = 0; 162 163 // Called when an AckFrequency frame need to be sent. 164 virtual void SendAckFrequency(const QuicAckFrequencyFrame& frame) = 0; 165 166 // Called to ask if the visitor wants to schedule write resumption as it both 167 // has pending data to write, and is able to write (e.g. based on flow control 168 // limits). 169 // Writes may be pending because they were write-blocked, congestion-throttled 170 // or yielded to other connections. 171 virtual bool WillingAndAbleToWrite() const = 0; 172 173 // Called to ask if the connection should be kept alive and prevented 174 // from timing out, for example if there are outstanding application 175 // transactions expecting a response. 176 virtual bool ShouldKeepConnectionAlive() const = 0; 177 178 // Called to retrieve streams information for logging purpose. 179 virtual std::string GetStreamsInfoForLogging() const = 0; 180 181 // Called when a self address change is observed. Returns true if self address 182 // change is allowed. 183 virtual bool AllowSelfAddressChange() const = 0; 184 185 // Called to get current handshake state. 186 virtual HandshakeState GetHandshakeState() const = 0; 187 188 // Called when a STOP_SENDING frame has been received. 189 virtual void OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0; 190 191 // Called when a packet of encryption |level| has been successfully decrypted. 192 virtual void OnPacketDecrypted(EncryptionLevel level) = 0; 193 194 // Called when a 1RTT packet has been acknowledged. 195 virtual void OnOneRttPacketAcknowledged() = 0; 196 197 // Called when a packet of ENCRYPTION_HANDSHAKE gets sent. 198 virtual void OnHandshakePacketSent() = 0; 199 200 // Called when a key update has occurred. 201 virtual void OnKeyUpdate(KeyUpdateReason reason) = 0; 202 203 // Called to generate a decrypter for the next key phase. Each call should 204 // generate the key for phase n+1. 205 virtual std::unique_ptr<QuicDecrypter> 206 AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0; 207 208 // Called to generate an encrypter for the same key phase of the last 209 // decrypter returned by AdvanceKeysAndCreateCurrentOneRttDecrypter(). 210 virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0; 211 212 // Called when connection is being closed right before a CONNECTION_CLOSE 213 // frame is serialized, but only on the server and only if forward secure 214 // encryption has already been established. 215 virtual void BeforeConnectionCloseSent() = 0; 216 }; 217 218 // Interface which gets callbacks from the QuicConnection at interesting 219 // points. Implementations must not mutate the state of the connection 220 // as a result of these callbacks. 221 class QUIC_EXPORT_PRIVATE QuicConnectionDebugVisitor 222 : public QuicSentPacketManager::DebugDelegate { 223 public: ~QuicConnectionDebugVisitor()224 ~QuicConnectionDebugVisitor() override {} 225 226 // Called when a packet has been sent. 227 // TODO(wub): Delete when deprecating 228 // --quic_give_sent_packet_to_debug_visitor_after_sent. OnPacketSent(const SerializedPacket &,TransmissionType,QuicTime)229 virtual void OnPacketSent(const SerializedPacket& /*serialized_packet*/, 230 TransmissionType /*transmission_type*/, 231 QuicTime /*sent_time*/) {} 232 OnPacketSent(QuicPacketNumber,QuicPacketLength,bool,TransmissionType,EncryptionLevel,const QuicFrames &,const QuicFrames &,QuicTime)233 virtual void OnPacketSent(QuicPacketNumber /*packet_number*/, 234 QuicPacketLength /*packet_length*/, 235 bool /*has_crypto_handshake*/, 236 TransmissionType /*transmission_type*/, 237 EncryptionLevel /*encryption_level*/, 238 const QuicFrames& /*retransmittable_frames*/, 239 const QuicFrames& /*nonretransmittable_frames*/, 240 QuicTime /*sent_time*/) {} 241 242 // Called when a coalesced packet has been sent. OnCoalescedPacketSent(const QuicCoalescedPacket &,size_t)243 virtual void OnCoalescedPacketSent( 244 const QuicCoalescedPacket& /*coalesced_packet*/, 245 size_t /*length*/) {} 246 247 // Called when a PING frame has been sent. OnPingSent()248 virtual void OnPingSent() {} 249 250 // Called when a packet has been received, but before it is 251 // validated or parsed. OnPacketReceived(const QuicSocketAddress &,const QuicSocketAddress &,const QuicEncryptedPacket &)252 virtual void OnPacketReceived(const QuicSocketAddress& /*self_address*/, 253 const QuicSocketAddress& /*peer_address*/, 254 const QuicEncryptedPacket& /*packet*/) {} 255 256 // Called when the unauthenticated portion of the header has been parsed. OnUnauthenticatedHeader(const QuicPacketHeader &)257 virtual void OnUnauthenticatedHeader(const QuicPacketHeader& /*header*/) {} 258 259 // Called when a packet is received with a connection id that does not 260 // match the ID of this connection. OnIncorrectConnectionId(QuicConnectionId)261 virtual void OnIncorrectConnectionId(QuicConnectionId /*connection_id*/) {} 262 263 // Called when an undecryptable packet has been received. If |dropped| is 264 // true, the packet has been dropped. Otherwise, the packet will be queued and 265 // connection will attempt to process it later. OnUndecryptablePacket(EncryptionLevel,bool)266 virtual void OnUndecryptablePacket(EncryptionLevel /*decryption_level*/, 267 bool /*dropped*/) {} 268 269 // Called when attempting to process a previously undecryptable packet. OnAttemptingToProcessUndecryptablePacket(EncryptionLevel)270 virtual void OnAttemptingToProcessUndecryptablePacket( 271 EncryptionLevel /*decryption_level*/) {} 272 273 // Called when a duplicate packet has been received. OnDuplicatePacket(QuicPacketNumber)274 virtual void OnDuplicatePacket(QuicPacketNumber /*packet_number*/) {} 275 276 // Called when the protocol version on the received packet doensn't match 277 // current protocol version of the connection. OnProtocolVersionMismatch(ParsedQuicVersion)278 virtual void OnProtocolVersionMismatch(ParsedQuicVersion /*version*/) {} 279 280 // Called when the complete header of a packet has been parsed. OnPacketHeader(const QuicPacketHeader &,QuicTime,EncryptionLevel)281 virtual void OnPacketHeader(const QuicPacketHeader& /*header*/, 282 QuicTime /*receive_time*/, 283 EncryptionLevel /*level*/) {} 284 285 // Called when a StreamFrame has been parsed. OnStreamFrame(const QuicStreamFrame &)286 virtual void OnStreamFrame(const QuicStreamFrame& /*frame*/) {} 287 288 // Called when a CRYPTO frame containing handshake data is received. OnCryptoFrame(const QuicCryptoFrame &)289 virtual void OnCryptoFrame(const QuicCryptoFrame& /*frame*/) {} 290 291 // Called when a StopWaitingFrame has been parsed. OnStopWaitingFrame(const QuicStopWaitingFrame &)292 virtual void OnStopWaitingFrame(const QuicStopWaitingFrame& /*frame*/) {} 293 294 // Called when a QuicPaddingFrame has been parsed. OnPaddingFrame(const QuicPaddingFrame &)295 virtual void OnPaddingFrame(const QuicPaddingFrame& /*frame*/) {} 296 297 // Called when a Ping has been parsed. OnPingFrame(const QuicPingFrame &,QuicTime::Delta)298 virtual void OnPingFrame(const QuicPingFrame& /*frame*/, 299 QuicTime::Delta /*ping_received_delay*/) {} 300 301 // Called when a GoAway has been parsed. OnGoAwayFrame(const QuicGoAwayFrame &)302 virtual void OnGoAwayFrame(const QuicGoAwayFrame& /*frame*/) {} 303 304 // Called when a RstStreamFrame has been parsed. OnRstStreamFrame(const QuicRstStreamFrame &)305 virtual void OnRstStreamFrame(const QuicRstStreamFrame& /*frame*/) {} 306 307 // Called when a ConnectionCloseFrame has been parsed. All forms 308 // of CONNECTION CLOSE are handled, Google QUIC, IETF QUIC 309 // CONNECTION CLOSE/Transport and IETF QUIC CONNECTION CLOSE/Application OnConnectionCloseFrame(const QuicConnectionCloseFrame &)310 virtual void OnConnectionCloseFrame( 311 const QuicConnectionCloseFrame& /*frame*/) {} 312 313 // Called when a WindowUpdate has been parsed. OnWindowUpdateFrame(const QuicWindowUpdateFrame &,const QuicTime &)314 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& /*frame*/, 315 const QuicTime& /*receive_time*/) {} 316 317 // Called when a BlockedFrame has been parsed. OnBlockedFrame(const QuicBlockedFrame &)318 virtual void OnBlockedFrame(const QuicBlockedFrame& /*frame*/) {} 319 320 // Called when a NewConnectionIdFrame has been parsed. OnNewConnectionIdFrame(const QuicNewConnectionIdFrame &)321 virtual void OnNewConnectionIdFrame( 322 const QuicNewConnectionIdFrame& /*frame*/) {} 323 324 // Called when a RetireConnectionIdFrame has been parsed. OnRetireConnectionIdFrame(const QuicRetireConnectionIdFrame &)325 virtual void OnRetireConnectionIdFrame( 326 const QuicRetireConnectionIdFrame& /*frame*/) {} 327 328 // Called when a NewTokenFrame has been parsed. OnNewTokenFrame(const QuicNewTokenFrame &)329 virtual void OnNewTokenFrame(const QuicNewTokenFrame& /*frame*/) {} 330 331 // Called when a MessageFrame has been parsed. OnMessageFrame(const QuicMessageFrame &)332 virtual void OnMessageFrame(const QuicMessageFrame& /*frame*/) {} 333 334 // Called when a HandshakeDoneFrame has been parsed. OnHandshakeDoneFrame(const QuicHandshakeDoneFrame &)335 virtual void OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& /*frame*/) {} 336 337 // Called when a public reset packet has been received. OnPublicResetPacket(const QuicPublicResetPacket &)338 virtual void OnPublicResetPacket(const QuicPublicResetPacket& /*packet*/) {} 339 340 // Called when a version negotiation packet has been received. OnVersionNegotiationPacket(const QuicVersionNegotiationPacket &)341 virtual void OnVersionNegotiationPacket( 342 const QuicVersionNegotiationPacket& /*packet*/) {} 343 344 // Called when the connection is closed. OnConnectionClosed(const QuicConnectionCloseFrame &,ConnectionCloseSource)345 virtual void OnConnectionClosed(const QuicConnectionCloseFrame& /*frame*/, 346 ConnectionCloseSource /*source*/) {} 347 348 // Called when the version negotiation is successful. OnSuccessfulVersionNegotiation(const ParsedQuicVersion &)349 virtual void OnSuccessfulVersionNegotiation( 350 const ParsedQuicVersion& /*version*/) {} 351 352 // Called when a CachedNetworkParameters is sent to the client. OnSendConnectionState(const CachedNetworkParameters &)353 virtual void OnSendConnectionState( 354 const CachedNetworkParameters& /*cached_network_params*/) {} 355 356 // Called when a CachedNetworkParameters are received from the client. OnReceiveConnectionState(const CachedNetworkParameters &)357 virtual void OnReceiveConnectionState( 358 const CachedNetworkParameters& /*cached_network_params*/) {} 359 360 // Called when the connection parameters are set from the supplied 361 // |config|. OnSetFromConfig(const QuicConfig &)362 virtual void OnSetFromConfig(const QuicConfig& /*config*/) {} 363 364 // Called when RTT may have changed, including when an RTT is read from 365 // the config. OnRttChanged(QuicTime::Delta)366 virtual void OnRttChanged(QuicTime::Delta /*rtt*/) const {} 367 368 // Called when a StopSendingFrame has been parsed. OnStopSendingFrame(const QuicStopSendingFrame &)369 virtual void OnStopSendingFrame(const QuicStopSendingFrame& /*frame*/) {} 370 371 // Called when a PathChallengeFrame has been parsed. OnPathChallengeFrame(const QuicPathChallengeFrame &)372 virtual void OnPathChallengeFrame(const QuicPathChallengeFrame& /*frame*/) {} 373 374 // Called when a PathResponseFrame has been parsed. OnPathResponseFrame(const QuicPathResponseFrame &)375 virtual void OnPathResponseFrame(const QuicPathResponseFrame& /*frame*/) {} 376 377 // Called when a StreamsBlockedFrame has been parsed. OnStreamsBlockedFrame(const QuicStreamsBlockedFrame &)378 virtual void OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& /*frame*/) { 379 } 380 381 // Called when a MaxStreamsFrame has been parsed. OnMaxStreamsFrame(const QuicMaxStreamsFrame &)382 virtual void OnMaxStreamsFrame(const QuicMaxStreamsFrame& /*frame*/) {} 383 384 // Called when an AckFrequencyFrame has been parsed. OnAckFrequencyFrame(const QuicAckFrequencyFrame &)385 virtual void OnAckFrequencyFrame(const QuicAckFrequencyFrame& /*frame*/) {} 386 387 // Called when |count| packet numbers have been skipped. OnNPacketNumbersSkipped(QuicPacketCount,QuicTime)388 virtual void OnNPacketNumbersSkipped(QuicPacketCount /*count*/, 389 QuicTime /*now*/) {} 390 391 // Called for QUIC+TLS versions when we send transport parameters. OnTransportParametersSent(const TransportParameters &)392 virtual void OnTransportParametersSent( 393 const TransportParameters& /*transport_parameters*/) {} 394 395 // Called for QUIC+TLS versions when we receive transport parameters. OnTransportParametersReceived(const TransportParameters &)396 virtual void OnTransportParametersReceived( 397 const TransportParameters& /*transport_parameters*/) {} 398 399 // Called for QUIC+TLS versions when we resume cached transport parameters for 400 // 0-RTT. OnTransportParametersResumed(const TransportParameters &)401 virtual void OnTransportParametersResumed( 402 const TransportParameters& /*transport_parameters*/) {} 403 404 // Called for QUIC+TLS versions when 0-RTT is rejected. OnZeroRttRejected(int)405 virtual void OnZeroRttRejected(int /*reject_reason*/) {} 406 407 // Called for QUIC+TLS versions when 0-RTT packet gets acked. OnZeroRttPacketAcked()408 virtual void OnZeroRttPacketAcked() {} 409 410 // Called on peer address change. OnPeerAddressChange(AddressChangeType,QuicTime::Delta)411 virtual void OnPeerAddressChange(AddressChangeType /*type*/, 412 QuicTime::Delta /*connection_time*/) {} 413 }; 414 415 class QUIC_EXPORT_PRIVATE QuicConnectionHelperInterface { 416 public: ~QuicConnectionHelperInterface()417 virtual ~QuicConnectionHelperInterface() {} 418 419 // Returns a QuicClock to be used for all time related functions. 420 virtual const QuicClock* GetClock() const = 0; 421 422 // Returns a QuicRandom to be used for all random number related functions. 423 virtual QuicRandom* GetRandomGenerator() = 0; 424 425 // Returns a QuicBufferAllocator to be used for stream send buffers. 426 virtual QuicBufferAllocator* GetStreamSendBufferAllocator() = 0; 427 }; 428 429 class QUIC_EXPORT_PRIVATE QuicConnection 430 : public QuicFramerVisitorInterface, 431 public QuicBlockedWriterInterface, 432 public QuicPacketCreator::DelegateInterface, 433 public QuicSentPacketManager::NetworkChangeVisitor, 434 public QuicNetworkBlackholeDetector::Delegate, 435 public QuicIdleNetworkDetector::Delegate { 436 public: 437 // Constructs a new QuicConnection for |connection_id| and 438 // |initial_peer_address| using |writer| to write packets. |owns_writer| 439 // specifies whether the connection takes ownership of |writer|. |helper| must 440 // outlive this connection. 441 QuicConnection(QuicConnectionId server_connection_id, 442 QuicSocketAddress initial_self_address, 443 QuicSocketAddress initial_peer_address, 444 QuicConnectionHelperInterface* helper, 445 QuicAlarmFactory* alarm_factory, 446 QuicPacketWriter* writer, 447 bool owns_writer, 448 Perspective perspective, 449 const ParsedQuicVersionVector& supported_versions); 450 QuicConnection(const QuicConnection&) = delete; 451 QuicConnection& operator=(const QuicConnection&) = delete; 452 ~QuicConnection() override; 453 454 // Sets connection parameters from the supplied |config|. 455 void SetFromConfig(const QuicConfig& config); 456 457 // Apply |connection_options| for this connection. Unlike SetFromConfig, this 458 // can happen at anytime in the life of a connection. 459 // Note there is no guarantee that all options can be applied. Components will 460 // only apply cherrypicked options that make sense at the time of the call. 461 void ApplyConnectionOptions(const QuicTagVector& connection_options); 462 463 // Called by the session when sending connection state to the client. 464 virtual void OnSendConnectionState( 465 const CachedNetworkParameters& cached_network_params); 466 467 // Called by the session when receiving connection state from the client. 468 virtual void OnReceiveConnectionState( 469 const CachedNetworkParameters& cached_network_params); 470 471 // Called by the Session when the client has provided CachedNetworkParameters. 472 virtual void ResumeConnectionState( 473 const CachedNetworkParameters& cached_network_params, 474 bool max_bandwidth_resumption); 475 476 // Called by the Session when a max pacing rate for the connection is needed. 477 virtual void SetMaxPacingRate(QuicBandwidth max_pacing_rate); 478 479 // Allows the client to adjust network parameters based on external 480 // information. 481 void AdjustNetworkParameters( 482 const SendAlgorithmInterface::NetworkParams& params); 483 void AdjustNetworkParameters(QuicBandwidth bandwidth, 484 QuicTime::Delta rtt, 485 bool allow_cwnd_to_decrease); 486 487 // Install a loss detection tuner. Must be called before OnConfigNegotiated. 488 void SetLossDetectionTuner( 489 std::unique_ptr<LossDetectionTunerInterface> tuner); 490 // Called by the session when session->is_configured() becomes true. 491 void OnConfigNegotiated(); 492 493 // Returns the max pacing rate for the connection. 494 virtual QuicBandwidth MaxPacingRate() const; 495 496 // Sends crypto handshake messages of length |write_length| to the peer in as 497 // few packets as possible. Returns the number of bytes consumed from the 498 // data. 499 virtual size_t SendCryptoData(EncryptionLevel level, 500 size_t write_length, 501 QuicStreamOffset offset); 502 503 // Send the data of length |write_length| to the peer in as few packets as 504 // possible. Returns the number of bytes consumed from data, and a boolean 505 // indicating if the fin bit was consumed. This does not indicate the data 506 // has been sent on the wire: it may have been turned into a packet and queued 507 // if the socket was unexpectedly blocked. 508 virtual QuicConsumedData SendStreamData(QuicStreamId id, 509 size_t write_length, 510 QuicStreamOffset offset, 511 StreamSendingState state); 512 513 // Send |frame| to the peer. Returns true if frame is consumed, false 514 // otherwise. 515 virtual bool SendControlFrame(const QuicFrame& frame); 516 517 // Called when stream |id| is reset because of |error|. 518 virtual void OnStreamReset(QuicStreamId id, QuicRstStreamErrorCode error); 519 520 // Closes the connection. 521 // |connection_close_behavior| determines whether or not a connection close 522 // packet is sent to the peer. 523 virtual void CloseConnection( 524 QuicErrorCode error, 525 const std::string& details, 526 ConnectionCloseBehavior connection_close_behavior); 527 mutable_stats()528 QuicConnectionStats& mutable_stats() { return stats_; } 529 retransmittable_on_wire_ping_count()530 int retransmittable_on_wire_ping_count() const { 531 return retransmittable_on_wire_ping_count_; 532 } 533 534 // Returns statistics tracked for this connection. 535 const QuicConnectionStats& GetStats(); 536 537 // Processes an incoming UDP packet (consisting of a QuicEncryptedPacket) from 538 // the peer. 539 // In a client, the packet may be "stray" and have a different connection ID 540 // than that of this connection. 541 virtual void ProcessUdpPacket(const QuicSocketAddress& self_address, 542 const QuicSocketAddress& peer_address, 543 const QuicReceivedPacket& packet); 544 545 // QuicBlockedWriterInterface 546 // Called when the underlying connection becomes writable to allow queued 547 // writes to happen. 548 void OnBlockedWriterCanWrite() override; 549 IsWriterBlocked()550 bool IsWriterBlocked() const override { 551 return writer_ != nullptr && writer_->IsWriteBlocked(); 552 } 553 554 // Called when the caller thinks it's worth a try to write. 555 virtual void OnCanWrite(); 556 557 // Called when an error occurs while attempting to write a packet to the 558 // network. 559 void OnWriteError(int error_code); 560 561 // Whether |result| represents a MSG TOO BIG write error. 562 bool IsMsgTooBig(const WriteResult& result); 563 564 // If the socket is not blocked, writes queued packets. 565 void WriteIfNotBlocked(); 566 567 // If the socket is not blocked, writes queued packets and bundles any pending 568 // ACKs. 569 void WriteAndBundleAcksIfNotBlocked(); 570 571 // Set the packet writer. SetQuicPacketWriter(QuicPacketWriter * writer,bool owns_writer)572 void SetQuicPacketWriter(QuicPacketWriter* writer, bool owns_writer) { 573 DCHECK(writer != nullptr); 574 if (writer_ != nullptr && owns_writer_) { 575 delete writer_; 576 } 577 writer_ = writer; 578 owns_writer_ = owns_writer; 579 } 580 581 // Set self address. SetSelfAddress(QuicSocketAddress address)582 void SetSelfAddress(QuicSocketAddress address) { self_address_ = address; } 583 584 // The version of the protocol this connection is using. transport_version()585 QuicTransportVersion transport_version() const { 586 return framer_.transport_version(); 587 } 588 version()589 ParsedQuicVersion version() const { return framer_.version(); } 590 591 // The versions of the protocol that this connection supports. supported_versions()592 const ParsedQuicVersionVector& supported_versions() const { 593 return framer_.supported_versions(); 594 } 595 596 // Mark version negotiated for this connection. Once called, the connection 597 // will ignore received version negotiation packets. SetVersionNegotiated()598 void SetVersionNegotiated() { 599 version_negotiated_ = true; 600 if (perspective_ == Perspective::IS_SERVER) { 601 framer_.InferPacketHeaderTypeFromVersion(); 602 } 603 } 604 605 // From QuicFramerVisitorInterface 606 void OnError(QuicFramer* framer) override; 607 bool OnProtocolVersionMismatch(ParsedQuicVersion received_version) override; 608 void OnPacket() override; 609 void OnPublicResetPacket(const QuicPublicResetPacket& packet) override; 610 void OnVersionNegotiationPacket( 611 const QuicVersionNegotiationPacket& packet) override; 612 void OnRetryPacket(QuicConnectionId original_connection_id, 613 QuicConnectionId new_connection_id, 614 absl::string_view retry_token, 615 absl::string_view retry_integrity_tag, 616 absl::string_view retry_without_tag) override; 617 bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override; 618 bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override; 619 void OnDecryptedPacket(EncryptionLevel level) override; 620 bool OnPacketHeader(const QuicPacketHeader& header) override; 621 void OnCoalescedPacket(const QuicEncryptedPacket& packet) override; 622 void OnUndecryptablePacket(const QuicEncryptedPacket& packet, 623 EncryptionLevel decryption_level, 624 bool has_decryption_key) override; 625 bool OnStreamFrame(const QuicStreamFrame& frame) override; 626 bool OnCryptoFrame(const QuicCryptoFrame& frame) override; 627 bool OnAckFrameStart(QuicPacketNumber largest_acked, 628 QuicTime::Delta ack_delay_time) override; 629 bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override; 630 bool OnAckTimestamp(QuicPacketNumber packet_number, 631 QuicTime timestamp) override; 632 bool OnAckFrameEnd(QuicPacketNumber start) override; 633 bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override; 634 bool OnPaddingFrame(const QuicPaddingFrame& frame) override; 635 bool OnPingFrame(const QuicPingFrame& frame) override; 636 bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override; 637 bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override; 638 bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override; 639 bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override; 640 bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override; 641 bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override; 642 bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; 643 bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; 644 bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; 645 bool OnBlockedFrame(const QuicBlockedFrame& frame) override; 646 bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override; 647 bool OnRetireConnectionIdFrame( 648 const QuicRetireConnectionIdFrame& frame) override; 649 bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override; 650 bool OnMessageFrame(const QuicMessageFrame& frame) override; 651 bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override; 652 bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override; 653 void OnPacketComplete() override; 654 bool IsValidStatelessResetToken(QuicUint128 token) const override; 655 void OnAuthenticatedIetfStatelessResetPacket( 656 const QuicIetfStatelessResetPacket& packet) override; 657 void OnKeyUpdate(KeyUpdateReason reason) override; 658 void OnDecryptedFirstPacketInKeyPhase() override; 659 std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() 660 override; 661 std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; 662 663 // QuicPacketCreator::DelegateInterface 664 bool ShouldGeneratePacket(HasRetransmittableData retransmittable, 665 IsHandshake handshake) override; 666 const QuicFrames MaybeBundleAckOpportunistically() override; 667 QuicPacketBuffer GetPacketBuffer() override; 668 void OnSerializedPacket(SerializedPacket packet) override; 669 void OnUnrecoverableError(QuicErrorCode error, 670 const std::string& error_details) override; 671 SerializedPacketFate GetSerializedPacketFate( 672 bool is_mtu_discovery, 673 EncryptionLevel encryption_level) override; 674 675 // QuicSentPacketManager::NetworkChangeVisitor 676 void OnCongestionChange() override; 677 void OnPathMtuIncreased(QuicPacketLength packet_size) override; 678 679 // QuicNetworkBlackholeDetector::Delegate 680 void OnPathDegradingDetected() override; 681 void OnBlackholeDetected() override; 682 void OnPathMtuReductionDetected() override; 683 684 // QuicIdleNetworkDetector::Delegate 685 void OnHandshakeTimeout() override; 686 void OnIdleNetworkDetected() override; 687 688 // Please note, this is not a const function. For logging purpose, please use 689 // ack_frame(). 690 const QuicFrame GetUpdatedAckFrame(); 691 692 // Called when the handshake completes. On the client side, handshake 693 // completes on receipt of SHLO. On the server side, handshake completes when 694 // SHLO gets ACKed (or a forward secure packet gets decrypted successfully). 695 // TODO(fayang): Add a guard that this only gets called once. 696 void OnHandshakeComplete(); 697 698 // Accessors set_visitor(QuicConnectionVisitorInterface * visitor)699 void set_visitor(QuicConnectionVisitorInterface* visitor) { 700 visitor_ = visitor; 701 } set_debug_visitor(QuicConnectionDebugVisitor * debug_visitor)702 void set_debug_visitor(QuicConnectionDebugVisitor* debug_visitor) { 703 debug_visitor_ = debug_visitor; 704 sent_packet_manager_.SetDebugDelegate(debug_visitor); 705 } 706 // Used in Chromium, but not internally. 707 // Must only be called before ping_alarm_ is set. set_ping_timeout(QuicTime::Delta ping_timeout)708 void set_ping_timeout(QuicTime::Delta ping_timeout) { 709 DCHECK(!ping_alarm_->IsSet()); 710 ping_timeout_ = ping_timeout; 711 } ping_timeout()712 const QuicTime::Delta ping_timeout() const { return ping_timeout_; } 713 // Used in Chromium, but not internally. 714 // Sets an initial timeout for the ping alarm when there is no retransmittable 715 // data in flight, allowing for a more aggressive ping alarm in that case. set_initial_retransmittable_on_wire_timeout(QuicTime::Delta retransmittable_on_wire_timeout)716 void set_initial_retransmittable_on_wire_timeout( 717 QuicTime::Delta retransmittable_on_wire_timeout) { 718 DCHECK(!ping_alarm_->IsSet()); 719 initial_retransmittable_on_wire_timeout_ = retransmittable_on_wire_timeout; 720 } initial_retransmittable_on_wire_timeout()721 const QuicTime::Delta initial_retransmittable_on_wire_timeout() const { 722 return initial_retransmittable_on_wire_timeout_; 723 } 724 // Used in Chromium, but not internally. set_creator_debug_delegate(QuicPacketCreator::DebugDelegate * visitor)725 void set_creator_debug_delegate(QuicPacketCreator::DebugDelegate* visitor) { 726 packet_creator_.set_debug_delegate(visitor); 727 } self_address()728 const QuicSocketAddress& self_address() const { return self_address_; } peer_address()729 const QuicSocketAddress& peer_address() const { return direct_peer_address_; } effective_peer_address()730 const QuicSocketAddress& effective_peer_address() const { 731 return effective_peer_address_; 732 } connection_id()733 QuicConnectionId connection_id() const { return server_connection_id_; } client_connection_id()734 QuicConnectionId client_connection_id() const { 735 return client_connection_id_; 736 } 737 void set_client_connection_id(QuicConnectionId client_connection_id); clock()738 const QuicClock* clock() const { return clock_; } random_generator()739 QuicRandom* random_generator() const { return random_generator_; } 740 QuicByteCount max_packet_length() const; 741 void SetMaxPacketLength(QuicByteCount length); 742 mtu_probe_count()743 size_t mtu_probe_count() const { return mtu_probe_count_; } 744 connected()745 bool connected() const { return connected_; } 746 747 // Must only be called on client connections. server_supported_versions()748 const ParsedQuicVersionVector& server_supported_versions() const { 749 DCHECK_EQ(Perspective::IS_CLIENT, perspective_); 750 return server_supported_versions_; 751 } 752 HasQueuedPackets()753 bool HasQueuedPackets() const { return !buffered_packets_.empty(); } 754 // Testing only. TODO(ianswett): Use a peer instead. NumQueuedPackets()755 size_t NumQueuedPackets() const { return buffered_packets_.size(); } 756 757 // Returns true if the connection has queued packets or frames. 758 bool HasQueuedData() const; 759 760 // Sets the handshake and idle state connection timeouts. 761 void SetNetworkTimeouts(QuicTime::Delta handshake_timeout, 762 QuicTime::Delta idle_timeout); 763 764 // Called when the ping alarm fires. Causes a ping frame to be sent only 765 // if the retransmission alarm is not running. 766 void OnPingTimeout(); 767 768 // Sets up a packet with an QuicAckFrame and sends it out. 769 void SendAck(); 770 771 // Called when an RTO fires. Resets the retransmission alarm if there are 772 // remaining unacked packets. 773 void OnRetransmissionTimeout(); 774 775 // Mark all sent 0-RTT encrypted packets for retransmission. Called when new 776 // 0-RTT or 1-RTT key is available in gQUIC, or when 0-RTT is rejected in IETF 777 // QUIC. |reject_reason| is used in TLS-QUIC to log why 0-RTT was rejected. 778 void MarkZeroRttPacketsForRetransmission(int reject_reason); 779 780 // Calls |sent_packet_manager_|'s NeuterUnencryptedPackets. Used when the 781 // connection becomes forward secure and hasn't received acks for all packets. 782 void NeuterUnencryptedPackets(); 783 784 // Changes the encrypter used for level |level| to |encrypter|. 785 void SetEncrypter(EncryptionLevel level, 786 std::unique_ptr<QuicEncrypter> encrypter); 787 788 // Called to remove encrypter of encryption |level|. 789 void RemoveEncrypter(EncryptionLevel level); 790 791 // SetNonceForPublicHeader sets the nonce that will be transmitted in the 792 // header of each packet encrypted at the initial encryption level decrypted. 793 // This should only be called on the server side. 794 void SetDiversificationNonce(const DiversificationNonce& nonce); 795 796 // SetDefaultEncryptionLevel sets the encryption level that will be applied 797 // to new packets. 798 void SetDefaultEncryptionLevel(EncryptionLevel level); 799 800 // SetDecrypter sets the primary decrypter, replacing any that already exists. 801 // If an alternative decrypter is in place then the function DCHECKs. This is 802 // intended for cases where one knows that future packets will be using the 803 // new decrypter and the previous decrypter is now obsolete. |level| indicates 804 // the encryption level of the new decrypter. 805 void SetDecrypter(EncryptionLevel level, 806 std::unique_ptr<QuicDecrypter> decrypter); 807 808 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt 809 // future packets. |level| indicates the encryption level of the decrypter. If 810 // |latch_once_used| is true, then the first time that the decrypter is 811 // successful it will replace the primary decrypter. Otherwise both 812 // decrypters will remain active and the primary decrypter will be the one 813 // last used. 814 void SetAlternativeDecrypter(EncryptionLevel level, 815 std::unique_ptr<QuicDecrypter> decrypter, 816 bool latch_once_used); 817 818 void InstallDecrypter(EncryptionLevel level, 819 std::unique_ptr<QuicDecrypter> decrypter); 820 void RemoveDecrypter(EncryptionLevel level); 821 822 // Discard keys for the previous key phase. 823 void DiscardPreviousOneRttKeys(); 824 825 // Returns true if it is currently allowed to initiate a key update. 826 bool IsKeyUpdateAllowed() const; 827 828 // Returns true if packets have been sent in the current 1-RTT key phase but 829 // none of these packets have been acked. 830 bool HaveSentPacketsInCurrentKeyPhaseButNoneAcked() const; 831 832 // Returns the count of packets received that appeared to attempt a key 833 // update but failed decryption that have been received since the last 834 // successfully decrypted packet. 835 QuicPacketCount PotentialPeerKeyUpdateAttemptCount() const; 836 837 // Increment the key phase. It is a bug to call this when IsKeyUpdateAllowed() 838 // is false. Returns false on error. 839 bool InitiateKeyUpdate(KeyUpdateReason reason); 840 841 const QuicDecrypter* decrypter() const; 842 const QuicDecrypter* alternative_decrypter() const; 843 perspective()844 Perspective perspective() const { return perspective_; } 845 846 // Allow easy overriding of truncated connection IDs. set_can_truncate_connection_ids(bool can)847 void set_can_truncate_connection_ids(bool can) { 848 can_truncate_connection_ids_ = can; 849 } 850 851 // Returns the underlying sent packet manager. sent_packet_manager()852 const QuicSentPacketManager& sent_packet_manager() const { 853 return sent_packet_manager_; 854 } 855 856 // Returns the underlying sent packet manager. sent_packet_manager()857 QuicSentPacketManager& sent_packet_manager() { return sent_packet_manager_; } 858 received_packet_manager()859 UberReceivedPacketManager& received_packet_manager() { 860 return uber_received_packet_manager_; 861 } 862 863 bool CanWrite(HasRetransmittableData retransmittable); 864 865 // When the flusher is out of scope, only the outermost flusher will cause a 866 // flush of the connection and set the retransmission alarm if there is one 867 // pending. In addition, this flusher can be configured to ensure that an ACK 868 // frame is included in the first packet created, if there's new ack 869 // information to be sent. 870 class QUIC_EXPORT_PRIVATE ScopedPacketFlusher { 871 public: 872 explicit ScopedPacketFlusher(QuicConnection* connection); 873 ~ScopedPacketFlusher(); 874 875 private: 876 QuicConnection* connection_; 877 // If true, when this flusher goes out of scope, flush connection and set 878 // retransmission alarm if there is one pending. 879 bool flush_and_set_pending_retransmission_alarm_on_delete_; 880 // Latched connection's handshake_packet_sent_ on creation of this flusher. 881 const bool handshake_packet_sent_; 882 }; 883 884 class QUIC_EXPORT_PRIVATE ScopedEncryptionLevelContext { 885 public: 886 ScopedEncryptionLevelContext(QuicConnection* connection, 887 EncryptionLevel level); 888 ~ScopedEncryptionLevelContext(); 889 890 private: 891 QuicConnection* connection_; 892 // Latched current write encryption level on creation of this context. 893 EncryptionLevel latched_encryption_level_; 894 }; 895 writer()896 QuicPacketWriter* writer() { return writer_; } writer()897 const QuicPacketWriter* writer() const { return writer_; } 898 899 // Sends an MTU discovery packet of size |target_mtu|. If the packet is 900 // acknowledged by the peer, the maximum packet size will be increased to 901 // |target_mtu|. 902 void SendMtuDiscoveryPacket(QuicByteCount target_mtu); 903 904 // Sends a connectivity probing packet to |peer_address| with 905 // |probing_writer|. If |probing_writer| is nullptr, will use default 906 // packet writer to write the packet. Returns true if subsequent packets can 907 // be written to the probing writer. If connection is V99, a padded IETF QUIC 908 // PATH_CHALLENGE packet is transmitted; if not V99, a Google QUIC padded PING 909 // packet is transmitted. 910 virtual bool SendConnectivityProbingPacket( 911 QuicPacketWriter* probing_writer, 912 const QuicSocketAddress& peer_address); 913 914 // Sends response to a connectivity probe. Sends either a Padded Ping 915 // or an IETF PATH_RESPONSE based on the version of the connection. 916 // Is the counterpart to SendConnectivityProbingPacket(). 917 // TODO(danzh): remove this method after deprecating 918 // --gfe2_reloadable_flag_quic_send_path_response. 919 virtual void SendConnectivityProbingResponsePacket( 920 const QuicSocketAddress& peer_address); 921 922 // Disable MTU discovery on this connection. 923 void DisableMtuDiscovery(); 924 925 // Sends an MTU discovery packet and updates the MTU discovery alarm. 926 void DiscoverMtu(); 927 928 // Sets the session notifier on the SentPacketManager. 929 void SetSessionNotifier(SessionNotifierInterface* session_notifier); 930 931 // Set data producer in framer. 932 void SetDataProducer(QuicStreamFrameDataProducer* data_producer); 933 934 // Set transmission type of next sending packets. 935 void SetTransmissionType(TransmissionType type); 936 937 // Tries to send |message| and returns the message status. 938 // If |flush| is false, this will return a MESSAGE_STATUS_BLOCKED 939 // when the connection is deemed unwritable. 940 virtual MessageStatus SendMessage(QuicMessageId message_id, 941 QuicMemSliceSpan message, 942 bool flush); 943 944 // Returns the largest payload that will fit into a single MESSAGE frame. 945 // Because overhead can vary during a connection, this method should be 946 // checked for every message. 947 QuicPacketLength GetCurrentLargestMessagePayload() const; 948 // Returns the largest payload that will fit into a single MESSAGE frame at 949 // any point during the connection. This assumes the version and 950 // connection ID lengths do not change. 951 QuicPacketLength GetGuaranteedLargestMessagePayload() const; 952 GetUnackedMapInitialCapacity()953 virtual int GetUnackedMapInitialCapacity() const { 954 return kDefaultUnackedPacketsInitialCapacity; 955 } 956 957 // Returns the id of the cipher last used for decrypting packets. 958 uint32_t cipher_id() const; 959 termination_packets()960 std::vector<std::unique_ptr<QuicEncryptedPacket>>* termination_packets() { 961 return termination_packets_.get(); 962 } 963 964 bool ack_frame_updated() const; 965 helper()966 QuicConnectionHelperInterface* helper() { return helper_; } helper()967 const QuicConnectionHelperInterface* helper() const { return helper_; } alarm_factory()968 QuicAlarmFactory* alarm_factory() { return alarm_factory_; } 969 970 absl::string_view GetCurrentPacket(); 971 framer()972 const QuicFramer& framer() const { return framer_; } 973 packet_creator()974 const QuicPacketCreator& packet_creator() const { return packet_creator_; } 975 encryption_level()976 EncryptionLevel encryption_level() const { return encryption_level_; } last_decrypted_level()977 EncryptionLevel last_decrypted_level() const { 978 return last_decrypted_packet_level_; 979 } 980 last_packet_source_address()981 const QuicSocketAddress& last_packet_source_address() const { 982 return last_packet_source_address_; 983 } 984 fill_up_link_during_probing()985 bool fill_up_link_during_probing() const { 986 return fill_up_link_during_probing_; 987 } set_fill_up_link_during_probing(bool new_value)988 void set_fill_up_link_during_probing(bool new_value) { 989 fill_up_link_during_probing_ = new_value; 990 } 991 992 // This setting may be changed during the crypto handshake in order to 993 // enable/disable padding of different packets in the crypto handshake. 994 // 995 // This setting should never be set to false in public facing endpoints. It 996 // can only be set to false if there is some other mechanism of preventing 997 // amplification attacks, such as ICE (plus its a non-standard quic). set_fully_pad_crypto_handshake_packets(bool new_value)998 void set_fully_pad_crypto_handshake_packets(bool new_value) { 999 packet_creator_.set_fully_pad_crypto_handshake_packets(new_value); 1000 } 1001 fully_pad_during_crypto_handshake()1002 bool fully_pad_during_crypto_handshake() const { 1003 return packet_creator_.fully_pad_crypto_handshake_packets(); 1004 } 1005 1006 size_t min_received_before_ack_decimation() const; 1007 void set_min_received_before_ack_decimation(size_t new_value); 1008 1009 // If |defer| is true, configures the connection to defer sending packets in 1010 // response to an ACK to the SendAlarm. If |defer| is false, packets may be 1011 // sent immediately after receiving an ACK. set_defer_send_in_response_to_packets(bool defer)1012 void set_defer_send_in_response_to_packets(bool defer) { 1013 defer_send_in_response_to_packets_ = defer; 1014 } 1015 1016 // Sets the current per-packet options for the connection. The QuicConnection 1017 // does not take ownership of |options|; |options| must live for as long as 1018 // the QuicConnection is in use. set_per_packet_options(PerPacketOptions * options)1019 void set_per_packet_options(PerPacketOptions* options) { 1020 per_packet_options_ = options; 1021 } 1022 IsPathDegrading()1023 bool IsPathDegrading() const { return is_path_degrading_; } 1024 1025 // Attempts to process any queued undecryptable packets. 1026 void MaybeProcessUndecryptablePackets(); 1027 1028 // Queue a coalesced packet. 1029 void QueueCoalescedPacket(const QuicEncryptedPacket& packet); 1030 1031 // Process previously queued coalesced packets. 1032 void MaybeProcessCoalescedPackets(); 1033 1034 enum PacketContent : uint8_t { 1035 NO_FRAMES_RECEIVED, 1036 // TODO(fkastenholz): Change name when we get rid of padded ping/ 1037 // pre-version-99. 1038 // Also PATH CHALLENGE and PATH RESPONSE. 1039 FIRST_FRAME_IS_PING, 1040 SECOND_FRAME_IS_PADDING, 1041 NOT_PADDED_PING, // Set if the packet is not {PING, PADDING}. 1042 }; 1043 1044 // Whether the handshake completes from this connection's perspective. 1045 bool IsHandshakeComplete() const; 1046 1047 // Whether peer completes handshake. Only used with TLS handshake. 1048 bool IsHandshakeConfirmed() const; 1049 1050 // Returns the largest received packet number sent by peer. 1051 QuicPacketNumber GetLargestReceivedPacket() const; 1052 1053 // Sets the original destination connection ID on the connection. 1054 // This is called by QuicDispatcher when it has replaced the connection ID. 1055 void SetOriginalDestinationConnectionId( 1056 const QuicConnectionId& original_destination_connection_id); 1057 1058 // Returns the original destination connection ID used for this connection. 1059 QuicConnectionId GetOriginalDestinationConnectionId(); 1060 1061 // Called when ACK alarm goes off. Sends ACKs of those packet number spaces 1062 // which have expired ACK timeout. Only used when this connection supports 1063 // multiple packet number spaces. 1064 void SendAllPendingAcks(); 1065 1066 // Returns true if this connection supports multiple packet number spaces. 1067 bool SupportsMultiplePacketNumberSpaces() const; 1068 1069 // For logging purpose. 1070 const QuicAckFrame& ack_frame() const; 1071 1072 // Install encrypter and decrypter for ENCRYPTION_INITIAL using 1073 // |connection_id| as the first client-sent destination connection ID, 1074 // or the one sent after an IETF Retry. 1075 void InstallInitialCrypters(QuicConnectionId connection_id); 1076 1077 // Called when version is considered negotiated. 1078 void OnSuccessfulVersionNegotiation(); 1079 1080 // Called when self migration succeeds after probing. 1081 void OnSuccessfulMigrationAfterProbing(); 1082 1083 // Called for QUIC+TLS versions when we send transport parameters. 1084 void OnTransportParametersSent( 1085 const TransportParameters& transport_parameters) const; 1086 1087 // Called for QUIC+TLS versions when we receive transport parameters. 1088 void OnTransportParametersReceived( 1089 const TransportParameters& transport_parameters) const; 1090 1091 // Called for QUIC+TLS versions when we resume cached transport parameters for 1092 // 0-RTT. 1093 void OnTransportParametersResumed( 1094 const TransportParameters& transport_parameters) const; 1095 1096 // Returns true if ack_alarm_ is set. 1097 bool HasPendingAcks() const; 1098 OnUserAgentIdKnown()1099 void OnUserAgentIdKnown() { sent_packet_manager_.OnUserAgentIdKnown(); } 1100 1101 // Enables Legacy Version Encapsulation using |server_name| as SNI. 1102 // Can only be set if this is a client connection. 1103 void EnableLegacyVersionEncapsulation(const std::string& server_name); 1104 send_path_response()1105 bool send_path_response() const { return send_path_response_; } 1106 1107 // If now is close to idle timeout, returns true and sends a connectivity 1108 // probing packet to test the connection for liveness. Otherwise, returns 1109 // false. 1110 bool MaybeTestLiveness(); 1111 1112 // Send PATH_CHALLENGE using the given path information. If |writer| is the 1113 // default writer, PATH_CHALLENGE can be bundled with other frames, and the 1114 // containing packet can be buffered if the writer is blocked. Otherwise, 1115 // PATH_CHALLENGE will be written in an individual packet and it will be 1116 // dropped if write fails. |data_buffer| will be populated with the payload 1117 // for future validation. 1118 void SendPathChallenge(QuicPathFrameBuffer* data_buffer, 1119 const QuicSocketAddress& self_address, 1120 const QuicSocketAddress& peer_address, 1121 QuicPacketWriter* writer); 1122 can_receive_ack_frequency_frame()1123 bool can_receive_ack_frequency_frame() const { 1124 return can_receive_ack_frequency_frame_; 1125 } 1126 set_can_receive_ack_frequency_frame()1127 void set_can_receive_ack_frequency_frame() { 1128 can_receive_ack_frequency_frame_ = true; 1129 } 1130 check_keys_before_writing()1131 bool check_keys_before_writing() const { return check_keys_before_writing_; } 1132 is_processing_packet()1133 bool is_processing_packet() const { return framer_.is_processing_packet(); } 1134 encrypted_control_frames()1135 bool encrypted_control_frames() const { return encrypted_control_frames_; } 1136 use_encryption_level_context()1137 bool use_encryption_level_context() const { 1138 return use_encryption_level_context_; 1139 } 1140 1141 protected: 1142 // Calls cancel() on all the alarms owned by this connection. 1143 void CancelAllAlarms(); 1144 1145 // Send a packet to the peer, and takes ownership of the packet if the packet 1146 // cannot be written immediately. 1147 virtual void SendOrQueuePacket(SerializedPacket packet); 1148 1149 // Called after a packet is received from a new effective peer address and is 1150 // decrypted. Starts validation of effective peer's address change. Calls 1151 // OnConnectionMigration as soon as the address changed. 1152 void StartEffectivePeerMigration(AddressChangeType type); 1153 1154 // Called when a effective peer address migration is validated. 1155 virtual void OnEffectivePeerMigrationValidated(); 1156 1157 // Get the effective peer address from the packet being processed. For proxied 1158 // connections, effective peer address is the address of the endpoint behind 1159 // the proxy. For non-proxied connections, effective peer address is the same 1160 // as peer address. 1161 // 1162 // Notes for implementations in subclasses: 1163 // - If the connection is not proxied, the overridden method should use the 1164 // base implementation: 1165 // 1166 // return QuicConnection::GetEffectivePeerAddressFromCurrentPacket(); 1167 // 1168 // - If the connection is proxied, the overridden method may return either of 1169 // the following: 1170 // a) The address of the endpoint behind the proxy. The address is used to 1171 // drive effective peer migration. 1172 // b) An uninitialized address, meaning the effective peer address does not 1173 // change. 1174 virtual QuicSocketAddress GetEffectivePeerAddressFromCurrentPacket() const; 1175 1176 // Selects and updates the version of the protocol being used by selecting a 1177 // version from |available_versions| which is also supported. Returns true if 1178 // such a version exists, false otherwise. 1179 bool SelectMutualVersion(const ParsedQuicVersionVector& available_versions); 1180 1181 // Returns the current per-packet options for the connection. per_packet_options()1182 PerPacketOptions* per_packet_options() { return per_packet_options_; } 1183 active_effective_peer_migration_type()1184 AddressChangeType active_effective_peer_migration_type() const { 1185 return active_effective_peer_migration_type_; 1186 } 1187 1188 // Sends a connection close packet to the peer and includes an ACK if the ACK 1189 // is not empty, the |error| is not PACKET_WRITE_ERROR, and it fits. 1190 virtual void SendConnectionClosePacket(QuicErrorCode error, 1191 const std::string& details); 1192 1193 // Returns true if the packet should be discarded and not sent. 1194 virtual bool ShouldDiscardPacket(EncryptionLevel encryption_level); 1195 1196 // Retransmits packets continuously until blocked by the congestion control. 1197 // If there are no packets to retransmit, does not do anything. 1198 void SendProbingRetransmissions(); 1199 1200 // Decides whether to send probing retransmissions, and does so if required. 1201 void MaybeSendProbingRetransmissions(); 1202 1203 // Notify various components(SendPacketManager, Session etc.) that this 1204 // connection has been migrated. 1205 virtual void OnConnectionMigration(AddressChangeType addr_change_type); 1206 1207 // Return whether the packet being processed is a connectivity probing. 1208 // A packet is a connectivity probing if it is a padded ping packet with self 1209 // and/or peer address changes. 1210 bool IsCurrentPacketConnectivityProbing() const; 1211 1212 // Return true iff the writer is blocked, if blocked, call 1213 // visitor_->OnWriteBlocked() to add the connection into the write blocked 1214 // list. 1215 bool HandleWriteBlocked(); 1216 1217 private: 1218 friend class test::QuicConnectionPeer; 1219 1220 using QueuedPacketList = std::list<SerializedPacket>; 1221 1222 // BufferedPacket stores necessary information (encrypted buffer and self/peer 1223 // addresses) of those packets which are serialized but failed to send because 1224 // socket is blocked. From unacked packet map and send algorithm's 1225 // perspective, buffered packets are treated as sent. 1226 struct QUIC_EXPORT_PRIVATE BufferedPacket { 1227 BufferedPacket(const SerializedPacket& packet, 1228 const QuicSocketAddress& self_address, 1229 const QuicSocketAddress& peer_address); 1230 BufferedPacket(char* encrypted_buffer, 1231 QuicPacketLength encrypted_length, 1232 const QuicSocketAddress& self_address, 1233 const QuicSocketAddress& peer_address); 1234 BufferedPacket(const BufferedPacket& other) = delete; 1235 BufferedPacket(const BufferedPacket&& other) = delete; 1236 1237 ~BufferedPacket(); 1238 1239 // encrypted_buffer is owned by buffered packet. 1240 absl::string_view encrypted_buffer; 1241 // Self and peer addresses when the packet is serialized. 1242 const QuicSocketAddress self_address; 1243 const QuicSocketAddress peer_address; 1244 }; 1245 1246 // UndecrytablePacket comprises a undecryptable packet and the its encryption 1247 // level. 1248 struct QUIC_EXPORT_PRIVATE UndecryptablePacket { UndecryptablePacketUndecryptablePacket1249 UndecryptablePacket(const QuicEncryptedPacket& packet, 1250 EncryptionLevel encryption_level) 1251 : packet(packet.Clone()), 1252 encryption_level(encryption_level), 1253 processed(false) {} 1254 1255 std::unique_ptr<QuicEncryptedPacket> packet; 1256 EncryptionLevel encryption_level; 1257 // This gets set to true if 1) connection sucessfully processed the packet 1258 // or 2) connection failed to process the packet and will not try to process 1259 // it later. 1260 // TODO(fayang): Remove this when deprecating 1261 // quic_fix_undecryptable_packets2. 1262 bool processed; 1263 }; 1264 1265 // Notifies the visitor of the close and marks the connection as disconnected. 1266 // Does not send a connection close frame to the peer. It should only be 1267 // called by CloseConnection or OnConnectionCloseFrame, OnPublicResetPacket, 1268 // and OnAuthenticatedIetfStatelessResetPacket. 1269 void TearDownLocalConnectionState(QuicErrorCode error, 1270 const std::string& details, 1271 ConnectionCloseSource source); 1272 void TearDownLocalConnectionState(const QuicConnectionCloseFrame& frame, 1273 ConnectionCloseSource source); 1274 1275 // Writes the given packet to socket, encrypted with packet's 1276 // encryption_level. Returns true on successful write, and false if the writer 1277 // was blocked and the write needs to be tried again. Notifies the 1278 // SentPacketManager when the write is successful and sets 1279 // retransmittable frames to nullptr. 1280 // Saves the connection close packet for later transmission, even if the 1281 // writer is write blocked. 1282 bool WritePacket(SerializedPacket* packet); 1283 1284 // Enforce AEAD Confidentiality limits by iniating key update or closing 1285 // connection if too many packets have been encrypted with the current key. 1286 // Returns true if the connection was closed. Should not be called for 1287 // termination packets. 1288 bool MaybeHandleAeadConfidentialityLimits(const SerializedPacket& packet); 1289 1290 // Flush packets buffered in the writer, if any. 1291 void FlushPackets(); 1292 1293 // Make sure a stop waiting we got from our peer is sane. 1294 // Returns nullptr if the frame is valid or an error string if it was invalid. 1295 const char* ValidateStopWaitingFrame( 1296 const QuicStopWaitingFrame& stop_waiting); 1297 1298 // Sends a version negotiation packet to the peer. 1299 void SendVersionNegotiationPacket(bool ietf_quic, bool has_length_prefix); 1300 1301 // Clears any accumulated frames from the last received packet. 1302 void ClearLastFrames(); 1303 1304 // Deletes and clears any queued packets. 1305 void ClearQueuedPackets(); 1306 1307 // Closes the connection if the sent packet manager is tracking too many 1308 // outstanding packets. 1309 void CloseIfTooManyOutstandingSentPackets(); 1310 1311 // Writes as many queued packets as possible. The connection must not be 1312 // blocked when this is called. 1313 void WriteQueuedPackets(); 1314 1315 // Writes new data if congestion control allows. 1316 void WriteNewData(); 1317 1318 // Queues |packet| in the hopes that it can be decrypted in the 1319 // future, when a new key is installed. 1320 void QueueUndecryptablePacket(const QuicEncryptedPacket& packet, 1321 EncryptionLevel decryption_level); 1322 1323 // Sends any packets which are a response to the last packet, including both 1324 // acks and pending writes if an ack opened the congestion window. 1325 void MaybeSendInResponseToPacket(); 1326 1327 // Gets the least unacked packet number, which is the next packet number to be 1328 // sent if there are no outstanding packets. 1329 QuicPacketNumber GetLeastUnacked() const; 1330 1331 // Sets the ping alarm to the appropriate value, if any. 1332 void SetPingAlarm(); 1333 1334 // Sets the retransmission alarm based on SentPacketManager. 1335 void SetRetransmissionAlarm(); 1336 1337 // Sets the MTU discovery alarm if necessary. 1338 // |sent_packet_number| is the recently sent packet number. 1339 void MaybeSetMtuAlarm(QuicPacketNumber sent_packet_number); 1340 1341 HasRetransmittableData IsRetransmittable(const SerializedPacket& packet); 1342 bool IsTerminationPacket(const SerializedPacket& packet, 1343 QuicErrorCode* error_code); 1344 1345 // Set the size of the packet we are targeting while doing path MTU discovery. 1346 void SetMtuDiscoveryTarget(QuicByteCount target); 1347 1348 // Returns |suggested_max_packet_size| clamped to any limits set by the 1349 // underlying writer, connection, or protocol. 1350 QuicByteCount GetLimitedMaxPacketSize( 1351 QuicByteCount suggested_max_packet_size); 1352 1353 // Do any work which logically would be done in OnPacket but can not be 1354 // safely done until the packet is validated. Returns true if packet can be 1355 // handled, false otherwise. 1356 bool ProcessValidatedPacket(const QuicPacketHeader& header); 1357 1358 // Returns true if received |packet_number| can be processed. Please note, 1359 // this is called after packet got decrypted successfully. 1360 bool ValidateReceivedPacketNumber(QuicPacketNumber packet_number); 1361 1362 // Consider receiving crypto frame on non crypto stream as memory corruption. 1363 bool MaybeConsiderAsMemoryCorruption(const QuicStreamFrame& frame); 1364 1365 // Check if the connection has no outstanding data to send and notify 1366 // congestion controller if it is the case. 1367 void CheckIfApplicationLimited(); 1368 1369 // Sets |current_packet_content_| to |type| if applicable. And 1370 // starts effective peer migration if current packet is confirmed not a 1371 // connectivity probe and |current_effective_peer_migration_type_| indicates 1372 // effective peer address change. 1373 void UpdatePacketContent(QuicFrameType type); 1374 1375 // Called when last received ack frame has been processed. 1376 // |send_stop_waiting| indicates whether a stop waiting needs to be sent. 1377 // |acked_new_packet| is true if a previously-unacked packet was acked. 1378 void PostProcessAfterAckFrame(bool send_stop_waiting, bool acked_new_packet); 1379 1380 // Updates the release time into the future. 1381 void UpdateReleaseTimeIntoFuture(); 1382 1383 // Sends generic path probe packet to the peer. If we are not IETF QUIC, will 1384 // always send a padded ping, regardless of whether this is a request or not. 1385 // TODO(danzh): remove |is_response| after deprecating 1386 // --gfe2_reloadable_flag_quic_send_path_response. 1387 bool SendGenericPathProbePacket(QuicPacketWriter* probing_writer, 1388 const QuicSocketAddress& peer_address, 1389 bool is_response); 1390 1391 // Called when an ACK is about to send. Resets ACK related internal states, 1392 // e.g., cancels ack_alarm_, resets 1393 // num_retransmittable_packets_received_since_last_ack_sent_ etc. 1394 void ResetAckStates(); 1395 1396 // Returns true if the ACK frame should be bundled with ACK-eliciting frame. 1397 bool ShouldBundleRetransmittableFrameWithAck() const; 1398 1399 void PopulateStopWaitingFrame(QuicStopWaitingFrame* stop_waiting); 1400 1401 // Enables multiple packet number spaces support based on handshake protocol 1402 // and flags. 1403 void MaybeEnableMultiplePacketNumberSpacesSupport(); 1404 1405 // Called to update ACK timeout when an retransmittable frame has been parsed. 1406 void MaybeUpdateAckTimeout(); 1407 1408 // Tries to fill coalesced packet with data of higher packet space. 1409 void MaybeCoalescePacketOfHigherSpace(); 1410 1411 // Serialize and send coalesced_packet. Returns false if serialization fails 1412 // or the write causes errors, otherwise, returns true. 1413 bool FlushCoalescedPacket(); 1414 1415 // Returns the encryption level the connection close packet should be sent at, 1416 // which is the highest encryption level that peer can guarantee to process. 1417 EncryptionLevel GetConnectionCloseEncryptionLevel() const; 1418 1419 // Called after an ACK frame is successfully processed to update largest 1420 // received packet number which contains an ACK frame. 1421 void SetLargestReceivedPacketWithAck(QuicPacketNumber new_value); 1422 1423 // Called when new packets have been acknowledged or old keys have been 1424 // discarded. 1425 void OnForwardProgressMade(); 1426 1427 // Returns largest received packet number which contains an ACK frame. 1428 QuicPacketNumber GetLargestReceivedPacketWithAck() const; 1429 1430 // Returns the largest packet number that has been sent. 1431 QuicPacketNumber GetLargestSentPacket() const; 1432 1433 // Returns the largest sent packet number that has been ACKed by peer. 1434 QuicPacketNumber GetLargestAckedPacket() const; 1435 1436 // Whether incoming_connection_ids_ contains connection_id. 1437 bool HasIncomingConnectionId(QuicConnectionId connection_id); 1438 1439 // Whether connection enforces anti-amplification limit. 1440 bool EnforceAntiAmplificationLimit() const; 1441 1442 // Whether connection is limited by amplification factor. 1443 bool LimitedByAmplificationFactor() const; 1444 1445 // Called before sending a packet to get packet send time and to set the 1446 // release time delay in |per_packet_options_|. Return the time when the 1447 // packet is scheduled to be released(a.k.a send time), which is NOW + delay. 1448 // Returns Now() and does not update release time delay if 1449 // |supports_release_time_| is false. 1450 QuicTime CalculatePacketSentTime(); 1451 1452 // If we have a previously validate MTU value, e.g. due to a write error, 1453 // revert to it and disable MTU discovery. 1454 // Return true iff we reverted to a previously validate MTU. 1455 bool MaybeRevertToPreviousMtu(); 1456 1457 QuicTime GetPathMtuReductionDeadline() const; 1458 1459 // Returns path degrading deadline. QuicTime::Zero() means no path degrading 1460 // detection is needed. 1461 QuicTime GetPathDegradingDeadline() const; 1462 1463 // Returns true if path degrading should be detected. 1464 bool ShouldDetectPathDegrading() const; 1465 1466 // Returns network blackhole deadline. QuicTime::Zero() means no blackhole 1467 // detection is needed. 1468 QuicTime GetNetworkBlackholeDeadline() const; 1469 1470 // Returns true if network blackhole should be detected. 1471 bool ShouldDetectBlackhole() const; 1472 1473 // Returns retransmission deadline. 1474 QuicTime GetRetransmissionDeadline() const; 1475 1476 // Validate connection IDs used during the handshake. Closes the connection 1477 // on validation failure. 1478 bool ValidateConfigConnectionIds(const QuicConfig& config); 1479 bool ValidateConfigConnectionIdsOld(const QuicConfig& config); 1480 1481 // Called when ACK alarm goes off. Try to bundle crypto data with ACKs. 1482 void MaybeBundleCryptoDataWithAcks(); 1483 1484 // Returns true if an undecryptable packet of |decryption_level| should be 1485 // buffered (such that connection can try to decrypt it later). 1486 bool ShouldEnqueueUnDecryptablePacket(EncryptionLevel decryption_level, 1487 bool has_decryption_key) const; 1488 1489 // Returns string which contains undecryptable packets information. 1490 std::string UndecryptablePacketsInfo() const; 1491 1492 // Sets the max packet length on the packet creator if needed. 1493 void MaybeUpdatePacketCreatorMaxPacketLengthAndPadding(); 1494 1495 // Sets internal state to enable or disable Legacy Version Encapsulation. 1496 void MaybeActivateLegacyVersionEncapsulation(); 1497 void MaybeDisactivateLegacyVersionEncapsulation(); 1498 1499 // For Google Quic, if the current packet is connectivity probing packet, call 1500 // session OnPacketReceived() which eventually sends connectivity probing 1501 // response on server side. And no-op on client side. And for both Google Quic 1502 // and IETF Quic, start migration if the current packet is a non-probing 1503 // packet. 1504 // TODO(danzh) rename to MaybeRespondToPeerMigration() when Google Quic is 1505 // deprecated. 1506 void MaybeRespondToConnectivityProbingOrMigration(); 1507 1508 // Called in IETF QUIC. Start peer migration if a non-probing frame is 1509 // received and the current packet number is largest received so far. 1510 void MaybeStartIetfPeerMigration(QuicFrameType type); 1511 1512 // Send PATH_RESPONSE to the given peer address. 1513 bool SendPathResponse(const QuicPathFrameBuffer& data_buffer, 1514 QuicSocketAddress peer_address_to_send); 1515 1516 // Update both connection's and packet creator's peer address. 1517 void UpdatePeerAddress(QuicSocketAddress peer_address); 1518 1519 // Send PING at encryption level. 1520 void SendPingAtLevel(EncryptionLevel level); 1521 1522 // Write the given packet with |self_address| and |peer_address| using 1523 // |writer|. 1524 bool WritePacketUsingWriter(std::unique_ptr<SerializedPacket> packet, 1525 QuicPacketWriter* writer, 1526 const QuicSocketAddress& self_address, 1527 const QuicSocketAddress& peer_address, 1528 bool measure_rtt); 1529 QuicFramer framer_; 1530 1531 // Contents received in the current packet, especially used to identify 1532 // whether the current packet is a padded PING packet. 1533 PacketContent current_packet_content_; 1534 // Set to true as soon as the packet currently being processed has been 1535 // detected as a connectivity probing. 1536 // Always false outside the context of ProcessUdpPacket(). 1537 bool is_current_packet_connectivity_probing_; 1538 1539 bool has_path_challenge_in_current_packet_; 1540 1541 // Caches the current effective peer migration type if a effective peer 1542 // migration might be initiated. As soon as the current packet is confirmed 1543 // not a connectivity probe, effective peer migration will start. 1544 AddressChangeType current_effective_peer_migration_type_; 1545 QuicConnectionHelperInterface* helper_; // Not owned. 1546 QuicAlarmFactory* alarm_factory_; // Not owned. 1547 PerPacketOptions* per_packet_options_; // Not owned. 1548 QuicPacketWriter* writer_; // Owned or not depending on |owns_writer_|. 1549 bool owns_writer_; 1550 // Encryption level for new packets. Should only be changed via 1551 // SetDefaultEncryptionLevel(). 1552 EncryptionLevel encryption_level_; 1553 const QuicClock* clock_; 1554 QuicRandom* random_generator_; 1555 1556 QuicConnectionId server_connection_id_; 1557 QuicConnectionId client_connection_id_; 1558 // On the server, the connection ID is set when receiving the first packet. 1559 // This variable ensures we only set it this way once. 1560 bool client_connection_id_is_set_; 1561 // Address on the last successfully processed packet received from the 1562 // direct peer. 1563 QuicSocketAddress self_address_; 1564 QuicSocketAddress peer_address_; 1565 1566 // Other than initialization, do not modify it directly, use 1567 // UpdatePeerAddress() instead. 1568 QuicSocketAddress direct_peer_address_; 1569 // Address of the endpoint behind the proxy if the connection is proxied. 1570 // Otherwise it is the same as |peer_address_|. 1571 // NOTE: Currently |effective_peer_address_| and |peer_address_| are always 1572 // the same(the address of the direct peer), but soon we'll change 1573 // |effective_peer_address_| to be the address of the endpoint behind the 1574 // proxy if the connection is proxied. 1575 QuicSocketAddress effective_peer_address_; 1576 1577 // Records change type when the effective peer initiates migration to a new 1578 // address. Reset to NO_CHANGE after effective peer migration is validated. 1579 AddressChangeType active_effective_peer_migration_type_; 1580 1581 // Records highest sent packet number when effective peer migration is 1582 // started. 1583 QuicPacketNumber highest_packet_sent_before_effective_peer_migration_; 1584 1585 // True if Key Update is supported on this connection. 1586 bool support_key_update_for_connection_; 1587 1588 // Tracks the lowest packet sent in the current key phase. Will be 1589 // uninitialized before the first one-RTT packet has been sent or after a 1590 // key update but before the first packet has been sent. 1591 QuicPacketNumber lowest_packet_sent_in_current_key_phase_; 1592 1593 // Honor the AEAD confidentiality and integrity limits by initiating key 1594 // update (if allowed) and/or closing the connection, as necessary. 1595 bool enable_aead_limits_; 1596 1597 // True if the last packet has gotten far enough in the framer to be 1598 // decrypted. 1599 bool last_packet_decrypted_; 1600 QuicByteCount last_size_; // Size of the last received packet. 1601 // TODO(rch): remove this when b/27221014 is fixed. 1602 const char* current_packet_data_; // UDP payload of packet currently being 1603 // parsed or nullptr. 1604 EncryptionLevel last_decrypted_packet_level_; 1605 QuicPacketHeader last_header_; 1606 bool should_last_packet_instigate_acks_; 1607 1608 // Track some peer state so we can do less bookkeeping 1609 // Largest sequence sent by the peer which had an ack frame (latest ack info). 1610 // Do not read or write directly, use GetLargestReceivedPacketWithAck() and 1611 // SetLargestReceivedPacketWithAck() instead. 1612 QuicPacketNumber largest_seen_packet_with_ack_; 1613 // Largest packet number sent by the peer which had an ACK frame per packet 1614 // number space. Only used when this connection supports multiple packet 1615 // number spaces. 1616 QuicPacketNumber largest_seen_packets_with_ack_[NUM_PACKET_NUMBER_SPACES]; 1617 1618 // Largest packet number sent by the peer which had a stop waiting frame. 1619 QuicPacketNumber largest_seen_packet_with_stop_waiting_; 1620 1621 // Collection of packets which were received before encryption was 1622 // established, but which could not be decrypted. We buffer these on 1623 // the assumption that they could not be processed because they were 1624 // sent with the INITIAL encryption and the CHLO message was lost. 1625 std::deque<UndecryptablePacket> undecryptable_packets_; 1626 1627 // Collection of coalesced packets which were received while processing 1628 // the current packet. 1629 QuicCircularDeque<std::unique_ptr<QuicEncryptedPacket>> 1630 received_coalesced_packets_; 1631 1632 // Maximum number of undecryptable packets the connection will store. 1633 size_t max_undecryptable_packets_; 1634 1635 // Maximum number of tracked packets. 1636 QuicPacketCount max_tracked_packets_; 1637 1638 // Contains the connection close packets if the connection has been closed. 1639 std::unique_ptr<std::vector<std::unique_ptr<QuicEncryptedPacket>>> 1640 termination_packets_; 1641 1642 // Determines whether or not a connection close packet is sent to the peer 1643 // after idle timeout due to lack of network activity. During the handshake, 1644 // a connection close packet is sent, but not after. 1645 ConnectionCloseBehavior idle_timeout_connection_close_behavior_; 1646 1647 // When > 0, close the QUIC connection after this number of RTOs. 1648 size_t num_rtos_for_blackhole_detection_; 1649 1650 // Statistics for this session. 1651 QuicConnectionStats stats_; 1652 1653 UberReceivedPacketManager uber_received_packet_manager_; 1654 1655 // Indicates how many consecutive times an ack has arrived which indicates 1656 // the peer needs to stop waiting for some packets. 1657 // TODO(fayang): remove this when deprecating Q043. 1658 int stop_waiting_count_; 1659 1660 // Indicates the retransmission alarm needs to be set. 1661 bool pending_retransmission_alarm_; 1662 1663 // If true, defer sending data in response to received packets to the 1664 // SendAlarm. 1665 bool defer_send_in_response_to_packets_; 1666 1667 // The timeout for PING. 1668 QuicTime::Delta ping_timeout_; 1669 1670 // Initial timeout for how long the wire can have no retransmittable packets. 1671 QuicTime::Delta initial_retransmittable_on_wire_timeout_; 1672 1673 // Indicates how many retransmittable-on-wire pings have been emitted without 1674 // receiving any new data in between. 1675 int consecutive_retransmittable_on_wire_ping_count_; 1676 1677 // Indicates how many retransmittable-on-wire pings have been emitted. 1678 int retransmittable_on_wire_ping_count_; 1679 1680 // Arena to store class implementations within the QuicConnection. 1681 QuicConnectionArena arena_; 1682 1683 // An alarm that fires when an ACK should be sent to the peer. 1684 QuicArenaScopedPtr<QuicAlarm> ack_alarm_; 1685 // An alarm that fires when a packet needs to be retransmitted. 1686 QuicArenaScopedPtr<QuicAlarm> retransmission_alarm_; 1687 // An alarm that is scheduled when the SentPacketManager requires a delay 1688 // before sending packets and fires when the packet may be sent. 1689 QuicArenaScopedPtr<QuicAlarm> send_alarm_; 1690 // An alarm that fires when a ping should be sent. 1691 QuicArenaScopedPtr<QuicAlarm> ping_alarm_; 1692 // An alarm that fires when an MTU probe should be sent. 1693 QuicArenaScopedPtr<QuicAlarm> mtu_discovery_alarm_; 1694 // An alarm that fires to process undecryptable packets when new decyrption 1695 // keys are available. 1696 QuicArenaScopedPtr<QuicAlarm> process_undecryptable_packets_alarm_; 1697 // An alarm that fires to discard keys for the previous key phase some time 1698 // after a key update has completed. 1699 QuicArenaScopedPtr<QuicAlarm> discard_previous_one_rtt_keys_alarm_; 1700 // Neither visitor is owned by this class. 1701 QuicConnectionVisitorInterface* visitor_; 1702 QuicConnectionDebugVisitor* debug_visitor_; 1703 1704 QuicPacketCreator packet_creator_; 1705 1706 // The time that a packet is received for this connection. Initialized to 1707 // connection creation time. 1708 // This does not indicate the packet was processed. 1709 QuicTime time_of_last_received_packet_; 1710 1711 // Sent packet manager which tracks the status of packets sent by this 1712 // connection and contains the send and receive algorithms to determine when 1713 // to send packets. 1714 QuicSentPacketManager sent_packet_manager_; 1715 1716 // Indicates whether connection version has been negotiated. 1717 // Always true for server connections. 1718 bool version_negotiated_; 1719 1720 // Tracks if the connection was created by the server or the client. 1721 Perspective perspective_; 1722 1723 // True by default. False if we've received or sent an explicit connection 1724 // close. 1725 bool connected_; 1726 1727 // Destination address of the last received packet. 1728 QuicSocketAddress last_packet_destination_address_; 1729 1730 // Source address of the last received packet. 1731 QuicSocketAddress last_packet_source_address_; 1732 1733 // Set to false if the connection should not send truncated connection IDs to 1734 // the peer, even if the peer supports it. 1735 bool can_truncate_connection_ids_; 1736 1737 // If non-empty this contains the set of versions received in a 1738 // version negotiation packet. 1739 ParsedQuicVersionVector server_supported_versions_; 1740 1741 // The number of MTU probes already sent. 1742 size_t mtu_probe_count_; 1743 1744 // The value of |long_term_mtu_| prior to the last successful MTU increase. 1745 // 0 means either 1746 // - MTU discovery has never been enabled, or 1747 // - MTU discovery has been enabled, but the connection got a packet write 1748 // error with a new (successfully probed) MTU, so it reverted 1749 // |long_term_mtu_| to the value before the last increase. 1750 QuicPacketLength previous_validated_mtu_; 1751 // The value of the MTU regularly used by the connection. This is different 1752 // from the value returned by max_packet_size(), as max_packet_size() returns 1753 // the value of the MTU as currently used by the serializer, so if 1754 // serialization of an MTU probe is in progress, those two values will be 1755 // different. 1756 QuicByteCount long_term_mtu_; 1757 1758 // The maximum UDP payload size that our peer has advertised support for. 1759 // Defaults to kDefaultMaxPacketSizeTransportParam until received from peer. 1760 QuicByteCount peer_max_packet_size_; 1761 1762 // The size of the largest packet received from peer. 1763 QuicByteCount largest_received_packet_size_; 1764 1765 // Indicates whether a write error is encountered currently. This is used to 1766 // avoid infinite write errors. 1767 bool write_error_occurred_; 1768 1769 // Indicates not to send or process stop waiting frames. 1770 bool no_stop_waiting_frames_; 1771 1772 // Consecutive number of sent packets which have no retransmittable frames. 1773 size_t consecutive_num_packets_with_no_retransmittable_frames_; 1774 1775 // After this many packets sent without retransmittable frames, an artificial 1776 // retransmittable frame(a WINDOW_UPDATE) will be created to solicit an ack 1777 // from the peer. Default to kMaxConsecutiveNonRetransmittablePackets. 1778 size_t max_consecutive_num_packets_with_no_retransmittable_frames_; 1779 1780 // If true, bundle an ack-eliciting frame with an ACK if the PTO or RTO alarm 1781 // have previously fired. 1782 bool bundle_retransmittable_with_pto_ack_; 1783 1784 // If true, the connection will fill up the pipe with extra data whenever the 1785 // congestion controller needs it in order to make a bandwidth estimate. This 1786 // is useful if the application pesistently underutilizes the link, but still 1787 // relies on having a reasonable bandwidth estimate from the connection, e.g. 1788 // for real time applications. 1789 bool fill_up_link_during_probing_; 1790 1791 // If true, the probing retransmission will not be started again. This is 1792 // used to safeguard against an accidental tail recursion in probing 1793 // retransmission code. 1794 bool probing_retransmission_pending_; 1795 1796 // Indicates whether a stateless reset token has been received from peer. 1797 bool stateless_reset_token_received_; 1798 // Stores received stateless reset token from peer. Used to verify whether a 1799 // packet is a stateless reset packet. 1800 QuicUint128 received_stateless_reset_token_; 1801 1802 // Id of latest sent control frame. 0 if no control frame has been sent. 1803 QuicControlFrameId last_control_frame_id_; 1804 1805 // True if the peer is unreachable on the current path. 1806 bool is_path_degrading_; 1807 1808 // True if an ack frame is being processed. 1809 bool processing_ack_frame_; 1810 1811 // True if the writer supports release timestamp. 1812 bool supports_release_time_; 1813 1814 // Time this connection can release packets into the future. 1815 QuicTime::Delta release_time_into_future_; 1816 1817 // Payload of most recently transmitted IETF QUIC connectivity 1818 // probe packet (the PATH_CHALLENGE payload). This implementation transmits 1819 // only one PATH_CHALLENGE per connectivity probe, so only one 1820 // QuicPathFrameBuffer is needed. 1821 std::unique_ptr<QuicPathFrameBuffer> transmitted_connectivity_probe_payload_; 1822 1823 // Payloads that were received in the most recent probe. This needs to be a 1824 // Deque because the peer might no be using this implementation, and others 1825 // might send a packet with more than one PATH_CHALLENGE, so all need to be 1826 // saved and responded to. 1827 // TODO(danzh) deprecate this field when deprecating 1828 // --quic_send_path_response. 1829 QuicCircularDeque<QuicPathFrameBuffer> received_path_challenge_payloads_; 1830 1831 // Buffer outstanding PATH_CHALLENGEs if socket write is blocked, future 1832 // OnCanWrite will attempt to respond with PATH_RESPONSEs using the retained 1833 // payload and peer addresses. 1834 QuicCircularDeque<std::pair<QuicPathFrameBuffer, QuicSocketAddress>> 1835 pending_path_challenge_payloads_; 1836 1837 // Set of connection IDs that should be accepted as destination on 1838 // received packets. This is conceptually a set but is implemented as a 1839 // vector to improve performance since it is expected to be very small. 1840 std::vector<QuicConnectionId> incoming_connection_ids_; 1841 1842 // When we receive a RETRY packet or some INITIAL packets, we replace 1843 // |server_connection_id_| with the value from that packet and save off the 1844 // original value of |server_connection_id_| into 1845 // |original_destination_connection_id_| for validation. 1846 absl::optional<QuicConnectionId> original_destination_connection_id_; 1847 1848 // After we receive a RETRY packet, |retry_source_connection_id_| contains 1849 // the source connection ID from that packet. 1850 absl::optional<QuicConnectionId> retry_source_connection_id_; 1851 1852 // Indicates whether received RETRY packets should be dropped. 1853 bool drop_incoming_retry_packets_; 1854 1855 // Bytes received before address validation. Only used when 1856 // EnforceAntiAmplificationLimit returns true. 1857 size_t bytes_received_before_address_validation_; 1858 1859 // Bytes sent before address validation. Only used when 1860 // EnforceAntiAmplificationLimit returns true. 1861 size_t bytes_sent_before_address_validation_; 1862 1863 // True if peer address has been validated. Address is considered validated 1864 // when 1) an address token is received and validated, or 2) a HANDSHAKE 1865 // packet has been successfully processed. Only used when 1866 // EnforceAntiAmplificationLimit returns true. 1867 bool address_validated_; 1868 1869 // Used to store content of packets which cannot be sent because of write 1870 // blocked. Packets' encrypted buffers are copied and owned by 1871 // buffered_packets_. From unacked_packet_map (and congestion control)'s 1872 // perspective, those packets are considered sent. 1873 std::list<BufferedPacket> buffered_packets_; 1874 1875 // Used to coalesce packets of different encryption level into the same UDP 1876 // datagram. Connection stops trying to coalesce packets if a forward secure 1877 // packet gets acknowledged. 1878 QuicCoalescedPacket coalesced_packet_; 1879 1880 QuicConnectionMtuDiscoverer mtu_discoverer_; 1881 1882 QuicNetworkBlackholeDetector blackhole_detector_; 1883 1884 QuicIdleNetworkDetector idle_network_detector_; 1885 1886 bool blackhole_detection_disabled_ = false; 1887 1888 // True if this connection supports handshake done frame. 1889 bool support_handshake_done_; 1890 1891 const bool default_enable_5rto_blackhole_detection_ = 1892 GetQuicReloadableFlag(quic_default_enable_5rto_blackhole_detection2); 1893 1894 // Whether the Legacy Version Encapsulation feature is enabled. 1895 bool legacy_version_encapsulation_enabled_ = false; 1896 // Whether we are in the middle of sending a packet using Legacy Version 1897 // Encapsulation. 1898 bool legacy_version_encapsulation_in_progress_ = false; 1899 // SNI to send when using Legacy Version Encapsulation. 1900 std::string legacy_version_encapsulation_sni_; 1901 // True if next packet is intended to consume remaining space in the 1902 // coalescer. 1903 bool fill_coalesced_packet_ = false; 1904 1905 size_t anti_amplification_factor_ = 1906 GetQuicFlag(FLAGS_quic_anti_amplification_factor); 1907 1908 bool start_peer_migration_earlier_ = 1909 GetQuicReloadableFlag(quic_start_peer_migration_earlier); 1910 1911 // latch --gfe2_reloadable_flag_quic_send_path_response and 1912 // --gfe2_reloadable_flag_quic_start_peer_migration_earlier. 1913 bool send_path_response_ = start_peer_migration_earlier_ && 1914 GetQuicReloadableFlag(quic_send_path_response); 1915 // True if AckFrequencyFrame is supported. 1916 bool can_receive_ack_frequency_frame_ = false; 1917 1918 // Indicate whether coalescing is done. 1919 bool coalescing_done_ = false; 1920 1921 // Indicate whether any ENCRYPTION_HANDSHAKE packet has been sent. 1922 bool handshake_packet_sent_ = false; 1923 1924 // Indicate whether to send an AckFrequencyFrame upon handshake completion. 1925 // The AckFrequencyFrame sent will updates client's max_ack_delay, which if 1926 // chosen properly can reduce the CPU and bandwidth usage for ACK frames. 1927 bool send_ack_frequency_on_handshake_completion_ = false; 1928 1929 // Indicate whether AckFrequency frame has been sent. 1930 bool ack_frequency_sent_ = false; 1931 1932 const bool fix_missing_initial_keys_ = 1933 GetQuicReloadableFlag(quic_fix_missing_initial_keys2); 1934 1935 const bool fix_out_of_order_sending_ = 1936 GetQuicReloadableFlag(quic_fix_out_of_order_sending2); 1937 1938 const bool check_keys_before_writing_ = 1939 GetQuicReloadableFlag(quic_check_keys_before_writing); 1940 1941 const bool encrypted_control_frames_; 1942 1943 const bool use_encryption_level_context_; 1944 }; 1945 1946 } // namespace quic 1947 1948 #endif // QUICHE_QUIC_CORE_QUIC_CONNECTION_H_ 1949