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