blob: 59883696a2c40acb0226c8df20761a0e01d01121 [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>
11#include <map>
12#include <memory>
vasilvv872e7a32019-03-12 16:42:44 -070013#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include <vector>
15
QUICHE teama6ef0a62019-03-07 20:34:33 -050016#include "net/third_party/quiche/src/quic/core/legacy_quic_stream_id_manager.h"
17#include "net/third_party/quiche/src/quic/core/quic_connection.h"
18#include "net/third_party/quiche/src/quic/core/quic_control_frame_manager.h"
19#include "net/third_party/quiche/src/quic/core/quic_crypto_stream.h"
wub2b5942f2019-04-11 13:22:50 -070020#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050021#include "net/third_party/quiche/src/quic/core/quic_packet_creator.h"
22#include "net/third_party/quiche/src/quic/core/quic_packets.h"
23#include "net/third_party/quiche/src/quic/core/quic_stream.h"
24#include "net/third_party/quiche/src/quic/core/quic_stream_frame_data_producer.h"
25#include "net/third_party/quiche/src/quic/core/quic_write_blocked_list.h"
26#include "net/third_party/quiche/src/quic/core/session_notifier_interface.h"
27#include "net/third_party/quiche/src/quic/core/uber_quic_stream_id_manager.h"
28#include "net/third_party/quiche/src/quic/platform/api/quic_containers.h"
29#include "net/third_party/quiche/src/quic/platform/api/quic_export.h"
30#include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050031
32namespace quic {
33
34class QuicCryptoStream;
35class QuicFlowController;
36class QuicStream;
37class QuicStreamIdManager;
38
39namespace test {
40class QuicSessionPeer;
41} // namespace test
42
43class QUIC_EXPORT_PRIVATE QuicSession : public QuicConnectionVisitorInterface,
44 public SessionNotifierInterface,
45 public QuicStreamFrameDataProducer {
46 public:
47 // An interface from the session to the entity owning the session.
48 // This lets the session notify its owner (the Dispatcher) when the connection
49 // is closed, blocked, or added/removed from the time-wait list.
50 class Visitor {
51 public:
52 virtual ~Visitor() {}
53
54 // Called when the connection is closed after the streams have been closed.
dschinazi7b9278c2019-05-20 07:36:21 -070055 virtual void OnConnectionClosed(QuicConnectionId server_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -050056 QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -070057 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -050058 ConnectionCloseSource source) = 0;
59
60 // Called when the session has become write blocked.
61 virtual void OnWriteBlocked(QuicBlockedWriterInterface* blocked_writer) = 0;
62
63 // Called when the session receives reset on a stream from the peer.
64 virtual void OnRstStreamReceived(const QuicRstStreamFrame& frame) = 0;
65
66 // Called when the session receives a STOP_SENDING for a stream from the
67 // peer.
68 virtual void OnStopSendingReceived(const QuicStopSendingFrame& frame) = 0;
69 };
70
71 // CryptoHandshakeEvent enumerates the events generated by a QuicCryptoStream.
72 enum CryptoHandshakeEvent {
73 // ENCRYPTION_FIRST_ESTABLISHED indicates that a full client hello has been
74 // sent by a client and that subsequent packets will be encrypted. (Client
75 // only.)
76 ENCRYPTION_FIRST_ESTABLISHED,
77 // ENCRYPTION_REESTABLISHED indicates that a client hello was rejected by
78 // the server and thus the encryption key has been updated. Therefore the
79 // connection should resend any packets that were sent under
80 // ENCRYPTION_ZERO_RTT. (Client only.)
81 ENCRYPTION_REESTABLISHED,
82 // HANDSHAKE_CONFIRMED, in a client, indicates the server has accepted
83 // our handshake. In a server it indicates that a full, valid client hello
84 // has been received. (Client and server.)
85 HANDSHAKE_CONFIRMED,
86 };
87
88 // Does not take ownership of |connection| or |visitor|.
89 QuicSession(QuicConnection* connection,
90 Visitor* owner,
91 const QuicConfig& config,
92 const ParsedQuicVersionVector& supported_versions);
93 QuicSession(const QuicSession&) = delete;
94 QuicSession& operator=(const QuicSession&) = delete;
95
96 ~QuicSession() override;
97
98 virtual void Initialize();
99
100 // QuicConnectionVisitorInterface methods:
101 void OnStreamFrame(const QuicStreamFrame& frame) override;
102 void OnCryptoFrame(const QuicCryptoFrame& frame) override;
103 void OnRstStream(const QuicRstStreamFrame& frame) override;
104 void OnGoAway(const QuicGoAwayFrame& frame) override;
105 void OnMessageReceived(QuicStringPiece message) override;
106 void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
107 void OnBlockedFrame(const QuicBlockedFrame& frame) override;
108 void OnConnectionClosed(QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -0700109 const std::string& error_details,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500110 ConnectionCloseSource source) override;
111 void OnWriteBlocked() override;
112 void OnSuccessfulVersionNegotiation(
113 const ParsedQuicVersion& version) override;
114 void OnConnectivityProbeReceived(
115 const QuicSocketAddress& self_address,
116 const QuicSocketAddress& peer_address) override;
117 void OnCanWrite() override;
QUICHE teamb8343252019-04-29 13:58:01 -0700118 bool SendProbingData() override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500119 void OnCongestionWindowChange(QuicTime /*now*/) override {}
120 void OnConnectionMigration(AddressChangeType type) override {}
121 // Adds a connection level WINDOW_UPDATE frame.
122 void OnAckNeedsRetransmittableFrame() override;
123 void SendPing() override;
124 bool WillingAndAbleToWrite() const override;
125 bool HasPendingHandshake() const override;
126 void OnPathDegrading() override;
127 bool AllowSelfAddressChange() const override;
128 void OnForwardProgressConfirmed() override;
fkastenholz3c4eabf2019-04-22 07:49:59 -0700129 bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override;
130 bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500131 bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override;
132
133 // QuicStreamFrameDataProducer
134 WriteStreamDataResult WriteStreamData(QuicStreamId id,
135 QuicStreamOffset offset,
136 QuicByteCount data_length,
137 QuicDataWriter* writer) override;
138 bool WriteCryptoData(EncryptionLevel level,
139 QuicStreamOffset offset,
140 QuicByteCount data_length,
141 QuicDataWriter* writer) override;
142
143 // SessionNotifierInterface methods:
144 bool OnFrameAcked(const QuicFrame& frame,
145 QuicTime::Delta ack_delay_time) override;
146 void OnStreamFrameRetransmitted(const QuicStreamFrame& frame) override;
147 void OnFrameLost(const QuicFrame& frame) override;
148 void RetransmitFrames(const QuicFrames& frames,
149 TransmissionType type) override;
150 bool IsFrameOutstanding(const QuicFrame& frame) const override;
151 bool HasUnackedCryptoData() const override;
152
153 // Called on every incoming packet. Passes |packet| through to |connection_|.
154 virtual void ProcessUdpPacket(const QuicSocketAddress& self_address,
155 const QuicSocketAddress& peer_address,
156 const QuicReceivedPacket& packet);
157
158 // Called by streams when they want to write data to the peer.
159 // Returns a pair with the number of bytes consumed from data, and a boolean
160 // indicating if the fin bit was consumed. This does not indicate the data
161 // has been sent on the wire: it may have been turned into a packet and queued
162 // if the socket was unexpectedly blocked.
163 virtual QuicConsumedData WritevData(QuicStream* stream,
164 QuicStreamId id,
165 size_t write_length,
166 QuicStreamOffset offset,
167 StreamSendingState state);
168
169 // Called by application to send |message|. Data copy can be avoided if
170 // |message| is provided in reference counted memory.
171 // Please note, |message| provided in reference counted memory would be moved
172 // internally when message is successfully sent. Thereafter, it would be
173 // undefined behavior if callers try to access the slices through their own
174 // copy of the span object.
175 // Returns the message result which includes the message status and message ID
176 // (valid if the write succeeds). SendMessage flushes a message packet even it
177 // is not full. If the application wants to bundle other data in the same
178 // packet, please consider adding a packet flusher around the SendMessage
179 // and/or WritevData calls.
180 //
181 // OnMessageAcked and OnMessageLost are called when a particular message gets
182 // acked or lost.
183 //
184 // Note that SendMessage will fail with status = MESSAGE_STATUS_BLOCKED
185 // if connection is congestion control blocked or underlying socket is write
186 // blocked. In this case the caller can retry sending message again when
187 // connection becomes available, for example after getting OnCanWrite()
188 // callback.
189 MessageResult SendMessage(QuicMemSliceSpan message);
190
191 // Called when message with |message_id| gets acked.
192 virtual void OnMessageAcked(QuicMessageId message_id);
193
194 // Called when message with |message_id| is considered as lost.
195 virtual void OnMessageLost(QuicMessageId message_id);
196
197 // Called by control frame manager when it wants to write control frames to
198 // the peer. Returns true if |frame| is consumed, false otherwise.
199 virtual bool WriteControlFrame(const QuicFrame& frame);
200
201 // Called by streams when they want to close the stream in both directions.
202 virtual void SendRstStream(QuicStreamId id,
203 QuicRstStreamErrorCode error,
204 QuicStreamOffset bytes_written);
205
206 // Called when the session wants to go away and not accept any new streams.
vasilvvc48c8712019-03-11 13:38:16 -0700207 virtual void SendGoAway(QuicErrorCode error_code, const std::string& reason);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500208
209 // Sends a BLOCKED frame.
210 virtual void SendBlocked(QuicStreamId id);
211
212 // Sends a WINDOW_UPDATE frame.
213 virtual void SendWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset);
214
fkastenholz3c4eabf2019-04-22 07:49:59 -0700215 // Send a MAX_STREAMS frame.
216 void SendMaxStreams(QuicStreamCount stream_count, bool unidirectional);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500217
fkastenholz3c4eabf2019-04-22 07:49:59 -0700218 // Send a STREAMS_BLOCKED frame.
219 void SendStreamsBlocked(QuicStreamCount stream_count, bool unidirectional);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500220
221 // Create and transmit a STOP_SENDING frame
222 virtual void SendStopSending(uint16_t code, QuicStreamId stream_id);
223
224 // Removes the stream associated with 'stream_id' from the active stream map.
225 virtual void CloseStream(QuicStreamId stream_id);
226
227 // Returns true if outgoing packets will be encrypted, even if the server
228 // hasn't confirmed the handshake yet.
229 virtual bool IsEncryptionEstablished() const;
230
231 // For a client, returns true if the server has confirmed our handshake. For
232 // a server, returns true if a full, valid client hello has been received.
233 virtual bool IsCryptoHandshakeConfirmed() const;
234
235 // Called by the QuicCryptoStream when a new QuicConfig has been negotiated.
236 virtual void OnConfigNegotiated();
237
238 // Called by the QuicCryptoStream when the handshake enters a new state.
239 //
240 // Clients will call this function in the order:
241 // ENCRYPTION_FIRST_ESTABLISHED
242 // zero or more ENCRYPTION_REESTABLISHED
243 // HANDSHAKE_CONFIRMED
244 //
245 // Servers will simply call it once with HANDSHAKE_CONFIRMED.
246 virtual void OnCryptoHandshakeEvent(CryptoHandshakeEvent event);
247
248 // Called by the QuicCryptoStream when a handshake message is sent.
249 virtual void OnCryptoHandshakeMessageSent(
250 const CryptoHandshakeMessage& message);
251
252 // Called by the QuicCryptoStream when a handshake message is received.
253 virtual void OnCryptoHandshakeMessageReceived(
254 const CryptoHandshakeMessage& message);
255
256 // Called by the stream on creation to set priority in the write blocked list.
257 virtual void RegisterStreamPriority(QuicStreamId id,
258 bool is_static,
259 spdy::SpdyPriority priority);
260 // Called by the stream on deletion to clear priority from the write blocked
261 // list.
262 virtual void UnregisterStreamPriority(QuicStreamId id, bool is_static);
263 // Called by the stream on SetPriority to update priority on the write blocked
264 // list.
265 virtual void UpdateStreamPriority(QuicStreamId id,
266 spdy::SpdyPriority new_priority);
267
268 // Returns mutable config for this session. Returned config is owned
269 // by QuicSession.
270 QuicConfig* config();
271
272 // Returns true if the stream existed previously and has been closed.
273 // Returns false if the stream is still active or if the stream has
274 // not yet been created.
275 bool IsClosedStream(QuicStreamId id);
276
277 QuicConnection* connection() { return connection_; }
278 const QuicConnection* connection() const { return connection_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500279 const QuicSocketAddress& peer_address() const {
280 return connection_->peer_address();
281 }
282 const QuicSocketAddress& self_address() const {
283 return connection_->self_address();
284 }
285 QuicConnectionId connection_id() const {
286 return connection_->connection_id();
287 }
288
289 // Returns the number of currently open streams, excluding the reserved
290 // headers and crypto streams, and never counting unfinished streams.
291 size_t GetNumActiveStreams() const;
292
293 // Returns the number of currently draining streams.
294 size_t GetNumDrainingStreams() const;
295
296 // Returns the number of currently open peer initiated streams, excluding the
297 // reserved headers and crypto streams.
298 size_t GetNumOpenIncomingStreams() const;
299
300 // Returns the number of currently open self initiated streams, excluding the
301 // reserved headers and crypto streams.
302 size_t GetNumOpenOutgoingStreams() const;
303
renjietangfbeb5bf2019-04-19 15:06:20 -0700304 // Returns the number of open peer initiated static streams.
305 size_t num_incoming_static_streams() const {
306 return num_incoming_static_streams_;
307 }
308
309 // Returns the number of open self initiated static streams.
310 size_t num_outgoing_static_streams() const {
311 return num_outgoing_static_streams_;
312 }
313
QUICHE teama6ef0a62019-03-07 20:34:33 -0500314 // Add the stream to the session's write-blocked list because it is blocked by
315 // connection-level flow control but not by its own stream-level flow control.
316 // The stream will be given a chance to write when a connection-level
317 // WINDOW_UPDATE arrives.
318 void MarkConnectionLevelWriteBlocked(QuicStreamId id);
319
320 // Called when stream |id| is done waiting for acks either because all data
321 // gets acked or is not interested in data being acked (which happens when
322 // a stream is reset because of an error).
323 void OnStreamDoneWaitingForAcks(QuicStreamId id);
324
325 // Called to cancel retransmission of unencypted crypto stream data.
326 void NeuterUnencryptedData();
327
328 // Returns true if the session has data to be sent, either queued in the
329 // connection, or in a write-blocked stream.
330 bool HasDataToWrite() const;
331
332 // Returns the largest payload that will fit into a single MESSAGE frame.
333 // Because overhead can vary during a connection, this method should be
334 // checked for every message.
ianswettb239f862019-04-05 09:15:06 -0700335 QuicPacketLength GetCurrentLargestMessagePayload() const;
336
337 // Returns the largest payload that will fit into a single MESSAGE frame at
338 // any point during the connection. This assumes the version and
339 // connection ID lengths do not change.
340 QuicPacketLength GetGuaranteedLargestMessagePayload() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500341
342 bool goaway_sent() const { return goaway_sent_; }
343
344 bool goaway_received() const { return goaway_received_; }
345
346 QuicErrorCode error() const { return error_; }
347
348 Perspective perspective() const { return connection_->perspective(); }
349
350 QuicFlowController* flow_controller() { return &flow_controller_; }
351
352 // Returns true if connection is flow controller blocked.
353 bool IsConnectionFlowControlBlocked() const;
354
355 // Returns true if any stream is flow controller blocked.
356 bool IsStreamFlowControlBlocked();
357
358 size_t max_open_incoming_bidirectional_streams() const;
359 size_t max_open_incoming_unidirectional_streams() const;
360
361 size_t MaxAvailableBidirectionalStreams() const;
362 size_t MaxAvailableUnidirectionalStreams() const;
363
364 // Returns existing static or dynamic stream with id = |stream_id|. If no
365 // such stream exists, and |stream_id| is a peer-created dynamic stream id,
366 // then a new stream is created and returned. In all other cases, nullptr is
367 // returned.
368 QuicStream* GetOrCreateStream(const QuicStreamId stream_id);
369
370 // Mark a stream as draining.
371 virtual void StreamDraining(QuicStreamId id);
372
373 // Returns true if this stream should yield writes to another blocked stream.
374 bool ShouldYield(QuicStreamId stream_id);
375
376 // Set transmission type of next sending packets.
377 void SetTransmissionType(TransmissionType type);
378
379 // Clean up closed_streams_.
380 void CleanUpClosedStreams();
381
382 bool session_decides_what_to_write() const;
383
384 const ParsedQuicVersionVector& supported_versions() const {
385 return supported_versions_;
386 }
387
388 // Called when new outgoing streams are available to be opened. This occurs
389 // when an extant, open, stream is moved to draining or closed. The default
390 // implementation does nothing.
391 virtual void OnCanCreateNewOutgoingStream();
392
393 QuicStreamId next_outgoing_bidirectional_stream_id() const;
394 QuicStreamId next_outgoing_unidirectional_stream_id() const;
395
396 // Return true if given stream is peer initiated.
397 bool IsIncomingStream(QuicStreamId id) const;
398
399 size_t GetNumLocallyClosedOutgoingStreamsHighestOffset() const;
400
401 size_t num_locally_closed_incoming_streams_highest_offset() const {
402 return num_locally_closed_incoming_streams_highest_offset_;
403 }
404
405 // Does actual work of sending reset-stream or reset-stream&stop-sending
406 // If the connection is not version 99/IETF QUIC, will always send a
407 // RESET_STREAM and close_write_side_only is ignored. If the connection is
408 // IETF QUIC/Version 99 then will send a RESET_STREAM and STOP_SENDING if
409 // close_write_side_only is false, just a RESET_STREAM if
410 // close_write_side_only is true.
411 virtual void SendRstStreamInner(QuicStreamId id,
412 QuicRstStreamErrorCode error,
413 QuicStreamOffset bytes_written,
414 bool close_write_side_only);
415
wub2b5942f2019-04-11 13:22:50 -0700416 // Record errors when a connection is closed at the server side, should only
417 // be called from server's perspective.
418 // Noop if |error| is QUIC_NO_ERROR.
419 static void RecordConnectionCloseAtServer(QuicErrorCode error,
420 ConnectionCloseSource source);
421
fkastenholzd3a1de92019-05-15 07:00:07 -0700422 inline QuicTransportVersion transport_version() const {
423 return connection_->transport_version();
424 }
425
QUICHE teama6ef0a62019-03-07 20:34:33 -0500426 protected:
427 using StaticStreamMap = QuicSmallMap<QuicStreamId, QuicStream*, 2>;
428
429 using DynamicStreamMap =
430 QuicSmallMap<QuicStreamId, std::unique_ptr<QuicStream>, 10>;
431
432 using PendingStreamMap =
433 QuicSmallMap<QuicStreamId, std::unique_ptr<PendingStream>, 10>;
434
435 using ClosedStreams = std::vector<std::unique_ptr<QuicStream>>;
436
437 using ZombieStreamMap =
438 QuicSmallMap<QuicStreamId, std::unique_ptr<QuicStream>, 10>;
439
440 // Creates a new stream to handle a peer-initiated stream.
441 // Caller does not own the returned stream.
442 // Returns nullptr and does error handling if the stream can not be created.
443 virtual QuicStream* CreateIncomingStream(QuicStreamId id) = 0;
renjietangbaea59c2019-05-29 15:08:14 -0700444 virtual QuicStream* CreateIncomingStream(PendingStream* pending) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500445
446 // Return the reserved crypto stream.
447 virtual QuicCryptoStream* GetMutableCryptoStream() = 0;
448
449 // Return the reserved crypto stream as a constant pointer.
450 virtual const QuicCryptoStream* GetCryptoStream() const = 0;
451
452 // Adds |stream| to the dynamic stream map.
453 virtual void ActivateStream(std::unique_ptr<QuicStream> stream);
454
455 // Returns the stream ID for a new outgoing bidirectional/unidirectional
456 // stream, and increments the underlying counter.
457 QuicStreamId GetNextOutgoingBidirectionalStreamId();
458 QuicStreamId GetNextOutgoingUnidirectionalStreamId();
459
460 // Indicates whether the next outgoing bidirectional/unidirectional stream ID
461 // can be allocated or not. The test for version-99/IETF QUIC is whether it
462 // will exceed the maximum-stream-id or not. For non-version-99 (Google) QUIC
463 // it checks whether the next stream would exceed the limit on the number of
464 // open streams.
465 bool CanOpenNextOutgoingBidirectionalStream();
466 bool CanOpenNextOutgoingUnidirectionalStream();
467
468 // Returns the number of open dynamic streams.
469 uint64_t GetNumOpenDynamicStreams() const;
470
471 // Returns existing stream with id = |stream_id|. If no such stream exists,
472 // and |stream_id| is a peer-created id, then a new stream is created and
473 // returned. However if |stream_id| is a locally-created id and no such stream
474 // exists, the connection is closed.
475 // Caller does not own the returned stream.
476 QuicStream* GetOrCreateDynamicStream(QuicStreamId stream_id);
477
478 // Performs the work required to close |stream_id|. If |locally_reset|
479 // then the stream has been reset by this endpoint, not by the peer.
480 virtual void CloseStreamInner(QuicStreamId stream_id, bool locally_reset);
481
482 // When a stream is closed locally, it may not yet know how many bytes the
483 // peer sent on that stream.
484 // When this data arrives (via stream frame w. FIN, trailing headers, or RST)
485 // this method is called, and correctly updates the connection level flow
486 // controller.
487 virtual void OnFinalByteOffsetReceived(QuicStreamId id,
488 QuicStreamOffset final_byte_offset);
489
renjietange76b2da2019-05-13 14:50:23 -0700490 // Returns true if incoming unidirectional streams should be buffered until
491 // the first byte of the stream arrives.
492 // If a subclass returns true here, it should make sure to implement
493 // ProcessPendingStream().
494 virtual bool UsesPendingStreams() const { return false; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500495
496 // Register (|id|, |stream|) with the static stream map. Override previous
497 // registrations with the same id.
498 void RegisterStaticStream(QuicStreamId id, QuicStream* stream);
renjietangfbeb5bf2019-04-19 15:06:20 -0700499 // TODO(renjietang): Replace the original Register method with the new one
500 // once flag is deprecated.
501 void RegisterStaticStreamNew(std::unique_ptr<QuicStream> stream);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500502 const StaticStreamMap& static_streams() const { return static_stream_map_; }
503
504 DynamicStreamMap& dynamic_streams() { return dynamic_stream_map_; }
505 const DynamicStreamMap& dynamic_streams() const {
506 return dynamic_stream_map_;
507 }
508
509 ClosedStreams* closed_streams() { return &closed_streams_; }
510
511 const ZombieStreamMap& zombie_streams() const { return zombie_streams_; }
512
513 void set_largest_peer_created_stream_id(
514 QuicStreamId largest_peer_created_stream_id);
515
516 void set_error(QuicErrorCode error) { error_ = error; }
517 QuicWriteBlockedList* write_blocked_streams() {
518 return &write_blocked_streams_;
519 }
520
521 size_t GetNumDynamicOutgoingStreams() const;
522
523 size_t GetNumDrainingOutgoingStreams() const;
524
525 // Returns true if the stream is still active.
526 bool IsOpenStream(QuicStreamId id);
527
rchda26cdb2019-05-17 11:57:37 -0700528 // Returns true if the stream is a static stream.
529 bool IsStaticStream(QuicStreamId id) const;
530
QUICHE teama6ef0a62019-03-07 20:34:33 -0500531 // Close connection when receive a frame for a locally-created nonexistant
532 // stream.
533 // Prerequisite: IsClosedStream(stream_id) == false
534 // Server session might need to override this method to allow server push
535 // stream to be promised before creating an active stream.
536 virtual void HandleFrameOnNonexistentOutgoingStream(QuicStreamId stream_id);
537
538 virtual bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId stream_id);
539
540 void InsertLocallyClosedStreamsHighestOffset(const QuicStreamId id,
541 QuicStreamOffset offset);
542 // If stream is a locally closed stream, this RST will update FIN offset.
543 // Otherwise stream is a preserved stream and the behavior of it depends on
544 // derived class's own implementation.
545 virtual void HandleRstOnValidNonexistentStream(
546 const QuicRstStreamFrame& frame);
547
548 // Returns a stateless reset token which will be included in the public reset
549 // packet.
550 virtual QuicUint128 GetStatelessResetToken() const;
551
552 QuicControlFrameManager& control_frame_manager() {
553 return control_frame_manager_;
554 }
555
556 const LegacyQuicStreamIdManager& stream_id_manager() const {
557 return stream_id_manager_;
558 }
559
renjietang0c558862019-05-08 13:26:23 -0700560 // Processes the stream type information of |pending| depending on
renjietangbb1c4892019-05-24 15:58:44 -0700561 // different kinds of sessions' own rules. Returns true if the pending stream
562 // is converted into a normal stream.
563 virtual bool ProcessPendingStream(PendingStream* pending) { return false; }
renjietang0c558862019-05-08 13:26:23 -0700564
QUICHE teame3954c22019-05-07 00:30:32 -0700565 bool eliminate_static_stream_map() const {
renjietang615f13b2019-05-06 17:08:02 -0700566 return eliminate_static_stream_map_;
567 }
568
QUICHE teama6ef0a62019-03-07 20:34:33 -0500569 private:
570 friend class test::QuicSessionPeer;
571
572 // Called in OnConfigNegotiated when we receive a new stream level flow
573 // control window in a negotiated config. Closes the connection if invalid.
574 void OnNewStreamFlowControlWindow(QuicStreamOffset new_window);
575
576 // Called in OnConfigNegotiated when we receive a new connection level flow
577 // control window in a negotiated config. Closes the connection if invalid.
578 void OnNewSessionFlowControlWindow(QuicStreamOffset new_window);
579
580 // Debug helper for |OnCanWrite()|, check that OnStreamWrite() makes
581 // forward progress. Returns false if busy loop detected.
582 bool CheckStreamNotBusyLooping(QuicStream* stream,
583 uint64_t previous_bytes_written,
584 bool previous_fin_sent);
585
586 // Debug helper for OnCanWrite. Check that after QuicStream::OnCanWrite(),
587 // if stream has buffered data and is not stream level flow control blocked,
588 // it has to be in the write blocked list.
589 bool CheckStreamWriteBlocked(QuicStream* stream) const;
590
591 // Called in OnConfigNegotiated for Finch trials to measure performance of
592 // starting with larger flow control receive windows.
593 void AdjustInitialFlowControlWindows(size_t stream_window);
594
595 // Find stream with |id|, returns nullptr if the stream does not exist or
596 // closed.
597 QuicStream* GetStream(QuicStreamId id) const;
598
renjietange76b2da2019-05-13 14:50:23 -0700599 PendingStream* GetOrCreatePendingStream(QuicStreamId stream_id);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500600
601 // Let streams and control frame managers retransmit lost data, returns true
602 // if all lost data is retransmitted. Returns false otherwise.
603 bool RetransmitLostData();
604
605 // Closes the pending stream |stream_id| before it has been created.
606 void ClosePendingStream(QuicStreamId stream_id);
607
renjietange76b2da2019-05-13 14:50:23 -0700608 // Creates or gets pending stream, feeds it with |frame|, and processes the
609 // pending stream.
610 void PendingStreamOnStreamFrame(const QuicStreamFrame& frame);
611
612 // Creates or gets pending strea, feed it with |frame|, and closes the pending
613 // stream.
614 void PendingStreamOnRstStream(const QuicRstStreamFrame& frame);
615
QUICHE teama6ef0a62019-03-07 20:34:33 -0500616 // Keep track of highest received byte offset of locally closed streams, while
617 // waiting for a definitive final highest offset from the peer.
618 std::map<QuicStreamId, QuicStreamOffset>
619 locally_closed_streams_highest_offset_;
620
621 QuicConnection* connection_;
622
623 // May be null.
624 Visitor* visitor_;
625
626 // A list of streams which need to write more data. Stream register
627 // themselves in their constructor, and unregisterm themselves in their
628 // destructors, so the write blocked list must outlive all streams.
629 QuicWriteBlockedList write_blocked_streams_;
630
631 ClosedStreams closed_streams_;
632 // Streams which are closed, but need to be kept alive. Currently, the only
633 // reason is the stream's sent data (including FIN) does not get fully acked.
634 ZombieStreamMap zombie_streams_;
635
636 QuicConfig config_;
637
638 // Static streams, such as crypto and header streams. Owned by child classes
639 // that create these streams.
640 StaticStreamMap static_stream_map_;
641
642 // Map from StreamId to pointers to streams. Owns the streams.
643 DynamicStreamMap dynamic_stream_map_;
644
645 // Map from StreamId to PendingStreams for peer-created unidirectional streams
646 // which are waiting for the first byte of payload to arrive.
647 PendingStreamMap pending_stream_map_;
648
649 // Set of stream ids that are "draining" -- a FIN has been sent and received,
650 // but the stream object still exists because not all the received data has
651 // been consumed.
652 QuicUnorderedSet<QuicStreamId> draining_streams_;
653
654 // TODO(fayang): Consider moving LegacyQuicStreamIdManager into
655 // UberQuicStreamIdManager.
656 // Manages stream IDs for Google QUIC.
657 LegacyQuicStreamIdManager stream_id_manager_;
658
659 // Manages stream IDs for version99/IETF QUIC
660 UberQuicStreamIdManager v99_streamid_manager_;
661
662 // A counter for peer initiated streams which are in the dynamic_stream_map_.
663 size_t num_dynamic_incoming_streams_;
664
665 // A counter for peer initiated streams which are in the draining_streams_.
666 size_t num_draining_incoming_streams_;
667
renjietangfbeb5bf2019-04-19 15:06:20 -0700668 // A counter for self initiated static streams which are in
669 // dynamic_stream_map_.
670 size_t num_outgoing_static_streams_;
671
672 // A counter for peer initiated static streams which are in
673 // dynamic_stream_map_.
674 size_t num_incoming_static_streams_;
675
QUICHE teama6ef0a62019-03-07 20:34:33 -0500676 // A counter for peer initiated streams which are in the
677 // locally_closed_streams_highest_offset_.
678 size_t num_locally_closed_incoming_streams_highest_offset_;
679
680 // The latched error with which the connection was closed.
681 QuicErrorCode error_;
682
683 // Used for connection-level flow control.
684 QuicFlowController flow_controller_;
685
686 // The stream id which was last popped in OnCanWrite, or 0, if not under the
687 // call stack of OnCanWrite.
688 QuicStreamId currently_writing_stream_id_;
689
690 // The largest stream id in |static_stream_map_|.
691 QuicStreamId largest_static_stream_id_;
692
693 // Cached value of whether the crypto handshake has been confirmed.
694 bool is_handshake_confirmed_;
695
696 // Whether a GoAway has been sent.
697 bool goaway_sent_;
698
699 // Whether a GoAway has been received.
700 bool goaway_received_;
701
702 QuicControlFrameManager control_frame_manager_;
703
704 // Id of latest successfully sent message.
705 QuicMessageId last_message_id_;
706
707 // TODO(fayang): switch to linked_hash_set when chromium supports it. The bool
708 // is not used here.
709 // List of streams with pending retransmissions.
710 QuicLinkedHashMap<QuicStreamId, bool> streams_with_pending_retransmission_;
711
712 // Clean up closed_streams_ when this alarm fires.
713 std::unique_ptr<QuicAlarm> closed_streams_clean_up_alarm_;
714
715 // Supported version list used by the crypto handshake only. Please note, this
716 // list may be a superset of the connection framer's supported versions.
717 ParsedQuicVersionVector supported_versions_;
renjietang615f13b2019-05-06 17:08:02 -0700718
719 // Latched value of quic_eliminate_static_stream_map.
720 const bool eliminate_static_stream_map_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500721};
722
723} // namespace quic
724
725#endif // QUICHE_QUIC_CORE_QUIC_SESSION_H_