blob: 466d17b7887d096e7b6ecd012c44e8fa46eed4c1 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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>
renjietang216dc012019-08-27 11:28:27 -070011#include <cstdint>
QUICHE teama6ef0a62019-03-07 20:34:33 -050012#include <map>
13#include <memory>
vasilvv872e7a32019-03-12 16:42:44 -070014#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050015#include <vector>
16
fayangd58736d2019-11-27 13:35:31 -080017#include "net/third_party/quiche/src/quic/core/handshaker_delegate_interface.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050018#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"
vasilvv2b0ab242020-01-07 07:32:09 -080022#include "net/third_party/quiche/src/quic/core/quic_datagram_queue.h"
wub2b5942f2019-04-11 13:22:50 -070023#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050024#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"
renjietang686ce582019-10-17 14:28:16 -070028#include "net/third_party/quiche/src/quic/core/quic_types.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050029#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"
renjietangf196f6a2020-02-12 12:34:23 -080031#include "net/third_party/quiche/src/quic/core/stream_delegate_interface.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050032#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"
dmcardlecf0bfcf2019-12-13 08:08:21 -080036#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050037
38namespace quic {
39
40class QuicCryptoStream;
41class QuicFlowController;
42class QuicStream;
43class QuicStreamIdManager;
44
45namespace test {
46class QuicSessionPeer;
47} // namespace test
48
rcha8b56e42019-09-20 10:41:48 -070049class QUIC_EXPORT_PRIVATE QuicSession
50 : public QuicConnectionVisitorInterface,
51 public SessionNotifierInterface,
52 public QuicStreamFrameDataProducer,
fayangd58736d2019-11-27 13:35:31 -080053 public QuicStreamIdManager::DelegateInterface,
renjietangf196f6a2020-02-12 12:34:23 -080054 public HandshakerDelegateInterface,
55 public StreamDelegateInterface {
QUICHE teama6ef0a62019-03-07 20:34:33 -050056 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.
dschinazif25169a2019-10-23 08:12:18 -070060 class QUIC_EXPORT_PRIVATE Visitor {
QUICHE teama6ef0a62019-03-07 20:34:33 -050061 public:
62 virtual ~Visitor() {}
63
64 // Called when the connection is closed after the streams have been closed.
dschinazi7b9278c2019-05-20 07:36:21 -070065 virtual void OnConnectionClosed(QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -050066 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -070067 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -050068 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
QUICHE teama6ef0a62019-03-07 20:34:33 -050081 // Does not take ownership of |connection| or |visitor|.
82 QuicSession(QuicConnection* connection,
83 Visitor* owner,
84 const QuicConfig& config,
renjietang216dc012019-08-27 11:28:27 -070085 const ParsedQuicVersionVector& supported_versions,
86 QuicStreamCount num_expected_unidirectional_static_streams);
QUICHE teama6ef0a62019-03-07 20:34:33 -050087 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;
dmcardlecf0bfcf2019-12-13 08:08:21 -080099 void OnMessageReceived(quiche::QuicheStringPiece message) override;
fayang01062942020-01-22 07:23:23 -0800100 void OnHandshakeDoneReceived() override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500101 void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
102 void OnBlockedFrame(const QuicBlockedFrame& frame) override;
fkastenholz5d880a92019-06-21 09:01:56 -0700103 void OnConnectionClosed(const QuicConnectionCloseFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500104 ConnectionCloseSource source) override;
105 void OnWriteBlocked() override;
106 void OnSuccessfulVersionNegotiation(
107 const ParsedQuicVersion& version) override;
zhongyi83161e42019-08-19 09:06:25 -0700108 void OnPacketReceived(const QuicSocketAddress& self_address,
109 const QuicSocketAddress& peer_address,
110 bool is_connectivity_probe) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500111 void OnCanWrite() override;
QUICHE teamb8343252019-04-29 13:58:01 -0700112 bool SendProbingData() override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500113 void OnCongestionWindowChange(QuicTime /*now*/) override {}
dschinazi17d42422019-06-18 16:35:07 -0700114 void OnConnectionMigration(AddressChangeType /*type*/) override {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500115 // 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;
fayangc67c5202020-01-22 07:43:15 -0800122 HandshakeState GetHandshakeState() const override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500123 void OnForwardProgressConfirmed() override;
fkastenholz3c4eabf2019-04-22 07:49:59 -0700124 bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override;
125 bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override;
renjietangeab918f2019-10-28 12:10:32 -0700126 void OnStopSendingFrame(const QuicStopSendingFrame& frame) override;
fayangd58736d2019-11-27 13:35:31 -0800127 void OnPacketDecrypted(EncryptionLevel level) override;
fayang2f2915d2020-01-24 06:47:15 -0800128 void OnOneRttPacketAcknowledged() override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500129
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,
QUICHE team9467db02019-05-30 09:38:45 -0700142 QuicTime::Delta ack_delay_time,
143 QuicTime receive_timestamp) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500144 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;
zhongyi1b2f7832019-06-14 13:31:34 -0700150 bool HasUnackedStreamData() const override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500151
rcha8b56e42019-09-20 10:41:48 -0700152 // QuicStreamIdManager::DelegateInterface methods:
renjietangff4b2b62020-02-12 16:52:32 -0800153 void OnStreamIdManagerError(QuicErrorCode error_code,
154 std::string error_details) override;
rcha8b56e42019-09-20 10:41:48 -0700155 void SendMaxStreams(QuicStreamCount stream_count,
156 bool unidirectional) override;
157 void SendStreamsBlocked(QuicStreamCount stream_count,
158 bool unidirectional) override;
159 // The default implementation does nothing. Subclasses should override if
160 // for example they queue up stream requests.
161 void OnCanCreateNewOutgoingStream(bool unidirectional) override;
162
QUICHE teama6ef0a62019-03-07 20:34:33 -0500163 // Called on every incoming packet. Passes |packet| through to |connection_|.
164 virtual void ProcessUdpPacket(const QuicSocketAddress& self_address,
165 const QuicSocketAddress& peer_address,
166 const QuicReceivedPacket& packet);
167
168 // Called by streams when they want to write data to the peer.
169 // Returns a pair with the number of bytes consumed from data, and a boolean
170 // indicating if the fin bit was consumed. This does not indicate the data
171 // has been sent on the wire: it may have been turned into a packet and queued
172 // if the socket was unexpectedly blocked.
173 virtual QuicConsumedData WritevData(QuicStream* stream,
174 QuicStreamId id,
175 size_t write_length,
176 QuicStreamOffset offset,
177 StreamSendingState state);
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
QUICHE team350e9e62019-11-19 13:16:24 -0800201 // 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
QUICHE teama6ef0a62019-03-07 20:34:33 -0500205 // Called when message with |message_id| gets acked.
QUICHE team9467db02019-05-30 09:38:45 -0700206 virtual void OnMessageAcked(QuicMessageId message_id,
207 QuicTime receive_timestamp);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500208
209 // Called when message with |message_id| is considered as lost.
210 virtual void OnMessageLost(QuicMessageId message_id);
211
212 // Called by control frame manager when it wants to write control frames to
213 // the peer. Returns true if |frame| is consumed, false otherwise.
214 virtual bool WriteControlFrame(const QuicFrame& frame);
215
renjietang64881612019-11-05 17:39:04 -0800216 // Close the stream in both directions.
217 // TODO(renjietang): rename this method as it sends both RST_STREAM and
218 // STOP_SENDING in IETF QUIC.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500219 virtual void SendRstStream(QuicStreamId id,
220 QuicRstStreamErrorCode error,
221 QuicStreamOffset bytes_written);
222
223 // Called when the session wants to go away and not accept any new streams.
vasilvvc48c8712019-03-11 13:38:16 -0700224 virtual void SendGoAway(QuicErrorCode error_code, const std::string& reason);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500225
226 // Sends a BLOCKED frame.
227 virtual void SendBlocked(QuicStreamId id);
228
229 // Sends a WINDOW_UPDATE frame.
230 virtual void SendWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset);
231
QUICHE teama6ef0a62019-03-07 20:34:33 -0500232 // Create and transmit a STOP_SENDING frame
233 virtual void SendStopSending(uint16_t code, QuicStreamId stream_id);
234
235 // Removes the stream associated with 'stream_id' from the active stream map.
236 virtual void CloseStream(QuicStreamId stream_id);
237
238 // Returns true if outgoing packets will be encrypted, even if the server
239 // hasn't confirmed the handshake yet.
240 virtual bool IsEncryptionEstablished() const;
241
fayanga3d8df72020-01-14 11:54:39 -0800242 // Returns true if 1RTT keys are available.
243 bool OneRttKeysAvailable() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500244
245 // Called by the QuicCryptoStream when a new QuicConfig has been negotiated.
246 virtual void OnConfigNegotiated();
247
fayangd58736d2019-11-27 13:35:31 -0800248 // From HandshakerDelegateInterface
fayangd2866522020-02-12 11:15:27 -0800249 bool OnNewDecryptionKeyAvailable(EncryptionLevel level,
fayang3f7bcbe2020-02-10 11:08:47 -0800250 std::unique_ptr<QuicDecrypter> decrypter,
251 bool set_alternative_decrypter,
252 bool latch_once_used) override;
253 void OnNewEncryptionKeyAvailable(
254 EncryptionLevel level,
255 std::unique_ptr<QuicEncrypter> encrypter) override;
fayangd58736d2019-11-27 13:35:31 -0800256 void SetDefaultEncryptionLevel(EncryptionLevel level) override;
257 void DiscardOldDecryptionKey(EncryptionLevel level) override;
258 void DiscardOldEncryptionKey(EncryptionLevel level) override;
259 void NeuterUnencryptedData() override;
260 void NeuterHandshakeData() override;
261
renjietangf196f6a2020-02-12 12:34:23 -0800262 // Implement StreamDelegateInterface.
263 void OnStreamError(QuicErrorCode error_code,
264 std::string error_details) override;
265
QUICHE teama6ef0a62019-03-07 20:34:33 -0500266 // Called by the QuicCryptoStream when a handshake message is sent.
267 virtual void OnCryptoHandshakeMessageSent(
268 const CryptoHandshakeMessage& message);
269
270 // Called by the QuicCryptoStream when a handshake message is received.
271 virtual void OnCryptoHandshakeMessageReceived(
272 const CryptoHandshakeMessage& message);
273
274 // Called by the stream on creation to set priority in the write blocked list.
fayang476683a2019-07-25 12:42:16 -0700275 virtual void RegisterStreamPriority(
276 QuicStreamId id,
277 bool is_static,
278 const spdy::SpdyStreamPrecedence& precedence);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500279 // Called by the stream on deletion to clear priority from the write blocked
280 // list.
281 virtual void UnregisterStreamPriority(QuicStreamId id, bool is_static);
282 // Called by the stream on SetPriority to update priority on the write blocked
283 // list.
fayang476683a2019-07-25 12:42:16 -0700284 virtual void UpdateStreamPriority(
285 QuicStreamId id,
286 const spdy::SpdyStreamPrecedence& new_precedence);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500287
288 // Returns mutable config for this session. Returned config is owned
289 // by QuicSession.
290 QuicConfig* config();
291
292 // Returns true if the stream existed previously and has been closed.
293 // Returns false if the stream is still active or if the stream has
294 // not yet been created.
295 bool IsClosedStream(QuicStreamId id);
296
297 QuicConnection* connection() { return connection_; }
298 const QuicConnection* connection() const { return connection_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500299 const QuicSocketAddress& peer_address() const {
300 return connection_->peer_address();
301 }
302 const QuicSocketAddress& self_address() const {
303 return connection_->self_address();
304 }
305 QuicConnectionId connection_id() const {
306 return connection_->connection_id();
307 }
308
renjietang69a8eaf2019-08-06 15:55:58 -0700309 // Returns the number of currently open streams, excluding static streams, and
310 // never counting unfinished streams.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500311 size_t GetNumActiveStreams() const;
312
313 // Returns the number of currently draining streams.
314 size_t GetNumDrainingStreams() const;
315
renjietang69a8eaf2019-08-06 15:55:58 -0700316 // Returns the number of currently open peer initiated streams, excluding
317 // static streams.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500318 size_t GetNumOpenIncomingStreams() const;
319
renjietang69a8eaf2019-08-06 15:55:58 -0700320 // Returns the number of currently open self initiated streams, excluding
321 // static streams.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500322 size_t GetNumOpenOutgoingStreams() const;
323
renjietangfbeb5bf2019-04-19 15:06:20 -0700324 // Returns the number of open peer initiated static streams.
325 size_t num_incoming_static_streams() const {
326 return num_incoming_static_streams_;
327 }
328
329 // Returns the number of open self initiated static streams.
330 size_t num_outgoing_static_streams() const {
331 return num_outgoing_static_streams_;
332 }
333
QUICHE teama6ef0a62019-03-07 20:34:33 -0500334 // Add the stream to the session's write-blocked list because it is blocked by
335 // connection-level flow control but not by its own stream-level flow control.
336 // The stream will be given a chance to write when a connection-level
337 // WINDOW_UPDATE arrives.
QUICHE teamdf0b19f2019-08-13 16:55:42 -0700338 virtual void MarkConnectionLevelWriteBlocked(QuicStreamId id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500339
340 // Called when stream |id| is done waiting for acks either because all data
341 // gets acked or is not interested in data being acked (which happens when
342 // a stream is reset because of an error).
343 void OnStreamDoneWaitingForAcks(QuicStreamId id);
344
zhongyi1b2f7832019-06-14 13:31:34 -0700345 // Called when stream |id| is newly waiting for acks.
346 void OnStreamWaitingForAcks(QuicStreamId id);
347
QUICHE teama6ef0a62019-03-07 20:34:33 -0500348 // Returns true if the session has data to be sent, either queued in the
349 // connection, or in a write-blocked stream.
350 bool HasDataToWrite() const;
351
352 // Returns the largest payload that will fit into a single MESSAGE frame.
353 // Because overhead can vary during a connection, this method should be
354 // checked for every message.
ianswettb239f862019-04-05 09:15:06 -0700355 QuicPacketLength GetCurrentLargestMessagePayload() const;
356
357 // Returns the largest payload that will fit into a single MESSAGE frame at
358 // any point during the connection. This assumes the version and
359 // connection ID lengths do not change.
360 QuicPacketLength GetGuaranteedLargestMessagePayload() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500361
362 bool goaway_sent() const { return goaway_sent_; }
363
364 bool goaway_received() const { return goaway_received_; }
365
fkastenholz488a4622019-08-26 06:24:46 -0700366 // Returns the Google QUIC error code
367 QuicErrorCode error() const { return on_closed_frame_.extracted_error_code; }
wub43652ca2019-09-05 11:18:19 -0700368 const std::string& error_details() const {
369 return on_closed_frame_.error_details;
370 }
fkastenholz488a4622019-08-26 06:24:46 -0700371 uint64_t transport_close_frame_type() const {
372 return on_closed_frame_.transport_close_frame_type;
373 }
374 QuicConnectionCloseType close_type() const {
375 return on_closed_frame_.close_type;
376 }
377 QuicIetfTransportErrorCodes transport_error_code() const {
378 return on_closed_frame_.transport_error_code;
379 }
380 uint16_t application_error_code() const {
381 return on_closed_frame_.application_error_code;
382 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500383
dschinazi31e94d42019-12-18 11:55:39 -0800384 Perspective perspective() const { return perspective_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500385
386 QuicFlowController* flow_controller() { return &flow_controller_; }
387
388 // Returns true if connection is flow controller blocked.
389 bool IsConnectionFlowControlBlocked() const;
390
391 // Returns true if any stream is flow controller blocked.
392 bool IsStreamFlowControlBlocked();
393
394 size_t max_open_incoming_bidirectional_streams() const;
395 size_t max_open_incoming_unidirectional_streams() const;
396
397 size_t MaxAvailableBidirectionalStreams() const;
398 size_t MaxAvailableUnidirectionalStreams() const;
399
renjietang55d182a2019-07-12 10:26:25 -0700400 // Returns existing stream with id = |stream_id|. If no
401 // such stream exists, and |stream_id| is a peer-created stream id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500402 // then a new stream is created and returned. In all other cases, nullptr is
403 // returned.
renjietang880d2432019-07-16 13:14:37 -0700404 // Caller does not own the returned stream.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500405 QuicStream* GetOrCreateStream(const QuicStreamId stream_id);
406
407 // Mark a stream as draining.
408 virtual void StreamDraining(QuicStreamId id);
409
410 // Returns true if this stream should yield writes to another blocked stream.
QUICHE teamdf0b19f2019-08-13 16:55:42 -0700411 virtual bool ShouldYield(QuicStreamId stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500412
413 // Set transmission type of next sending packets.
414 void SetTransmissionType(TransmissionType type);
415
416 // Clean up closed_streams_.
417 void CleanUpClosedStreams();
418
QUICHE teama6ef0a62019-03-07 20:34:33 -0500419 const ParsedQuicVersionVector& supported_versions() const {
420 return supported_versions_;
421 }
422
QUICHE teama6ef0a62019-03-07 20:34:33 -0500423 QuicStreamId next_outgoing_bidirectional_stream_id() const;
424 QuicStreamId next_outgoing_unidirectional_stream_id() const;
425
426 // Return true if given stream is peer initiated.
427 bool IsIncomingStream(QuicStreamId id) const;
428
429 size_t GetNumLocallyClosedOutgoingStreamsHighestOffset() const;
430
431 size_t num_locally_closed_incoming_streams_highest_offset() const {
432 return num_locally_closed_incoming_streams_highest_offset_;
433 }
434
wub2b5942f2019-04-11 13:22:50 -0700435 // Record errors when a connection is closed at the server side, should only
436 // be called from server's perspective.
437 // Noop if |error| is QUIC_NO_ERROR.
438 static void RecordConnectionCloseAtServer(QuicErrorCode error,
439 ConnectionCloseSource source);
440
fkastenholzd3a1de92019-05-15 07:00:07 -0700441 inline QuicTransportVersion transport_version() const {
442 return connection_->transport_version();
443 }
444
nharper46c1e672020-01-16 14:50:31 -0800445 inline ParsedQuicVersion version() const { return connection_->version(); }
446
fayang944cfbc2019-07-31 09:15:00 -0700447 bool use_http2_priority_write_scheduler() const {
448 return use_http2_priority_write_scheduler_;
449 }
450
fkastenholz9b4b0ad2019-08-20 05:10:40 -0700451 bool is_configured() const { return is_configured_; }
452
renjietang216dc012019-08-27 11:28:27 -0700453 QuicStreamCount num_expected_unidirectional_static_streams() const {
454 return num_expected_unidirectional_static_streams_;
455 }
456
457 // Set the number of unidirectional stream that the peer is allowed to open to
458 // be |max_stream| + |num_expected_static_streams_|.
renjietange6d94672020-01-07 10:30:10 -0800459 void ConfigureMaxDynamicStreamsToSend(QuicStreamCount max_stream) {
460 config_.SetMaxUnidirectionalStreamsToSend(
renjietang216dc012019-08-27 11:28:27 -0700461 max_stream + num_expected_unidirectional_static_streams_);
462 }
463
vasilvv4724c9c2019-08-29 11:52:11 -0700464 // Returns the ALPN values to negotiate on this session.
vasilvvad7424f2019-08-30 00:27:14 -0700465 virtual std::vector<std::string> GetAlpnsToOffer() const {
vasilvv4724c9c2019-08-29 11:52:11 -0700466 // TODO(vasilvv): this currently sets HTTP/3 by default. Switch all
467 // non-HTTP applications to appropriate ALPNs.
468 return std::vector<std::string>({AlpnForVersion(connection()->version())});
469 }
470
vasilvvad7424f2019-08-30 00:27:14 -0700471 // Provided a list of ALPNs offered by the client, selects an ALPN from the
472 // list, or alpns.end() if none of the ALPNs are acceptable.
dmcardlecf0bfcf2019-12-13 08:08:21 -0800473 virtual std::vector<quiche::QuicheStringPiece>::const_iterator SelectAlpn(
474 const std::vector<quiche::QuicheStringPiece>& alpns) const;
vasilvvad7424f2019-08-30 00:27:14 -0700475
476 // Called when the ALPN of the connection is established for a connection that
477 // uses TLS handshake.
dmcardlecf0bfcf2019-12-13 08:08:21 -0800478 virtual void OnAlpnSelected(quiche::QuicheStringPiece alpn);
vasilvvad7424f2019-08-30 00:27:14 -0700479
QUICHE teama6ef0a62019-03-07 20:34:33 -0500480 protected:
renjietang55d182a2019-07-12 10:26:25 -0700481 using StreamMap = QuicSmallMap<QuicStreamId, std::unique_ptr<QuicStream>, 10>;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500482
483 using PendingStreamMap =
484 QuicSmallMap<QuicStreamId, std::unique_ptr<PendingStream>, 10>;
485
486 using ClosedStreams = std::vector<std::unique_ptr<QuicStream>>;
487
488 using ZombieStreamMap =
489 QuicSmallMap<QuicStreamId, std::unique_ptr<QuicStream>, 10>;
490
491 // Creates a new stream to handle a peer-initiated stream.
492 // Caller does not own the returned stream.
493 // Returns nullptr and does error handling if the stream can not be created.
494 virtual QuicStream* CreateIncomingStream(QuicStreamId id) = 0;
renjietangbaea59c2019-05-29 15:08:14 -0700495 virtual QuicStream* CreateIncomingStream(PendingStream* pending) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500496
497 // Return the reserved crypto stream.
498 virtual QuicCryptoStream* GetMutableCryptoStream() = 0;
499
500 // Return the reserved crypto stream as a constant pointer.
501 virtual const QuicCryptoStream* GetCryptoStream() const = 0;
502
renjietang55d182a2019-07-12 10:26:25 -0700503 // Adds |stream| to the stream map.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500504 virtual void ActivateStream(std::unique_ptr<QuicStream> stream);
505
506 // Returns the stream ID for a new outgoing bidirectional/unidirectional
507 // stream, and increments the underlying counter.
508 QuicStreamId GetNextOutgoingBidirectionalStreamId();
509 QuicStreamId GetNextOutgoingUnidirectionalStreamId();
510
511 // Indicates whether the next outgoing bidirectional/unidirectional stream ID
512 // can be allocated or not. The test for version-99/IETF QUIC is whether it
513 // will exceed the maximum-stream-id or not. For non-version-99 (Google) QUIC
514 // it checks whether the next stream would exceed the limit on the number of
515 // open streams.
516 bool CanOpenNextOutgoingBidirectionalStream();
517 bool CanOpenNextOutgoingUnidirectionalStream();
518
519 // Returns the number of open dynamic streams.
520 uint64_t GetNumOpenDynamicStreams() const;
521
bnc41c19ca2020-01-21 18:55:26 -0800522 // Returns the maximum bidirectional streams parameter sent with the handshake
523 // as a transport parameter, or in the most recent MAX_STREAMS frame.
524 QuicStreamCount GetAdvertisedMaxIncomingBidirectionalStreams() const;
525
renjietang75bbf982020-02-03 16:40:05 -0800526 // Performs the work required to close |stream_id|. If |rst_sent| then a
527 // Reset Stream frame has already been sent for this stream.
528 virtual void CloseStreamInner(QuicStreamId stream_id, bool rst_sent);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500529
530 // When a stream is closed locally, it may not yet know how many bytes the
531 // peer sent on that stream.
532 // When this data arrives (via stream frame w. FIN, trailing headers, or RST)
533 // this method is called, and correctly updates the connection level flow
534 // controller.
535 virtual void OnFinalByteOffsetReceived(QuicStreamId id,
536 QuicStreamOffset final_byte_offset);
537
renjietange76b2da2019-05-13 14:50:23 -0700538 // Returns true if incoming unidirectional streams should be buffered until
539 // the first byte of the stream arrives.
540 // If a subclass returns true here, it should make sure to implement
541 // ProcessPendingStream().
542 virtual bool UsesPendingStreams() const { return false; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500543
renjietang55d182a2019-07-12 10:26:25 -0700544 StreamMap& stream_map() { return stream_map_; }
545 const StreamMap& stream_map() const { return stream_map_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500546
renjietang56d2ed22019-10-22 14:11:55 -0700547 const PendingStreamMap& pending_streams() const {
548 return pending_stream_map_;
549 }
550
QUICHE teama6ef0a62019-03-07 20:34:33 -0500551 ClosedStreams* closed_streams() { return &closed_streams_; }
552
553 const ZombieStreamMap& zombie_streams() const { return zombie_streams_; }
554
555 void set_largest_peer_created_stream_id(
556 QuicStreamId largest_peer_created_stream_id);
557
QUICHE teama6ef0a62019-03-07 20:34:33 -0500558 QuicWriteBlockedList* write_blocked_streams() {
559 return &write_blocked_streams_;
560 }
561
562 size_t GetNumDynamicOutgoingStreams() const;
563
564 size_t GetNumDrainingOutgoingStreams() const;
565
566 // Returns true if the stream is still active.
567 bool IsOpenStream(QuicStreamId id);
568
rchda26cdb2019-05-17 11:57:37 -0700569 // Returns true if the stream is a static stream.
570 bool IsStaticStream(QuicStreamId id) const;
571
renjietang5c729f02019-09-06 12:43:48 -0700572 // Close connection when receive a frame for a locally-created nonexistent
QUICHE teama6ef0a62019-03-07 20:34:33 -0500573 // stream.
574 // Prerequisite: IsClosedStream(stream_id) == false
575 // Server session might need to override this method to allow server push
576 // stream to be promised before creating an active stream.
577 virtual void HandleFrameOnNonexistentOutgoingStream(QuicStreamId stream_id);
578
579 virtual bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId stream_id);
580
581 void InsertLocallyClosedStreamsHighestOffset(const QuicStreamId id,
582 QuicStreamOffset offset);
583 // If stream is a locally closed stream, this RST will update FIN offset.
584 // Otherwise stream is a preserved stream and the behavior of it depends on
585 // derived class's own implementation.
586 virtual void HandleRstOnValidNonexistentStream(
587 const QuicRstStreamFrame& frame);
588
589 // Returns a stateless reset token which will be included in the public reset
590 // packet.
591 virtual QuicUint128 GetStatelessResetToken() const;
592
593 QuicControlFrameManager& control_frame_manager() {
594 return control_frame_manager_;
595 }
596
597 const LegacyQuicStreamIdManager& stream_id_manager() const {
598 return stream_id_manager_;
599 }
600
vasilvv2b0ab242020-01-07 07:32:09 -0800601 QuicDatagramQueue* datagram_queue() { return &datagram_queue_; }
602
renjietang0c558862019-05-08 13:26:23 -0700603 // Processes the stream type information of |pending| depending on
renjietangbb1c4892019-05-24 15:58:44 -0700604 // different kinds of sessions' own rules. Returns true if the pending stream
605 // is converted into a normal stream.
dschinazi17d42422019-06-18 16:35:07 -0700606 virtual bool ProcessPendingStream(PendingStream* /*pending*/) {
607 return false;
608 }
renjietang0c558862019-05-08 13:26:23 -0700609
renjietang686ce582019-10-17 14:28:16 -0700610 // Return the largest peer created stream id depending on directionality
611 // indicated by |unidirectional|.
612 QuicStreamId GetLargestPeerCreatedStreamId(bool unidirectional) const;
613
ianswett6aefa0b2019-12-10 07:26:15 -0800614 // Deletes the connection and sets it to nullptr, so calling it mulitiple
615 // times is safe.
616 void DeleteConnection();
617
bncb4e7b992020-01-21 18:36:14 -0800618 // Call SetPriority() on stream id |id| and return true if stream is active.
619 bool MaybeSetStreamPriority(QuicStreamId stream_id,
620 const spdy::SpdyStreamPrecedence& precedence);
621
QUICHE teama6ef0a62019-03-07 20:34:33 -0500622 private:
623 friend class test::QuicSessionPeer;
624
625 // Called in OnConfigNegotiated when we receive a new stream level flow
626 // control window in a negotiated config. Closes the connection if invalid.
627 void OnNewStreamFlowControlWindow(QuicStreamOffset new_window);
628
dschinazi18cdf132019-10-09 16:08:18 -0700629 // Called in OnConfigNegotiated when we receive a new unidirectional stream
630 // flow control window in a negotiated config.
631 void OnNewStreamUnidirectionalFlowControlWindow(QuicStreamOffset new_window);
632
633 // Called in OnConfigNegotiated when we receive a new outgoing bidirectional
634 // stream flow control window in a negotiated config.
635 void OnNewStreamOutgoingBidirectionalFlowControlWindow(
636 QuicStreamOffset new_window);
637
638 // Called in OnConfigNegotiated when we receive a new incoming bidirectional
639 // stream flow control window in a negotiated config.
640 void OnNewStreamIncomingBidirectionalFlowControlWindow(
641 QuicStreamOffset new_window);
642
QUICHE teama6ef0a62019-03-07 20:34:33 -0500643 // Called in OnConfigNegotiated when we receive a new connection level flow
644 // control window in a negotiated config. Closes the connection if invalid.
645 void OnNewSessionFlowControlWindow(QuicStreamOffset new_window);
646
647 // Debug helper for |OnCanWrite()|, check that OnStreamWrite() makes
648 // forward progress. Returns false if busy loop detected.
649 bool CheckStreamNotBusyLooping(QuicStream* stream,
650 uint64_t previous_bytes_written,
651 bool previous_fin_sent);
652
653 // Debug helper for OnCanWrite. Check that after QuicStream::OnCanWrite(),
654 // if stream has buffered data and is not stream level flow control blocked,
655 // it has to be in the write blocked list.
656 bool CheckStreamWriteBlocked(QuicStream* stream) const;
657
658 // Called in OnConfigNegotiated for Finch trials to measure performance of
659 // starting with larger flow control receive windows.
660 void AdjustInitialFlowControlWindows(size_t stream_window);
661
662 // Find stream with |id|, returns nullptr if the stream does not exist or
663 // closed.
664 QuicStream* GetStream(QuicStreamId id) const;
665
renjietange76b2da2019-05-13 14:50:23 -0700666 PendingStream* GetOrCreatePendingStream(QuicStreamId stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500667
668 // Let streams and control frame managers retransmit lost data, returns true
669 // if all lost data is retransmitted. Returns false otherwise.
670 bool RetransmitLostData();
671
672 // Closes the pending stream |stream_id| before it has been created.
673 void ClosePendingStream(QuicStreamId stream_id);
674
renjietange76b2da2019-05-13 14:50:23 -0700675 // Creates or gets pending stream, feeds it with |frame|, and processes the
676 // pending stream.
677 void PendingStreamOnStreamFrame(const QuicStreamFrame& frame);
678
679 // Creates or gets pending strea, feed it with |frame|, and closes the pending
680 // stream.
681 void PendingStreamOnRstStream(const QuicRstStreamFrame& frame);
682
renjietang61cc2452019-11-26 10:57:10 -0800683 // Does actual work of sending RESET_STREAM, if the stream type allows.
684 void MaybeSendRstStreamFrame(QuicStreamId id,
685 QuicRstStreamErrorCode error,
686 QuicStreamOffset bytes_written);
687
688 // Sends a STOP_SENDING frame if the stream type allows.
689 void MaybeSendStopSendingFrame(QuicStreamId id, QuicRstStreamErrorCode error);
690
QUICHE teama6ef0a62019-03-07 20:34:33 -0500691 // Keep track of highest received byte offset of locally closed streams, while
692 // waiting for a definitive final highest offset from the peer.
693 std::map<QuicStreamId, QuicStreamOffset>
694 locally_closed_streams_highest_offset_;
695
696 QuicConnection* connection_;
697
dschinazi31e94d42019-12-18 11:55:39 -0800698 // Store perspective on QuicSession during the constructor as it may be needed
699 // during our destructor when connection_ may have already been destroyed.
700 Perspective perspective_;
701
QUICHE teama6ef0a62019-03-07 20:34:33 -0500702 // May be null.
703 Visitor* visitor_;
704
705 // A list of streams which need to write more data. Stream register
706 // themselves in their constructor, and unregisterm themselves in their
707 // destructors, so the write blocked list must outlive all streams.
708 QuicWriteBlockedList write_blocked_streams_;
709
710 ClosedStreams closed_streams_;
711 // Streams which are closed, but need to be kept alive. Currently, the only
712 // reason is the stream's sent data (including FIN) does not get fully acked.
713 ZombieStreamMap zombie_streams_;
714
715 QuicConfig config_;
716
QUICHE teama6ef0a62019-03-07 20:34:33 -0500717 // Map from StreamId to pointers to streams. Owns the streams.
renjietang55d182a2019-07-12 10:26:25 -0700718 StreamMap stream_map_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500719
720 // Map from StreamId to PendingStreams for peer-created unidirectional streams
721 // which are waiting for the first byte of payload to arrive.
722 PendingStreamMap pending_stream_map_;
723
724 // Set of stream ids that are "draining" -- a FIN has been sent and received,
725 // but the stream object still exists because not all the received data has
726 // been consumed.
727 QuicUnorderedSet<QuicStreamId> draining_streams_;
728
zhongyi1b2f7832019-06-14 13:31:34 -0700729 // Set of stream ids that are waiting for acks excluding crypto stream id.
730 QuicUnorderedSet<QuicStreamId> streams_waiting_for_acks_;
731
QUICHE teama6ef0a62019-03-07 20:34:33 -0500732 // TODO(fayang): Consider moving LegacyQuicStreamIdManager into
733 // UberQuicStreamIdManager.
734 // Manages stream IDs for Google QUIC.
735 LegacyQuicStreamIdManager stream_id_manager_;
736
737 // Manages stream IDs for version99/IETF QUIC
738 UberQuicStreamIdManager v99_streamid_manager_;
739
renjietang55d182a2019-07-12 10:26:25 -0700740 // A counter for peer initiated dynamic streams which are in the stream_map_.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500741 size_t num_dynamic_incoming_streams_;
742
743 // A counter for peer initiated streams which are in the draining_streams_.
744 size_t num_draining_incoming_streams_;
745
renjietangfbeb5bf2019-04-19 15:06:20 -0700746 // A counter for self initiated static streams which are in
renjietang55d182a2019-07-12 10:26:25 -0700747 // stream_map_.
renjietangfbeb5bf2019-04-19 15:06:20 -0700748 size_t num_outgoing_static_streams_;
749
750 // A counter for peer initiated static streams which are in
renjietang55d182a2019-07-12 10:26:25 -0700751 // stream_map_.
renjietangfbeb5bf2019-04-19 15:06:20 -0700752 size_t num_incoming_static_streams_;
753
QUICHE teama6ef0a62019-03-07 20:34:33 -0500754 // A counter for peer initiated streams which are in the
755 // locally_closed_streams_highest_offset_.
756 size_t num_locally_closed_incoming_streams_highest_offset_;
757
fkastenholz488a4622019-08-26 06:24:46 -0700758 // Received information for a connection close.
759 QuicConnectionCloseFrame on_closed_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500760
761 // Used for connection-level flow control.
762 QuicFlowController flow_controller_;
763
764 // The stream id which was last popped in OnCanWrite, or 0, if not under the
765 // call stack of OnCanWrite.
766 QuicStreamId currently_writing_stream_id_;
767
QUICHE teama6ef0a62019-03-07 20:34:33 -0500768 // Whether a GoAway has been sent.
769 bool goaway_sent_;
770
771 // Whether a GoAway has been received.
772 bool goaway_received_;
773
774 QuicControlFrameManager control_frame_manager_;
775
776 // Id of latest successfully sent message.
777 QuicMessageId last_message_id_;
778
vasilvv2b0ab242020-01-07 07:32:09 -0800779 // The buffer used to queue the DATAGRAM frames.
780 QuicDatagramQueue datagram_queue_;
781
QUICHE teama6ef0a62019-03-07 20:34:33 -0500782 // TODO(fayang): switch to linked_hash_set when chromium supports it. The bool
783 // is not used here.
784 // List of streams with pending retransmissions.
785 QuicLinkedHashMap<QuicStreamId, bool> streams_with_pending_retransmission_;
786
787 // Clean up closed_streams_ when this alarm fires.
788 std::unique_ptr<QuicAlarm> closed_streams_clean_up_alarm_;
789
790 // Supported version list used by the crypto handshake only. Please note, this
791 // list may be a superset of the connection framer's supported versions.
792 ParsedQuicVersionVector supported_versions_;
fayang944cfbc2019-07-31 09:15:00 -0700793
794 // If true, write_blocked_streams_ uses HTTP2 (tree-style) priority write
795 // scheduler.
796 bool use_http2_priority_write_scheduler_;
fkastenholz9b4b0ad2019-08-20 05:10:40 -0700797
798 // Initialized to false. Set to true when the session has been properly
799 // configured and is ready for general operation.
800 bool is_configured_;
renjietang216dc012019-08-27 11:28:27 -0700801
802 // The number of expected static streams.
803 QuicStreamCount num_expected_unidirectional_static_streams_;
fayang1b11b962019-09-16 14:01:48 -0700804
805 // If true, enables round robin scheduling.
806 bool enable_round_robin_scheduling_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500807};
808
809} // namespace quic
810
811#endif // QUICHE_QUIC_CORE_QUIC_SESSION_H_