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 // A QuicSession, which demuxes a single connection to individual streams. 6 7 #ifndef QUICHE_QUIC_CORE_QUIC_SESSION_H_ 8 #define QUICHE_QUIC_CORE_QUIC_SESSION_H_ 9 10 #include <cstddef> 11 #include <cstdint> 12 #include <map> 13 #include <memory> 14 #include <string> 15 #include <vector> 16 17 #include "absl/container/flat_hash_map.h" 18 #include "absl/strings/string_view.h" 19 #include "absl/types/optional.h" 20 #include "absl/types/span.h" 21 #include "quiche/quic/core/crypto/tls_connection.h" 22 #include "quiche/quic/core/frames/quic_ack_frequency_frame.h" 23 #include "quiche/quic/core/frames/quic_stop_sending_frame.h" 24 #include "quiche/quic/core/frames/quic_window_update_frame.h" 25 #include "quiche/quic/core/handshaker_delegate_interface.h" 26 #include "quiche/quic/core/legacy_quic_stream_id_manager.h" 27 #include "quiche/quic/core/proto/cached_network_parameters_proto.h" 28 #include "quiche/quic/core/quic_connection.h" 29 #include "quiche/quic/core/quic_control_frame_manager.h" 30 #include "quiche/quic/core/quic_crypto_stream.h" 31 #include "quiche/quic/core/quic_datagram_queue.h" 32 #include "quiche/quic/core/quic_error_codes.h" 33 #include "quiche/quic/core/quic_packet_creator.h" 34 #include "quiche/quic/core/quic_packets.h" 35 #include "quiche/quic/core/quic_path_validator.h" 36 #include "quiche/quic/core/quic_stream.h" 37 #include "quiche/quic/core/quic_stream_frame_data_producer.h" 38 #include "quiche/quic/core/quic_stream_priority.h" 39 #include "quiche/quic/core/quic_types.h" 40 #include "quiche/quic/core/quic_write_blocked_list.h" 41 #include "quiche/quic/core/session_notifier_interface.h" 42 #include "quiche/quic/core/stream_delegate_interface.h" 43 #include "quiche/quic/core/uber_quic_stream_id_manager.h" 44 #include "quiche/quic/platform/api/quic_export.h" 45 #include "quiche/quic/platform/api/quic_flags.h" 46 #include "quiche/quic/platform/api/quic_socket_address.h" 47 #include "quiche/common/platform/api/quiche_mem_slice.h" 48 #include "quiche/common/quiche_linked_hash_map.h" 49 50 namespace quic { 51 52 class QuicCryptoStream; 53 class QuicFlowController; 54 class QuicStream; 55 class QuicStreamIdManager; 56 57 namespace test { 58 class QuicSessionPeer; 59 } // namespace test 60 61 class QUIC_EXPORT_PRIVATE QuicSession 62 : public QuicConnectionVisitorInterface, 63 public SessionNotifierInterface, 64 public QuicStreamFrameDataProducer, 65 public QuicStreamIdManager::DelegateInterface, 66 public HandshakerDelegateInterface, 67 public StreamDelegateInterface, 68 public QuicControlFrameManager::DelegateInterface { 69 public: 70 // An interface from the session to the entity owning the session. 71 // This lets the session notify its owner when the connection 72 // is closed, blocked, etc. 73 // TODO(danzh): split this visitor to separate visitors for client and server 74 // respectively as not all methods in this class are interesting to both 75 // perspectives. 76 class QUIC_EXPORT_PRIVATE Visitor { 77 public: ~Visitor()78 virtual ~Visitor() {} 79 80 // Called when the connection is closed after the streams have been closed. 81 virtual void OnConnectionClosed(QuicConnectionId server_connection_id, 82 QuicErrorCode error, 83 const std::string& error_details, 84 ConnectionCloseSource source) = 0; 85 86 // Called when the session has become write blocked. 87 virtual void OnWriteBlocked(QuicBlockedWriterInterface* blocked_writer) = 0; 88 89 // Called when the session receives reset on a stream from the peer. 90 virtual void OnRstStreamReceived(const QuicRstStreamFrame& frame) = 0; 91 92 // Called when the session receives a STOP_SENDING for a stream from the 93 // peer. 94 virtual void OnStopSendingReceived(const QuicStopSendingFrame& frame) = 0; 95 96 // Called when on whether a NewConnectionId frame can been sent. 97 virtual bool TryAddNewConnectionId( 98 const QuicConnectionId& server_connection_id, 99 const QuicConnectionId& new_connection_id) = 0; 100 101 // Called when a ConnectionId has been retired. 102 virtual void OnConnectionIdRetired( 103 const QuicConnectionId& server_connection_id) = 0; 104 105 virtual void OnServerPreferredAddressAvailable( 106 const QuicSocketAddress& /*server_preferred_address*/) = 0; 107 }; 108 109 // Does not take ownership of |connection| or |visitor|. 110 QuicSession(QuicConnection* connection, Visitor* owner, 111 const QuicConfig& config, 112 const ParsedQuicVersionVector& supported_versions, 113 QuicStreamCount num_expected_unidirectional_static_streams); 114 QuicSession(QuicConnection* connection, Visitor* owner, 115 const QuicConfig& config, 116 const ParsedQuicVersionVector& supported_versions, 117 QuicStreamCount num_expected_unidirectional_static_streams, 118 std::unique_ptr<QuicDatagramQueue::Observer> datagram_observer); 119 QuicSession(const QuicSession&) = delete; 120 QuicSession& operator=(const QuicSession&) = delete; 121 122 ~QuicSession() override; 123 124 virtual void Initialize(); 125 126 // Return the reserved crypto stream as a constant pointer. 127 virtual const QuicCryptoStream* GetCryptoStream() const = 0; 128 129 // QuicConnectionVisitorInterface methods: 130 void OnStreamFrame(const QuicStreamFrame& frame) override; 131 void OnCryptoFrame(const QuicCryptoFrame& frame) override; 132 void OnRstStream(const QuicRstStreamFrame& frame) override; 133 void OnGoAway(const QuicGoAwayFrame& frame) override; 134 void OnMessageReceived(absl::string_view message) override; 135 void OnHandshakeDoneReceived() override; 136 void OnNewTokenReceived(absl::string_view token) override; 137 void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; 138 void OnBlockedFrame(const QuicBlockedFrame& frame) override; 139 void OnConnectionClosed(const QuicConnectionCloseFrame& frame, 140 ConnectionCloseSource source) override; 141 void OnWriteBlocked() override; 142 void OnSuccessfulVersionNegotiation( 143 const ParsedQuicVersion& version) override; 144 void OnPacketReceived(const QuicSocketAddress& self_address, 145 const QuicSocketAddress& peer_address, 146 bool is_connectivity_probe) override; 147 void OnCanWrite() override; OnCongestionWindowChange(QuicTime)148 void OnCongestionWindowChange(QuicTime /*now*/) override {} OnConnectionMigration(AddressChangeType)149 void OnConnectionMigration(AddressChangeType /*type*/) override {} 150 // Adds a connection level WINDOW_UPDATE frame. 151 void OnAckNeedsRetransmittableFrame() override; 152 void SendAckFrequency(const QuicAckFrequencyFrame& frame) override; 153 void SendNewConnectionId(const QuicNewConnectionIdFrame& frame) override; 154 void SendRetireConnectionId(uint64_t sequence_number) override; 155 // Returns true if server_connection_id can be issued. If returns true, 156 // |visitor_| may establish a mapping from |server_connection_id| to this 157 // session, if that's not desired, 158 // OnServerConnectionIdRetired(server_connection_id) can be used to remove the 159 // mapping. 160 bool MaybeReserveConnectionId( 161 const QuicConnectionId& server_connection_id) override; 162 void OnServerConnectionIdRetired( 163 const QuicConnectionId& server_connection_id) override; 164 bool WillingAndAbleToWrite() const override; 165 std::string GetStreamsInfoForLogging() const override; 166 void OnPathDegrading() override; 167 void OnForwardProgressMadeAfterPathDegrading() override; 168 bool AllowSelfAddressChange() const override; 169 HandshakeState GetHandshakeState() const override; 170 bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; 171 bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; 172 void OnStopSendingFrame(const QuicStopSendingFrame& frame) override; 173 void OnPacketDecrypted(EncryptionLevel level) override; 174 void OnOneRttPacketAcknowledged() override; 175 void OnHandshakePacketSent() override; OnKeyUpdate(KeyUpdateReason)176 void OnKeyUpdate(KeyUpdateReason /*reason*/) override {} 177 std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() 178 override; 179 std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; BeforeConnectionCloseSent()180 void BeforeConnectionCloseSent() override {} 181 bool ValidateToken(absl::string_view token) override; 182 bool MaybeSendAddressToken() override; OnBandwidthUpdateTimeout()183 void OnBandwidthUpdateTimeout() override {} CreateContextForMultiPortPath()184 std::unique_ptr<QuicPathValidationContext> CreateContextForMultiPortPath() 185 override { 186 return nullptr; 187 } MigrateToMultiPortPath(std::unique_ptr<QuicPathValidationContext>)188 void MigrateToMultiPortPath( 189 std::unique_ptr<QuicPathValidationContext> /*context*/) override {} 190 void OnServerPreferredAddressAvailable( 191 const QuicSocketAddress& /*server_preferred_address*/) override; 192 193 // QuicStreamFrameDataProducer 194 WriteStreamDataResult WriteStreamData(QuicStreamId id, 195 QuicStreamOffset offset, 196 QuicByteCount data_length, 197 QuicDataWriter* writer) override; 198 bool WriteCryptoData(EncryptionLevel level, QuicStreamOffset offset, 199 QuicByteCount data_length, 200 QuicDataWriter* writer) override; 201 202 // SessionNotifierInterface methods: 203 bool OnFrameAcked(const QuicFrame& frame, QuicTime::Delta ack_delay_time, 204 QuicTime receive_timestamp) override; 205 void OnStreamFrameRetransmitted(const QuicStreamFrame& frame) override; 206 void OnFrameLost(const QuicFrame& frame) override; 207 bool RetransmitFrames(const QuicFrames& frames, 208 TransmissionType type) override; 209 bool IsFrameOutstanding(const QuicFrame& frame) const override; 210 bool HasUnackedCryptoData() const override; 211 bool HasUnackedStreamData() const override; 212 213 void SendMaxStreams(QuicStreamCount stream_count, 214 bool unidirectional) override; 215 // The default implementation does nothing. Subclasses should override if 216 // for example they queue up stream requests. OnCanCreateNewOutgoingStream(bool)217 virtual void OnCanCreateNewOutgoingStream(bool /*unidirectional*/) {} 218 219 // Called on every incoming packet. Passes |packet| through to |connection_|. 220 virtual void ProcessUdpPacket(const QuicSocketAddress& self_address, 221 const QuicSocketAddress& peer_address, 222 const QuicReceivedPacket& packet); 223 224 // Sends |message| as a QUIC DATAGRAM frame (QUIC MESSAGE frame in gQUIC). 225 // See <https://datatracker.ietf.org/doc/html/draft-ietf-quic-datagram> for 226 // more details. 227 // 228 // Returns a MessageResult struct which includes the status of the write 229 // operation and a message ID. The message ID (not sent on the wire) can be 230 // used to track the message; OnMessageAcked and OnMessageLost are called when 231 // a specific message gets acked or lost. 232 // 233 // If the write operation is successful, all of the slices in |message| are 234 // consumed, leaving them empty. If MESSAGE_STATUS_INTERNAL_ERROR is 235 // returned, the slices in question may or may not be consumed; it is no 236 // longer safe to access those. For all other status codes, |message| is kept 237 // intact. 238 // 239 // Note that SendMessage will fail with status = MESSAGE_STATUS_BLOCKED 240 // if the connection is congestion control blocked or the underlying socket is 241 // write blocked. In this case the caller can retry sending message again when 242 // connection becomes available, for example after getting OnCanWrite() 243 // callback. 244 // 245 // SendMessage flushes the current packet even it is not full; if the 246 // application needs to bundle other data in the same packet, consider using 247 // QuicConnection::ScopedPacketFlusher around the relevant write operations. 248 MessageResult SendMessage(absl::Span<quiche::QuicheMemSlice> message); 249 250 // Same as above SendMessage, except caller can specify if the given |message| 251 // should be flushed even if the underlying connection is deemed unwritable. 252 MessageResult SendMessage(absl::Span<quiche::QuicheMemSlice> message, 253 bool flush); 254 255 // Single-slice version of SendMessage(). Unlike the version above, this 256 // version always takes ownership of the slice. 257 MessageResult SendMessage(quiche::QuicheMemSlice message); 258 259 // Called when message with |message_id| gets acked. 260 virtual void OnMessageAcked(QuicMessageId message_id, 261 QuicTime receive_timestamp); 262 263 // Called when message with |message_id| is considered as lost. 264 virtual void OnMessageLost(QuicMessageId message_id); 265 266 // QuicControlFrameManager::DelegateInterface 267 // Close the connection on error. 268 void OnControlFrameManagerError(QuicErrorCode error_code, 269 std::string error_details) override; 270 // Called by control frame manager when it wants to write control frames to 271 // the peer. Returns true if |frame| is consumed, false otherwise. The frame 272 // will be sent in specified transmission |type|. 273 bool WriteControlFrame(const QuicFrame& frame, 274 TransmissionType type) override; 275 276 // Called to send RST_STREAM (and STOP_SENDING) and close stream. If stream 277 // |id| does not exist, just send RST_STREAM (and STOP_SENDING). 278 virtual void ResetStream(QuicStreamId id, QuicRstStreamErrorCode error); 279 280 // Called when the session wants to go away and not accept any new streams. 281 virtual void SendGoAway(QuicErrorCode error_code, const std::string& reason); 282 283 // Sends a BLOCKED frame. 284 virtual void SendBlocked(QuicStreamId id, QuicStreamOffset byte_offset); 285 286 // Sends a WINDOW_UPDATE frame. 287 virtual void SendWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset); 288 289 // Called by stream |stream_id| when it gets closed. 290 virtual void OnStreamClosed(QuicStreamId stream_id); 291 292 // Returns true if outgoing packets will be encrypted, even if the server 293 // hasn't confirmed the handshake yet. 294 virtual bool IsEncryptionEstablished() const; 295 296 // Returns true if 1RTT keys are available. 297 bool OneRttKeysAvailable() const; 298 299 // Called by the QuicCryptoStream when a new QuicConfig has been negotiated. 300 virtual void OnConfigNegotiated(); 301 302 // Called by the TLS handshaker when ALPS data is received. 303 // Returns an error message if an error has occurred, or nullopt otherwise. 304 virtual absl::optional<std::string> OnAlpsData(const uint8_t* alps_data, 305 size_t alps_length); 306 307 // From HandshakerDelegateInterface 308 bool OnNewDecryptionKeyAvailable(EncryptionLevel level, 309 std::unique_ptr<QuicDecrypter> decrypter, 310 bool set_alternative_decrypter, 311 bool latch_once_used) override; 312 void OnNewEncryptionKeyAvailable( 313 EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) override; 314 void SetDefaultEncryptionLevel(EncryptionLevel level) override; 315 void OnTlsHandshakeComplete() override; 316 void DiscardOldDecryptionKey(EncryptionLevel level) override; 317 void DiscardOldEncryptionKey(EncryptionLevel level) override; 318 void NeuterUnencryptedData() override; 319 void NeuterHandshakeData() override; 320 void OnZeroRttRejected(int reason) override; 321 bool FillTransportParameters(TransportParameters* params) override; 322 QuicErrorCode ProcessTransportParameters(const TransportParameters& params, 323 bool is_resumption, 324 std::string* error_details) override; 325 void OnHandshakeCallbackDone() override; 326 bool PacketFlusherAttached() const override; parsed_version()327 ParsedQuicVersion parsed_version() const override { return version(); } 328 329 // Implement StreamDelegateInterface. 330 void OnStreamError(QuicErrorCode error_code, 331 std::string error_details) override; 332 void OnStreamError(QuicErrorCode error_code, 333 QuicIetfTransportErrorCodes ietf_error, 334 std::string error_details) override; 335 // Sets priority in the write blocked list. 336 void RegisterStreamPriority(QuicStreamId id, bool is_static, 337 const QuicStreamPriority& priority) override; 338 // Clears priority from the write blocked list. 339 void UnregisterStreamPriority(QuicStreamId id) override; 340 // Updates priority on the write blocked list. 341 void UpdateStreamPriority(QuicStreamId id, 342 const QuicStreamPriority& new_priority) override; 343 344 // Called by streams when they want to write data to the peer. 345 // Returns a pair with the number of bytes consumed from data, and a boolean 346 // indicating if the fin bit was consumed. This does not indicate the data 347 // has been sent on the wire: it may have been turned into a packet and queued 348 // if the socket was unexpectedly blocked. 349 QuicConsumedData WritevData(QuicStreamId id, size_t write_length, 350 QuicStreamOffset offset, StreamSendingState state, 351 TransmissionType type, 352 EncryptionLevel level) override; 353 354 size_t SendCryptoData(EncryptionLevel level, size_t write_length, 355 QuicStreamOffset offset, 356 TransmissionType type) override; 357 358 // Called by the QuicCryptoStream when a handshake message is sent. 359 virtual void OnCryptoHandshakeMessageSent( 360 const CryptoHandshakeMessage& message); 361 362 // Called by the QuicCryptoStream when a handshake message is received. 363 virtual void OnCryptoHandshakeMessageReceived( 364 const CryptoHandshakeMessage& message); 365 366 // Returns mutable config for this session. Returned config is owned 367 // by QuicSession. config()368 QuicConfig* config() { return &config_; } config()369 const QuicConfig* config() const { return &config_; } 370 371 // Returns true if the stream existed previously and has been closed. 372 // Returns false if the stream is still active or if the stream has 373 // not yet been created. 374 bool IsClosedStream(QuicStreamId id); 375 connection()376 QuicConnection* connection() { return connection_; } connection()377 const QuicConnection* connection() const { return connection_; } peer_address()378 const QuicSocketAddress& peer_address() const { 379 return connection_->peer_address(); 380 } self_address()381 const QuicSocketAddress& self_address() const { 382 return connection_->self_address(); 383 } connection_id()384 QuicConnectionId connection_id() const { 385 return connection_->connection_id(); 386 } 387 388 // Returns the number of currently open streams, excluding static streams, and 389 // never counting unfinished streams. 390 size_t GetNumActiveStreams() const; 391 392 // Add the stream to the session's write-blocked list because it is blocked by 393 // connection-level flow control but not by its own stream-level flow control. 394 // The stream will be given a chance to write when a connection-level 395 // WINDOW_UPDATE arrives. 396 virtual void MarkConnectionLevelWriteBlocked(QuicStreamId id); 397 398 // Called to close zombie stream |id|. 399 void MaybeCloseZombieStream(QuicStreamId id); 400 401 // Returns true if there is pending handshake data in the crypto stream. 402 // TODO(ianswett): Make this private or remove. 403 bool HasPendingHandshake() const; 404 405 // Returns true if the session has data to be sent, either queued in the 406 // connection, or in a write-blocked stream. 407 bool HasDataToWrite() const; 408 409 // Initiates a path validation on the path described in the given context, 410 // asynchronously calls |result_delegate| upon success or failure. 411 // The initiator should extend QuicPathValidationContext to provide the writer 412 // and ResultDelegate to react upon the validation result. 413 // Example implementations of these for path validation for connection 414 // migration could be: 415 // class QUIC_EXPORT_PRIVATE PathMigrationContext 416 // : public QuicPathValidationContext { 417 // public: 418 // PathMigrationContext(std::unique_ptr<QuicPacketWriter> writer, 419 // const QuicSocketAddress& self_address, 420 // const QuicSocketAddress& peer_address) 421 // : QuicPathValidationContext(self_address, peer_address), 422 // alternative_writer_(std::move(writer)) {} 423 // 424 // QuicPacketWriter* WriterToUse() override { 425 // return alternative_writer_.get(); 426 // } 427 // 428 // QuicPacketWriter* ReleaseWriter() { 429 // return alternative_writer_.release(); 430 // } 431 // 432 // private: 433 // std::unique_ptr<QuicPacketWriter> alternative_writer_; 434 // }; 435 // 436 // class PathMigrationValidationResultDelegate 437 // : public QuicPathValidator::ResultDelegate { 438 // public: 439 // PathMigrationValidationResultDelegate(QuicConnection* connection) 440 // : QuicPathValidator::ResultDelegate(), connection_(connection) {} 441 // 442 // void OnPathValidationSuccess( 443 // std::unique_ptr<QuicPathValidationContext> context) override { 444 // // Do some work to prepare for migration. 445 // // ... 446 // 447 // // Actually migrate to the validated path. 448 // auto migration_context = std::unique_ptr<PathMigrationContext>( 449 // static_cast<PathMigrationContext*>(context.release())); 450 // connection_->MigratePath(migration_context->self_address(), 451 // migration_context->peer_address(), 452 // migration_context->ReleaseWriter(), 453 // /*owns_writer=*/true); 454 // 455 // // Post-migration actions 456 // // ... 457 // } 458 // 459 // void OnPathValidationFailure( 460 // std::unique_ptr<QuicPathValidationContext> /*context*/) override { 461 // // Handle validation failure. 462 // } 463 // 464 // private: 465 // QuicConnection* connection_; 466 // }; 467 void ValidatePath( 468 std::unique_ptr<QuicPathValidationContext> context, 469 std::unique_ptr<QuicPathValidator::ResultDelegate> result_delegate, 470 PathValidationReason reason); 471 472 // Return true if there is a path being validated. 473 bool HasPendingPathValidation() const; 474 475 // Switch to the path described in |context| without validating the path. 476 bool MigratePath(const QuicSocketAddress& self_address, 477 const QuicSocketAddress& peer_address, 478 QuicPacketWriter* writer, bool owns_writer); 479 480 // Returns the largest payload that will fit into a single MESSAGE frame. 481 // Because overhead can vary during a connection, this method should be 482 // checked for every message. 483 QuicPacketLength GetCurrentLargestMessagePayload() const; 484 485 // Returns the largest payload that will fit into a single MESSAGE frame at 486 // any point during the connection. This assumes the version and 487 // connection ID lengths do not change. 488 QuicPacketLength GetGuaranteedLargestMessagePayload() const; 489 transport_goaway_sent()490 bool transport_goaway_sent() const { return transport_goaway_sent_; } 491 transport_goaway_received()492 bool transport_goaway_received() const { return transport_goaway_received_; } 493 494 // Returns the Google QUIC error code error()495 QuicErrorCode error() const { return on_closed_frame_.quic_error_code; } error_details()496 const std::string& error_details() const { 497 return on_closed_frame_.error_details; 498 } transport_close_frame_type()499 uint64_t transport_close_frame_type() const { 500 return on_closed_frame_.transport_close_frame_type; 501 } close_type()502 QuicConnectionCloseType close_type() const { 503 return on_closed_frame_.close_type; 504 } 505 perspective()506 Perspective perspective() const { return perspective_; } 507 flow_controller()508 QuicFlowController* flow_controller() { return &flow_controller_; } 509 510 // Returns true if connection is flow controller blocked. 511 bool IsConnectionFlowControlBlocked() const; 512 513 // Returns true if any stream is flow controller blocked. 514 bool IsStreamFlowControlBlocked(); 515 516 size_t max_open_incoming_bidirectional_streams() const; 517 size_t max_open_incoming_unidirectional_streams() const; 518 519 size_t MaxAvailableBidirectionalStreams() const; 520 size_t MaxAvailableUnidirectionalStreams() const; 521 522 // Returns existing stream with id = |stream_id|. If no 523 // such stream exists, and |stream_id| is a peer-created stream id, 524 // then a new stream is created and returned. In all other cases, nullptr is 525 // returned. 526 // Caller does not own the returned stream. 527 QuicStream* GetOrCreateStream(const QuicStreamId stream_id); 528 529 // Mark a stream as draining. 530 void StreamDraining(QuicStreamId id, bool unidirectional); 531 532 // Returns true if this stream should yield writes to another blocked stream. 533 virtual bool ShouldYield(QuicStreamId stream_id); 534 535 // Clean up closed_streams_. 536 void CleanUpClosedStreams(); 537 supported_versions()538 const ParsedQuicVersionVector& supported_versions() const { 539 return supported_versions_; 540 } 541 542 QuicStreamId next_outgoing_bidirectional_stream_id() const; 543 QuicStreamId next_outgoing_unidirectional_stream_id() const; 544 545 // Return true if given stream is peer initiated. 546 bool IsIncomingStream(QuicStreamId id) const; 547 548 // Record errors when a connection is closed at the server side, should only 549 // be called from server's perspective. 550 // Noop if |error| is QUIC_NO_ERROR. 551 static void RecordConnectionCloseAtServer(QuicErrorCode error, 552 ConnectionCloseSource source); 553 transport_version()554 QuicTransportVersion transport_version() const { 555 return connection_->transport_version(); 556 } 557 version()558 ParsedQuicVersion version() const { return connection_->version(); } 559 is_configured()560 bool is_configured() const { return is_configured_; } 561 562 // Called to neuter crypto data of encryption |level|. 563 void NeuterCryptoDataOfEncryptionLevel(EncryptionLevel level); 564 565 // Returns the ALPN values to negotiate on this session. GetAlpnsToOffer()566 virtual std::vector<std::string> GetAlpnsToOffer() const { 567 // TODO(vasilvv): this currently sets HTTP/3 by default. Switch all 568 // non-HTTP applications to appropriate ALPNs. 569 return std::vector<std::string>({AlpnForVersion(connection()->version())}); 570 } 571 572 // Provided a list of ALPNs offered by the client, selects an ALPN from the 573 // list, or alpns.end() if none of the ALPNs are acceptable. 574 virtual std::vector<absl::string_view>::const_iterator SelectAlpn( 575 const std::vector<absl::string_view>& alpns) const; 576 577 // Called when the ALPN of the connection is established for a connection that 578 // uses TLS handshake. 579 virtual void OnAlpnSelected(absl::string_view alpn); 580 581 // Called on clients by the crypto handshaker to provide application state 582 // necessary for sending application data in 0-RTT. The state provided here is 583 // the same state that was provided to the crypto handshaker in 584 // QuicCryptoStream::SetServerApplicationStateForResumption on a previous 585 // connection. Application protocols that require state to be carried over 586 // from the previous connection to support 0-RTT data must implement this 587 // method to ingest this state. For example, an HTTP/3 QuicSession would 588 // implement this function to process the remembered server SETTINGS and apply 589 // those SETTINGS to 0-RTT data. This function returns true if the application 590 // state has been successfully processed, and false if there was an error 591 // processing the cached state and the connection should be closed. ResumeApplicationState(ApplicationState *)592 virtual bool ResumeApplicationState(ApplicationState* /*cached_state*/) { 593 return true; 594 } 595 596 // Does actual work of sending RESET_STREAM, if the stream type allows. 597 // Also informs the connection so that pending stream frames can be flushed. 598 virtual void MaybeSendRstStreamFrame(QuicStreamId id, 599 QuicResetStreamError error, 600 QuicStreamOffset bytes_written); 601 602 // Sends a STOP_SENDING frame if the stream type allows. 603 virtual void MaybeSendStopSendingFrame(QuicStreamId id, 604 QuicResetStreamError error); 605 606 // Returns the encryption level to send application data. 607 EncryptionLevel GetEncryptionLevelToSendApplicationData() const; 608 user_agent_id()609 const absl::optional<std::string> user_agent_id() const { 610 return user_agent_id_; 611 } 612 613 // TODO(wub): remove saving user-agent to QuicSession. SetUserAgentId(std::string user_agent_id)614 void SetUserAgentId(std::string user_agent_id) { 615 user_agent_id_ = std::move(user_agent_id); 616 connection()->OnUserAgentIdKnown(user_agent_id_.value()); 617 } 618 SetSourceAddressTokenToSend(absl::string_view token)619 void SetSourceAddressTokenToSend(absl::string_view token) { 620 connection()->SetSourceAddressTokenToSend(token); 621 } 622 GetClock()623 const QuicClock* GetClock() const { 624 return connection()->helper()->GetClock(); 625 } 626 liveness_testing_in_progress()627 bool liveness_testing_in_progress() const { 628 return liveness_testing_in_progress_; 629 } 630 GetSSLConfig()631 virtual QuicSSLConfig GetSSLConfig() const { return QuicSSLConfig(); } 632 633 // Try converting all pending streams to normal streams. 634 void ProcessAllPendingStreams(); 635 client_original_supported_versions()636 const ParsedQuicVersionVector& client_original_supported_versions() const { 637 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); 638 return client_original_supported_versions_; 639 } set_client_original_supported_versions(const ParsedQuicVersionVector & client_original_supported_versions)640 void set_client_original_supported_versions( 641 const ParsedQuicVersionVector& client_original_supported_versions) { 642 QUICHE_DCHECK_EQ(perspective_, Perspective::IS_CLIENT); 643 client_original_supported_versions_ = client_original_supported_versions; 644 } 645 646 // Controls whether the default datagram queue used by the session actually 647 // queues the datagram. If set to true, the datagrams in the default queue 648 // will be forcefully flushed, potentially bypassing congestion control and 649 // other limitations. SetForceFlushForDefaultQueue(bool force_flush)650 void SetForceFlushForDefaultQueue(bool force_flush) { 651 datagram_queue_.SetForceFlush(force_flush); 652 } 653 654 // Find stream with |id|, returns nullptr if the stream does not exist or 655 // closed. static streams and zombie streams are not considered active 656 // streams. 657 QuicStream* GetActiveStream(QuicStreamId id) const; 658 659 // Returns the priority type used by the streams in the session. priority_type()660 QuicPriorityType priority_type() const { return QuicPriorityType::kHttp; } 661 662 protected: 663 using StreamMap = 664 absl::flat_hash_map<QuicStreamId, std::unique_ptr<QuicStream>>; 665 666 using PendingStreamMap = 667 absl::flat_hash_map<QuicStreamId, std::unique_ptr<PendingStream>>; 668 669 using ClosedStreams = std::vector<std::unique_ptr<QuicStream>>; 670 671 using ZombieStreamMap = 672 absl::flat_hash_map<QuicStreamId, std::unique_ptr<QuicStream>>; 673 674 std::string on_closed_frame_string() const; 675 676 // Creates a new stream to handle a peer-initiated stream. 677 // Caller does not own the returned stream. 678 // Returns nullptr and does error handling if the stream can not be created. 679 virtual QuicStream* CreateIncomingStream(QuicStreamId id) = 0; 680 virtual QuicStream* CreateIncomingStream(PendingStream* pending) = 0; 681 682 // Return the reserved crypto stream. 683 virtual QuicCryptoStream* GetMutableCryptoStream() = 0; 684 685 // Adds |stream| to the stream map. 686 virtual void ActivateStream(std::unique_ptr<QuicStream> stream); 687 688 // Set transmission type of next sending packets. 689 void SetTransmissionType(TransmissionType type); 690 691 // Returns the stream ID for a new outgoing bidirectional/unidirectional 692 // stream, and increments the underlying counter. 693 QuicStreamId GetNextOutgoingBidirectionalStreamId(); 694 QuicStreamId GetNextOutgoingUnidirectionalStreamId(); 695 696 // Indicates whether the next outgoing bidirectional/unidirectional stream ID 697 // can be allocated or not. The test for version-99/IETF QUIC is whether it 698 // will exceed the maximum-stream-id or not. For non-version-99 (Google) QUIC 699 // it checks whether the next stream would exceed the limit on the number of 700 // open streams. 701 bool CanOpenNextOutgoingBidirectionalStream(); 702 bool CanOpenNextOutgoingUnidirectionalStream(); 703 704 // Returns the maximum bidirectional streams parameter sent with the handshake 705 // as a transport parameter, or in the most recent MAX_STREAMS frame. 706 QuicStreamCount GetAdvertisedMaxIncomingBidirectionalStreams() const; 707 708 // When a stream is closed locally, it may not yet know how many bytes the 709 // peer sent on that stream. 710 // When this data arrives (via stream frame w. FIN, trailing headers, or RST) 711 // this method is called, and correctly updates the connection level flow 712 // controller. 713 virtual void OnFinalByteOffsetReceived(QuicStreamId id, 714 QuicStreamOffset final_byte_offset); 715 716 // Returns true if a frame with the given type and id can be prcoessed by a 717 // PendingStream. However, the frame will always be processed by a QuicStream 718 // if one exists with the given stream_id. UsesPendingStreamForFrame(QuicFrameType,QuicStreamId)719 virtual bool UsesPendingStreamForFrame(QuicFrameType /*type*/, 720 QuicStreamId /*stream_id*/) const { 721 return false; 722 } 723 724 // Returns true if a pending stream should be converted to a real stream after 725 // a corresponding STREAM_FRAME is received. ShouldProcessPendingStreamImmediately()726 virtual bool ShouldProcessPendingStreamImmediately() const { return true; } 727 GetSpdyPriorityofStream(QuicStreamId stream_id)728 spdy::SpdyPriority GetSpdyPriorityofStream(QuicStreamId stream_id) const { 729 return write_blocked_streams_->GetPriorityOfStream(stream_id) 730 .http() 731 .urgency; 732 } 733 pending_streams_size()734 size_t pending_streams_size() const { return pending_stream_map_.size(); } 735 closed_streams()736 ClosedStreams* closed_streams() { return &closed_streams_; } 737 738 void set_largest_peer_created_stream_id( 739 QuicStreamId largest_peer_created_stream_id); 740 write_blocked_streams()741 QuicWriteBlockedListInterface* write_blocked_streams() { 742 return write_blocked_streams_.get(); 743 } 744 745 // Returns true if the stream is still active. 746 bool IsOpenStream(QuicStreamId id); 747 748 // Returns true if the stream is a static stream. 749 bool IsStaticStream(QuicStreamId id) const; 750 751 // Close connection when receive a frame for a locally-created nonexistent 752 // stream. 753 // Prerequisite: IsClosedStream(stream_id) == false 754 // Server session might need to override this method to allow server push 755 // stream to be promised before creating an active stream. 756 virtual void HandleFrameOnNonexistentOutgoingStream(QuicStreamId stream_id); 757 758 virtual bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId stream_id); 759 760 void InsertLocallyClosedStreamsHighestOffset(const QuicStreamId id, 761 QuicStreamOffset offset); 762 // If stream is a locally closed stream, this RST will update FIN offset. 763 // Otherwise stream is a preserved stream and the behavior of it depends on 764 // derived class's own implementation. 765 virtual void HandleRstOnValidNonexistentStream( 766 const QuicRstStreamFrame& frame); 767 768 // Returns a stateless reset token which will be included in the public reset 769 // packet. 770 virtual StatelessResetToken GetStatelessResetToken() const; 771 control_frame_manager()772 QuicControlFrameManager& control_frame_manager() { 773 return control_frame_manager_; 774 } 775 stream_id_manager()776 const LegacyQuicStreamIdManager& stream_id_manager() const { 777 return stream_id_manager_; 778 } 779 datagram_queue()780 QuicDatagramQueue* datagram_queue() { return &datagram_queue_; } 781 num_static_streams()782 size_t num_static_streams() const { return num_static_streams_; } 783 num_zombie_streams()784 size_t num_zombie_streams() const { return num_zombie_streams_; } 785 was_zero_rtt_rejected()786 bool was_zero_rtt_rejected() const { return was_zero_rtt_rejected_; } 787 num_outgoing_draining_streams()788 size_t num_outgoing_draining_streams() const { 789 return num_outgoing_draining_streams_; 790 } 791 num_draining_streams()792 size_t num_draining_streams() const { return num_draining_streams_; } 793 794 // Processes the stream type information of |pending| depending on 795 // different kinds of sessions' own rules. If the pending stream has been 796 // converted to a normal stream, returns a pointer to the new stream; 797 // otherwise, returns nullptr. ProcessPendingStream(PendingStream *)798 virtual QuicStream* ProcessPendingStream(PendingStream* /*pending*/) { 799 return nullptr; 800 } 801 802 // Called by applications to perform |action| on active streams. 803 // Stream iteration will be stopped if action returns false. 804 void PerformActionOnActiveStreams(std::function<bool(QuicStream*)> action); 805 void PerformActionOnActiveStreams( 806 std::function<bool(QuicStream*)> action) const; 807 808 // Return the largest peer created stream id depending on directionality 809 // indicated by |unidirectional|. 810 QuicStreamId GetLargestPeerCreatedStreamId(bool unidirectional) const; 811 812 // Deletes the connection and sets it to nullptr, so calling it mulitiple 813 // times is safe. 814 void DeleteConnection(); 815 816 // Call SetPriority() on stream id |id| and return true if stream is active. 817 bool MaybeSetStreamPriority(QuicStreamId stream_id, 818 const QuicStreamPriority& priority); 819 SetLossDetectionTuner(std::unique_ptr<LossDetectionTunerInterface> tuner)820 void SetLossDetectionTuner( 821 std::unique_ptr<LossDetectionTunerInterface> tuner) { 822 connection()->SetLossDetectionTuner(std::move(tuner)); 823 } 824 ietf_streamid_manager()825 const UberQuicStreamIdManager& ietf_streamid_manager() const { 826 QUICHE_DCHECK(VersionHasIetfQuicFrames(transport_version())); 827 return ietf_streamid_manager_; 828 } 829 830 // Only called at a server session. Generate a CachedNetworkParameters that 831 // can be sent to the client as part of the address token, based on the latest 832 // bandwidth/rtt information. If return absl::nullopt, address token will not 833 // contain the CachedNetworkParameters. 834 virtual absl::optional<CachedNetworkParameters> GenerateCachedNetworkParameters()835 GenerateCachedNetworkParameters() const { 836 return absl::nullopt; 837 } 838 839 private: 840 friend class test::QuicSessionPeer; 841 842 // Called in OnConfigNegotiated when we receive a new stream level flow 843 // control window in a negotiated config. Closes the connection if invalid. 844 void OnNewStreamFlowControlWindow(QuicStreamOffset new_window); 845 846 // Called in OnConfigNegotiated when we receive a new unidirectional stream 847 // flow control window in a negotiated config. 848 void OnNewStreamUnidirectionalFlowControlWindow(QuicStreamOffset new_window); 849 850 // Called in OnConfigNegotiated when we receive a new outgoing bidirectional 851 // stream flow control window in a negotiated config. 852 void OnNewStreamOutgoingBidirectionalFlowControlWindow( 853 QuicStreamOffset new_window); 854 855 // Called in OnConfigNegotiated when we receive a new incoming bidirectional 856 // stream flow control window in a negotiated config. 857 void OnNewStreamIncomingBidirectionalFlowControlWindow( 858 QuicStreamOffset new_window); 859 860 // Called in OnConfigNegotiated when we receive a new connection level flow 861 // control window in a negotiated config. Closes the connection if invalid. 862 void OnNewSessionFlowControlWindow(QuicStreamOffset new_window); 863 864 // Debug helper for |OnCanWrite()|, check that OnStreamWrite() makes 865 // forward progress. Returns false if busy loop detected. 866 bool CheckStreamNotBusyLooping(QuicStream* stream, 867 uint64_t previous_bytes_written, 868 bool previous_fin_sent); 869 870 // Debug helper for OnCanWrite. Check that after QuicStream::OnCanWrite(), 871 // if stream has buffered data and is not stream level flow control blocked, 872 // it has to be in the write blocked list. 873 bool CheckStreamWriteBlocked(QuicStream* stream) const; 874 875 // Called in OnConfigNegotiated for Finch trials to measure performance of 876 // starting with larger flow control receive windows. 877 void AdjustInitialFlowControlWindows(size_t stream_window); 878 879 // Find stream with |id|, returns nullptr if the stream does not exist or 880 // closed. 881 QuicStream* GetStream(QuicStreamId id) const; 882 883 // Can return NULL, e.g., if the stream has been closed before. 884 PendingStream* GetOrCreatePendingStream(QuicStreamId stream_id); 885 886 // Let streams and control frame managers retransmit lost data, returns true 887 // if all lost data is retransmitted. Returns false otherwise. 888 bool RetransmitLostData(); 889 890 // Returns true if stream data should be written. 891 bool CanWriteStreamData() const; 892 893 // Closes the pending stream |stream_id| before it has been created. 894 void ClosePendingStream(QuicStreamId stream_id); 895 896 // Whether the frame with given type and id should be feed to a pending 897 // stream. 898 bool ShouldProcessFrameByPendingStream(QuicFrameType type, 899 QuicStreamId id) const; 900 901 // Process the pending stream if possible. 902 void MaybeProcessPendingStream(PendingStream* pending); 903 904 // Creates or gets pending stream, feeds it with |frame|, and returns the 905 // pending stream. Can return NULL, e.g., if the stream ID is invalid. 906 PendingStream* PendingStreamOnStreamFrame(const QuicStreamFrame& frame); 907 908 // Creates or gets pending strea, feed it with |frame|, and closes the pending 909 // stream. 910 void PendingStreamOnRstStream(const QuicRstStreamFrame& frame); 911 912 // Creates or gets pending stream, feeds it with |frame|, and records the 913 // max_data in the pending stream. 914 void PendingStreamOnWindowUpdateFrame(const QuicWindowUpdateFrame& frame); 915 916 // Creates or gets pending stream, feeds it with |frame|, and records the 917 // ietf_error_code in the pending stream. 918 void PendingStreamOnStopSendingFrame(const QuicStopSendingFrame& frame); 919 920 // Keep track of highest received byte offset of locally closed streams, while 921 // waiting for a definitive final highest offset from the peer. 922 absl::flat_hash_map<QuicStreamId, QuicStreamOffset> 923 locally_closed_streams_highest_offset_; 924 925 QuicConnection* connection_; 926 927 // Store perspective on QuicSession during the constructor as it may be needed 928 // during our destructor when connection_ may have already been destroyed. 929 Perspective perspective_; 930 931 // May be null. 932 Visitor* visitor_; 933 934 // A list of streams which need to write more data. Stream register 935 // themselves in their constructor, and unregisterm themselves in their 936 // destructors, so the write blocked list must outlive all streams. 937 std::unique_ptr<QuicWriteBlockedList> write_blocked_streams_; 938 939 ClosedStreams closed_streams_; 940 941 QuicConfig config_; 942 943 // Map from StreamId to pointers to streams. Owns the streams. 944 StreamMap stream_map_; 945 946 // Map from StreamId to PendingStreams for peer-created unidirectional streams 947 // which are waiting for the first byte of payload to arrive. 948 PendingStreamMap pending_stream_map_; 949 950 // TODO(fayang): Consider moving LegacyQuicStreamIdManager into 951 // UberQuicStreamIdManager. 952 // Manages stream IDs for Google QUIC. 953 LegacyQuicStreamIdManager stream_id_manager_; 954 955 // Manages stream IDs for version99/IETF QUIC 956 UberQuicStreamIdManager ietf_streamid_manager_; 957 958 // A counter for streams which have sent and received FIN but waiting for 959 // application to consume data. 960 size_t num_draining_streams_; 961 962 // A counter for self initiated streams which have sent and received FIN but 963 // waiting for application to consume data. 964 size_t num_outgoing_draining_streams_; 965 966 // A counter for static streams which are in stream_map_. 967 size_t num_static_streams_; 968 969 // A counter for streams which have done reading and writing, but are waiting 970 // for acks. 971 size_t num_zombie_streams_; 972 973 // Received information for a connection close. 974 QuicConnectionCloseFrame on_closed_frame_; 975 absl::optional<ConnectionCloseSource> source_; 976 977 // Used for connection-level flow control. 978 QuicFlowController flow_controller_; 979 980 // The stream id which was last popped in OnCanWrite, or 0, if not under the 981 // call stack of OnCanWrite. 982 QuicStreamId currently_writing_stream_id_; 983 984 // Whether a transport layer GOAWAY frame has been sent. 985 // Such a frame only exists in Google QUIC, therefore |transport_goaway_sent_| 986 // is always false when using IETF QUIC. 987 bool transport_goaway_sent_; 988 989 // Whether a transport layer GOAWAY frame has been received. 990 // Such a frame only exists in Google QUIC, therefore 991 // |transport_goaway_received_| is always false when using IETF QUIC. 992 bool transport_goaway_received_; 993 994 QuicControlFrameManager control_frame_manager_; 995 996 // Id of latest successfully sent message. 997 QuicMessageId last_message_id_; 998 999 // The buffer used to queue the DATAGRAM frames. 1000 QuicDatagramQueue datagram_queue_; 1001 1002 // TODO(fayang): switch to linked_hash_set when chromium supports it. The bool 1003 // is not used here. 1004 // List of streams with pending retransmissions. 1005 quiche::QuicheLinkedHashMap<QuicStreamId, bool> 1006 streams_with_pending_retransmission_; 1007 1008 // Clean up closed_streams_ when this alarm fires. 1009 std::unique_ptr<QuicAlarm> closed_streams_clean_up_alarm_; 1010 1011 // Supported version list used by the crypto handshake only. Please note, this 1012 // list may be a superset of the connection framer's supported versions. 1013 ParsedQuicVersionVector supported_versions_; 1014 1015 // Only non-empty on the client after receiving a version negotiation packet, 1016 // contains the configured versions from the original session before version 1017 // negotiation was received. 1018 ParsedQuicVersionVector client_original_supported_versions_; 1019 1020 absl::optional<std::string> user_agent_id_; 1021 1022 // Initialized to false. Set to true when the session has been properly 1023 // configured and is ready for general operation. 1024 bool is_configured_; 1025 1026 // Whether the session has received a 0-RTT rejection (QUIC+TLS only). 1027 bool was_zero_rtt_rejected_; 1028 1029 // This indicates a liveness testing is in progress, and push back the 1030 // creation of new outgoing bidirectional streams. 1031 bool liveness_testing_in_progress_; 1032 }; 1033 1034 } // namespace quic 1035 1036 #endif // QUICHE_QUIC_CORE_QUIC_SESSION_H_ 1037