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_TOO_LARGE
= 21,
100 PROTOCOL_ERROR_UNEXPECTED_PING
= 22,
101 PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM
= 23,
102 PROTOCOL_ERROR_SPDY_COMPRESSION_FAILURE
= 24,
103 PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION
= 25,
104 PROTOCOL_ERROR_SYN_REPLY_NOT_RECEIVED
= 26,
105 PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
= 27,
106 PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION
= 28,
109 NUM_SPDY_PROTOCOL_ERROR_DETAILS
= 32,
111 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
MapFramerErrorToProtocolError(
112 SpdyFramer::SpdyError
);
113 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
MapRstStreamStatusToProtocolError(
114 SpdyRstStreamStatus
);
116 // If these compile asserts fail then SpdyProtocolErrorDetails needs
117 // to be updated with new values, as do the mapping functions above.
118 COMPILE_ASSERT(12 == SpdyFramer::LAST_ERROR
,
119 SpdyProtocolErrorDetails_SpdyErrors_mismatch
);
120 COMPILE_ASSERT(12 == RST_STREAM_NUM_STATUS_CODES
,
121 SpdyProtocolErrorDetails_RstStreamStatus_mismatch
);
123 // A helper class used to manage a request to create a stream.
124 class NET_EXPORT_PRIVATE SpdyStreamRequest
{
127 // Calls CancelRequest().
128 ~SpdyStreamRequest();
130 // Starts the request to create a stream. If OK is returned, then
131 // ReleaseStream() may be called. If ERR_IO_PENDING is returned,
132 // then when the stream is created, |callback| will be called, at
133 // which point ReleaseStream() may be called. Otherwise, the stream
134 // is not created, an error is returned, and ReleaseStream() may not
137 // If OK is returned, must not be called again without
138 // ReleaseStream() being called first. If ERR_IO_PENDING is
139 // returned, must not be called again without CancelRequest() or
140 // ReleaseStream() being called first. Otherwise, in case of an
141 // immediate error, this may be called again.
142 int StartRequest(SpdyStreamType type
,
143 const base::WeakPtr
<SpdySession
>& session
,
145 RequestPriority priority
,
146 const BoundNetLog
& net_log
,
147 const CompletionCallback
& callback
);
149 // Cancels any pending stream creation request. May be called
151 void CancelRequest();
153 // Transfers the created stream (guaranteed to not be NULL) to the
154 // caller. Must be called at most once after StartRequest() returns
155 // OK or |callback| is called with OK. The caller must immediately
156 // set a delegate for the returned stream (except for test code).
157 base::WeakPtr
<SpdyStream
> ReleaseStream();
160 friend class SpdySession
;
162 // Called by |session_| when the stream attempt has finished
164 void OnRequestCompleteSuccess(const base::WeakPtr
<SpdyStream
>& stream
);
166 // Called by |session_| when the stream attempt has finished with an
167 // error. Also called with ERR_ABORTED if |session_| is destroyed
168 // while the stream attempt is still pending.
169 void OnRequestCompleteFailure(int rv
);
171 // Accessors called by |session_|.
172 SpdyStreamType
type() const { return type_
; }
173 const GURL
& url() const { return url_
; }
174 RequestPriority
priority() const { return priority_
; }
175 const BoundNetLog
& net_log() const { return net_log_
; }
179 base::WeakPtrFactory
<SpdyStreamRequest
> weak_ptr_factory_
;
180 SpdyStreamType type_
;
181 base::WeakPtr
<SpdySession
> session_
;
182 base::WeakPtr
<SpdyStream
> stream_
;
184 RequestPriority priority_
;
185 BoundNetLog net_log_
;
186 CompletionCallback callback_
;
188 DISALLOW_COPY_AND_ASSIGN(SpdyStreamRequest
);
191 class NET_EXPORT SpdySession
: public BufferedSpdyFramerVisitorInterface
,
192 public SpdyFramerDebugVisitorInterface
,
193 public HigherLayeredPool
{
195 // TODO(akalin): Use base::TickClock when it becomes available.
196 typedef base::TimeTicks (*TimeFunc
)(void);
198 // How we handle flow control (version-dependent).
199 enum FlowControlState
{
202 FLOW_CONTROL_STREAM_AND_SESSION
205 // Create a new SpdySession.
206 // |spdy_session_key| is the host/port that this session connects to, privacy
207 // and proxy configuration settings that it's using.
208 // |session| is the HttpNetworkSession. |net_log| is the NetLog that we log
209 // network events to.
210 SpdySession(const SpdySessionKey
& spdy_session_key
,
211 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
212 bool verify_domain_authentication
,
213 bool enable_sending_initial_data
,
214 bool enable_compression
,
215 bool enable_ping_based_connection_checking
,
216 NextProto default_protocol
,
217 size_t stream_initial_recv_window_size
,
218 size_t initial_max_concurrent_streams
,
219 size_t max_concurrent_streams_limit
,
221 const HostPortPair
& trusted_spdy_proxy
,
224 virtual ~SpdySession();
226 const HostPortPair
& host_port_pair() const {
227 return spdy_session_key_
.host_port_proxy_pair().first
;
229 const HostPortProxyPair
& host_port_proxy_pair() const {
230 return spdy_session_key_
.host_port_proxy_pair();
232 const SpdySessionKey
& spdy_session_key() const {
233 return spdy_session_key_
;
235 // Get a pushed stream for a given |url|. If the server initiates a
236 // stream, it might already exist for a given path. The server
237 // might also not have initiated the stream yet, but indicated it
238 // will via X-Associated-Content. Returns OK if a stream was found
239 // and put into |spdy_stream|, or if one was not found but it is
240 // okay to create a new stream (in which case |spdy_stream| is
241 // reset). Returns an error (not ERR_IO_PENDING) otherwise, and
242 // resets |spdy_stream|.
245 base::WeakPtr
<SpdyStream
>* spdy_stream
,
246 const BoundNetLog
& stream_net_log
);
248 // Initialize the session with the given connection. |is_secure|
249 // must indicate whether |connection| uses an SSL socket or not; it
250 // is usually true, but it can be false for testing or when SPDY is
251 // configured to work with non-secure sockets.
253 // |pool| is the SpdySessionPool that owns us. Its lifetime must
254 // strictly be greater than |this|.
256 // |certificate_error_code| must either be OK or less than
259 // Returns OK on success, or an error on failure. Never returns
260 // ERR_IO_PENDING. If an error is returned, the session must be
261 // destroyed immediately.
262 Error
InitializeWithSocket(scoped_ptr
<ClientSocketHandle
> connection
,
263 SpdySessionPool
* pool
,
265 int certificate_error_code
);
267 // Returns the protocol used by this session. Always between
268 // kProtoSPDYMinimumVersion and kProtoSPDYMaximumVersion.
269 NextProto
protocol() const { return protocol_
; }
271 // Check to see if this SPDY session can support an additional domain.
272 // If the session is un-authenticated, then this call always returns true.
273 // For SSL-based sessions, verifies that the server certificate in use by
274 // this session provides authentication for the domain and no client
275 // certificate or channel ID was sent to the original server during the SSL
276 // handshake. NOTE: This function can have false negatives on some
278 // TODO(wtc): rename this function and the Net.SpdyIPPoolDomainMatch
279 // histogram because this function does more than verifying domain
280 // authentication now.
281 bool VerifyDomainAuthentication(const std::string
& domain
);
283 // Pushes the given producer into the write queue for
284 // |stream|. |stream| is guaranteed to be activated before the
285 // producer is used to produce its frame.
286 void EnqueueStreamWrite(const base::WeakPtr
<SpdyStream
>& stream
,
287 SpdyFrameType frame_type
,
288 scoped_ptr
<SpdyBufferProducer
> producer
);
290 // Creates and returns a SYN frame for |stream_id|.
291 scoped_ptr
<SpdyFrame
> CreateSynStream(
292 SpdyStreamId stream_id
,
293 RequestPriority priority
,
294 SpdyControlFlags flags
,
295 const SpdyHeaderBlock
& headers
);
297 // Creates and returns a SpdyBuffer holding a data frame with the
298 // given data. May return NULL if stalled by flow control.
299 scoped_ptr
<SpdyBuffer
> CreateDataBuffer(SpdyStreamId stream_id
,
302 SpdyDataFlags flags
);
304 // Close the stream with the given ID, which must exist and be
305 // active. Note that that stream may hold the last reference to the
307 void CloseActiveStream(SpdyStreamId stream_id
, int status
);
309 // Close the given created stream, which must exist but not yet be
310 // active. Note that |stream| may hold the last reference to the
312 void CloseCreatedStream(const base::WeakPtr
<SpdyStream
>& stream
, int status
);
314 // Send a RST_STREAM frame with the given status code and close the
315 // stream with the given ID, which must exist and be active. Note
316 // that that stream may hold the last reference to the session.
317 void ResetStream(SpdyStreamId stream_id
,
318 SpdyRstStreamStatus status
,
319 const std::string
& description
);
321 // Check if a stream is active.
322 bool IsStreamActive(SpdyStreamId stream_id
) const;
324 // The LoadState is used for informing the user of the current network
325 // status, such as "resolving host", "connecting", etc.
326 LoadState
GetLoadState() const;
328 // Fills SSL info in |ssl_info| and returns true when SSL is in use.
329 bool GetSSLInfo(SSLInfo
* ssl_info
,
330 bool* was_npn_negotiated
,
331 NextProto
* protocol_negotiated
);
333 // Fills SSL Certificate Request info |cert_request_info| and returns
334 // true when SSL is in use.
335 bool GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
);
337 // Send a WINDOW_UPDATE frame for a stream. Called by a stream
338 // whenever receive window size is increased.
339 void SendStreamWindowUpdate(SpdyStreamId stream_id
,
340 uint32 delta_window_size
);
342 // Whether the stream is closed, i.e. it has stopped processing data
343 // and is about to be destroyed.
345 // TODO(akalin): This is only used in tests. Remove this function
346 // and have tests test the WeakPtr instead.
347 bool IsClosed() const { return availability_state_
== STATE_CLOSED
; }
349 // Closes this session. This will close all active streams and mark
350 // the session as permanently closed. Callers must assume that the
351 // session is destroyed after this is called. (However, it may not
352 // be destroyed right away, e.g. when a SpdySession function is
353 // present in the call stack.)
355 // |err| should be < ERR_IO_PENDING; this function is intended to be
357 // |description| indicates the reason for the error.
358 void CloseSessionOnError(Error err
, const std::string
& description
);
360 // Mark this session as unavailable, meaning that it will not be used to
361 // service new streams. Unlike when a GOAWAY frame is received, this function
362 // will not close any streams.
363 void MakeUnavailable();
365 // Retrieves information on the current state of the SPDY session as a
366 // Value. Caller takes possession of the returned value.
367 base::Value
* GetInfoAsValue() const;
369 // Indicates whether the session is being reused after having successfully
370 // used to send/receive data in the past.
371 bool IsReused() const;
373 // Returns true if the underlying transport socket ever had any reads or
375 bool WasEverUsed() const {
376 return connection_
->socket()->WasEverUsed();
379 // Returns the load timing information from the perspective of the given
380 // stream. If it's not the first stream, the connection is considered reused
383 // This uses a different notion of reuse than IsReused(). This function
384 // sets |socket_reused| to false only if |stream_id| is the ID of the first
385 // stream using the session. IsReused(), on the other hand, indicates if the
386 // session has been used to send/receive data at all.
387 bool GetLoadTimingInfo(SpdyStreamId stream_id
,
388 LoadTimingInfo
* load_timing_info
) const;
390 // Returns true if session is not currently active
391 bool is_active() const {
392 return !active_streams_
.empty() || !created_streams_
.empty();
395 // Access to the number of active and pending streams. These are primarily
396 // available for testing and diagnostics.
397 size_t num_active_streams() const { return active_streams_
.size(); }
398 size_t num_unclaimed_pushed_streams() const {
399 return unclaimed_pushed_streams_
.size();
401 size_t num_created_streams() const { return created_streams_
.size(); }
403 size_t pending_create_stream_queue_size(RequestPriority priority
) const {
404 DCHECK_GE(priority
, MINIMUM_PRIORITY
);
405 DCHECK_LE(priority
, MAXIMUM_PRIORITY
);
406 return pending_create_stream_queues_
[priority
].size();
409 // Returns the (version-dependent) flow control state.
410 FlowControlState
flow_control_state() const {
411 return flow_control_state_
;
414 // Returns the current |stream_initial_send_window_size_|.
415 int32
stream_initial_send_window_size() const {
416 return stream_initial_send_window_size_
;
419 // Returns the current |stream_initial_recv_window_size_|.
420 int32
stream_initial_recv_window_size() const {
421 return stream_initial_recv_window_size_
;
424 // Returns true if no stream in the session can send data due to
425 // session flow control.
426 bool IsSendStalled() const {
428 flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
&&
429 session_send_window_size_
== 0;
432 const BoundNetLog
& net_log() const { return net_log_
; }
434 int GetPeerAddress(IPEndPoint
* address
) const;
435 int GetLocalAddress(IPEndPoint
* address
) const;
437 // Adds |alias| to set of aliases associated with this session.
438 void AddPooledAlias(const SpdySessionKey
& alias_key
);
440 // Returns the set of aliases associated with this session.
441 const std::set
<SpdySessionKey
>& pooled_aliases() const {
442 return pooled_aliases_
;
445 SpdyMajorVersion
GetProtocolVersion() const;
447 size_t GetDataFrameMinimumSize() const {
448 return buffered_spdy_framer_
->GetDataFrameMinimumSize();
451 size_t GetControlFrameHeaderSize() const {
452 return buffered_spdy_framer_
->GetControlFrameHeaderSize();
455 size_t GetFrameMinimumSize() const {
456 return buffered_spdy_framer_
->GetFrameMinimumSize();
459 size_t GetFrameMaximumSize() const {
460 return buffered_spdy_framer_
->GetFrameMaximumSize();
463 size_t GetDataFrameMaximumPayload() const {
464 return buffered_spdy_framer_
->GetDataFrameMaximumPayload();
467 // Must be used only by |pool_|.
468 base::WeakPtr
<SpdySession
> GetWeakPtr();
470 // HigherLayeredPool implementation:
471 virtual bool CloseOneIdleConnection() OVERRIDE
;
474 friend class base::RefCounted
<SpdySession
>;
475 friend class SpdyStreamRequest
;
476 friend class SpdySessionTest
;
478 // Allow tests to access our innards for testing purposes.
479 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClientPing
);
480 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, FailedPing
);
481 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, GetActivePushStream
);
482 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, DeleteExpiredPushStreams
);
483 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ProtocolNegotiation
);
484 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClearSettings
);
485 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustRecvWindowSize
);
486 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustSendWindowSize
);
487 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlInactiveStream
);
488 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoReceiveLeaks
);
489 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoSendLeaks
);
490 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlEndToEnd
);
492 typedef std::deque
<base::WeakPtr
<SpdyStreamRequest
> >
493 PendingStreamRequestQueue
;
495 struct ActiveStreamInfo
{
497 explicit ActiveStreamInfo(SpdyStream
* stream
);
501 bool waiting_for_syn_reply
;
503 typedef std::map
<SpdyStreamId
, ActiveStreamInfo
> ActiveStreamMap
;
505 struct PushedStreamInfo
{
507 PushedStreamInfo(SpdyStreamId stream_id
, base::TimeTicks creation_time
);
510 SpdyStreamId stream_id
;
511 base::TimeTicks creation_time
;
513 typedef std::map
<GURL
, PushedStreamInfo
> PushedStreamMap
;
515 typedef std::set
<SpdyStream
*> CreatedStreamSet
;
517 enum AvailabilityState
{
518 // The session is available in its socket pool and can be used
521 // The session can process data on existing streams but will
522 // refuse to create new ones.
524 // The session has been closed, is waiting to be deleted, and will
525 // refuse to process any more data.
531 READ_STATE_DO_READ_COMPLETE
,
535 // There is no in-flight write and the write queue is empty.
537 WRITE_STATE_DO_WRITE
,
538 WRITE_STATE_DO_WRITE_COMPLETE
,
541 // The return value of DoCloseSession() describing what was done.
542 enum CloseSessionResult
{
543 // The session was already closed so nothing was done.
544 SESSION_ALREADY_CLOSED
,
545 // The session was moved into the closed state but was not removed
546 // from |pool_| (because we're in an IO loop).
547 SESSION_CLOSED_BUT_NOT_REMOVED
,
548 // The session was moved into the closed state and removed from
550 SESSION_CLOSED_AND_REMOVED
,
553 // Checks whether a stream for the given |url| can be created or
554 // retrieved from the set of unclaimed push streams. Returns OK if
555 // so. Otherwise, the session is closed and an error <
556 // ERR_IO_PENDING is returned.
557 Error
TryAccessStream(const GURL
& url
);
559 // Called by SpdyStreamRequest to start a request to create a
560 // stream. If OK is returned, then |stream| will be filled in with a
561 // valid stream. If ERR_IO_PENDING is returned, then
562 // |request->OnRequestComplete{Success,Failure}()| will be called
563 // when the stream is created (unless it is cancelled). Otherwise,
564 // no stream is created and the error is returned.
565 int TryCreateStream(const base::WeakPtr
<SpdyStreamRequest
>& request
,
566 base::WeakPtr
<SpdyStream
>* stream
);
568 // Actually create a stream into |stream|. Returns OK if successful;
569 // otherwise, returns an error and |stream| is not filled.
570 int CreateStream(const SpdyStreamRequest
& request
,
571 base::WeakPtr
<SpdyStream
>* stream
);
573 // Called by SpdyStreamRequest to remove |request| from the stream
575 void CancelStreamRequest(const base::WeakPtr
<SpdyStreamRequest
>& request
);
577 // Returns the next pending stream request to process, or NULL if
579 base::WeakPtr
<SpdyStreamRequest
> GetNextPendingStreamRequest();
581 // Called when there is room to create more streams (e.g., a stream
582 // was closed). Processes as many pending stream requests as
584 void ProcessPendingStreamRequests();
586 // Close the stream pointed to by the given iterator. Note that that
587 // stream may hold the last reference to the session.
588 void CloseActiveStreamIterator(ActiveStreamMap::iterator it
, int status
);
590 // Close the stream pointed to by the given iterator. Note that that
591 // stream may hold the last reference to the session.
592 void CloseCreatedStreamIterator(CreatedStreamSet::iterator it
, int status
);
594 // Calls EnqueueResetStreamFrame() and then
595 // CloseActiveStreamIterator().
596 void ResetStreamIterator(ActiveStreamMap::iterator it
,
597 SpdyRstStreamStatus status
,
598 const std::string
& description
);
600 // Send a RST_STREAM frame with the given parameters. There should
601 // either be no active stream with the given ID, or that active
602 // stream should be closed shortly after this function is called.
604 // TODO(akalin): Rename this to EnqueueResetStreamFrame().
605 void EnqueueResetStreamFrame(SpdyStreamId stream_id
,
606 RequestPriority priority
,
607 SpdyRstStreamStatus status
,
608 const std::string
& description
);
610 // Calls DoReadLoop and then if |availability_state_| is
611 // STATE_CLOSED, calls RemoveFromPool().
613 // Use this function instead of DoReadLoop when posting a task to
614 // pump the read loop.
615 void PumpReadLoop(ReadState expected_read_state
, int result
);
617 // Advance the ReadState state machine. |expected_read_state| is the
618 // expected starting read state.
620 // This function must always be called via PumpReadLoop() except for
621 // from InitializeWithSocket().
622 int DoReadLoop(ReadState expected_read_state
, int result
);
623 // The implementations of the states of the ReadState state machine.
625 int DoReadComplete(int result
);
627 // Calls DoWriteLoop and then if |availability_state_| is
628 // STATE_CLOSED, calls RemoveFromPool().
630 // Use this function instead of DoWriteLoop when posting a task to
631 // pump the write loop.
632 void PumpWriteLoop(WriteState expected_write_state
, int result
);
634 // Advance the WriteState state machine. |expected_write_state| is
635 // the expected starting write state.
637 // This function must always be called via PumpWriteLoop().
638 int DoWriteLoop(WriteState expected_write_state
, int result
);
639 // The implementations of the states of the WriteState state machine.
641 int DoWriteComplete(int result
);
643 // TODO(akalin): Rename the Send* and Write* functions below to
646 // Send initial data. Called when a connection is successfully
647 // established in InitializeWithSocket() and
648 // |enable_sending_initial_data_| is true.
649 void SendInitialData();
651 // Helper method to send a SETTINGS frame.
652 void SendSettings(const SettingsMap
& settings
);
654 // Handle SETTING. Either when we send settings, or when we receive a
655 // SETTINGS control frame, update our SpdySession accordingly.
656 void HandleSetting(uint32 id
, uint32 value
);
658 // Adjust the send window size of all ActiveStreams and PendingStreamRequests.
659 void UpdateStreamsSendWindowSize(int32 delta_window_size
);
661 // Send the PING (preface-PING) frame.
662 void SendPrefacePingIfNoneInFlight();
664 // Send PING if there are no PINGs in flight and we haven't heard from server.
665 void SendPrefacePing();
667 // Send a single WINDOW_UPDATE frame.
668 void SendWindowUpdateFrame(SpdyStreamId stream_id
, uint32 delta_window_size
,
669 RequestPriority priority
);
671 // Send the PING frame.
672 void WritePingFrame(uint32 unique_id
, bool is_ack
);
674 // Post a CheckPingStatus call after delay. Don't post if there is already
675 // CheckPingStatus running.
676 void PlanToCheckPingStatus();
678 // Check the status of the connection. It calls |CloseSessionOnError| if we
679 // haven't received any data in |kHungInterval| time period.
680 void CheckPingStatus(base::TimeTicks last_check_time
);
682 // Get a new stream id.
683 int GetNewStreamId();
685 // Pushes the given frame with the given priority into the write
686 // queue for the session.
687 void EnqueueSessionWrite(RequestPriority priority
,
688 SpdyFrameType frame_type
,
689 scoped_ptr
<SpdyFrame
> frame
);
691 // Puts |producer| associated with |stream| onto the write queue
692 // with the given priority.
693 void EnqueueWrite(RequestPriority priority
,
694 SpdyFrameType frame_type
,
695 scoped_ptr
<SpdyBufferProducer
> producer
,
696 const base::WeakPtr
<SpdyStream
>& stream
);
698 // Inserts a newly-created stream into |created_streams_|.
699 void InsertCreatedStream(scoped_ptr
<SpdyStream
> stream
);
701 // Activates |stream| (which must be in |created_streams_|) by
702 // assigning it an ID and returns it.
703 scoped_ptr
<SpdyStream
> ActivateCreatedStream(SpdyStream
* stream
);
705 // Inserts a newly-activated stream into |active_streams_|.
706 void InsertActivatedStream(scoped_ptr
<SpdyStream
> stream
);
708 // Remove all internal references to |stream|, call OnClose() on it,
709 // and process any pending stream requests before deleting it. Note
710 // that |stream| may hold the last reference to the session.
711 void DeleteStream(scoped_ptr
<SpdyStream
> stream
, int status
);
713 // Check if we have a pending pushed-stream for this url
714 // Returns the stream if found (and returns it from the pending
715 // list). Returns NULL otherwise.
716 base::WeakPtr
<SpdyStream
> GetActivePushStream(const GURL
& url
);
718 // Delegates to |stream->OnInitialResponseHeadersReceived()|. If an
719 // error is returned, the last reference to |this| may have been
721 int OnInitialResponseHeadersReceived(const SpdyHeaderBlock
& response_headers
,
722 base::Time response_time
,
723 base::TimeTicks recv_first_byte_time
,
726 void RecordPingRTTHistogram(base::TimeDelta duration
);
727 void RecordHistograms();
728 void RecordProtocolErrorHistogram(SpdyProtocolErrorDetails details
);
730 // DCHECKs that |availability_state_| >= STATE_GOING_AWAY, that
731 // there are no pending stream creation requests, and that there are
732 // no created streams.
733 void DcheckGoingAway() const;
735 // Calls DcheckGoingAway(), then DCHECKs that |availability_state_|
736 // == STATE_CLOSED, |error_on_close_| has a valid value, that there
737 // are no active streams or unclaimed pushed streams, and that the
738 // write queue is empty.
739 void DcheckClosed() const;
741 // Closes all active streams with stream id's greater than
742 // |last_good_stream_id|, as well as any created or pending
743 // streams. Must be called only when |availability_state_| >=
744 // STATE_GOING_AWAY. After this function, DcheckGoingAway() will
745 // pass. May be called multiple times.
746 void StartGoingAway(SpdyStreamId last_good_stream_id
, Error status
);
748 // Must be called only when going away (i.e., DcheckGoingAway()
749 // passes). If there are no more active streams and the session
750 // isn't closed yet, close it.
751 void MaybeFinishGoingAway();
753 // If the stream is already closed, does nothing. Otherwise, moves
754 // the session to a closed state. Then, if we're in an IO loop,
755 // returns (as the IO loop will do the pool removal itself when its
756 // done). Otherwise, also removes |this| from |pool_|. The returned
757 // result describes what was done.
758 CloseSessionResult
DoCloseSession(Error err
, const std::string
& description
);
760 // Remove this session from its pool, which must exist. Must be
761 // called only when the session is closed.
763 // Must be called only via Pump{Read,Write}Loop() or
765 void RemoveFromPool();
767 // Called right before closing a (possibly-inactive) stream for a
768 // reason other than being requested to by the stream.
769 void LogAbandonedStream(SpdyStream
* stream
, Error status
);
771 // Called right before closing an active stream for a reason other
772 // than being requested to by the stream.
773 void LogAbandonedActiveStream(ActiveStreamMap::const_iterator it
,
776 // Invokes a user callback for stream creation. We provide this method so it
777 // can be deferred to the MessageLoop, so we avoid re-entrancy problems.
778 void CompleteStreamRequest(
779 const base::WeakPtr
<SpdyStreamRequest
>& pending_request
);
781 // Remove old unclaimed pushed streams.
782 void DeleteExpiredPushedStreams();
784 // BufferedSpdyFramerVisitorInterface:
785 virtual void OnError(SpdyFramer::SpdyError error_code
) OVERRIDE
;
786 virtual void OnStreamError(SpdyStreamId stream_id
,
787 const std::string
& description
) OVERRIDE
;
788 virtual void OnPing(SpdyPingId unique_id
, bool is_ack
) OVERRIDE
;
789 virtual void OnRstStream(SpdyStreamId stream_id
,
790 SpdyRstStreamStatus status
) OVERRIDE
;
791 virtual void OnGoAway(SpdyStreamId last_accepted_stream_id
,
792 SpdyGoAwayStatus status
) OVERRIDE
;
793 virtual void OnDataFrameHeader(SpdyStreamId stream_id
,
796 virtual void OnStreamFrameData(SpdyStreamId stream_id
,
800 virtual void OnSettings(bool clear_persisted
) OVERRIDE
;
801 virtual void OnSetting(
802 SpdySettingsIds id
, uint8 flags
, uint32 value
) OVERRIDE
;
803 virtual void OnWindowUpdate(SpdyStreamId stream_id
,
804 uint32 delta_window_size
) OVERRIDE
;
805 virtual void OnPushPromise(SpdyStreamId stream_id
,
806 SpdyStreamId promised_stream_id
) OVERRIDE
;
807 virtual void OnSynStream(SpdyStreamId stream_id
,
808 SpdyStreamId associated_stream_id
,
809 SpdyPriority priority
,
812 const SpdyHeaderBlock
& headers
) OVERRIDE
;
813 virtual void OnSynReply(
814 SpdyStreamId stream_id
,
816 const SpdyHeaderBlock
& headers
) OVERRIDE
;
817 virtual void OnHeaders(
818 SpdyStreamId stream_id
,
820 const SpdyHeaderBlock
& headers
) OVERRIDE
;
822 // SpdyFramerDebugVisitorInterface
823 virtual void OnSendCompressedFrame(
824 SpdyStreamId stream_id
,
827 size_t frame_len
) OVERRIDE
;
828 virtual void OnReceiveCompressedFrame(
829 SpdyStreamId stream_id
,
831 size_t frame_len
) OVERRIDE
;
833 // Called when bytes are consumed from a SpdyBuffer for a DATA frame
834 // that is to be written or is being written. Increases the send
835 // window size accordingly if some or all of the SpdyBuffer is being
838 // If session flow control is turned off, this must not be called.
839 void OnWriteBufferConsumed(size_t frame_payload_size
,
841 SpdyBuffer::ConsumeSource consume_source
);
843 // Called by OnWindowUpdate() (which is in turn called by the
844 // framer) to increase this session's send window size by
845 // |delta_window_size| from a WINDOW_UPDATE frome, which must be at
846 // least 1. If |delta_window_size| would cause this session's send
847 // window size to overflow, does nothing.
849 // If session flow control is turned off, this must not be called.
850 void IncreaseSendWindowSize(int32 delta_window_size
);
852 // If session flow control is turned on, called by CreateDataFrame()
853 // (which is in turn called by a stream) to decrease this session's
854 // send window size by |delta_window_size|, which must be at least 1
855 // and at most kMaxSpdyFrameChunkSize. |delta_window_size| must not
856 // cause this session's send window size to go negative.
858 // If session flow control is turned off, this must not be called.
859 void DecreaseSendWindowSize(int32 delta_window_size
);
861 // Called when bytes are consumed by the delegate from a SpdyBuffer
862 // containing received data. Increases the receive window size
865 // If session flow control is turned off, this must not be called.
866 void OnReadBufferConsumed(size_t consume_size
,
867 SpdyBuffer::ConsumeSource consume_source
);
869 // Called by OnReadBufferConsume to increase this session's receive
870 // window size by |delta_window_size|, which must be at least 1 and
871 // must not cause this session's receive window size to overflow,
872 // possibly also sending a WINDOW_UPDATE frame. Also called during
873 // initialization to set the initial receive window size.
875 // If session flow control is turned off, this must not be called.
876 void IncreaseRecvWindowSize(int32 delta_window_size
);
878 // Called by OnStreamFrameData (which is in turn called by the
879 // framer) to decrease this session's receive window size by
880 // |delta_window_size|, which must be at least 1 and must not cause
881 // this session's receive window size to go negative.
883 // If session flow control is turned off, this must not be called.
884 void DecreaseRecvWindowSize(int32 delta_window_size
);
886 // Queue a send-stalled stream for possibly resuming once we're not
887 // send-stalled anymore.
888 void QueueSendStalledStream(const SpdyStream
& stream
);
890 // Go through the queue of send-stalled streams and try to resume as
892 void ResumeSendStalledStreams();
894 // Returns the next stream to possibly resume, or 0 if the queue is
896 SpdyStreamId
PopStreamToPossiblyResume();
898 // --------------------------
899 // Helper methods for testing
900 // --------------------------
902 void set_connection_at_risk_of_loss_time(base::TimeDelta duration
) {
903 connection_at_risk_of_loss_time_
= duration
;
906 void set_hung_interval(base::TimeDelta duration
) {
907 hung_interval_
= duration
;
910 int64
pings_in_flight() const { return pings_in_flight_
; }
912 uint32
next_ping_id() const { return next_ping_id_
; }
914 base::TimeTicks
last_activity_time() const { return last_activity_time_
; }
916 bool check_ping_status_pending() const { return check_ping_status_pending_
; }
918 size_t max_concurrent_streams() const { return max_concurrent_streams_
; }
920 // Returns the SSLClientSocket that this SPDY session sits on top of,
921 // or NULL, if the transport is not SSL.
922 SSLClientSocket
* GetSSLClientSocket() const;
924 // Used for posting asynchronous IO tasks. We use this even though
925 // SpdySession is refcounted because we don't need to keep the SpdySession
926 // alive if the last reference is within a RunnableMethod. Just revoke the
928 base::WeakPtrFactory
<SpdySession
> weak_factory_
;
930 // Whether Do{Read,Write}Loop() is in the call stack. Useful for
931 // making sure we don't destroy ourselves prematurely in that case.
934 // The key used to identify this session.
935 const SpdySessionKey spdy_session_key_
;
937 // Set set of SpdySessionKeys for which this session has serviced
939 std::set
<SpdySessionKey
> pooled_aliases_
;
941 // |pool_| owns us, therefore its lifetime must exceed ours. We set
942 // this to NULL after we are removed from the pool.
943 SpdySessionPool
* pool_
;
944 const base::WeakPtr
<HttpServerProperties
> http_server_properties_
;
946 // The socket handle for this session.
947 scoped_ptr
<ClientSocketHandle
> connection_
;
949 // The read buffer used to read data from the socket.
950 scoped_refptr
<IOBuffer
> read_buffer_
;
952 int stream_hi_water_mark_
; // The next stream id to use.
954 // Queue, for each priority, of pending stream requests that have
955 // not yet been satisfied.
956 PendingStreamRequestQueue pending_create_stream_queues_
[NUM_PRIORITIES
];
958 // Map from stream id to all active streams. Streams are active in the sense
959 // that they have a consumer (typically SpdyNetworkTransaction and regardless
960 // of whether or not there is currently any ongoing IO [might be waiting for
961 // the server to start pushing the stream]) or there are still network events
962 // incoming even though the consumer has already gone away (cancellation).
964 // |active_streams_| owns all its SpdyStream objects.
966 // TODO(willchan): Perhaps we should separate out cancelled streams and move
967 // them into a separate ActiveStreamMap, and not deliver network events to
969 ActiveStreamMap active_streams_
;
971 // (Bijective) map from the URL to the ID of the streams that have
972 // already started to be pushed by the server, but do not have
973 // consumers yet. Contains a subset of |active_streams_|.
974 PushedStreamMap unclaimed_pushed_streams_
;
976 // Set of all created streams but that have not yet sent any frames.
978 // |created_streams_| owns all its SpdyStream objects.
979 CreatedStreamSet created_streams_
;
982 SpdyWriteQueue write_queue_
;
984 // Data for the frame we are currently sending.
986 // The buffer we're currently writing.
987 scoped_ptr
<SpdyBuffer
> in_flight_write_
;
988 // The type of the frame in |in_flight_write_|.
989 SpdyFrameType in_flight_write_frame_type_
;
990 // The size of the frame in |in_flight_write_|.
991 size_t in_flight_write_frame_size_
;
992 // The stream to notify when |in_flight_write_| has been written to
993 // the socket completely.
994 base::WeakPtr
<SpdyStream
> in_flight_write_stream_
;
996 // Flag if we're using an SSL connection for this SpdySession.
999 // Certificate error code when using a secure connection.
1000 int certificate_error_code_
;
1002 // Spdy Frame state.
1003 scoped_ptr
<BufferedSpdyFramer
> buffered_spdy_framer_
;
1005 // The state variables.
1006 AvailabilityState availability_state_
;
1007 ReadState read_state_
;
1008 WriteState write_state_
;
1010 // If the session was closed (i.e., |availability_state_| is
1011 // STATE_CLOSED), then |error_on_close_| holds the error with which
1012 // it was closed, which is < ERR_IO_PENDING. Otherwise, it is set to
1014 Error error_on_close_
;
1017 size_t max_concurrent_streams_
; // 0 if no limit
1018 size_t max_concurrent_streams_limit_
;
1020 // Some statistics counters for the session.
1021 int streams_initiated_count_
;
1022 int streams_pushed_count_
;
1023 int streams_pushed_and_claimed_count_
;
1024 int streams_abandoned_count_
;
1026 // |total_bytes_received_| keeps track of all the bytes read by the
1027 // SpdySession. It is used by the |Net.SpdySettingsCwnd...| histograms.
1028 int total_bytes_received_
;
1030 bool sent_settings_
; // Did this session send settings when it started.
1031 bool received_settings_
; // Did this session receive at least one settings
1033 int stalled_streams_
; // Count of streams that were ever stalled.
1035 // Count of all pings on the wire, for which we have not gotten a response.
1036 int64 pings_in_flight_
;
1038 // This is the next ping_id (unique_id) to be sent in PING frame.
1039 uint32 next_ping_id_
;
1041 // This is the last time we have sent a PING.
1042 base::TimeTicks last_ping_sent_time_
;
1044 // This is the last time we had activity in the session.
1045 base::TimeTicks last_activity_time_
;
1047 // This is the length of the last compressed frame.
1048 size_t last_compressed_frame_len_
;
1050 // This is the next time that unclaimed push streams should be checked for
1052 base::TimeTicks next_unclaimed_push_stream_sweep_time_
;
1054 // Indicate if we have already scheduled a delayed task to check the ping
1056 bool check_ping_status_pending_
;
1058 // Whether to send the (HTTP/2) connection header prefix.
1059 bool send_connection_header_prefix_
;
1061 // The (version-dependent) flow control state.
1062 FlowControlState flow_control_state_
;
1064 // Initial send window size for this session's streams. Can be
1065 // changed by an arriving SETTINGS frame. Newly created streams use
1066 // this value for the initial send window size.
1067 int32 stream_initial_send_window_size_
;
1069 // Initial receive window size for this session's streams. There are
1070 // plans to add a command line switch that would cause a SETTINGS
1071 // frame with window size announcement to be sent on startup. Newly
1072 // created streams will use this value for the initial receive
1074 int32 stream_initial_recv_window_size_
;
1076 // Session flow control variables. All zero unless session flow
1077 // control is turned on.
1078 int32 session_send_window_size_
;
1079 int32 session_recv_window_size_
;
1080 int32 session_unacked_recv_window_bytes_
;
1082 // A queue of stream IDs that have been send-stalled at some point
1084 std::deque
<SpdyStreamId
> stream_send_unstall_queue_
[NUM_PRIORITIES
];
1086 BoundNetLog net_log_
;
1088 // Outside of tests, these should always be true.
1089 bool verify_domain_authentication_
;
1090 bool enable_sending_initial_data_
;
1091 bool enable_compression_
;
1092 bool enable_ping_based_connection_checking_
;
1094 // The SPDY protocol used. Always between kProtoSPDYMinimumVersion and
1095 // kProtoSPDYMaximumVersion.
1096 NextProto protocol_
;
1098 // |connection_at_risk_of_loss_time_| is an optimization to avoid sending
1099 // wasteful preface pings (when we just got some data).
1101 // If it is zero (the most conservative figure), then we always send the
1102 // preface ping (when none are in flight).
1104 // It is common for TCP/IP sessions to time out in about 3-5 minutes.
1105 // Certainly if it has been more than 3 minutes, we do want to send a preface
1108 // We don't think any connection will time out in under about 10 seconds. So
1109 // this might as well be set to something conservative like 10 seconds. Later,
1110 // we could adjust it to send fewer pings perhaps.
1111 base::TimeDelta connection_at_risk_of_loss_time_
;
1113 // The amount of time that we are willing to tolerate with no activity (of any
1114 // form), while there is a ping in flight, before we declare the connection to
1115 // be hung. TODO(rtenneti): When hung, instead of resetting connection, race
1116 // to build a new connection, and see if that completes before we (finally)
1117 // get a PING response (http://crbug.com/127812).
1118 base::TimeDelta hung_interval_
;
1120 // This SPDY proxy is allowed to push resources from origins that are
1121 // different from those of their associated streams.
1122 HostPortPair trusted_spdy_proxy_
;
1124 TimeFunc time_func_
;
1129 #endif // NET_SPDY_SPDY_SESSION_H_