1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef NET_SPDY_SPDY_SESSION_H_
6 #define NET_SPDY_SPDY_SESSION_H_
13 #include "base/basictypes.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/weak_ptr.h"
18 #include "base/time/time.h"
19 #include "net/base/io_buffer.h"
20 #include "net/base/load_states.h"
21 #include "net/base/net_errors.h"
22 #include "net/base/net_export.h"
23 #include "net/base/request_priority.h"
24 #include "net/socket/client_socket_handle.h"
25 #include "net/socket/client_socket_pool.h"
26 #include "net/socket/next_proto.h"
27 #include "net/socket/ssl_client_socket.h"
28 #include "net/socket/stream_socket.h"
29 #include "net/spdy/buffered_spdy_framer.h"
30 #include "net/spdy/spdy_buffer.h"
31 #include "net/spdy/spdy_framer.h"
32 #include "net/spdy/spdy_header_block.h"
33 #include "net/spdy/spdy_protocol.h"
34 #include "net/spdy/spdy_session_pool.h"
35 #include "net/spdy/spdy_stream.h"
36 #include "net/spdy/spdy_write_queue.h"
37 #include "net/ssl/ssl_config_service.h"
42 // This is somewhat arbitrary and not really fixed, but it will always work
43 // reasonably with ethernet. Chop the world into 2-packet chunks. This is
44 // somewhat arbitrary, but is reasonably small and ensures that we elicit
45 // ACKs quickly from TCP (because TCP tries to only ACK every other packet).
46 const int kMss
= 1430;
47 // The 8 is the size of the SPDY frame header.
48 const int kMaxSpdyFrameChunkSize
= (2 * kMss
) - 8;
50 // Maximum number of concurrent streams we will create, unless the server
51 // sends a SETTINGS frame with a different value.
52 const size_t kInitialMaxConcurrentStreams
= 100;
54 // Specifies the maxiumum concurrent streams server could send (via push).
55 const int kMaxConcurrentPushedStreams
= 1000;
57 // Specifies the maximum number of bytes to read synchronously before
59 const int kMaxReadBytesWithoutYielding
= 32 * 1024;
61 // The initial receive window size for both streams and sessions.
62 const int32 kDefaultInitialRecvWindowSize
= 10 * 1024 * 1024; // 10MB
65 struct LoadTimingInfo
;
69 // NOTE: There's an enum of the same name (also with numeric suffixes)
70 // in histograms.xml. Be sure to add new values there also.
71 enum SpdyProtocolErrorDetails
{
72 // SpdyFramer::SpdyError mappings.
73 SPDY_ERROR_NO_ERROR
= 0,
74 SPDY_ERROR_INVALID_CONTROL_FRAME
= 1,
75 SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE
= 2,
76 SPDY_ERROR_ZLIB_INIT_FAILURE
= 3,
77 SPDY_ERROR_UNSUPPORTED_VERSION
= 4,
78 SPDY_ERROR_DECOMPRESS_FAILURE
= 5,
79 SPDY_ERROR_COMPRESS_FAILURE
= 6,
80 // SPDY_ERROR_CREDENTIAL_FRAME_CORRUPT = 7, (removed).
81 SPDY_ERROR_GOAWAY_FRAME_CORRUPT
= 29,
82 SPDY_ERROR_RST_STREAM_FRAME_CORRUPT
= 30,
83 SPDY_ERROR_INVALID_DATA_FRAME_FLAGS
= 8,
84 SPDY_ERROR_INVALID_CONTROL_FRAME_FLAGS
= 9,
85 SPDY_ERROR_UNEXPECTED_FRAME
= 31,
86 // SpdyRstStreamStatus mappings.
87 // RST_STREAM_INVALID not mapped.
88 STATUS_CODE_PROTOCOL_ERROR
= 11,
89 STATUS_CODE_INVALID_STREAM
= 12,
90 STATUS_CODE_REFUSED_STREAM
= 13,
91 STATUS_CODE_UNSUPPORTED_VERSION
= 14,
92 STATUS_CODE_CANCEL
= 15,
93 STATUS_CODE_INTERNAL_ERROR
= 16,
94 STATUS_CODE_FLOW_CONTROL_ERROR
= 17,
95 STATUS_CODE_STREAM_IN_USE
= 18,
96 STATUS_CODE_STREAM_ALREADY_CLOSED
= 19,
97 STATUS_CODE_INVALID_CREDENTIALS
= 20,
98 STATUS_CODE_FRAME_SIZE_ERROR
= 21,
99 STATUS_CODE_SETTINGS_TIMEOUT
= 32,
100 STATUS_CODE_CONNECT_ERROR
= 33,
101 STATUS_CODE_ENHANCE_YOUR_CALM
= 34,
103 // SpdySession errors
104 PROTOCOL_ERROR_UNEXPECTED_PING
= 22,
105 PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM
= 23,
106 PROTOCOL_ERROR_SPDY_COMPRESSION_FAILURE
= 24,
107 PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION
= 25,
108 PROTOCOL_ERROR_SYN_REPLY_NOT_RECEIVED
= 26,
109 PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
= 27,
110 PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION
= 28,
113 NUM_SPDY_PROTOCOL_ERROR_DETAILS
= 35,
115 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
MapFramerErrorToProtocolError(
116 SpdyFramer::SpdyError
);
117 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
MapRstStreamStatusToProtocolError(
118 SpdyRstStreamStatus
);
120 // If these compile asserts fail then SpdyProtocolErrorDetails needs
121 // to be updated with new values, as do the mapping functions above.
122 COMPILE_ASSERT(12 == SpdyFramer::LAST_ERROR
,
123 SpdyProtocolErrorDetails_SpdyErrors_mismatch
);
124 COMPILE_ASSERT(15 == RST_STREAM_NUM_STATUS_CODES
,
125 SpdyProtocolErrorDetails_RstStreamStatus_mismatch
);
127 // A helper class used to manage a request to create a stream.
128 class NET_EXPORT_PRIVATE SpdyStreamRequest
{
131 // Calls CancelRequest().
132 ~SpdyStreamRequest();
134 // Starts the request to create a stream. If OK is returned, then
135 // ReleaseStream() may be called. If ERR_IO_PENDING is returned,
136 // then when the stream is created, |callback| will be called, at
137 // which point ReleaseStream() may be called. Otherwise, the stream
138 // is not created, an error is returned, and ReleaseStream() may not
141 // If OK is returned, must not be called again without
142 // ReleaseStream() being called first. If ERR_IO_PENDING is
143 // returned, must not be called again without CancelRequest() or
144 // ReleaseStream() being called first. Otherwise, in case of an
145 // immediate error, this may be called again.
146 int StartRequest(SpdyStreamType type
,
147 const base::WeakPtr
<SpdySession
>& session
,
149 RequestPriority priority
,
150 const BoundNetLog
& net_log
,
151 const CompletionCallback
& callback
);
153 // Cancels any pending stream creation request. May be called
155 void CancelRequest();
157 // Transfers the created stream (guaranteed to not be NULL) to the
158 // caller. Must be called at most once after StartRequest() returns
159 // OK or |callback| is called with OK. The caller must immediately
160 // set a delegate for the returned stream (except for test code).
161 base::WeakPtr
<SpdyStream
> ReleaseStream();
164 friend class SpdySession
;
166 // Called by |session_| when the stream attempt has finished
168 void OnRequestCompleteSuccess(const base::WeakPtr
<SpdyStream
>& stream
);
170 // Called by |session_| when the stream attempt has finished with an
171 // error. Also called with ERR_ABORTED if |session_| is destroyed
172 // while the stream attempt is still pending.
173 void OnRequestCompleteFailure(int rv
);
175 // Accessors called by |session_|.
176 SpdyStreamType
type() const { return type_
; }
177 const GURL
& url() const { return url_
; }
178 RequestPriority
priority() const { return priority_
; }
179 const BoundNetLog
& net_log() const { return net_log_
; }
183 SpdyStreamType type_
;
184 base::WeakPtr
<SpdySession
> session_
;
185 base::WeakPtr
<SpdyStream
> stream_
;
187 RequestPriority priority_
;
188 BoundNetLog net_log_
;
189 CompletionCallback callback_
;
191 base::WeakPtrFactory
<SpdyStreamRequest
> weak_ptr_factory_
;
193 DISALLOW_COPY_AND_ASSIGN(SpdyStreamRequest
);
196 class NET_EXPORT SpdySession
: public BufferedSpdyFramerVisitorInterface
,
197 public SpdyFramerDebugVisitorInterface
,
198 public HigherLayeredPool
{
200 // TODO(akalin): Use base::TickClock when it becomes available.
201 typedef base::TimeTicks (*TimeFunc
)(void);
203 // How we handle flow control (version-dependent).
204 enum FlowControlState
{
207 FLOW_CONTROL_STREAM_AND_SESSION
210 // Create a new SpdySession.
211 // |spdy_session_key| is the host/port that this session connects to, privacy
212 // and proxy configuration settings that it's using.
213 // |session| is the HttpNetworkSession. |net_log| is the NetLog that we log
214 // network events to.
215 SpdySession(const SpdySessionKey
& spdy_session_key
,
216 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
217 bool verify_domain_authentication
,
218 bool enable_sending_initial_data
,
219 bool enable_compression
,
220 bool enable_ping_based_connection_checking
,
221 NextProto default_protocol
,
222 size_t stream_initial_recv_window_size
,
223 size_t initial_max_concurrent_streams
,
224 size_t max_concurrent_streams_limit
,
226 const HostPortPair
& trusted_spdy_proxy
,
229 virtual ~SpdySession();
231 const HostPortPair
& host_port_pair() const {
232 return spdy_session_key_
.host_port_proxy_pair().first
;
234 const HostPortProxyPair
& host_port_proxy_pair() const {
235 return spdy_session_key_
.host_port_proxy_pair();
237 const SpdySessionKey
& spdy_session_key() const {
238 return spdy_session_key_
;
240 // Get a pushed stream for a given |url|. If the server initiates a
241 // stream, it might already exist for a given path. The server
242 // might also not have initiated the stream yet, but indicated it
243 // will via X-Associated-Content. Returns OK if a stream was found
244 // and put into |spdy_stream|, or if one was not found but it is
245 // okay to create a new stream (in which case |spdy_stream| is
246 // reset). Returns an error (not ERR_IO_PENDING) otherwise, and
247 // resets |spdy_stream|.
250 base::WeakPtr
<SpdyStream
>* spdy_stream
,
251 const BoundNetLog
& stream_net_log
);
253 // Initialize the session with the given connection. |is_secure|
254 // must indicate whether |connection| uses an SSL socket or not; it
255 // is usually true, but it can be false for testing or when SPDY is
256 // configured to work with non-secure sockets.
258 // |pool| is the SpdySessionPool that owns us. Its lifetime must
259 // strictly be greater than |this|.
261 // |certificate_error_code| must either be OK or less than
264 // The session begins reading from |connection| on a subsequent event loop
265 // iteration, so the SpdySession may close immediately afterwards if the first
266 // read of |connection| fails.
267 void InitializeWithSocket(scoped_ptr
<ClientSocketHandle
> connection
,
268 SpdySessionPool
* pool
,
270 int certificate_error_code
);
272 // Returns the protocol used by this session. Always between
273 // kProtoSPDYMinimumVersion and kProtoSPDYMaximumVersion.
274 NextProto
protocol() const { return protocol_
; }
276 // Check to see if this SPDY session can support an additional domain.
277 // If the session is un-authenticated, then this call always returns true.
278 // For SSL-based sessions, verifies that the server certificate in use by
279 // this session provides authentication for the domain and no client
280 // certificate or channel ID was sent to the original server during the SSL
281 // handshake. NOTE: This function can have false negatives on some
283 // TODO(wtc): rename this function and the Net.SpdyIPPoolDomainMatch
284 // histogram because this function does more than verifying domain
285 // authentication now.
286 bool VerifyDomainAuthentication(const std::string
& domain
);
288 // Pushes the given producer into the write queue for
289 // |stream|. |stream| is guaranteed to be activated before the
290 // producer is used to produce its frame.
291 void EnqueueStreamWrite(const base::WeakPtr
<SpdyStream
>& stream
,
292 SpdyFrameType frame_type
,
293 scoped_ptr
<SpdyBufferProducer
> producer
);
295 // Creates and returns a SYN frame for |stream_id|.
296 scoped_ptr
<SpdyFrame
> CreateSynStream(
297 SpdyStreamId stream_id
,
298 RequestPriority priority
,
299 SpdyControlFlags flags
,
300 const SpdyHeaderBlock
& headers
);
302 // Creates and returns a SpdyBuffer holding a data frame with the
303 // given data. May return NULL if stalled by flow control.
304 scoped_ptr
<SpdyBuffer
> CreateDataBuffer(SpdyStreamId stream_id
,
307 SpdyDataFlags flags
);
309 // Close the stream with the given ID, which must exist and be
310 // active. Note that that stream may hold the last reference to the
312 void CloseActiveStream(SpdyStreamId stream_id
, int status
);
314 // Close the given created stream, which must exist but not yet be
315 // active. Note that |stream| may hold the last reference to the
317 void CloseCreatedStream(const base::WeakPtr
<SpdyStream
>& stream
, int status
);
319 // Send a RST_STREAM frame with the given status code and close the
320 // stream with the given ID, which must exist and be active. Note
321 // that that stream may hold the last reference to the session.
322 void ResetStream(SpdyStreamId stream_id
,
323 SpdyRstStreamStatus status
,
324 const std::string
& description
);
326 // Check if a stream is active.
327 bool IsStreamActive(SpdyStreamId stream_id
) const;
329 // The LoadState is used for informing the user of the current network
330 // status, such as "resolving host", "connecting", etc.
331 LoadState
GetLoadState() const;
333 // Fills SSL info in |ssl_info| and returns true when SSL is in use.
334 bool GetSSLInfo(SSLInfo
* ssl_info
,
335 bool* was_npn_negotiated
,
336 NextProto
* protocol_negotiated
);
338 // Fills SSL Certificate Request info |cert_request_info| and returns
339 // true when SSL is in use.
340 bool GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
);
342 // Send a WINDOW_UPDATE frame for a stream. Called by a stream
343 // whenever receive window size is increased.
344 void SendStreamWindowUpdate(SpdyStreamId stream_id
,
345 uint32 delta_window_size
);
347 // Whether the stream is closed, i.e. it has stopped processing data
348 // and is about to be destroyed.
350 // TODO(akalin): This is only used in tests. Remove this function
351 // and have tests test the WeakPtr instead.
352 bool IsClosed() const { return availability_state_
== STATE_CLOSED
; }
354 // Closes this session. This will close all active streams and mark
355 // the session as permanently closed. Callers must assume that the
356 // session is destroyed after this is called. (However, it may not
357 // be destroyed right away, e.g. when a SpdySession function is
358 // present in the call stack.)
360 // |err| should be < ERR_IO_PENDING; this function is intended to be
362 // |description| indicates the reason for the error.
363 void CloseSessionOnError(Error err
, const std::string
& description
);
365 // Mark this session as unavailable, meaning that it will not be used to
366 // service new streams. Unlike when a GOAWAY frame is received, this function
367 // will not close any streams.
368 void MakeUnavailable();
370 // Retrieves information on the current state of the SPDY session as a
371 // Value. Caller takes possession of the returned value.
372 base::Value
* GetInfoAsValue() const;
374 // Indicates whether the session is being reused after having successfully
375 // used to send/receive data in the past or if the underlying socket was idle
376 // before being used for a SPDY session.
377 bool IsReused() const;
379 // Returns true if the underlying transport socket ever had any reads or
381 bool WasEverUsed() const {
382 return connection_
->socket()->WasEverUsed();
385 // Returns the load timing information from the perspective of the given
386 // stream. If it's not the first stream, the connection is considered reused
389 // This uses a different notion of reuse than IsReused(). This function
390 // sets |socket_reused| to false only if |stream_id| is the ID of the first
391 // stream using the session. IsReused(), on the other hand, indicates if the
392 // session has been used to send/receive data at all.
393 bool GetLoadTimingInfo(SpdyStreamId stream_id
,
394 LoadTimingInfo
* load_timing_info
) const;
396 // Returns true if session is not currently active
397 bool is_active() const {
398 return !active_streams_
.empty() || !created_streams_
.empty();
401 // Access to the number of active and pending streams. These are primarily
402 // available for testing and diagnostics.
403 size_t num_active_streams() const { return active_streams_
.size(); }
404 size_t num_unclaimed_pushed_streams() const {
405 return unclaimed_pushed_streams_
.size();
407 size_t num_created_streams() const { return created_streams_
.size(); }
409 size_t pending_create_stream_queue_size(RequestPriority priority
) const {
410 DCHECK_GE(priority
, MINIMUM_PRIORITY
);
411 DCHECK_LE(priority
, MAXIMUM_PRIORITY
);
412 return pending_create_stream_queues_
[priority
].size();
415 // Returns the (version-dependent) flow control state.
416 FlowControlState
flow_control_state() const {
417 return flow_control_state_
;
420 // Returns the current |stream_initial_send_window_size_|.
421 int32
stream_initial_send_window_size() const {
422 return stream_initial_send_window_size_
;
425 // Returns the current |stream_initial_recv_window_size_|.
426 int32
stream_initial_recv_window_size() const {
427 return stream_initial_recv_window_size_
;
430 // Returns true if no stream in the session can send data due to
431 // session flow control.
432 bool IsSendStalled() const {
434 flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
&&
435 session_send_window_size_
== 0;
438 const BoundNetLog
& net_log() const { return net_log_
; }
440 int GetPeerAddress(IPEndPoint
* address
) const;
441 int GetLocalAddress(IPEndPoint
* address
) const;
443 // Adds |alias| to set of aliases associated with this session.
444 void AddPooledAlias(const SpdySessionKey
& alias_key
);
446 // Returns the set of aliases associated with this session.
447 const std::set
<SpdySessionKey
>& pooled_aliases() const {
448 return pooled_aliases_
;
451 SpdyMajorVersion
GetProtocolVersion() const;
453 size_t GetDataFrameMinimumSize() const {
454 return buffered_spdy_framer_
->GetDataFrameMinimumSize();
457 size_t GetControlFrameHeaderSize() const {
458 return buffered_spdy_framer_
->GetControlFrameHeaderSize();
461 size_t GetFrameMinimumSize() const {
462 return buffered_spdy_framer_
->GetFrameMinimumSize();
465 size_t GetFrameMaximumSize() const {
466 return buffered_spdy_framer_
->GetFrameMaximumSize();
469 size_t GetDataFrameMaximumPayload() const {
470 return buffered_spdy_framer_
->GetDataFrameMaximumPayload();
473 // https://http2.github.io/http2-spec/#TLSUsage mandates minimum security
474 // standards for TLS.
475 bool HasAcceptableTransportSecurity() const;
477 // Must be used only by |pool_|.
478 base::WeakPtr
<SpdySession
> GetWeakPtr();
480 // HigherLayeredPool implementation:
481 virtual bool CloseOneIdleConnection() OVERRIDE
;
484 friend class base::RefCounted
<SpdySession
>;
485 friend class SpdyStreamRequest
;
486 friend class SpdySessionTest
;
488 // Allow tests to access our innards for testing purposes.
489 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClientPing
);
490 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, FailedPing
);
491 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, GetActivePushStream
);
492 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, DeleteExpiredPushStreams
);
493 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ProtocolNegotiation
);
494 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClearSettings
);
495 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustRecvWindowSize
);
496 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustSendWindowSize
);
497 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlInactiveStream
);
498 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoReceiveLeaks
);
499 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoSendLeaks
);
500 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlEndToEnd
);
501 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, StreamIdSpaceExhausted
);
502 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, UnstallRacesWithStreamCreation
);
504 typedef std::deque
<base::WeakPtr
<SpdyStreamRequest
> >
505 PendingStreamRequestQueue
;
507 struct ActiveStreamInfo
{
509 explicit ActiveStreamInfo(SpdyStream
* stream
);
513 bool waiting_for_syn_reply
;
515 typedef std::map
<SpdyStreamId
, ActiveStreamInfo
> ActiveStreamMap
;
517 struct PushedStreamInfo
{
519 PushedStreamInfo(SpdyStreamId stream_id
, base::TimeTicks creation_time
);
522 SpdyStreamId stream_id
;
523 base::TimeTicks creation_time
;
525 typedef std::map
<GURL
, PushedStreamInfo
> PushedStreamMap
;
527 typedef std::set
<SpdyStream
*> CreatedStreamSet
;
529 enum AvailabilityState
{
530 // The session is available in its socket pool and can be used
533 // The session can process data on existing streams but will
534 // refuse to create new ones.
536 // The session has been closed, is waiting to be deleted, and will
537 // refuse to process any more data.
543 READ_STATE_DO_READ_COMPLETE
,
547 // There is no in-flight write and the write queue is empty.
549 WRITE_STATE_DO_WRITE
,
550 WRITE_STATE_DO_WRITE_COMPLETE
,
553 // The return value of DoCloseSession() describing what was done.
554 enum CloseSessionResult
{
555 // The session was already closed so nothing was done.
556 SESSION_ALREADY_CLOSED
,
557 // The session was moved into the closed state but was not removed
558 // from |pool_| (because we're in an IO loop).
559 SESSION_CLOSED_BUT_NOT_REMOVED
,
560 // The session was moved into the closed state and removed from
562 SESSION_CLOSED_AND_REMOVED
,
565 // Checks whether a stream for the given |url| can be created or
566 // retrieved from the set of unclaimed push streams. Returns OK if
567 // so. Otherwise, the session is closed and an error <
568 // ERR_IO_PENDING is returned.
569 Error
TryAccessStream(const GURL
& url
);
571 // Called by SpdyStreamRequest to start a request to create a
572 // stream. If OK is returned, then |stream| will be filled in with a
573 // valid stream. If ERR_IO_PENDING is returned, then
574 // |request->OnRequestComplete{Success,Failure}()| will be called
575 // when the stream is created (unless it is cancelled). Otherwise,
576 // no stream is created and the error is returned.
577 int TryCreateStream(const base::WeakPtr
<SpdyStreamRequest
>& request
,
578 base::WeakPtr
<SpdyStream
>* stream
);
580 // Actually create a stream into |stream|. Returns OK if successful;
581 // otherwise, returns an error and |stream| is not filled.
582 int CreateStream(const SpdyStreamRequest
& request
,
583 base::WeakPtr
<SpdyStream
>* stream
);
585 // Called by SpdyStreamRequest to remove |request| from the stream
587 void CancelStreamRequest(const base::WeakPtr
<SpdyStreamRequest
>& request
);
589 // Returns the next pending stream request to process, or NULL if
591 base::WeakPtr
<SpdyStreamRequest
> GetNextPendingStreamRequest();
593 // Called when there is room to create more streams (e.g., a stream
594 // was closed). Processes as many pending stream requests as
596 void ProcessPendingStreamRequests();
598 // Close the stream pointed to by the given iterator. Note that that
599 // stream may hold the last reference to the session.
600 void CloseActiveStreamIterator(ActiveStreamMap::iterator it
, int status
);
602 // Close the stream pointed to by the given iterator. Note that that
603 // stream may hold the last reference to the session.
604 void CloseCreatedStreamIterator(CreatedStreamSet::iterator it
, int status
);
606 // Calls EnqueueResetStreamFrame() and then
607 // CloseActiveStreamIterator().
608 void ResetStreamIterator(ActiveStreamMap::iterator it
,
609 SpdyRstStreamStatus status
,
610 const std::string
& description
);
612 // Send a RST_STREAM frame with the given parameters. There should
613 // either be no active stream with the given ID, or that active
614 // stream should be closed shortly after this function is called.
616 // TODO(akalin): Rename this to EnqueueResetStreamFrame().
617 void EnqueueResetStreamFrame(SpdyStreamId stream_id
,
618 RequestPriority priority
,
619 SpdyRstStreamStatus status
,
620 const std::string
& description
);
622 // Calls DoReadLoop and then if |availability_state_| is
623 // STATE_CLOSED, calls RemoveFromPool().
625 // Use this function instead of DoReadLoop when posting a task to
626 // pump the read loop.
627 void PumpReadLoop(ReadState expected_read_state
, int result
);
629 // Advance the ReadState state machine. |expected_read_state| is the
630 // expected starting read state.
632 // This function must always be called via PumpReadLoop().
633 int DoReadLoop(ReadState expected_read_state
, int result
);
634 // The implementations of the states of the ReadState state machine.
636 int DoReadComplete(int result
);
638 // Calls DoWriteLoop and then if |availability_state_| is
639 // STATE_CLOSED, calls RemoveFromPool().
641 // Use this function instead of DoWriteLoop when posting a task to
642 // pump the write loop.
643 void PumpWriteLoop(WriteState expected_write_state
, int result
);
645 // Advance the WriteState state machine. |expected_write_state| is
646 // the expected starting write state.
648 // This function must always be called via PumpWriteLoop().
649 int DoWriteLoop(WriteState expected_write_state
, int result
);
650 // The implementations of the states of the WriteState state machine.
652 int DoWriteComplete(int result
);
654 // TODO(akalin): Rename the Send* and Write* functions below to
657 // Send initial data. Called when a connection is successfully
658 // established in InitializeWithSocket() and
659 // |enable_sending_initial_data_| is true.
660 void SendInitialData();
662 // Helper method to send a SETTINGS frame.
663 void SendSettings(const SettingsMap
& settings
);
665 // Handle SETTING. Either when we send settings, or when we receive a
666 // SETTINGS control frame, update our SpdySession accordingly.
667 void HandleSetting(uint32 id
, uint32 value
);
669 // Adjust the send window size of all ActiveStreams and PendingStreamRequests.
670 void UpdateStreamsSendWindowSize(int32 delta_window_size
);
672 // Send the PING (preface-PING) frame.
673 void SendPrefacePingIfNoneInFlight();
675 // Send PING if there are no PINGs in flight and we haven't heard from server.
676 void SendPrefacePing();
678 // Send a single WINDOW_UPDATE frame.
679 void SendWindowUpdateFrame(SpdyStreamId stream_id
, uint32 delta_window_size
,
680 RequestPriority priority
);
682 // Send the PING frame.
683 void WritePingFrame(uint32 unique_id
, bool is_ack
);
685 // Post a CheckPingStatus call after delay. Don't post if there is already
686 // CheckPingStatus running.
687 void PlanToCheckPingStatus();
689 // Check the status of the connection. It calls |CloseSessionOnError| if we
690 // haven't received any data in |kHungInterval| time period.
691 void CheckPingStatus(base::TimeTicks last_check_time
);
693 // Get a new stream id.
694 SpdyStreamId
GetNewStreamId();
696 // Pushes the given frame with the given priority into the write
697 // queue for the session.
698 void EnqueueSessionWrite(RequestPriority priority
,
699 SpdyFrameType frame_type
,
700 scoped_ptr
<SpdyFrame
> frame
);
702 // Puts |producer| associated with |stream| onto the write queue
703 // with the given priority.
704 void EnqueueWrite(RequestPriority priority
,
705 SpdyFrameType frame_type
,
706 scoped_ptr
<SpdyBufferProducer
> producer
,
707 const base::WeakPtr
<SpdyStream
>& stream
);
709 // Inserts a newly-created stream into |created_streams_|.
710 void InsertCreatedStream(scoped_ptr
<SpdyStream
> stream
);
712 // Activates |stream| (which must be in |created_streams_|) by
713 // assigning it an ID and returns it.
714 scoped_ptr
<SpdyStream
> ActivateCreatedStream(SpdyStream
* stream
);
716 // Inserts a newly-activated stream into |active_streams_|.
717 void InsertActivatedStream(scoped_ptr
<SpdyStream
> stream
);
719 // Remove all internal references to |stream|, call OnClose() on it,
720 // and process any pending stream requests before deleting it. Note
721 // that |stream| may hold the last reference to the session.
722 void DeleteStream(scoped_ptr
<SpdyStream
> stream
, int status
);
724 // Check if we have a pending pushed-stream for this url
725 // Returns the stream if found (and returns it from the pending
726 // list). Returns NULL otherwise.
727 base::WeakPtr
<SpdyStream
> GetActivePushStream(const GURL
& url
);
729 // Delegates to |stream->OnInitialResponseHeadersReceived()|. If an
730 // error is returned, the last reference to |this| may have been
732 int OnInitialResponseHeadersReceived(const SpdyHeaderBlock
& response_headers
,
733 base::Time response_time
,
734 base::TimeTicks recv_first_byte_time
,
737 void RecordPingRTTHistogram(base::TimeDelta duration
);
738 void RecordHistograms();
739 void RecordProtocolErrorHistogram(SpdyProtocolErrorDetails details
);
741 // DCHECKs that |availability_state_| >= STATE_GOING_AWAY, that
742 // there are no pending stream creation requests, and that there are
743 // no created streams.
744 void DcheckGoingAway() const;
746 // Calls DcheckGoingAway(), then DCHECKs that |availability_state_|
747 // == STATE_CLOSED, |error_on_close_| has a valid value, that there
748 // are no active streams or unclaimed pushed streams, and that the
749 // write queue is empty.
750 void DcheckClosed() const;
752 // Closes all active streams with stream id's greater than
753 // |last_good_stream_id|, as well as any created or pending
754 // streams. Must be called only when |availability_state_| >=
755 // STATE_GOING_AWAY. After this function, DcheckGoingAway() will
756 // pass. May be called multiple times.
757 void StartGoingAway(SpdyStreamId last_good_stream_id
, Error status
);
759 // Must be called only when going away (i.e., DcheckGoingAway()
760 // passes). If there are no more active streams and the session
761 // isn't closed yet, close it.
762 void MaybeFinishGoingAway();
764 // If the stream is already closed, does nothing. Otherwise, moves
765 // the session to a closed state. Then, if we're in an IO loop,
766 // returns (as the IO loop will do the pool removal itself when its
767 // done). Otherwise, also removes |this| from |pool_|. The returned
768 // result describes what was done.
769 CloseSessionResult
DoCloseSession(Error err
, const std::string
& description
);
771 // Remove this session from its pool, which must exist. Must be
772 // called only when the session is closed.
774 // Must be called only via Pump{Read,Write}Loop() or
776 void RemoveFromPool();
778 // Called right before closing a (possibly-inactive) stream for a
779 // reason other than being requested to by the stream.
780 void LogAbandonedStream(SpdyStream
* stream
, Error status
);
782 // Called right before closing an active stream for a reason other
783 // than being requested to by the stream.
784 void LogAbandonedActiveStream(ActiveStreamMap::const_iterator it
,
787 // Invokes a user callback for stream creation. We provide this method so it
788 // can be deferred to the MessageLoop, so we avoid re-entrancy problems.
789 void CompleteStreamRequest(
790 const base::WeakPtr
<SpdyStreamRequest
>& pending_request
);
792 // Remove old unclaimed pushed streams.
793 void DeleteExpiredPushedStreams();
795 // BufferedSpdyFramerVisitorInterface:
796 virtual void OnError(SpdyFramer::SpdyError error_code
) OVERRIDE
;
797 virtual void OnStreamError(SpdyStreamId stream_id
,
798 const std::string
& description
) OVERRIDE
;
799 virtual void OnPing(SpdyPingId unique_id
, bool is_ack
) OVERRIDE
;
800 virtual void OnRstStream(SpdyStreamId stream_id
,
801 SpdyRstStreamStatus status
) OVERRIDE
;
802 virtual void OnGoAway(SpdyStreamId last_accepted_stream_id
,
803 SpdyGoAwayStatus status
) OVERRIDE
;
804 virtual void OnDataFrameHeader(SpdyStreamId stream_id
,
807 virtual void OnStreamFrameData(SpdyStreamId stream_id
,
811 virtual void OnSettings(bool clear_persisted
) OVERRIDE
;
812 virtual void OnSetting(
813 SpdySettingsIds id
, uint8 flags
, uint32 value
) OVERRIDE
;
814 virtual void OnWindowUpdate(SpdyStreamId stream_id
,
815 uint32 delta_window_size
) OVERRIDE
;
816 virtual void OnPushPromise(SpdyStreamId stream_id
,
817 SpdyStreamId promised_stream_id
,
818 const SpdyHeaderBlock
& headers
) OVERRIDE
;
819 virtual void OnSynStream(SpdyStreamId stream_id
,
820 SpdyStreamId associated_stream_id
,
821 SpdyPriority priority
,
824 const SpdyHeaderBlock
& headers
) OVERRIDE
;
825 virtual void OnSynReply(
826 SpdyStreamId stream_id
,
828 const SpdyHeaderBlock
& headers
) OVERRIDE
;
829 virtual void OnHeaders(
830 SpdyStreamId stream_id
,
832 const SpdyHeaderBlock
& headers
) OVERRIDE
;
834 // SpdyFramerDebugVisitorInterface
835 virtual void OnSendCompressedFrame(
836 SpdyStreamId stream_id
,
839 size_t frame_len
) OVERRIDE
;
840 virtual void OnReceiveCompressedFrame(
841 SpdyStreamId stream_id
,
843 size_t frame_len
) OVERRIDE
;
845 // Called when bytes are consumed from a SpdyBuffer for a DATA frame
846 // that is to be written or is being written. Increases the send
847 // window size accordingly if some or all of the SpdyBuffer is being
850 // If session flow control is turned off, this must not be called.
851 void OnWriteBufferConsumed(size_t frame_payload_size
,
853 SpdyBuffer::ConsumeSource consume_source
);
855 // Called by OnWindowUpdate() (which is in turn called by the
856 // framer) to increase this session's send window size by
857 // |delta_window_size| from a WINDOW_UPDATE frome, which must be at
858 // least 1. If |delta_window_size| would cause this session's send
859 // window size to overflow, does nothing.
861 // If session flow control is turned off, this must not be called.
862 void IncreaseSendWindowSize(int32 delta_window_size
);
864 // If session flow control is turned on, called by CreateDataFrame()
865 // (which is in turn called by a stream) to decrease this session's
866 // send window size by |delta_window_size|, which must be at least 1
867 // and at most kMaxSpdyFrameChunkSize. |delta_window_size| must not
868 // cause this session's send window size to go negative.
870 // If session flow control is turned off, this must not be called.
871 void DecreaseSendWindowSize(int32 delta_window_size
);
873 // Called when bytes are consumed by the delegate from a SpdyBuffer
874 // containing received data. Increases the receive window size
877 // If session flow control is turned off, this must not be called.
878 void OnReadBufferConsumed(size_t consume_size
,
879 SpdyBuffer::ConsumeSource consume_source
);
881 // Called by OnReadBufferConsume to increase this session's receive
882 // window size by |delta_window_size|, which must be at least 1 and
883 // must not cause this session's receive window size to overflow,
884 // possibly also sending a WINDOW_UPDATE frame. Also called during
885 // initialization to set the initial receive window size.
887 // If session flow control is turned off, this must not be called.
888 void IncreaseRecvWindowSize(int32 delta_window_size
);
890 // Called by OnStreamFrameData (which is in turn called by the
891 // framer) to decrease this session's receive window size by
892 // |delta_window_size|, which must be at least 1 and must not cause
893 // this session's receive window size to go negative.
895 // If session flow control is turned off, this must not be called.
896 void DecreaseRecvWindowSize(int32 delta_window_size
);
898 // Queue a send-stalled stream for possibly resuming once we're not
899 // send-stalled anymore.
900 void QueueSendStalledStream(const SpdyStream
& stream
);
902 // Go through the queue of send-stalled streams and try to resume as
904 void ResumeSendStalledStreams();
906 // Returns the next stream to possibly resume, or 0 if the queue is
908 SpdyStreamId
PopStreamToPossiblyResume();
910 // --------------------------
911 // Helper methods for testing
912 // --------------------------
914 void set_connection_at_risk_of_loss_time(base::TimeDelta duration
) {
915 connection_at_risk_of_loss_time_
= duration
;
918 void set_hung_interval(base::TimeDelta duration
) {
919 hung_interval_
= duration
;
922 int64
pings_in_flight() const { return pings_in_flight_
; }
924 uint32
next_ping_id() const { return next_ping_id_
; }
926 base::TimeTicks
last_activity_time() const { return last_activity_time_
; }
928 bool check_ping_status_pending() const { return check_ping_status_pending_
; }
930 size_t max_concurrent_streams() const { return max_concurrent_streams_
; }
932 // Returns the SSLClientSocket that this SPDY session sits on top of,
933 // or NULL, if the transport is not SSL.
934 SSLClientSocket
* GetSSLClientSocket() const;
936 // Whether Do{Read,Write}Loop() is in the call stack. Useful for
937 // making sure we don't destroy ourselves prematurely in that case.
940 // The key used to identify this session.
941 const SpdySessionKey spdy_session_key_
;
943 // Set set of SpdySessionKeys for which this session has serviced
945 std::set
<SpdySessionKey
> pooled_aliases_
;
947 // |pool_| owns us, therefore its lifetime must exceed ours. We set
948 // this to NULL after we are removed from the pool.
949 SpdySessionPool
* pool_
;
950 const base::WeakPtr
<HttpServerProperties
> http_server_properties_
;
952 // The socket handle for this session.
953 scoped_ptr
<ClientSocketHandle
> connection_
;
955 // The read buffer used to read data from the socket.
956 scoped_refptr
<IOBuffer
> read_buffer_
;
958 SpdyStreamId stream_hi_water_mark_
; // The next stream id to use.
960 // Queue, for each priority, of pending stream requests that have
961 // not yet been satisfied.
962 PendingStreamRequestQueue pending_create_stream_queues_
[NUM_PRIORITIES
];
964 // Map from stream id to all active streams. Streams are active in the sense
965 // that they have a consumer (typically SpdyNetworkTransaction and regardless
966 // of whether or not there is currently any ongoing IO [might be waiting for
967 // the server to start pushing the stream]) or there are still network events
968 // incoming even though the consumer has already gone away (cancellation).
970 // |active_streams_| owns all its SpdyStream objects.
972 // TODO(willchan): Perhaps we should separate out cancelled streams and move
973 // them into a separate ActiveStreamMap, and not deliver network events to
975 ActiveStreamMap active_streams_
;
977 // (Bijective) map from the URL to the ID of the streams that have
978 // already started to be pushed by the server, but do not have
979 // consumers yet. Contains a subset of |active_streams_|.
980 PushedStreamMap unclaimed_pushed_streams_
;
982 // Set of all created streams but that have not yet sent any frames.
984 // |created_streams_| owns all its SpdyStream objects.
985 CreatedStreamSet created_streams_
;
988 SpdyWriteQueue write_queue_
;
990 // Data for the frame we are currently sending.
992 // The buffer we're currently writing.
993 scoped_ptr
<SpdyBuffer
> in_flight_write_
;
994 // The type of the frame in |in_flight_write_|.
995 SpdyFrameType in_flight_write_frame_type_
;
996 // The size of the frame in |in_flight_write_|.
997 size_t in_flight_write_frame_size_
;
998 // The stream to notify when |in_flight_write_| has been written to
999 // the socket completely.
1000 base::WeakPtr
<SpdyStream
> in_flight_write_stream_
;
1002 // Flag if we're using an SSL connection for this SpdySession.
1005 // Certificate error code when using a secure connection.
1006 int certificate_error_code_
;
1008 // Spdy Frame state.
1009 scoped_ptr
<BufferedSpdyFramer
> buffered_spdy_framer_
;
1011 // The state variables.
1012 AvailabilityState availability_state_
;
1013 ReadState read_state_
;
1014 WriteState write_state_
;
1016 // If the session was closed (i.e., |availability_state_| is
1017 // STATE_CLOSED), then |error_on_close_| holds the error with which
1018 // it was closed, which is < ERR_IO_PENDING. Otherwise, it is set to
1020 Error error_on_close_
;
1023 size_t max_concurrent_streams_
; // 0 if no limit
1024 size_t max_concurrent_streams_limit_
;
1026 // Some statistics counters for the session.
1027 int streams_initiated_count_
;
1028 int streams_pushed_count_
;
1029 int streams_pushed_and_claimed_count_
;
1030 int streams_abandoned_count_
;
1032 // |total_bytes_received_| keeps track of all the bytes read by the
1033 // SpdySession. It is used by the |Net.SpdySettingsCwnd...| histograms.
1034 int total_bytes_received_
;
1036 bool sent_settings_
; // Did this session send settings when it started.
1037 bool received_settings_
; // Did this session receive at least one settings
1039 int stalled_streams_
; // Count of streams that were ever stalled.
1041 // Count of all pings on the wire, for which we have not gotten a response.
1042 int64 pings_in_flight_
;
1044 // This is the next ping_id (unique_id) to be sent in PING frame.
1045 uint32 next_ping_id_
;
1047 // This is the last time we have sent a PING.
1048 base::TimeTicks last_ping_sent_time_
;
1050 // This is the last time we had activity in the session.
1051 base::TimeTicks last_activity_time_
;
1053 // This is the length of the last compressed frame.
1054 size_t last_compressed_frame_len_
;
1056 // This is the next time that unclaimed push streams should be checked for
1058 base::TimeTicks next_unclaimed_push_stream_sweep_time_
;
1060 // Indicate if we have already scheduled a delayed task to check the ping
1062 bool check_ping_status_pending_
;
1064 // Whether to send the (HTTP/2) connection header prefix.
1065 bool send_connection_header_prefix_
;
1067 // The (version-dependent) flow control state.
1068 FlowControlState flow_control_state_
;
1070 // Initial send window size for this session's streams. Can be
1071 // changed by an arriving SETTINGS frame. Newly created streams use
1072 // this value for the initial send window size.
1073 int32 stream_initial_send_window_size_
;
1075 // Initial receive window size for this session's streams. There are
1076 // plans to add a command line switch that would cause a SETTINGS
1077 // frame with window size announcement to be sent on startup. Newly
1078 // created streams will use this value for the initial receive
1080 int32 stream_initial_recv_window_size_
;
1082 // Session flow control variables. All zero unless session flow
1083 // control is turned on.
1084 int32 session_send_window_size_
;
1085 int32 session_recv_window_size_
;
1086 int32 session_unacked_recv_window_bytes_
;
1088 // A queue of stream IDs that have been send-stalled at some point
1090 std::deque
<SpdyStreamId
> stream_send_unstall_queue_
[NUM_PRIORITIES
];
1092 BoundNetLog net_log_
;
1094 // Outside of tests, these should always be true.
1095 bool verify_domain_authentication_
;
1096 bool enable_sending_initial_data_
;
1097 bool enable_compression_
;
1098 bool enable_ping_based_connection_checking_
;
1100 // The SPDY protocol used. Always between kProtoSPDYMinimumVersion and
1101 // kProtoSPDYMaximumVersion.
1102 NextProto protocol_
;
1104 // |connection_at_risk_of_loss_time_| is an optimization to avoid sending
1105 // wasteful preface pings (when we just got some data).
1107 // If it is zero (the most conservative figure), then we always send the
1108 // preface ping (when none are in flight).
1110 // It is common for TCP/IP sessions to time out in about 3-5 minutes.
1111 // Certainly if it has been more than 3 minutes, we do want to send a preface
1114 // We don't think any connection will time out in under about 10 seconds. So
1115 // this might as well be set to something conservative like 10 seconds. Later,
1116 // we could adjust it to send fewer pings perhaps.
1117 base::TimeDelta connection_at_risk_of_loss_time_
;
1119 // The amount of time that we are willing to tolerate with no activity (of any
1120 // form), while there is a ping in flight, before we declare the connection to
1121 // be hung. TODO(rtenneti): When hung, instead of resetting connection, race
1122 // to build a new connection, and see if that completes before we (finally)
1123 // get a PING response (http://crbug.com/127812).
1124 base::TimeDelta hung_interval_
;
1126 // This SPDY proxy is allowed to push resources from origins that are
1127 // different from those of their associated streams.
1128 HostPortPair trusted_spdy_proxy_
;
1130 TimeFunc time_func_
;
1132 // Used for posting asynchronous IO tasks. We use this even though
1133 // SpdySession is refcounted because we don't need to keep the SpdySession
1134 // alive if the last reference is within a RunnableMethod. Just revoke the
1136 base::WeakPtrFactory
<SpdySession
> weak_factory_
;
1141 #endif // NET_SPDY_SPDY_SESSION_H_