blob: c4f2d98a0523fbc2acf49478eeaa6bd191498f9a [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
QUICHE teama6ef0a62019-03-07 20:34:33 -050017#include "net/third_party/quiche/src/quic/core/legacy_quic_stream_id_manager.h"
18#include "net/third_party/quiche/src/quic/core/quic_connection.h"
19#include "net/third_party/quiche/src/quic/core/quic_control_frame_manager.h"
20#include "net/third_party/quiche/src/quic/core/quic_crypto_stream.h"
wub2b5942f2019-04-11 13:22:50 -070021#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050022#include "net/third_party/quiche/src/quic/core/quic_packet_creator.h"
23#include "net/third_party/quiche/src/quic/core/quic_packets.h"
24#include "net/third_party/quiche/src/quic/core/quic_stream.h"
25#include "net/third_party/quiche/src/quic/core/quic_stream_frame_data_producer.h"
renjietang686ce582019-10-17 14:28:16 -070026#include "net/third_party/quiche/src/quic/core/quic_types.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050027#include "net/third_party/quiche/src/quic/core/quic_write_blocked_list.h"
28#include "net/third_party/quiche/src/quic/core/session_notifier_interface.h"
29#include "net/third_party/quiche/src/quic/core/uber_quic_stream_id_manager.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_containers.h"
31#include "net/third_party/quiche/src/quic/platform/api/quic_export.h"
32#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050033
34namespace quic {
35
36class QuicCryptoStream;
37class QuicFlowController;
38class QuicStream;
39class QuicStreamIdManager;
40
41namespace test {
42class QuicSessionPeer;
43} // namespace test
44
rcha8b56e42019-09-20 10:41:48 -070045class QUIC_EXPORT_PRIVATE QuicSession
46 : public QuicConnectionVisitorInterface,
47 public SessionNotifierInterface,
48 public QuicStreamFrameDataProducer,
49 public QuicStreamIdManager::DelegateInterface {
QUICHE teama6ef0a62019-03-07 20:34:33 -050050 public:
51 // An interface from the session to the entity owning the session.
52 // This lets the session notify its owner (the Dispatcher) when the connection
53 // is closed, blocked, or added/removed from the time-wait list.
dschinazif25169a2019-10-23 08:12:18 -070054 class QUIC_EXPORT_PRIVATE Visitor {
QUICHE teama6ef0a62019-03-07 20:34:33 -050055 public:
56 virtual ~Visitor() {}
57
58 // Called when the connection is closed after the streams have been closed.
dschinazi7b9278c2019-05-20 07:36:21 -070059 virtual void OnConnectionClosed(QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -050060 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -070061 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -050062 ConnectionCloseSource source) = 0;
63
64 // Called when the session has become write blocked.
65 virtual void OnWriteBlocked(QuicBlockedWriterInterface* blocked_writer) = 0;
66
67 // Called when the session receives reset on a stream from the peer.
68 virtual void OnRstStreamReceived(const QuicRstStreamFrame& frame) = 0;
69
70 // Called when the session receives a STOP_SENDING for a stream from the
71 // peer.
72 virtual void OnStopSendingReceived(const QuicStopSendingFrame& frame) = 0;
73 };
74
75 // CryptoHandshakeEvent enumerates the events generated by a QuicCryptoStream.
76 enum CryptoHandshakeEvent {
renjietangea71d6f2019-08-19 12:22:28 -070077 // ENCRYPTION_ESTABLISHED indicates that a client hello has been sent and
78 // subsequent packets will be encrypted. (Client only.)
79 ENCRYPTION_ESTABLISHED,
QUICHE teama6ef0a62019-03-07 20:34:33 -050080 // HANDSHAKE_CONFIRMED, in a client, indicates the server has accepted
81 // our handshake. In a server it indicates that a full, valid client hello
82 // has been received. (Client and server.)
83 HANDSHAKE_CONFIRMED,
84 };
85
86 // Does not take ownership of |connection| or |visitor|.
87 QuicSession(QuicConnection* connection,
88 Visitor* owner,
89 const QuicConfig& config,
renjietang216dc012019-08-27 11:28:27 -070090 const ParsedQuicVersionVector& supported_versions,
91 QuicStreamCount num_expected_unidirectional_static_streams);
QUICHE teama6ef0a62019-03-07 20:34:33 -050092 QuicSession(const QuicSession&) = delete;
93 QuicSession& operator=(const QuicSession&) = delete;
94
95 ~QuicSession() override;
96
97 virtual void Initialize();
98
99 // QuicConnectionVisitorInterface methods:
100 void OnStreamFrame(const QuicStreamFrame& frame) override;
101 void OnCryptoFrame(const QuicCryptoFrame& frame) override;
102 void OnRstStream(const QuicRstStreamFrame& frame) override;
103 void OnGoAway(const QuicGoAwayFrame& frame) override;
104 void OnMessageReceived(QuicStringPiece message) override;
105 void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
106 void OnBlockedFrame(const QuicBlockedFrame& frame) override;
fkastenholz5d880a92019-06-21 09:01:56 -0700107 void OnConnectionClosed(const QuicConnectionCloseFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500108 ConnectionCloseSource source) override;
109 void OnWriteBlocked() override;
110 void OnSuccessfulVersionNegotiation(
111 const ParsedQuicVersion& version) override;
zhongyi83161e42019-08-19 09:06:25 -0700112 void OnPacketReceived(const QuicSocketAddress& self_address,
113 const QuicSocketAddress& peer_address,
114 bool is_connectivity_probe) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500115 void OnCanWrite() override;
QUICHE teamb8343252019-04-29 13:58:01 -0700116 bool SendProbingData() override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500117 void OnCongestionWindowChange(QuicTime /*now*/) override {}
dschinazi17d42422019-06-18 16:35:07 -0700118 void OnConnectionMigration(AddressChangeType /*type*/) override {}
QUICHE teama6ef0a62019-03-07 20:34:33 -0500119 // Adds a connection level WINDOW_UPDATE frame.
120 void OnAckNeedsRetransmittableFrame() override;
121 void SendPing() override;
122 bool WillingAndAbleToWrite() const override;
123 bool HasPendingHandshake() const override;
124 void OnPathDegrading() override;
125 bool AllowSelfAddressChange() const override;
126 void OnForwardProgressConfirmed() override;
fkastenholz3c4eabf2019-04-22 07:49:59 -0700127 bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override;
128 bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override;
renjietangeab918f2019-10-28 12:10:32 -0700129 void OnStopSendingFrame(const QuicStopSendingFrame& frame) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500130
131 // QuicStreamFrameDataProducer
132 WriteStreamDataResult WriteStreamData(QuicStreamId id,
133 QuicStreamOffset offset,
134 QuicByteCount data_length,
135 QuicDataWriter* writer) override;
136 bool WriteCryptoData(EncryptionLevel level,
137 QuicStreamOffset offset,
138 QuicByteCount data_length,
139 QuicDataWriter* writer) override;
140
141 // SessionNotifierInterface methods:
142 bool OnFrameAcked(const QuicFrame& frame,
QUICHE team9467db02019-05-30 09:38:45 -0700143 QuicTime::Delta ack_delay_time,
144 QuicTime receive_timestamp) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500145 void OnStreamFrameRetransmitted(const QuicStreamFrame& frame) override;
146 void OnFrameLost(const QuicFrame& frame) override;
147 void RetransmitFrames(const QuicFrames& frames,
148 TransmissionType type) override;
149 bool IsFrameOutstanding(const QuicFrame& frame) const override;
150 bool HasUnackedCryptoData() const override;
zhongyi1b2f7832019-06-14 13:31:34 -0700151 bool HasUnackedStreamData() const override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500152
rcha8b56e42019-09-20 10:41:48 -0700153 // QuicStreamIdManager::DelegateInterface methods:
154 void OnError(QuicErrorCode error_code, std::string error_details) override;
155 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
201 // Called when message with |message_id| gets acked.
QUICHE team9467db02019-05-30 09:38:45 -0700202 virtual void OnMessageAcked(QuicMessageId message_id,
203 QuicTime receive_timestamp);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500204
205 // Called when message with |message_id| is considered as lost.
206 virtual void OnMessageLost(QuicMessageId message_id);
207
208 // Called by control frame manager when it wants to write control frames to
209 // the peer. Returns true if |frame| is consumed, false otherwise.
210 virtual bool WriteControlFrame(const QuicFrame& frame);
211
renjietang64881612019-11-05 17:39:04 -0800212 // Close the stream in both directions.
213 // TODO(renjietang): rename this method as it sends both RST_STREAM and
214 // STOP_SENDING in IETF QUIC.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500215 virtual void SendRstStream(QuicStreamId id,
216 QuicRstStreamErrorCode error,
217 QuicStreamOffset bytes_written);
218
219 // Called when the session wants to go away and not accept any new streams.
vasilvvc48c8712019-03-11 13:38:16 -0700220 virtual void SendGoAway(QuicErrorCode error_code, const std::string& reason);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500221
222 // Sends a BLOCKED frame.
223 virtual void SendBlocked(QuicStreamId id);
224
225 // Sends a WINDOW_UPDATE frame.
226 virtual void SendWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset);
227
QUICHE teama6ef0a62019-03-07 20:34:33 -0500228 // Create and transmit a STOP_SENDING frame
229 virtual void SendStopSending(uint16_t code, QuicStreamId stream_id);
230
231 // Removes the stream associated with 'stream_id' from the active stream map.
232 virtual void CloseStream(QuicStreamId stream_id);
233
234 // Returns true if outgoing packets will be encrypted, even if the server
235 // hasn't confirmed the handshake yet.
236 virtual bool IsEncryptionEstablished() const;
237
238 // For a client, returns true if the server has confirmed our handshake. For
239 // a server, returns true if a full, valid client hello has been received.
renjietang4f8e0bc2019-10-14 17:53:49 -0700240 bool IsCryptoHandshakeConfirmed() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500241
242 // Called by the QuicCryptoStream when a new QuicConfig has been negotiated.
243 virtual void OnConfigNegotiated();
244
245 // Called by the QuicCryptoStream when the handshake enters a new state.
246 //
247 // Clients will call this function in the order:
renjietangea71d6f2019-08-19 12:22:28 -0700248 // zero or more ENCRYPTION_ESTABLISHED
QUICHE teama6ef0a62019-03-07 20:34:33 -0500249 // HANDSHAKE_CONFIRMED
250 //
251 // Servers will simply call it once with HANDSHAKE_CONFIRMED.
252 virtual void OnCryptoHandshakeEvent(CryptoHandshakeEvent event);
253
254 // Called by the QuicCryptoStream when a handshake message is sent.
255 virtual void OnCryptoHandshakeMessageSent(
256 const CryptoHandshakeMessage& message);
257
258 // Called by the QuicCryptoStream when a handshake message is received.
259 virtual void OnCryptoHandshakeMessageReceived(
260 const CryptoHandshakeMessage& message);
261
262 // Called by the stream on creation to set priority in the write blocked list.
fayang476683a2019-07-25 12:42:16 -0700263 virtual void RegisterStreamPriority(
264 QuicStreamId id,
265 bool is_static,
266 const spdy::SpdyStreamPrecedence& precedence);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500267 // Called by the stream on deletion to clear priority from the write blocked
268 // list.
269 virtual void UnregisterStreamPriority(QuicStreamId id, bool is_static);
270 // Called by the stream on SetPriority to update priority on the write blocked
271 // list.
fayang476683a2019-07-25 12:42:16 -0700272 virtual void UpdateStreamPriority(
273 QuicStreamId id,
274 const spdy::SpdyStreamPrecedence& new_precedence);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500275
276 // Returns mutable config for this session. Returned config is owned
277 // by QuicSession.
278 QuicConfig* config();
279
280 // Returns true if the stream existed previously and has been closed.
281 // Returns false if the stream is still active or if the stream has
282 // not yet been created.
283 bool IsClosedStream(QuicStreamId id);
284
285 QuicConnection* connection() { return connection_; }
286 const QuicConnection* connection() const { return connection_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500287 const QuicSocketAddress& peer_address() const {
288 return connection_->peer_address();
289 }
290 const QuicSocketAddress& self_address() const {
291 return connection_->self_address();
292 }
293 QuicConnectionId connection_id() const {
294 return connection_->connection_id();
295 }
296
renjietang69a8eaf2019-08-06 15:55:58 -0700297 // Returns the number of currently open streams, excluding static streams, and
298 // never counting unfinished streams.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500299 size_t GetNumActiveStreams() const;
300
301 // Returns the number of currently draining streams.
302 size_t GetNumDrainingStreams() const;
303
renjietang69a8eaf2019-08-06 15:55:58 -0700304 // Returns the number of currently open peer initiated streams, excluding
305 // static streams.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500306 size_t GetNumOpenIncomingStreams() const;
307
renjietang69a8eaf2019-08-06 15:55:58 -0700308 // Returns the number of currently open self initiated streams, excluding
309 // static streams.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500310 size_t GetNumOpenOutgoingStreams() const;
311
renjietangfbeb5bf2019-04-19 15:06:20 -0700312 // Returns the number of open peer initiated static streams.
313 size_t num_incoming_static_streams() const {
314 return num_incoming_static_streams_;
315 }
316
317 // Returns the number of open self initiated static streams.
318 size_t num_outgoing_static_streams() const {
319 return num_outgoing_static_streams_;
320 }
321
QUICHE teama6ef0a62019-03-07 20:34:33 -0500322 // Add the stream to the session's write-blocked list because it is blocked by
323 // connection-level flow control but not by its own stream-level flow control.
324 // The stream will be given a chance to write when a connection-level
325 // WINDOW_UPDATE arrives.
QUICHE teamdf0b19f2019-08-13 16:55:42 -0700326 virtual void MarkConnectionLevelWriteBlocked(QuicStreamId id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500327
328 // Called when stream |id| is done waiting for acks either because all data
329 // gets acked or is not interested in data being acked (which happens when
330 // a stream is reset because of an error).
331 void OnStreamDoneWaitingForAcks(QuicStreamId id);
332
zhongyi1b2f7832019-06-14 13:31:34 -0700333 // Called when stream |id| is newly waiting for acks.
334 void OnStreamWaitingForAcks(QuicStreamId id);
335
QUICHE teama6ef0a62019-03-07 20:34:33 -0500336 // Called to cancel retransmission of unencypted crypto stream data.
337 void NeuterUnencryptedData();
338
339 // Returns true if the session has data to be sent, either queued in the
340 // connection, or in a write-blocked stream.
341 bool HasDataToWrite() const;
342
343 // Returns the largest payload that will fit into a single MESSAGE frame.
344 // Because overhead can vary during a connection, this method should be
345 // checked for every message.
ianswettb239f862019-04-05 09:15:06 -0700346 QuicPacketLength GetCurrentLargestMessagePayload() const;
347
348 // Returns the largest payload that will fit into a single MESSAGE frame at
349 // any point during the connection. This assumes the version and
350 // connection ID lengths do not change.
351 QuicPacketLength GetGuaranteedLargestMessagePayload() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500352
353 bool goaway_sent() const { return goaway_sent_; }
354
355 bool goaway_received() const { return goaway_received_; }
356
fkastenholz488a4622019-08-26 06:24:46 -0700357 // Returns the Google QUIC error code
358 QuicErrorCode error() const { return on_closed_frame_.extracted_error_code; }
wub43652ca2019-09-05 11:18:19 -0700359 const std::string& error_details() const {
360 return on_closed_frame_.error_details;
361 }
fkastenholz488a4622019-08-26 06:24:46 -0700362 uint64_t transport_close_frame_type() const {
363 return on_closed_frame_.transport_close_frame_type;
364 }
365 QuicConnectionCloseType close_type() const {
366 return on_closed_frame_.close_type;
367 }
368 QuicIetfTransportErrorCodes transport_error_code() const {
369 return on_closed_frame_.transport_error_code;
370 }
371 uint16_t application_error_code() const {
372 return on_closed_frame_.application_error_code;
373 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500374
375 Perspective perspective() const { return connection_->perspective(); }
376
377 QuicFlowController* flow_controller() { return &flow_controller_; }
378
379 // Returns true if connection is flow controller blocked.
380 bool IsConnectionFlowControlBlocked() const;
381
382 // Returns true if any stream is flow controller blocked.
383 bool IsStreamFlowControlBlocked();
384
385 size_t max_open_incoming_bidirectional_streams() const;
386 size_t max_open_incoming_unidirectional_streams() const;
387
388 size_t MaxAvailableBidirectionalStreams() const;
389 size_t MaxAvailableUnidirectionalStreams() const;
390
renjietang55d182a2019-07-12 10:26:25 -0700391 // Returns existing stream with id = |stream_id|. If no
392 // such stream exists, and |stream_id| is a peer-created stream id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500393 // then a new stream is created and returned. In all other cases, nullptr is
394 // returned.
renjietang880d2432019-07-16 13:14:37 -0700395 // Caller does not own the returned stream.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500396 QuicStream* GetOrCreateStream(const QuicStreamId stream_id);
397
398 // Mark a stream as draining.
399 virtual void StreamDraining(QuicStreamId id);
400
401 // Returns true if this stream should yield writes to another blocked stream.
QUICHE teamdf0b19f2019-08-13 16:55:42 -0700402 virtual bool ShouldYield(QuicStreamId stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500403
404 // Set transmission type of next sending packets.
405 void SetTransmissionType(TransmissionType type);
406
407 // Clean up closed_streams_.
408 void CleanUpClosedStreams();
409
QUICHE teama6ef0a62019-03-07 20:34:33 -0500410 const ParsedQuicVersionVector& supported_versions() const {
411 return supported_versions_;
412 }
413
QUICHE teama6ef0a62019-03-07 20:34:33 -0500414 QuicStreamId next_outgoing_bidirectional_stream_id() const;
415 QuicStreamId next_outgoing_unidirectional_stream_id() const;
416
417 // Return true if given stream is peer initiated.
418 bool IsIncomingStream(QuicStreamId id) const;
419
420 size_t GetNumLocallyClosedOutgoingStreamsHighestOffset() const;
421
422 size_t num_locally_closed_incoming_streams_highest_offset() const {
423 return num_locally_closed_incoming_streams_highest_offset_;
424 }
425
426 // Does actual work of sending reset-stream or reset-stream&stop-sending
427 // If the connection is not version 99/IETF QUIC, will always send a
428 // RESET_STREAM and close_write_side_only is ignored. If the connection is
429 // IETF QUIC/Version 99 then will send a RESET_STREAM and STOP_SENDING if
430 // close_write_side_only is false, just a RESET_STREAM if
431 // close_write_side_only is true.
432 virtual void SendRstStreamInner(QuicStreamId id,
433 QuicRstStreamErrorCode error,
434 QuicStreamOffset bytes_written,
435 bool close_write_side_only);
436
wub2b5942f2019-04-11 13:22:50 -0700437 // Record errors when a connection is closed at the server side, should only
438 // be called from server's perspective.
439 // Noop if |error| is QUIC_NO_ERROR.
440 static void RecordConnectionCloseAtServer(QuicErrorCode error,
441 ConnectionCloseSource source);
442
fkastenholzd3a1de92019-05-15 07:00:07 -0700443 inline QuicTransportVersion transport_version() const {
444 return connection_->transport_version();
445 }
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_|.
459 void ConfigureMaxIncomingDynamicStreamsToSend(QuicStreamCount max_stream) {
460 config_.SetMaxIncomingUnidirectionalStreamsToSend(
461 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.
473 virtual std::vector<QuicStringPiece>::const_iterator SelectAlpn(
474 const std::vector<QuicStringPiece>& alpns) const;
475
476 // Called when the ALPN of the connection is established for a connection that
477 // uses TLS handshake.
478 virtual void OnAlpnSelected(QuicStringPiece alpn);
479
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
QUICHE teama6ef0a62019-03-07 20:34:33 -0500522 // Performs the work required to close |stream_id|. If |locally_reset|
523 // then the stream has been reset by this endpoint, not by the peer.
524 virtual void CloseStreamInner(QuicStreamId stream_id, bool locally_reset);
525
526 // When a stream is closed locally, it may not yet know how many bytes the
527 // peer sent on that stream.
528 // When this data arrives (via stream frame w. FIN, trailing headers, or RST)
529 // this method is called, and correctly updates the connection level flow
530 // controller.
531 virtual void OnFinalByteOffsetReceived(QuicStreamId id,
532 QuicStreamOffset final_byte_offset);
533
renjietange76b2da2019-05-13 14:50:23 -0700534 // Returns true if incoming unidirectional streams should be buffered until
535 // the first byte of the stream arrives.
536 // If a subclass returns true here, it should make sure to implement
537 // ProcessPendingStream().
538 virtual bool UsesPendingStreams() const { return false; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500539
renjietang55d182a2019-07-12 10:26:25 -0700540 StreamMap& stream_map() { return stream_map_; }
541 const StreamMap& stream_map() const { return stream_map_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500542
renjietang56d2ed22019-10-22 14:11:55 -0700543 const PendingStreamMap& pending_streams() const {
544 return pending_stream_map_;
545 }
546
QUICHE teama6ef0a62019-03-07 20:34:33 -0500547 ClosedStreams* closed_streams() { return &closed_streams_; }
548
549 const ZombieStreamMap& zombie_streams() const { return zombie_streams_; }
550
551 void set_largest_peer_created_stream_id(
552 QuicStreamId largest_peer_created_stream_id);
553
QUICHE teama6ef0a62019-03-07 20:34:33 -0500554 QuicWriteBlockedList* write_blocked_streams() {
555 return &write_blocked_streams_;
556 }
557
558 size_t GetNumDynamicOutgoingStreams() const;
559
560 size_t GetNumDrainingOutgoingStreams() const;
561
562 // Returns true if the stream is still active.
563 bool IsOpenStream(QuicStreamId id);
564
rchda26cdb2019-05-17 11:57:37 -0700565 // Returns true if the stream is a static stream.
566 bool IsStaticStream(QuicStreamId id) const;
567
renjietang5c729f02019-09-06 12:43:48 -0700568 // Close connection when receive a frame for a locally-created nonexistent
QUICHE teama6ef0a62019-03-07 20:34:33 -0500569 // stream.
570 // Prerequisite: IsClosedStream(stream_id) == false
571 // Server session might need to override this method to allow server push
572 // stream to be promised before creating an active stream.
573 virtual void HandleFrameOnNonexistentOutgoingStream(QuicStreamId stream_id);
574
575 virtual bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId stream_id);
576
577 void InsertLocallyClosedStreamsHighestOffset(const QuicStreamId id,
578 QuicStreamOffset offset);
579 // If stream is a locally closed stream, this RST will update FIN offset.
580 // Otherwise stream is a preserved stream and the behavior of it depends on
581 // derived class's own implementation.
582 virtual void HandleRstOnValidNonexistentStream(
583 const QuicRstStreamFrame& frame);
584
585 // Returns a stateless reset token which will be included in the public reset
586 // packet.
587 virtual QuicUint128 GetStatelessResetToken() const;
588
589 QuicControlFrameManager& control_frame_manager() {
590 return control_frame_manager_;
591 }
592
593 const LegacyQuicStreamIdManager& stream_id_manager() const {
594 return stream_id_manager_;
595 }
596
renjietang0c558862019-05-08 13:26:23 -0700597 // Processes the stream type information of |pending| depending on
renjietangbb1c4892019-05-24 15:58:44 -0700598 // different kinds of sessions' own rules. Returns true if the pending stream
599 // is converted into a normal stream.
dschinazi17d42422019-06-18 16:35:07 -0700600 virtual bool ProcessPendingStream(PendingStream* /*pending*/) {
601 return false;
602 }
renjietang0c558862019-05-08 13:26:23 -0700603
renjietang686ce582019-10-17 14:28:16 -0700604 // Return the largest peer created stream id depending on directionality
605 // indicated by |unidirectional|.
606 QuicStreamId GetLargestPeerCreatedStreamId(bool unidirectional) const;
607
QUICHE teama6ef0a62019-03-07 20:34:33 -0500608 private:
609 friend class test::QuicSessionPeer;
610
611 // Called in OnConfigNegotiated when we receive a new stream level flow
612 // control window in a negotiated config. Closes the connection if invalid.
613 void OnNewStreamFlowControlWindow(QuicStreamOffset new_window);
614
dschinazi18cdf132019-10-09 16:08:18 -0700615 // Called in OnConfigNegotiated when we receive a new unidirectional stream
616 // flow control window in a negotiated config.
617 void OnNewStreamUnidirectionalFlowControlWindow(QuicStreamOffset new_window);
618
619 // Called in OnConfigNegotiated when we receive a new outgoing bidirectional
620 // stream flow control window in a negotiated config.
621 void OnNewStreamOutgoingBidirectionalFlowControlWindow(
622 QuicStreamOffset new_window);
623
624 // Called in OnConfigNegotiated when we receive a new incoming bidirectional
625 // stream flow control window in a negotiated config.
626 void OnNewStreamIncomingBidirectionalFlowControlWindow(
627 QuicStreamOffset new_window);
628
QUICHE teama6ef0a62019-03-07 20:34:33 -0500629 // Called in OnConfigNegotiated when we receive a new connection level flow
630 // control window in a negotiated config. Closes the connection if invalid.
631 void OnNewSessionFlowControlWindow(QuicStreamOffset new_window);
632
633 // Debug helper for |OnCanWrite()|, check that OnStreamWrite() makes
634 // forward progress. Returns false if busy loop detected.
635 bool CheckStreamNotBusyLooping(QuicStream* stream,
636 uint64_t previous_bytes_written,
637 bool previous_fin_sent);
638
639 // Debug helper for OnCanWrite. Check that after QuicStream::OnCanWrite(),
640 // if stream has buffered data and is not stream level flow control blocked,
641 // it has to be in the write blocked list.
642 bool CheckStreamWriteBlocked(QuicStream* stream) const;
643
644 // Called in OnConfigNegotiated for Finch trials to measure performance of
645 // starting with larger flow control receive windows.
646 void AdjustInitialFlowControlWindows(size_t stream_window);
647
648 // Find stream with |id|, returns nullptr if the stream does not exist or
649 // closed.
650 QuicStream* GetStream(QuicStreamId id) const;
651
renjietange76b2da2019-05-13 14:50:23 -0700652 PendingStream* GetOrCreatePendingStream(QuicStreamId stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500653
654 // Let streams and control frame managers retransmit lost data, returns true
655 // if all lost data is retransmitted. Returns false otherwise.
656 bool RetransmitLostData();
657
658 // Closes the pending stream |stream_id| before it has been created.
659 void ClosePendingStream(QuicStreamId stream_id);
660
renjietange76b2da2019-05-13 14:50:23 -0700661 // Creates or gets pending stream, feeds it with |frame|, and processes the
662 // pending stream.
663 void PendingStreamOnStreamFrame(const QuicStreamFrame& frame);
664
665 // Creates or gets pending strea, feed it with |frame|, and closes the pending
666 // stream.
667 void PendingStreamOnRstStream(const QuicRstStreamFrame& frame);
668
QUICHE teama6ef0a62019-03-07 20:34:33 -0500669 // Keep track of highest received byte offset of locally closed streams, while
670 // waiting for a definitive final highest offset from the peer.
671 std::map<QuicStreamId, QuicStreamOffset>
672 locally_closed_streams_highest_offset_;
673
674 QuicConnection* connection_;
675
676 // May be null.
677 Visitor* visitor_;
678
679 // A list of streams which need to write more data. Stream register
680 // themselves in their constructor, and unregisterm themselves in their
681 // destructors, so the write blocked list must outlive all streams.
682 QuicWriteBlockedList write_blocked_streams_;
683
684 ClosedStreams closed_streams_;
685 // Streams which are closed, but need to be kept alive. Currently, the only
686 // reason is the stream's sent data (including FIN) does not get fully acked.
687 ZombieStreamMap zombie_streams_;
688
689 QuicConfig config_;
690
QUICHE teama6ef0a62019-03-07 20:34:33 -0500691 // Map from StreamId to pointers to streams. Owns the streams.
renjietang55d182a2019-07-12 10:26:25 -0700692 StreamMap stream_map_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500693
694 // Map from StreamId to PendingStreams for peer-created unidirectional streams
695 // which are waiting for the first byte of payload to arrive.
696 PendingStreamMap pending_stream_map_;
697
698 // Set of stream ids that are "draining" -- a FIN has been sent and received,
699 // but the stream object still exists because not all the received data has
700 // been consumed.
701 QuicUnorderedSet<QuicStreamId> draining_streams_;
702
zhongyi1b2f7832019-06-14 13:31:34 -0700703 // Set of stream ids that are waiting for acks excluding crypto stream id.
704 QuicUnorderedSet<QuicStreamId> streams_waiting_for_acks_;
705
QUICHE teama6ef0a62019-03-07 20:34:33 -0500706 // TODO(fayang): Consider moving LegacyQuicStreamIdManager into
707 // UberQuicStreamIdManager.
708 // Manages stream IDs for Google QUIC.
709 LegacyQuicStreamIdManager stream_id_manager_;
710
711 // Manages stream IDs for version99/IETF QUIC
712 UberQuicStreamIdManager v99_streamid_manager_;
713
renjietang55d182a2019-07-12 10:26:25 -0700714 // A counter for peer initiated dynamic streams which are in the stream_map_.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500715 size_t num_dynamic_incoming_streams_;
716
717 // A counter for peer initiated streams which are in the draining_streams_.
718 size_t num_draining_incoming_streams_;
719
renjietangfbeb5bf2019-04-19 15:06:20 -0700720 // A counter for self initiated static streams which are in
renjietang55d182a2019-07-12 10:26:25 -0700721 // stream_map_.
renjietangfbeb5bf2019-04-19 15:06:20 -0700722 size_t num_outgoing_static_streams_;
723
724 // A counter for peer initiated static streams which are in
renjietang55d182a2019-07-12 10:26:25 -0700725 // stream_map_.
renjietangfbeb5bf2019-04-19 15:06:20 -0700726 size_t num_incoming_static_streams_;
727
QUICHE teama6ef0a62019-03-07 20:34:33 -0500728 // A counter for peer initiated streams which are in the
729 // locally_closed_streams_highest_offset_.
730 size_t num_locally_closed_incoming_streams_highest_offset_;
731
fkastenholz488a4622019-08-26 06:24:46 -0700732 // Received information for a connection close.
733 QuicConnectionCloseFrame on_closed_frame_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500734
735 // Used for connection-level flow control.
736 QuicFlowController flow_controller_;
737
738 // The stream id which was last popped in OnCanWrite, or 0, if not under the
739 // call stack of OnCanWrite.
740 QuicStreamId currently_writing_stream_id_;
741
QUICHE teama6ef0a62019-03-07 20:34:33 -0500742 // Whether a GoAway has been sent.
743 bool goaway_sent_;
744
745 // Whether a GoAway has been received.
746 bool goaway_received_;
747
748 QuicControlFrameManager control_frame_manager_;
749
750 // Id of latest successfully sent message.
751 QuicMessageId last_message_id_;
752
753 // TODO(fayang): switch to linked_hash_set when chromium supports it. The bool
754 // is not used here.
755 // List of streams with pending retransmissions.
756 QuicLinkedHashMap<QuicStreamId, bool> streams_with_pending_retransmission_;
757
758 // Clean up closed_streams_ when this alarm fires.
759 std::unique_ptr<QuicAlarm> closed_streams_clean_up_alarm_;
760
761 // Supported version list used by the crypto handshake only. Please note, this
762 // list may be a superset of the connection framer's supported versions.
763 ParsedQuicVersionVector supported_versions_;
fayang944cfbc2019-07-31 09:15:00 -0700764
765 // If true, write_blocked_streams_ uses HTTP2 (tree-style) priority write
766 // scheduler.
767 bool use_http2_priority_write_scheduler_;
fkastenholz9b4b0ad2019-08-20 05:10:40 -0700768
769 // Initialized to false. Set to true when the session has been properly
770 // configured and is ready for general operation.
771 bool is_configured_;
renjietang216dc012019-08-27 11:28:27 -0700772
773 // The number of expected static streams.
774 QuicStreamCount num_expected_unidirectional_static_streams_;
fayang1b11b962019-09-16 14:01:48 -0700775
776 // If true, enables round robin scheduling.
777 bool enable_round_robin_scheduling_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500778};
779
780} // namespace quic
781
782#endif // QUICHE_QUIC_CORE_QUIC_SESSION_H_