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