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/strings/string_view.h" 18 #include "absl/types/optional.h" 19 #include "net/third_party/quiche/src/quic/core/frames/quic_ack_frequency_frame.h" 20 #include "net/third_party/quiche/src/quic/core/handshaker_delegate_interface.h" 21 #include "net/third_party/quiche/src/quic/core/legacy_quic_stream_id_manager.h" 22 #include "net/third_party/quiche/src/quic/core/quic_connection.h" 23 #include "net/third_party/quiche/src/quic/core/quic_control_frame_manager.h" 24 #include "net/third_party/quiche/src/quic/core/quic_crypto_stream.h" 25 #include "net/third_party/quiche/src/quic/core/quic_datagram_queue.h" 26 #include "net/third_party/quiche/src/quic/core/quic_error_codes.h" 27 #include "net/third_party/quiche/src/quic/core/quic_packet_creator.h" 28 #include "net/third_party/quiche/src/quic/core/quic_packets.h" 29 #include "net/third_party/quiche/src/quic/core/quic_stream.h" 30 #include "net/third_party/quiche/src/quic/core/quic_stream_frame_data_producer.h" 31 #include "net/third_party/quiche/src/quic/core/quic_types.h" 32 #include "net/third_party/quiche/src/quic/core/quic_write_blocked_list.h" 33 #include "net/third_party/quiche/src/quic/core/session_notifier_interface.h" 34 #include "net/third_party/quiche/src/quic/core/stream_delegate_interface.h" 35 #include "net/third_party/quiche/src/quic/core/uber_quic_stream_id_manager.h" 36 #include "net/third_party/quiche/src/quic/platform/api/quic_containers.h" 37 #include "net/third_party/quiche/src/quic/platform/api/quic_export.h" 38 #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" 39 #include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h" 40 41 namespace quic { 42 43 class QuicCryptoStream; 44 class QuicFlowController; 45 class QuicStream; 46 class QuicStreamIdManager; 47 48 namespace test { 49 class QuicSessionPeer; 50 } // namespace test 51 52 class QUIC_EXPORT_PRIVATE QuicSession 53 : public QuicConnectionVisitorInterface, 54 public SessionNotifierInterface, 55 public QuicStreamFrameDataProducer, 56 public QuicStreamIdManager::DelegateInterface, 57 public HandshakerDelegateInterface, 58 public StreamDelegateInterface, 59 public QuicControlFrameManager::DelegateInterface { 60 public: 61 // An interface from the session to the entity owning the session. 62 // This lets the session notify its owner (the Dispatcher) when the connection 63 // is closed, blocked, or added/removed from the time-wait list. 64 class QUIC_EXPORT_PRIVATE Visitor { 65 public: ~Visitor()66 virtual ~Visitor() {} 67 68 // Called when the connection is closed after the streams have been closed. 69 virtual void OnConnectionClosed(QuicConnectionId server_connection_id, 70 QuicErrorCode error, 71 const std::string& error_details, 72 ConnectionCloseSource source) = 0; 73 74 // Called when the session has become write blocked. 75 virtual void OnWriteBlocked(QuicBlockedWriterInterface* blocked_writer) = 0; 76 77 // Called when the session receives reset on a stream from the peer. 78 virtual void OnRstStreamReceived(const QuicRstStreamFrame& frame) = 0; 79 80 // Called when the session receives a STOP_SENDING for a stream from the 81 // peer. 82 virtual void OnStopSendingReceived(const QuicStopSendingFrame& frame) = 0; 83 }; 84 85 // Does not take ownership of |connection| or |visitor|. 86 QuicSession(QuicConnection* connection, 87 Visitor* owner, 88 const QuicConfig& config, 89 const ParsedQuicVersionVector& supported_versions, 90 QuicStreamCount num_expected_unidirectional_static_streams); 91 QuicSession(const QuicSession&) = delete; 92 QuicSession& operator=(const QuicSession&) = delete; 93 94 ~QuicSession() override; 95 96 virtual void Initialize(); 97 98 // QuicConnectionVisitorInterface methods: 99 void OnStreamFrame(const QuicStreamFrame& frame) override; 100 void OnCryptoFrame(const QuicCryptoFrame& frame) override; 101 void OnRstStream(const QuicRstStreamFrame& frame) override; 102 void OnGoAway(const QuicGoAwayFrame& frame) override; 103 void OnMessageReceived(absl::string_view message) override; 104 void OnHandshakeDoneReceived() override; 105 void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override; 106 void OnBlockedFrame(const QuicBlockedFrame& frame) override; 107 void OnConnectionClosed(const QuicConnectionCloseFrame& frame, 108 ConnectionCloseSource source) override; 109 void OnWriteBlocked() override; 110 void OnSuccessfulVersionNegotiation( 111 const ParsedQuicVersion& version) override; 112 void OnPacketReceived(const QuicSocketAddress& self_address, 113 const QuicSocketAddress& peer_address, 114 bool is_connectivity_probe) override; 115 void OnCanWrite() override; 116 bool SendProbingData() override; ValidateStatelessReset(const quic::QuicSocketAddress &,const quic::QuicSocketAddress &)117 bool ValidateStatelessReset( 118 const quic::QuicSocketAddress& /*self_address*/, 119 const quic::QuicSocketAddress& /*peer_address*/) override { 120 return true; 121 } OnCongestionWindowChange(QuicTime)122 void OnCongestionWindowChange(QuicTime /*now*/) override {} OnConnectionMigration(AddressChangeType)123 void OnConnectionMigration(AddressChangeType /*type*/) override {} 124 // Adds a connection level WINDOW_UPDATE frame. 125 void OnAckNeedsRetransmittableFrame() override; 126 void SendPing() override; 127 void SendAckFrequency(const QuicAckFrequencyFrame& frame) override; 128 bool WillingAndAbleToWrite() const override; 129 std::string GetStreamsInfoForLogging() const override; 130 void OnPathDegrading() override; 131 void OnForwardProgressMadeAfterPathDegrading() override; 132 bool AllowSelfAddressChange() const override; 133 HandshakeState GetHandshakeState() const override; 134 bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override; 135 bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override; 136 void OnStopSendingFrame(const QuicStopSendingFrame& frame) override; 137 void OnPacketDecrypted(EncryptionLevel level) override; 138 void OnOneRttPacketAcknowledged() override; 139 void OnHandshakePacketSent() override; OnKeyUpdate(KeyUpdateReason)140 void OnKeyUpdate(KeyUpdateReason /*reason*/) override {} 141 std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter() 142 override; 143 std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override; BeforeConnectionCloseSent()144 void BeforeConnectionCloseSent() override {} 145 146 // QuicStreamFrameDataProducer 147 WriteStreamDataResult WriteStreamData(QuicStreamId id, 148 QuicStreamOffset offset, 149 QuicByteCount data_length, 150 QuicDataWriter* writer) override; 151 bool WriteCryptoData(EncryptionLevel level, 152 QuicStreamOffset offset, 153 QuicByteCount data_length, 154 QuicDataWriter* writer) override; 155 156 // SessionNotifierInterface methods: 157 bool OnFrameAcked(const QuicFrame& frame, 158 QuicTime::Delta ack_delay_time, 159 QuicTime receive_timestamp) override; 160 void OnStreamFrameRetransmitted(const QuicStreamFrame& frame) override; 161 void OnFrameLost(const QuicFrame& frame) override; 162 void RetransmitFrames(const QuicFrames& frames, 163 TransmissionType type) override; 164 bool IsFrameOutstanding(const QuicFrame& frame) const override; 165 bool HasUnackedCryptoData() const override; 166 bool HasUnackedStreamData() const override; 167 168 void SendMaxStreams(QuicStreamCount stream_count, 169 bool unidirectional) override; 170 // The default implementation does nothing. Subclasses should override if 171 // for example they queue up stream requests. OnCanCreateNewOutgoingStream(bool)172 virtual void OnCanCreateNewOutgoingStream(bool /*unidirectional*/) {} 173 174 // Called on every incoming packet. Passes |packet| through to |connection_|. 175 virtual void ProcessUdpPacket(const QuicSocketAddress& self_address, 176 const QuicSocketAddress& peer_address, 177 const QuicReceivedPacket& packet); 178 179 // Called by application to send |message|. Data copy can be avoided if 180 // |message| is provided in reference counted memory. 181 // Please note, |message| provided in reference counted memory would be moved 182 // internally when message is successfully sent. Thereafter, it would be 183 // undefined behavior if callers try to access the slices through their own 184 // copy of the span object. 185 // Returns the message result which includes the message status and message ID 186 // (valid if the write succeeds). SendMessage flushes a message packet even it 187 // is not full. If the application wants to bundle other data in the same 188 // packet, please consider adding a packet flusher around the SendMessage 189 // and/or WritevData calls. 190 // 191 // OnMessageAcked and OnMessageLost are called when a particular message gets 192 // acked or lost. 193 // 194 // Note that SendMessage will fail with status = MESSAGE_STATUS_BLOCKED 195 // if connection is congestion control blocked or underlying socket is write 196 // blocked. In this case the caller can retry sending message again when 197 // connection becomes available, for example after getting OnCanWrite() 198 // callback. 199 MessageResult SendMessage(QuicMemSliceSpan message); 200 201 // Same as above SendMessage, except caller can specify if the given |message| 202 // should be flushed even if the underlying connection is deemed unwritable. 203 MessageResult SendMessage(QuicMemSliceSpan message, bool flush); 204 205 // Called when message with |message_id| gets acked. 206 virtual void OnMessageAcked(QuicMessageId message_id, 207 QuicTime receive_timestamp); 208 209 // Called when message with |message_id| is considered as lost. 210 virtual void OnMessageLost(QuicMessageId message_id); 211 212 // QuicControlFrameManager::DelegateInterface 213 // Close the connection on error. 214 void OnControlFrameManagerError(QuicErrorCode error_code, 215 std::string error_details) override; 216 // Called by control frame manager when it wants to write control frames to 217 // the peer. Returns true if |frame| is consumed, false otherwise. The frame 218 // will be sent in specified transmission |type|. 219 bool WriteControlFrame(const QuicFrame& frame, 220 TransmissionType type) override; 221 222 // Called by stream to send RST_STREAM (and STOP_SENDING in IETF QUIC). 223 // if |send_rst_only|, STOP_SENDING will not be sent for IETF QUIC. 224 // TODO(b/170233449): Delete this method when flag quic_split_up_send_rst_2 is 225 // deprecated. 226 virtual void SendRstStream(QuicStreamId id, 227 QuicRstStreamErrorCode error, 228 QuicStreamOffset bytes_written, 229 bool send_rst_only); 230 231 // Called to send RST_STREAM (and STOP_SENDING) and close stream. If stream 232 // |id| does not exist, just send RST_STREAM (and STOP_SENDING). 233 virtual void ResetStream(QuicStreamId id, QuicRstStreamErrorCode error); 234 235 // Called when the session wants to go away and not accept any new streams. 236 virtual void SendGoAway(QuicErrorCode error_code, const std::string& reason); 237 238 // Sends a BLOCKED frame. 239 virtual void SendBlocked(QuicStreamId id); 240 241 // Sends a WINDOW_UPDATE frame. 242 virtual void SendWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset); 243 244 // Create and transmit a STOP_SENDING frame 245 virtual void SendStopSending(QuicRstStreamErrorCode code, 246 QuicStreamId stream_id); 247 248 // Called by stream |stream_id| when it gets closed. 249 virtual void OnStreamClosed(QuicStreamId stream_id); 250 251 // Returns true if outgoing packets will be encrypted, even if the server 252 // hasn't confirmed the handshake yet. 253 virtual bool IsEncryptionEstablished() const; 254 255 // Returns true if 1RTT keys are available. 256 bool OneRttKeysAvailable() const; 257 258 // Called by the QuicCryptoStream when a new QuicConfig has been negotiated. 259 virtual void OnConfigNegotiated(); 260 261 // From HandshakerDelegateInterface 262 bool OnNewDecryptionKeyAvailable(EncryptionLevel level, 263 std::unique_ptr<QuicDecrypter> decrypter, 264 bool set_alternative_decrypter, 265 bool latch_once_used) override; 266 void OnNewEncryptionKeyAvailable( 267 EncryptionLevel level, 268 std::unique_ptr<QuicEncrypter> encrypter) override; 269 void SetDefaultEncryptionLevel(EncryptionLevel level) override; 270 void OnTlsHandshakeComplete() override; 271 void DiscardOldDecryptionKey(EncryptionLevel level) override; 272 void DiscardOldEncryptionKey(EncryptionLevel level) override; 273 void NeuterUnencryptedData() override; 274 void NeuterHandshakeData() override; 275 void OnZeroRttRejected(int reason) override; 276 bool FillTransportParameters(TransportParameters* params) override; 277 QuicErrorCode ProcessTransportParameters(const TransportParameters& params, 278 bool is_resumption, 279 std::string* error_details) override; 280 void OnHandshakeCallbackDone() override; 281 282 // Implement StreamDelegateInterface. 283 void OnStreamError(QuicErrorCode error_code, 284 std::string error_details) override; 285 // Sets priority in the write blocked list. 286 void RegisterStreamPriority( 287 QuicStreamId id, 288 bool is_static, 289 const spdy::SpdyStreamPrecedence& precedence) override; 290 // Clears priority from the write blocked list. 291 void UnregisterStreamPriority(QuicStreamId id, bool is_static) override; 292 // Updates priority on the write blocked list. 293 void UpdateStreamPriority( 294 QuicStreamId id, 295 const spdy::SpdyStreamPrecedence& new_precedence) override; 296 297 // Called by streams when they want to write data to the peer. 298 // Returns a pair with the number of bytes consumed from data, and a boolean 299 // indicating if the fin bit was consumed. This does not indicate the data 300 // has been sent on the wire: it may have been turned into a packet and queued 301 // if the socket was unexpectedly blocked. 302 QuicConsumedData WritevData(QuicStreamId id, 303 size_t write_length, 304 QuicStreamOffset offset, 305 StreamSendingState state, 306 TransmissionType type, 307 absl::optional<EncryptionLevel> level) override; 308 309 size_t SendCryptoData(EncryptionLevel level, 310 size_t write_length, 311 QuicStreamOffset offset, 312 TransmissionType type) override; 313 314 // Called by the QuicCryptoStream when a handshake message is sent. 315 virtual void OnCryptoHandshakeMessageSent( 316 const CryptoHandshakeMessage& message); 317 318 // Called by the QuicCryptoStream when a handshake message is received. 319 virtual void OnCryptoHandshakeMessageReceived( 320 const CryptoHandshakeMessage& message); 321 322 // Returns mutable config for this session. Returned config is owned 323 // by QuicSession. 324 QuicConfig* config(); 325 326 // Returns true if the stream existed previously and has been closed. 327 // Returns false if the stream is still active or if the stream has 328 // not yet been created. 329 bool IsClosedStream(QuicStreamId id); 330 connection()331 QuicConnection* connection() { return connection_; } connection()332 const QuicConnection* connection() const { return connection_; } peer_address()333 const QuicSocketAddress& peer_address() const { 334 return connection_->peer_address(); 335 } self_address()336 const QuicSocketAddress& self_address() const { 337 return connection_->self_address(); 338 } connection_id()339 QuicConnectionId connection_id() const { 340 return connection_->connection_id(); 341 } 342 split_up_send_rst()343 bool split_up_send_rst() const { return split_up_send_rst_; } 344 345 // Returns the number of currently open streams, excluding static streams, and 346 // never counting unfinished streams. 347 size_t GetNumActiveStreams() const; 348 349 // Add the stream to the session's write-blocked list because it is blocked by 350 // connection-level flow control but not by its own stream-level flow control. 351 // The stream will be given a chance to write when a connection-level 352 // WINDOW_UPDATE arrives. 353 virtual void MarkConnectionLevelWriteBlocked(QuicStreamId id); 354 355 // Called to close zombie stream |id|. 356 void MaybeCloseZombieStream(QuicStreamId id); 357 358 // Returns true if there is pending handshake data in the crypto stream. 359 // TODO(ianswett): Make this private or remove. 360 bool HasPendingHandshake() const; 361 362 // Returns true if the session has data to be sent, either queued in the 363 // connection, or in a write-blocked stream. 364 bool HasDataToWrite() const; 365 366 // Returns the largest payload that will fit into a single MESSAGE frame. 367 // Because overhead can vary during a connection, this method should be 368 // checked for every message. 369 QuicPacketLength GetCurrentLargestMessagePayload() const; 370 371 // Returns the largest payload that will fit into a single MESSAGE frame at 372 // any point during the connection. This assumes the version and 373 // connection ID lengths do not change. 374 QuicPacketLength GetGuaranteedLargestMessagePayload() const; 375 transport_goaway_sent()376 bool transport_goaway_sent() const { return transport_goaway_sent_; } 377 transport_goaway_received()378 bool transport_goaway_received() const { return transport_goaway_received_; } 379 380 // Returns the Google QUIC error code error()381 QuicErrorCode error() const { return on_closed_frame_.quic_error_code; } error_details()382 const std::string& error_details() const { 383 return on_closed_frame_.error_details; 384 } transport_close_frame_type()385 uint64_t transport_close_frame_type() const { 386 return on_closed_frame_.transport_close_frame_type; 387 } close_type()388 QuicConnectionCloseType close_type() const { 389 return on_closed_frame_.close_type; 390 } 391 perspective()392 Perspective perspective() const { return perspective_; } 393 flow_controller()394 QuicFlowController* flow_controller() { return &flow_controller_; } 395 396 // Returns true if connection is flow controller blocked. 397 bool IsConnectionFlowControlBlocked() const; 398 399 // Returns true if any stream is flow controller blocked. 400 bool IsStreamFlowControlBlocked(); 401 402 size_t max_open_incoming_bidirectional_streams() const; 403 size_t max_open_incoming_unidirectional_streams() const; 404 405 size_t MaxAvailableBidirectionalStreams() const; 406 size_t MaxAvailableUnidirectionalStreams() const; 407 408 // Returns existing stream with id = |stream_id|. If no 409 // such stream exists, and |stream_id| is a peer-created stream id, 410 // then a new stream is created and returned. In all other cases, nullptr is 411 // returned. 412 // Caller does not own the returned stream. 413 QuicStream* GetOrCreateStream(const QuicStreamId stream_id); 414 415 // Mark a stream as draining. 416 void StreamDraining(QuicStreamId id, bool unidirectional); 417 418 // Returns true if this stream should yield writes to another blocked stream. 419 virtual bool ShouldYield(QuicStreamId stream_id); 420 421 // Clean up closed_streams_. 422 void CleanUpClosedStreams(); 423 supported_versions()424 const ParsedQuicVersionVector& supported_versions() const { 425 return supported_versions_; 426 } 427 428 QuicStreamId next_outgoing_bidirectional_stream_id() const; 429 QuicStreamId next_outgoing_unidirectional_stream_id() const; 430 431 // Return true if given stream is peer initiated. 432 bool IsIncomingStream(QuicStreamId id) const; 433 434 // Record errors when a connection is closed at the server side, should only 435 // be called from server's perspective. 436 // Noop if |error| is QUIC_NO_ERROR. 437 static void RecordConnectionCloseAtServer(QuicErrorCode error, 438 ConnectionCloseSource source); 439 transport_version()440 inline QuicTransportVersion transport_version() const { 441 return connection_->transport_version(); 442 } 443 version()444 inline ParsedQuicVersion version() const { return connection_->version(); } 445 use_http2_priority_write_scheduler()446 bool use_http2_priority_write_scheduler() const { 447 return use_http2_priority_write_scheduler_; 448 } 449 is_configured()450 bool is_configured() const { return is_configured_; } 451 452 // Called to neuter crypto data of encryption |level|. 453 void NeuterCryptoDataOfEncryptionLevel(EncryptionLevel level); 454 455 // Returns the ALPN values to negotiate on this session. GetAlpnsToOffer()456 virtual std::vector<std::string> GetAlpnsToOffer() const { 457 // TODO(vasilvv): this currently sets HTTP/3 by default. Switch all 458 // non-HTTP applications to appropriate ALPNs. 459 return std::vector<std::string>({AlpnForVersion(connection()->version())}); 460 } 461 462 // Provided a list of ALPNs offered by the client, selects an ALPN from the 463 // list, or alpns.end() if none of the ALPNs are acceptable. 464 virtual std::vector<absl::string_view>::const_iterator SelectAlpn( 465 const std::vector<absl::string_view>& alpns) const; 466 467 // Called when the ALPN of the connection is established for a connection that 468 // uses TLS handshake. 469 virtual void OnAlpnSelected(absl::string_view alpn); 470 471 // Called on clients by the crypto handshaker to provide application state 472 // necessary for sending application data in 0-RTT. The state provided here is 473 // the same state that was provided to the crypto handshaker in 474 // QuicCryptoStream::SetServerApplicationStateForResumption on a previous 475 // connection. Application protocols that require state to be carried over 476 // from the previous connection to support 0-RTT data must implement this 477 // method to ingest this state. For example, an HTTP/3 QuicSession would 478 // implement this function to process the remembered server SETTINGS and apply 479 // those SETTINGS to 0-RTT data. This function returns true if the application 480 // state has been successfully processed, and false if there was an error 481 // processing the cached state and the connection should be closed. ResumeApplicationState(ApplicationState *)482 virtual bool ResumeApplicationState(ApplicationState* /*cached_state*/) { 483 return true; 484 } 485 486 // Does actual work of sending RESET_STREAM, if the stream type allows. 487 // Also informs the connection so that pending stream frames can be flushed. 488 virtual void MaybeSendRstStreamFrame(QuicStreamId id, 489 QuicRstStreamErrorCode error, 490 QuicStreamOffset bytes_written); 491 492 // Sends a STOP_SENDING frame if the stream type allows. 493 virtual void MaybeSendStopSendingFrame(QuicStreamId id, 494 QuicRstStreamErrorCode error); 495 496 // Returns the encryption level to send application data. 497 EncryptionLevel GetEncryptionLevelToSendApplicationData() const; 498 user_agent_id()499 const absl::optional<std::string> user_agent_id() const { 500 return user_agent_id_; 501 } 502 SetUserAgentId(std::string user_agent_id)503 void SetUserAgentId(std::string user_agent_id) { 504 user_agent_id_ = std::move(user_agent_id); 505 connection()->OnUserAgentIdKnown(); 506 } 507 GetClock()508 const QuicClock* GetClock() const { 509 return connection()->helper()->GetClock(); 510 } 511 liveness_testing_in_progress()512 bool liveness_testing_in_progress() const { 513 return liveness_testing_in_progress_; 514 } 515 use_write_or_buffer_data_at_level()516 bool use_write_or_buffer_data_at_level() const { 517 return use_write_or_buffer_data_at_level_; 518 } 519 use_encryption_level_context()520 bool use_encryption_level_context() const { 521 return connection_->use_encryption_level_context() && 522 use_write_or_buffer_data_at_level_; 523 } 524 525 protected: 526 using StreamMap = QuicHashMap<QuicStreamId, std::unique_ptr<QuicStream>>; 527 528 using PendingStreamMap = 529 QuicHashMap<QuicStreamId, std::unique_ptr<PendingStream>>; 530 531 using ClosedStreams = std::vector<std::unique_ptr<QuicStream>>; 532 533 using ZombieStreamMap = 534 QuicHashMap<QuicStreamId, std::unique_ptr<QuicStream>>; 535 536 // Creates a new stream to handle a peer-initiated stream. 537 // Caller does not own the returned stream. 538 // Returns nullptr and does error handling if the stream can not be created. 539 virtual QuicStream* CreateIncomingStream(QuicStreamId id) = 0; 540 virtual QuicStream* CreateIncomingStream(PendingStream* pending) = 0; 541 542 // Return the reserved crypto stream. 543 virtual QuicCryptoStream* GetMutableCryptoStream() = 0; 544 545 // Return the reserved crypto stream as a constant pointer. 546 virtual const QuicCryptoStream* GetCryptoStream() const = 0; 547 548 // Adds |stream| to the stream map. 549 virtual void ActivateStream(std::unique_ptr<QuicStream> stream); 550 551 // Set transmission type of next sending packets. 552 void SetTransmissionType(TransmissionType type); 553 554 // Returns the stream ID for a new outgoing bidirectional/unidirectional 555 // stream, and increments the underlying counter. 556 QuicStreamId GetNextOutgoingBidirectionalStreamId(); 557 QuicStreamId GetNextOutgoingUnidirectionalStreamId(); 558 559 // Indicates whether the next outgoing bidirectional/unidirectional stream ID 560 // can be allocated or not. The test for version-99/IETF QUIC is whether it 561 // will exceed the maximum-stream-id or not. For non-version-99 (Google) QUIC 562 // it checks whether the next stream would exceed the limit on the number of 563 // open streams. 564 bool CanOpenNextOutgoingBidirectionalStream(); 565 bool CanOpenNextOutgoingUnidirectionalStream(); 566 567 // Returns the maximum bidirectional streams parameter sent with the handshake 568 // as a transport parameter, or in the most recent MAX_STREAMS frame. 569 QuicStreamCount GetAdvertisedMaxIncomingBidirectionalStreams() const; 570 571 // When a stream is closed locally, it may not yet know how many bytes the 572 // peer sent on that stream. 573 // When this data arrives (via stream frame w. FIN, trailing headers, or RST) 574 // this method is called, and correctly updates the connection level flow 575 // controller. 576 virtual void OnFinalByteOffsetReceived(QuicStreamId id, 577 QuicStreamOffset final_byte_offset); 578 579 // Returns true if incoming unidirectional streams should be buffered until 580 // the first byte of the stream arrives. 581 // If a subclass returns true here, it should make sure to implement 582 // ProcessPendingStream(). UsesPendingStreams()583 virtual bool UsesPendingStreams() const { return false; } 584 GetSpdyPriorityofStream(QuicStreamId stream_id)585 spdy::SpdyPriority GetSpdyPriorityofStream(QuicStreamId stream_id) const { 586 return write_blocked_streams_.GetSpdyPriorityofStream(stream_id); 587 } 588 stream_map()589 StreamMap& stream_map() { return stream_map_; } 590 pending_streams_size()591 size_t pending_streams_size() const { return pending_stream_map_.size(); } 592 closed_streams()593 ClosedStreams* closed_streams() { return &closed_streams_; } 594 595 void set_largest_peer_created_stream_id( 596 QuicStreamId largest_peer_created_stream_id); 597 write_blocked_streams()598 QuicWriteBlockedList* write_blocked_streams() { 599 return &write_blocked_streams_; 600 } 601 602 // Returns true if the stream is still active. 603 bool IsOpenStream(QuicStreamId id); 604 605 // Returns true if the stream is a static stream. 606 bool IsStaticStream(QuicStreamId id) const; 607 608 // Close connection when receive a frame for a locally-created nonexistent 609 // stream. 610 // Prerequisite: IsClosedStream(stream_id) == false 611 // Server session might need to override this method to allow server push 612 // stream to be promised before creating an active stream. 613 virtual void HandleFrameOnNonexistentOutgoingStream(QuicStreamId stream_id); 614 615 virtual bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId stream_id); 616 617 void InsertLocallyClosedStreamsHighestOffset(const QuicStreamId id, 618 QuicStreamOffset offset); 619 // If stream is a locally closed stream, this RST will update FIN offset. 620 // Otherwise stream is a preserved stream and the behavior of it depends on 621 // derived class's own implementation. 622 virtual void HandleRstOnValidNonexistentStream( 623 const QuicRstStreamFrame& frame); 624 625 // Returns a stateless reset token which will be included in the public reset 626 // packet. 627 virtual QuicUint128 GetStatelessResetToken() const; 628 control_frame_manager()629 QuicControlFrameManager& control_frame_manager() { 630 return control_frame_manager_; 631 } 632 stream_id_manager()633 const LegacyQuicStreamIdManager& stream_id_manager() const { 634 return stream_id_manager_; 635 } 636 datagram_queue()637 QuicDatagramQueue* datagram_queue() { return &datagram_queue_; } 638 num_static_streams()639 size_t num_static_streams() const { return num_static_streams_; } 640 num_zombie_streams()641 size_t num_zombie_streams() const { return num_zombie_streams_; } 642 was_zero_rtt_rejected()643 bool was_zero_rtt_rejected() const { return was_zero_rtt_rejected_; } 644 num_outgoing_draining_streams()645 size_t num_outgoing_draining_streams() const { 646 return num_outgoing_draining_streams_; 647 } 648 num_draining_streams()649 size_t num_draining_streams() const { return num_draining_streams_; } 650 651 // Processes the stream type information of |pending| depending on 652 // different kinds of sessions' own rules. Returns true if the pending stream 653 // is converted into a normal stream. ProcessPendingStream(PendingStream *)654 virtual bool ProcessPendingStream(PendingStream* /*pending*/) { 655 return false; 656 } 657 658 // Called by applications to perform |action| on active streams. 659 // Stream iteration will be stopped if action returns false. 660 void PerformActionOnActiveStreams(std::function<bool(QuicStream*)> action); 661 void PerformActionOnActiveStreams( 662 std::function<bool(QuicStream*)> action) const; 663 664 // Return the largest peer created stream id depending on directionality 665 // indicated by |unidirectional|. 666 QuicStreamId GetLargestPeerCreatedStreamId(bool unidirectional) const; 667 668 // Deletes the connection and sets it to nullptr, so calling it mulitiple 669 // times is safe. 670 void DeleteConnection(); 671 672 // Call SetPriority() on stream id |id| and return true if stream is active. 673 bool MaybeSetStreamPriority(QuicStreamId stream_id, 674 const spdy::SpdyStreamPrecedence& precedence); 675 SetLossDetectionTuner(std::unique_ptr<LossDetectionTunerInterface> tuner)676 void SetLossDetectionTuner( 677 std::unique_ptr<LossDetectionTunerInterface> tuner) { 678 connection()->SetLossDetectionTuner(std::move(tuner)); 679 } 680 681 // Find stream with |id|, returns nullptr if the stream does not exist or 682 // closed. static streams and zombie streams are not considered active 683 // streams. 684 QuicStream* GetActiveStream(QuicStreamId id) const; 685 686 private: 687 friend class test::QuicSessionPeer; 688 689 // Called in OnConfigNegotiated when we receive a new stream level flow 690 // control window in a negotiated config. Closes the connection if invalid. 691 void OnNewStreamFlowControlWindow(QuicStreamOffset new_window); 692 693 // Called in OnConfigNegotiated when we receive a new unidirectional stream 694 // flow control window in a negotiated config. 695 void OnNewStreamUnidirectionalFlowControlWindow(QuicStreamOffset new_window); 696 697 // Called in OnConfigNegotiated when we receive a new outgoing bidirectional 698 // stream flow control window in a negotiated config. 699 void OnNewStreamOutgoingBidirectionalFlowControlWindow( 700 QuicStreamOffset new_window); 701 702 // Called in OnConfigNegotiated when we receive a new incoming bidirectional 703 // stream flow control window in a negotiated config. 704 void OnNewStreamIncomingBidirectionalFlowControlWindow( 705 QuicStreamOffset new_window); 706 707 // Called in OnConfigNegotiated when we receive a new connection level flow 708 // control window in a negotiated config. Closes the connection if invalid. 709 void OnNewSessionFlowControlWindow(QuicStreamOffset new_window); 710 711 // Debug helper for |OnCanWrite()|, check that OnStreamWrite() makes 712 // forward progress. Returns false if busy loop detected. 713 bool CheckStreamNotBusyLooping(QuicStream* stream, 714 uint64_t previous_bytes_written, 715 bool previous_fin_sent); 716 717 // Debug helper for OnCanWrite. Check that after QuicStream::OnCanWrite(), 718 // if stream has buffered data and is not stream level flow control blocked, 719 // it has to be in the write blocked list. 720 bool CheckStreamWriteBlocked(QuicStream* stream) const; 721 722 // Called in OnConfigNegotiated for Finch trials to measure performance of 723 // starting with larger flow control receive windows. 724 void AdjustInitialFlowControlWindows(size_t stream_window); 725 726 // Find stream with |id|, returns nullptr if the stream does not exist or 727 // closed. 728 QuicStream* GetStream(QuicStreamId id) const; 729 730 PendingStream* GetOrCreatePendingStream(QuicStreamId stream_id); 731 732 // Let streams and control frame managers retransmit lost data, returns true 733 // if all lost data is retransmitted. Returns false otherwise. 734 bool RetransmitLostData(); 735 736 // Returns true if stream data should be written. 737 bool CanWriteStreamData() const; 738 739 // Closes the pending stream |stream_id| before it has been created. 740 void ClosePendingStream(QuicStreamId stream_id); 741 742 // Creates or gets pending stream, feeds it with |frame|, and processes the 743 // pending stream. 744 void PendingStreamOnStreamFrame(const QuicStreamFrame& frame); 745 746 // Creates or gets pending strea, feed it with |frame|, and closes the pending 747 // stream. 748 void PendingStreamOnRstStream(const QuicRstStreamFrame& frame); 749 750 // Keep track of highest received byte offset of locally closed streams, while 751 // waiting for a definitive final highest offset from the peer. 752 QuicHashMap<QuicStreamId, QuicStreamOffset> 753 locally_closed_streams_highest_offset_; 754 755 QuicConnection* connection_; 756 757 // Store perspective on QuicSession during the constructor as it may be needed 758 // during our destructor when connection_ may have already been destroyed. 759 Perspective perspective_; 760 761 // May be null. 762 Visitor* visitor_; 763 764 // A list of streams which need to write more data. Stream register 765 // themselves in their constructor, and unregisterm themselves in their 766 // destructors, so the write blocked list must outlive all streams. 767 QuicWriteBlockedList write_blocked_streams_; 768 769 ClosedStreams closed_streams_; 770 771 QuicConfig config_; 772 773 // Map from StreamId to pointers to streams. Owns the streams. 774 StreamMap stream_map_; 775 776 // Map from StreamId to PendingStreams for peer-created unidirectional streams 777 // which are waiting for the first byte of payload to arrive. 778 PendingStreamMap pending_stream_map_; 779 780 // TODO(fayang): Consider moving LegacyQuicStreamIdManager into 781 // UberQuicStreamIdManager. 782 // Manages stream IDs for Google QUIC. 783 LegacyQuicStreamIdManager stream_id_manager_; 784 785 // Manages stream IDs for version99/IETF QUIC 786 UberQuicStreamIdManager ietf_streamid_manager_; 787 788 // A counter for streams which have sent and received FIN but waiting for 789 // application to consume data. 790 size_t num_draining_streams_; 791 792 // A counter for self initiated streams which have sent and received FIN but 793 // waiting for application to consume data. 794 size_t num_outgoing_draining_streams_; 795 796 // A counter for static streams which are in stream_map_. 797 size_t num_static_streams_; 798 799 // A counter for streams which have done reading and writing, but are waiting 800 // for acks. 801 size_t num_zombie_streams_; 802 803 // Received information for a connection close. 804 QuicConnectionCloseFrame on_closed_frame_; 805 806 // Used for connection-level flow control. 807 QuicFlowController flow_controller_; 808 809 // The stream id which was last popped in OnCanWrite, or 0, if not under the 810 // call stack of OnCanWrite. 811 QuicStreamId currently_writing_stream_id_; 812 813 // Whether a transport layer GOAWAY frame has been sent. 814 // Such a frame only exists in Google QUIC, therefore |transport_goaway_sent_| 815 // is always false when using IETF QUIC. 816 bool transport_goaway_sent_; 817 818 // Whether a transport layer GOAWAY frame has been received. 819 // Such a frame only exists in Google QUIC, therefore 820 // |transport_goaway_received_| is always false when using IETF QUIC. 821 bool transport_goaway_received_; 822 823 QuicControlFrameManager control_frame_manager_; 824 825 // Id of latest successfully sent message. 826 QuicMessageId last_message_id_; 827 828 // The buffer used to queue the DATAGRAM frames. 829 QuicDatagramQueue datagram_queue_; 830 831 // TODO(fayang): switch to linked_hash_set when chromium supports it. The bool 832 // is not used here. 833 // List of streams with pending retransmissions. 834 QuicLinkedHashMap<QuicStreamId, bool> streams_with_pending_retransmission_; 835 836 // Clean up closed_streams_ when this alarm fires. 837 std::unique_ptr<QuicAlarm> closed_streams_clean_up_alarm_; 838 839 // Supported version list used by the crypto handshake only. Please note, this 840 // list may be a superset of the connection framer's supported versions. 841 ParsedQuicVersionVector supported_versions_; 842 843 absl::optional<std::string> user_agent_id_; 844 845 // If true, write_blocked_streams_ uses HTTP2 (tree-style) priority write 846 // scheduler. 847 bool use_http2_priority_write_scheduler_; 848 849 // Initialized to false. Set to true when the session has been properly 850 // configured and is ready for general operation. 851 bool is_configured_; 852 853 // If true, enables round robin scheduling. 854 bool enable_round_robin_scheduling_; 855 856 // Whether the session has received a 0-RTT rejection (QUIC+TLS only). 857 bool was_zero_rtt_rejected_; 858 859 // This indicates a liveness testing is in progress, and push back the 860 // creation of new outgoing bidirectional streams. 861 bool liveness_testing_in_progress_; 862 863 const bool split_up_send_rst_ = 864 GetQuicReloadableFlag(quic_split_up_send_rst_2); 865 866 const bool use_write_or_buffer_data_at_level_ = 867 GetQuicReloadableFlag(quic_use_write_or_buffer_data_at_level); 868 }; 869 870 } // namespace quic 871 872 #endif // QUICHE_QUIC_CORE_QUIC_SESSION_H_ 873