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
64 // First and last valid stream IDs. As we always act as the client,
65 // start at 1 for the first stream id.
66 const SpdyStreamId kFirstStreamId
= 1;
67 const SpdyStreamId kLastStreamId
= 0x7fffffff;
70 struct LoadTimingInfo
;
74 // NOTE: There's an enum of the same name (also with numeric suffixes)
75 // in histograms.xml. Be sure to add new values there also.
76 enum SpdyProtocolErrorDetails
{
77 // SpdyFramer::SpdyError mappings.
78 SPDY_ERROR_NO_ERROR
= 0,
79 SPDY_ERROR_INVALID_CONTROL_FRAME
= 1,
80 SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE
= 2,
81 SPDY_ERROR_ZLIB_INIT_FAILURE
= 3,
82 SPDY_ERROR_UNSUPPORTED_VERSION
= 4,
83 SPDY_ERROR_DECOMPRESS_FAILURE
= 5,
84 SPDY_ERROR_COMPRESS_FAILURE
= 6,
85 // SPDY_ERROR_CREDENTIAL_FRAME_CORRUPT = 7, (removed).
86 SPDY_ERROR_GOAWAY_FRAME_CORRUPT
= 29,
87 SPDY_ERROR_RST_STREAM_FRAME_CORRUPT
= 30,
88 SPDY_ERROR_INVALID_DATA_FRAME_FLAGS
= 8,
89 SPDY_ERROR_INVALID_CONTROL_FRAME_FLAGS
= 9,
90 SPDY_ERROR_UNEXPECTED_FRAME
= 31,
91 // SpdyRstStreamStatus mappings.
92 // RST_STREAM_INVALID not mapped.
93 STATUS_CODE_PROTOCOL_ERROR
= 11,
94 STATUS_CODE_INVALID_STREAM
= 12,
95 STATUS_CODE_REFUSED_STREAM
= 13,
96 STATUS_CODE_UNSUPPORTED_VERSION
= 14,
97 STATUS_CODE_CANCEL
= 15,
98 STATUS_CODE_INTERNAL_ERROR
= 16,
99 STATUS_CODE_FLOW_CONTROL_ERROR
= 17,
100 STATUS_CODE_STREAM_IN_USE
= 18,
101 STATUS_CODE_STREAM_ALREADY_CLOSED
= 19,
102 STATUS_CODE_INVALID_CREDENTIALS
= 20,
103 STATUS_CODE_FRAME_SIZE_ERROR
= 21,
104 STATUS_CODE_SETTINGS_TIMEOUT
= 32,
105 STATUS_CODE_CONNECT_ERROR
= 33,
106 STATUS_CODE_ENHANCE_YOUR_CALM
= 34,
108 // SpdySession errors
109 PROTOCOL_ERROR_UNEXPECTED_PING
= 22,
110 PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM
= 23,
111 PROTOCOL_ERROR_SPDY_COMPRESSION_FAILURE
= 24,
112 PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION
= 25,
113 PROTOCOL_ERROR_SYN_REPLY_NOT_RECEIVED
= 26,
114 PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
= 27,
115 PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION
= 28,
118 NUM_SPDY_PROTOCOL_ERROR_DETAILS
= 35,
120 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
121 MapFramerErrorToProtocolError(SpdyFramer::SpdyError error
);
122 Error NET_EXPORT_PRIVATE
MapFramerErrorToNetError(SpdyFramer::SpdyError error
);
123 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
124 MapRstStreamStatusToProtocolError(SpdyRstStreamStatus status
);
125 SpdyGoAwayStatus NET_EXPORT_PRIVATE
MapNetErrorToGoAwayStatus(Error err
);
127 // If these compile asserts fail then SpdyProtocolErrorDetails needs
128 // to be updated with new values, as do the mapping functions above.
129 COMPILE_ASSERT(12 == SpdyFramer::LAST_ERROR
,
130 SpdyProtocolErrorDetails_SpdyErrors_mismatch
);
131 COMPILE_ASSERT(15 == RST_STREAM_NUM_STATUS_CODES
,
132 SpdyProtocolErrorDetails_RstStreamStatus_mismatch
);
134 // Splits pushed |headers| into request and response parts. Request headers are
135 // the headers specifying resource URL.
136 void NET_EXPORT_PRIVATE
137 SplitPushedHeadersToRequestAndResponse(const SpdyHeaderBlock
& headers
,
138 SpdyMajorVersion protocol_version
,
139 SpdyHeaderBlock
* request_headers
,
140 SpdyHeaderBlock
* response_headers
);
142 // A helper class used to manage a request to create a stream.
143 class NET_EXPORT_PRIVATE SpdyStreamRequest
{
146 // Calls CancelRequest().
147 ~SpdyStreamRequest();
149 // Starts the request to create a stream. If OK is returned, then
150 // ReleaseStream() may be called. If ERR_IO_PENDING is returned,
151 // then when the stream is created, |callback| will be called, at
152 // which point ReleaseStream() may be called. Otherwise, the stream
153 // is not created, an error is returned, and ReleaseStream() may not
156 // If OK is returned, must not be called again without
157 // ReleaseStream() being called first. If ERR_IO_PENDING is
158 // returned, must not be called again without CancelRequest() or
159 // ReleaseStream() being called first. Otherwise, in case of an
160 // immediate error, this may be called again.
161 int StartRequest(SpdyStreamType type
,
162 const base::WeakPtr
<SpdySession
>& session
,
164 RequestPriority priority
,
165 const BoundNetLog
& net_log
,
166 const CompletionCallback
& callback
);
168 // Cancels any pending stream creation request. May be called
170 void CancelRequest();
172 // Transfers the created stream (guaranteed to not be NULL) to the
173 // caller. Must be called at most once after StartRequest() returns
174 // OK or |callback| is called with OK. The caller must immediately
175 // set a delegate for the returned stream (except for test code).
176 base::WeakPtr
<SpdyStream
> ReleaseStream();
179 friend class SpdySession
;
181 // Called by |session_| when the stream attempt has finished
183 void OnRequestCompleteSuccess(const base::WeakPtr
<SpdyStream
>& stream
);
185 // Called by |session_| when the stream attempt has finished with an
186 // error. Also called with ERR_ABORTED if |session_| is destroyed
187 // while the stream attempt is still pending.
188 void OnRequestCompleteFailure(int rv
);
190 // Accessors called by |session_|.
191 SpdyStreamType
type() const { return type_
; }
192 const GURL
& url() const { return url_
; }
193 RequestPriority
priority() const { return priority_
; }
194 const BoundNetLog
& net_log() const { return net_log_
; }
198 SpdyStreamType type_
;
199 base::WeakPtr
<SpdySession
> session_
;
200 base::WeakPtr
<SpdyStream
> stream_
;
202 RequestPriority priority_
;
203 BoundNetLog net_log_
;
204 CompletionCallback callback_
;
206 base::WeakPtrFactory
<SpdyStreamRequest
> weak_ptr_factory_
;
208 DISALLOW_COPY_AND_ASSIGN(SpdyStreamRequest
);
211 class NET_EXPORT SpdySession
: public BufferedSpdyFramerVisitorInterface
,
212 public SpdyFramerDebugVisitorInterface
,
213 public HigherLayeredPool
{
215 // TODO(akalin): Use base::TickClock when it becomes available.
216 typedef base::TimeTicks (*TimeFunc
)(void);
218 // How we handle flow control (version-dependent).
219 enum FlowControlState
{
222 FLOW_CONTROL_STREAM_AND_SESSION
225 // Create a new SpdySession.
226 // |spdy_session_key| is the host/port that this session connects to, privacy
227 // and proxy configuration settings that it's using.
228 // |session| is the HttpNetworkSession. |net_log| is the NetLog that we log
229 // network events to.
230 SpdySession(const SpdySessionKey
& spdy_session_key
,
231 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
232 bool verify_domain_authentication
,
233 bool enable_sending_initial_data
,
234 bool enable_compression
,
235 bool enable_ping_based_connection_checking
,
236 NextProto default_protocol
,
237 size_t stream_initial_recv_window_size
,
238 size_t initial_max_concurrent_streams
,
239 size_t max_concurrent_streams_limit
,
241 const HostPortPair
& trusted_spdy_proxy
,
244 virtual ~SpdySession();
246 const HostPortPair
& host_port_pair() const {
247 return spdy_session_key_
.host_port_proxy_pair().first
;
249 const HostPortProxyPair
& host_port_proxy_pair() const {
250 return spdy_session_key_
.host_port_proxy_pair();
252 const SpdySessionKey
& spdy_session_key() const {
253 return spdy_session_key_
;
255 // Get a pushed stream for a given |url|. If the server initiates a
256 // stream, it might already exist for a given path. The server
257 // might also not have initiated the stream yet, but indicated it
258 // will via X-Associated-Content. Returns OK if a stream was found
259 // and put into |spdy_stream|, or if one was not found but it is
260 // okay to create a new stream (in which case |spdy_stream| is
261 // reset). Returns an error (not ERR_IO_PENDING) otherwise, and
262 // resets |spdy_stream|.
265 base::WeakPtr
<SpdyStream
>* spdy_stream
,
266 const BoundNetLog
& stream_net_log
);
268 // Initialize the session with the given connection. |is_secure|
269 // must indicate whether |connection| uses an SSL socket or not; it
270 // is usually true, but it can be false for testing or when SPDY is
271 // configured to work with non-secure sockets.
273 // |pool| is the SpdySessionPool that owns us. Its lifetime must
274 // strictly be greater than |this|.
276 // |certificate_error_code| must either be OK or less than
279 // The session begins reading from |connection| on a subsequent event loop
280 // iteration, so the SpdySession may close immediately afterwards if the first
281 // read of |connection| fails.
282 void InitializeWithSocket(scoped_ptr
<ClientSocketHandle
> connection
,
283 SpdySessionPool
* pool
,
285 int certificate_error_code
);
287 // Returns the protocol used by this session. Always between
288 // kProtoSPDYMinimumVersion and kProtoSPDYMaximumVersion.
289 NextProto
protocol() const { return protocol_
; }
291 // Check to see if this SPDY session can support an additional domain.
292 // If the session is un-authenticated, then this call always returns true.
293 // For SSL-based sessions, verifies that the server certificate in use by
294 // this session provides authentication for the domain and no client
295 // certificate or channel ID was sent to the original server during the SSL
296 // handshake. NOTE: This function can have false negatives on some
298 // TODO(wtc): rename this function and the Net.SpdyIPPoolDomainMatch
299 // histogram because this function does more than verifying domain
300 // authentication now.
301 bool VerifyDomainAuthentication(const std::string
& domain
);
303 // Pushes the given producer into the write queue for
304 // |stream|. |stream| is guaranteed to be activated before the
305 // producer is used to produce its frame.
306 void EnqueueStreamWrite(const base::WeakPtr
<SpdyStream
>& stream
,
307 SpdyFrameType frame_type
,
308 scoped_ptr
<SpdyBufferProducer
> producer
);
310 // Creates and returns a SYN frame for |stream_id|.
311 scoped_ptr
<SpdyFrame
> CreateSynStream(
312 SpdyStreamId stream_id
,
313 RequestPriority priority
,
314 SpdyControlFlags flags
,
315 const SpdyHeaderBlock
& headers
);
317 // Creates and returns a SpdyBuffer holding a data frame with the
318 // given data. May return NULL if stalled by flow control.
319 scoped_ptr
<SpdyBuffer
> CreateDataBuffer(SpdyStreamId stream_id
,
322 SpdyDataFlags flags
);
324 // Close the stream with the given ID, which must exist and be
325 // active. Note that that stream may hold the last reference to the
327 void CloseActiveStream(SpdyStreamId stream_id
, int status
);
329 // Close the given created stream, which must exist but not yet be
330 // active. Note that |stream| may hold the last reference to the
332 void CloseCreatedStream(const base::WeakPtr
<SpdyStream
>& stream
, int status
);
334 // Send a RST_STREAM frame with the given status code and close the
335 // stream with the given ID, which must exist and be active. Note
336 // that that stream may hold the last reference to the session.
337 void ResetStream(SpdyStreamId stream_id
,
338 SpdyRstStreamStatus status
,
339 const std::string
& description
);
341 // Check if a stream is active.
342 bool IsStreamActive(SpdyStreamId stream_id
) const;
344 // The LoadState is used for informing the user of the current network
345 // status, such as "resolving host", "connecting", etc.
346 LoadState
GetLoadState() const;
348 // Fills SSL info in |ssl_info| and returns true when SSL is in use.
349 bool GetSSLInfo(SSLInfo
* ssl_info
,
350 bool* was_npn_negotiated
,
351 NextProto
* protocol_negotiated
);
353 // Fills SSL Certificate Request info |cert_request_info| and returns
354 // true when SSL is in use.
355 bool GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
);
357 // Send a WINDOW_UPDATE frame for a stream. Called by a stream
358 // whenever receive window size is increased.
359 void SendStreamWindowUpdate(SpdyStreamId stream_id
,
360 uint32 delta_window_size
);
362 // Accessors for the session's availability state.
363 bool IsAvailable() const { return availability_state_
== STATE_AVAILABLE
; }
364 bool IsGoingAway() const { return availability_state_
== STATE_GOING_AWAY
; }
365 bool IsDraining() const { return availability_state_
== STATE_DRAINING
; }
367 // Closes this session. This will close all active streams and mark
368 // the session as permanently closed. Callers must assume that the
369 // session is destroyed after this is called. (However, it may not
370 // be destroyed right away, e.g. when a SpdySession function is
371 // present in the call stack.)
373 // |err| should be < ERR_IO_PENDING; this function is intended to be
375 // |description| indicates the reason for the error.
376 void CloseSessionOnError(Error err
, const std::string
& description
);
378 // Mark this session as unavailable, meaning that it will not be used to
379 // service new streams. Unlike when a GOAWAY frame is received, this function
380 // will not close any streams.
381 void MakeUnavailable();
383 // Closes all active streams with stream id's greater than
384 // |last_good_stream_id|, as well as any created or pending
385 // streams. Must be called only when |availability_state_| >=
386 // STATE_GOING_AWAY. After this function, DcheckGoingAway() will
387 // pass. May be called multiple times.
388 void StartGoingAway(SpdyStreamId last_good_stream_id
, Error status
);
390 // Must be called only when going away (i.e., DcheckGoingAway()
391 // passes). If there are no more active streams and the session
392 // isn't closed yet, close it.
393 void MaybeFinishGoingAway();
395 // Retrieves information on the current state of the SPDY session as a
396 // Value. Caller takes possession of the returned value.
397 base::Value
* GetInfoAsValue() const;
399 // Indicates whether the session is being reused after having successfully
400 // used to send/receive data in the past or if the underlying socket was idle
401 // before being used for a SPDY session.
402 bool IsReused() const;
404 // Returns true if the underlying transport socket ever had any reads or
406 bool WasEverUsed() const {
407 return connection_
->socket()->WasEverUsed();
410 // Returns the load timing information from the perspective of the given
411 // stream. If it's not the first stream, the connection is considered reused
414 // This uses a different notion of reuse than IsReused(). This function
415 // sets |socket_reused| to false only if |stream_id| is the ID of the first
416 // stream using the session. IsReused(), on the other hand, indicates if the
417 // session has been used to send/receive data at all.
418 bool GetLoadTimingInfo(SpdyStreamId stream_id
,
419 LoadTimingInfo
* load_timing_info
) const;
421 // Returns true if session is not currently active
422 bool is_active() const {
423 return !active_streams_
.empty() || !created_streams_
.empty();
426 // Access to the number of active and pending streams. These are primarily
427 // available for testing and diagnostics.
428 size_t num_active_streams() const { return active_streams_
.size(); }
429 size_t num_unclaimed_pushed_streams() const {
430 return unclaimed_pushed_streams_
.size();
432 size_t num_created_streams() const { return created_streams_
.size(); }
434 size_t num_pushed_streams() const { return num_pushed_streams_
; }
435 size_t num_active_pushed_streams() const {
436 return num_active_pushed_streams_
;
439 size_t pending_create_stream_queue_size(RequestPriority priority
) const {
440 DCHECK_GE(priority
, MINIMUM_PRIORITY
);
441 DCHECK_LE(priority
, MAXIMUM_PRIORITY
);
442 return pending_create_stream_queues_
[priority
].size();
445 // Returns the (version-dependent) flow control state.
446 FlowControlState
flow_control_state() const {
447 return flow_control_state_
;
450 // Returns the current |stream_initial_send_window_size_|.
451 int32
stream_initial_send_window_size() const {
452 return stream_initial_send_window_size_
;
455 // Returns the current |stream_initial_recv_window_size_|.
456 int32
stream_initial_recv_window_size() const {
457 return stream_initial_recv_window_size_
;
460 // Returns true if no stream in the session can send data due to
461 // session flow control.
462 bool IsSendStalled() const {
464 flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
&&
465 session_send_window_size_
== 0;
468 const BoundNetLog
& net_log() const { return net_log_
; }
470 int GetPeerAddress(IPEndPoint
* address
) const;
471 int GetLocalAddress(IPEndPoint
* address
) const;
473 // Adds |alias| to set of aliases associated with this session.
474 void AddPooledAlias(const SpdySessionKey
& alias_key
);
476 // Returns the set of aliases associated with this session.
477 const std::set
<SpdySessionKey
>& pooled_aliases() const {
478 return pooled_aliases_
;
481 SpdyMajorVersion
GetProtocolVersion() const;
483 size_t GetDataFrameMinimumSize() const {
484 return buffered_spdy_framer_
->GetDataFrameMinimumSize();
487 size_t GetControlFrameHeaderSize() const {
488 return buffered_spdy_framer_
->GetControlFrameHeaderSize();
491 size_t GetFrameMinimumSize() const {
492 return buffered_spdy_framer_
->GetFrameMinimumSize();
495 size_t GetFrameMaximumSize() const {
496 return buffered_spdy_framer_
->GetFrameMaximumSize();
499 size_t GetDataFrameMaximumPayload() const {
500 return buffered_spdy_framer_
->GetDataFrameMaximumPayload();
503 // https://http2.github.io/http2-spec/#TLSUsage mandates minimum security
504 // standards for TLS.
505 bool HasAcceptableTransportSecurity() const;
507 // Must be used only by |pool_|.
508 base::WeakPtr
<SpdySession
> GetWeakPtr();
510 // HigherLayeredPool implementation:
511 virtual bool CloseOneIdleConnection() OVERRIDE
;
514 friend class base::RefCounted
<SpdySession
>;
515 friend class SpdyStreamRequest
;
516 friend class SpdySessionTest
;
518 // Allow tests to access our innards for testing purposes.
519 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClientPing
);
520 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, FailedPing
);
521 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, GetActivePushStream
);
522 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, DeleteExpiredPushStreams
);
523 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ProtocolNegotiation
);
524 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClearSettings
);
525 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustRecvWindowSize
);
526 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustSendWindowSize
);
527 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlInactiveStream
);
528 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoReceiveLeaks
);
529 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoSendLeaks
);
530 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlEndToEnd
);
531 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, StreamIdSpaceExhausted
);
532 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, UnstallRacesWithStreamCreation
);
533 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, GoAwayOnSessionFlowControlError
);
534 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
,
535 RejectPushedStreamExceedingConcurrencyLimit
);
536 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, IgnoreReservedRemoteStreamsCount
);
537 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
,
538 CancelReservedStreamOnHeadersReceived
);
540 typedef std::deque
<base::WeakPtr
<SpdyStreamRequest
> >
541 PendingStreamRequestQueue
;
543 struct ActiveStreamInfo
{
545 explicit ActiveStreamInfo(SpdyStream
* stream
);
549 bool waiting_for_syn_reply
;
551 typedef std::map
<SpdyStreamId
, ActiveStreamInfo
> ActiveStreamMap
;
553 struct PushedStreamInfo
{
555 PushedStreamInfo(SpdyStreamId stream_id
, base::TimeTicks creation_time
);
558 SpdyStreamId stream_id
;
559 base::TimeTicks creation_time
;
561 typedef std::map
<GURL
, PushedStreamInfo
> PushedStreamMap
;
563 typedef std::set
<SpdyStream
*> CreatedStreamSet
;
565 enum AvailabilityState
{
566 // The session is available in its socket pool and can be used
569 // The session can process data on existing streams but will
570 // refuse to create new ones.
572 // The session is draining its write queue in preparation of closing.
573 // Further writes will not be queued, and further reads will not be issued
574 // (though the remainder of a current read may be processed). The session
575 // will be destroyed by its write loop once the write queue is drained.
581 READ_STATE_DO_READ_COMPLETE
,
585 // There is no in-flight write and the write queue is empty.
587 WRITE_STATE_DO_WRITE
,
588 WRITE_STATE_DO_WRITE_COMPLETE
,
591 // Checks whether a stream for the given |url| can be created or
592 // retrieved from the set of unclaimed push streams. Returns OK if
593 // so. Otherwise, the session is closed and an error <
594 // ERR_IO_PENDING is returned.
595 Error
TryAccessStream(const GURL
& url
);
597 // Called by SpdyStreamRequest to start a request to create a
598 // stream. If OK is returned, then |stream| will be filled in with a
599 // valid stream. If ERR_IO_PENDING is returned, then
600 // |request->OnRequestComplete{Success,Failure}()| will be called
601 // when the stream is created (unless it is cancelled). Otherwise,
602 // no stream is created and the error is returned.
603 int TryCreateStream(const base::WeakPtr
<SpdyStreamRequest
>& request
,
604 base::WeakPtr
<SpdyStream
>* stream
);
606 // Actually create a stream into |stream|. Returns OK if successful;
607 // otherwise, returns an error and |stream| is not filled.
608 int CreateStream(const SpdyStreamRequest
& request
,
609 base::WeakPtr
<SpdyStream
>* stream
);
611 // Called by SpdyStreamRequest to remove |request| from the stream
613 void CancelStreamRequest(const base::WeakPtr
<SpdyStreamRequest
>& request
);
615 // Returns the next pending stream request to process, or NULL if
617 base::WeakPtr
<SpdyStreamRequest
> GetNextPendingStreamRequest();
619 // Called when there is room to create more streams (e.g., a stream
620 // was closed). Processes as many pending stream requests as
622 void ProcessPendingStreamRequests();
624 bool TryCreatePushStream(SpdyStreamId stream_id
,
625 SpdyStreamId associated_stream_id
,
626 SpdyPriority priority
,
627 const SpdyHeaderBlock
& headers
);
629 // Close the stream pointed to by the given iterator. Note that that
630 // stream may hold the last reference to the session.
631 void CloseActiveStreamIterator(ActiveStreamMap::iterator it
, int status
);
633 // Close the stream pointed to by the given iterator. Note that that
634 // stream may hold the last reference to the session.
635 void CloseCreatedStreamIterator(CreatedStreamSet::iterator it
, int status
);
637 // Calls EnqueueResetStreamFrame() and then
638 // CloseActiveStreamIterator().
639 void ResetStreamIterator(ActiveStreamMap::iterator it
,
640 SpdyRstStreamStatus status
,
641 const std::string
& description
);
643 // Send a RST_STREAM frame with the given parameters. There should
644 // either be no active stream with the given ID, or that active
645 // stream should be closed shortly after this function is called.
647 // TODO(akalin): Rename this to EnqueueResetStreamFrame().
648 void EnqueueResetStreamFrame(SpdyStreamId stream_id
,
649 RequestPriority priority
,
650 SpdyRstStreamStatus status
,
651 const std::string
& description
);
653 // Calls DoReadLoop. Use this function instead of DoReadLoop when
654 // posting a task to pump the read loop.
655 void PumpReadLoop(ReadState expected_read_state
, int result
);
657 // Advance the ReadState state machine. |expected_read_state| is the
658 // expected starting read state.
660 // This function must always be called via PumpReadLoop().
661 int DoReadLoop(ReadState expected_read_state
, int result
);
662 // The implementations of the states of the ReadState state machine.
664 int DoReadComplete(int result
);
666 // Calls DoWriteLoop. If |availability_state_| is STATE_DRAINING and no
667 // writes remain, the session is removed from the session pool and
670 // Use this function instead of DoWriteLoop when posting a task to
671 // pump the write loop.
672 void PumpWriteLoop(WriteState expected_write_state
, int result
);
674 // Iff the write loop is not currently active, posts a callback into
676 void MaybePostWriteLoop();
678 // Advance the WriteState state machine. |expected_write_state| is
679 // the expected starting write state.
681 // This function must always be called via PumpWriteLoop().
682 int DoWriteLoop(WriteState expected_write_state
, int result
);
683 // The implementations of the states of the WriteState state machine.
685 int DoWriteComplete(int result
);
687 // TODO(akalin): Rename the Send* and Write* functions below to
690 // Send initial data. Called when a connection is successfully
691 // established in InitializeWithSocket() and
692 // |enable_sending_initial_data_| is true.
693 void SendInitialData();
695 // Helper method to send a SETTINGS frame.
696 void SendSettings(const SettingsMap
& settings
);
698 // Handle SETTING. Either when we send settings, or when we receive a
699 // SETTINGS control frame, update our SpdySession accordingly.
700 void HandleSetting(uint32 id
, uint32 value
);
702 // Adjust the send window size of all ActiveStreams and PendingStreamRequests.
703 void UpdateStreamsSendWindowSize(int32 delta_window_size
);
705 // Send the PING (preface-PING) frame.
706 void SendPrefacePingIfNoneInFlight();
708 // Send PING if there are no PINGs in flight and we haven't heard from server.
709 void SendPrefacePing();
711 // Send a single WINDOW_UPDATE frame.
712 void SendWindowUpdateFrame(SpdyStreamId stream_id
, uint32 delta_window_size
,
713 RequestPriority priority
);
715 // Send the PING frame.
716 void WritePingFrame(uint32 unique_id
, bool is_ack
);
718 // Post a CheckPingStatus call after delay. Don't post if there is already
719 // CheckPingStatus running.
720 void PlanToCheckPingStatus();
722 // Check the status of the connection. It calls |CloseSessionOnError| if we
723 // haven't received any data in |kHungInterval| time period.
724 void CheckPingStatus(base::TimeTicks last_check_time
);
726 // Get a new stream id.
727 SpdyStreamId
GetNewStreamId();
729 // Pushes the given frame with the given priority into the write
730 // queue for the session.
731 void EnqueueSessionWrite(RequestPriority priority
,
732 SpdyFrameType frame_type
,
733 scoped_ptr
<SpdyFrame
> frame
);
735 // Puts |producer| associated with |stream| onto the write queue
736 // with the given priority.
737 void EnqueueWrite(RequestPriority priority
,
738 SpdyFrameType frame_type
,
739 scoped_ptr
<SpdyBufferProducer
> producer
,
740 const base::WeakPtr
<SpdyStream
>& stream
);
742 // Inserts a newly-created stream into |created_streams_|.
743 void InsertCreatedStream(scoped_ptr
<SpdyStream
> stream
);
745 // Activates |stream| (which must be in |created_streams_|) by
746 // assigning it an ID and returns it.
747 scoped_ptr
<SpdyStream
> ActivateCreatedStream(SpdyStream
* stream
);
749 // Inserts a newly-activated stream into |active_streams_|.
750 void InsertActivatedStream(scoped_ptr
<SpdyStream
> stream
);
752 // Remove all internal references to |stream|, call OnClose() on it,
753 // and process any pending stream requests before deleting it. Note
754 // that |stream| may hold the last reference to the session.
755 void DeleteStream(scoped_ptr
<SpdyStream
> stream
, int status
);
757 // Check if we have a pending pushed-stream for this url
758 // Returns the stream if found (and returns it from the pending
759 // list). Returns NULL otherwise.
760 base::WeakPtr
<SpdyStream
> GetActivePushStream(const GURL
& url
);
762 // Delegates to |stream->OnInitialResponseHeadersReceived()|. If an
763 // error is returned, the last reference to |this| may have been
765 int OnInitialResponseHeadersReceived(const SpdyHeaderBlock
& response_headers
,
766 base::Time response_time
,
767 base::TimeTicks recv_first_byte_time
,
770 void RecordPingRTTHistogram(base::TimeDelta duration
);
771 void RecordHistograms();
772 void RecordProtocolErrorHistogram(SpdyProtocolErrorDetails details
);
774 // DCHECKs that |availability_state_| >= STATE_GOING_AWAY, that
775 // there are no pending stream creation requests, and that there are
776 // no created streams.
777 void DcheckGoingAway() const;
779 // Calls DcheckGoingAway(), then DCHECKs that |availability_state_|
780 // == STATE_DRAINING, |error_on_close_| has a valid value, and that there
781 // are no active streams or unclaimed pushed streams.
782 void DcheckDraining() const;
784 // If the session is already draining, does nothing. Otherwise, moves
785 // the session to the draining state.
786 void DoDrainSession(Error err
, const std::string
& description
);
788 // Called right before closing a (possibly-inactive) stream for a
789 // reason other than being requested to by the stream.
790 void LogAbandonedStream(SpdyStream
* stream
, Error status
);
792 // Called right before closing an active stream for a reason other
793 // than being requested to by the stream.
794 void LogAbandonedActiveStream(ActiveStreamMap::const_iterator it
,
797 // Invokes a user callback for stream creation. We provide this method so it
798 // can be deferred to the MessageLoop, so we avoid re-entrancy problems.
799 void CompleteStreamRequest(
800 const base::WeakPtr
<SpdyStreamRequest
>& pending_request
);
802 // Remove old unclaimed pushed streams.
803 void DeleteExpiredPushedStreams();
805 // BufferedSpdyFramerVisitorInterface:
806 virtual void OnError(SpdyFramer::SpdyError error_code
) OVERRIDE
;
807 virtual void OnStreamError(SpdyStreamId stream_id
,
808 const std::string
& description
) OVERRIDE
;
809 virtual void OnPing(SpdyPingId unique_id
, bool is_ack
) OVERRIDE
;
810 virtual void OnRstStream(SpdyStreamId stream_id
,
811 SpdyRstStreamStatus status
) OVERRIDE
;
812 virtual void OnGoAway(SpdyStreamId last_accepted_stream_id
,
813 SpdyGoAwayStatus status
) OVERRIDE
;
814 virtual void OnDataFrameHeader(SpdyStreamId stream_id
,
817 virtual void OnStreamFrameData(SpdyStreamId stream_id
,
821 virtual void OnSettings(bool clear_persisted
) OVERRIDE
;
822 virtual void OnSetting(
823 SpdySettingsIds id
, uint8 flags
, uint32 value
) OVERRIDE
;
824 virtual void OnWindowUpdate(SpdyStreamId stream_id
,
825 uint32 delta_window_size
) OVERRIDE
;
826 virtual void OnPushPromise(SpdyStreamId stream_id
,
827 SpdyStreamId promised_stream_id
,
828 const SpdyHeaderBlock
& headers
) OVERRIDE
;
829 virtual void OnSynStream(SpdyStreamId stream_id
,
830 SpdyStreamId associated_stream_id
,
831 SpdyPriority priority
,
834 const SpdyHeaderBlock
& headers
) OVERRIDE
;
835 virtual void OnSynReply(
836 SpdyStreamId stream_id
,
838 const SpdyHeaderBlock
& headers
) OVERRIDE
;
839 virtual void OnHeaders(
840 SpdyStreamId stream_id
,
842 const SpdyHeaderBlock
& headers
) OVERRIDE
;
844 // SpdyFramerDebugVisitorInterface
845 virtual void OnSendCompressedFrame(
846 SpdyStreamId stream_id
,
849 size_t frame_len
) OVERRIDE
;
850 virtual void OnReceiveCompressedFrame(
851 SpdyStreamId stream_id
,
853 size_t frame_len
) OVERRIDE
;
855 // Called when bytes are consumed from a SpdyBuffer for a DATA frame
856 // that is to be written or is being written. Increases the send
857 // window size accordingly if some or all of the SpdyBuffer is being
860 // If session flow control is turned off, this must not be called.
861 void OnWriteBufferConsumed(size_t frame_payload_size
,
863 SpdyBuffer::ConsumeSource consume_source
);
865 // Called by OnWindowUpdate() (which is in turn called by the
866 // framer) to increase this session's send window size by
867 // |delta_window_size| from a WINDOW_UPDATE frome, which must be at
868 // least 1. If |delta_window_size| would cause this session's send
869 // window size to overflow, does nothing.
871 // If session flow control is turned off, this must not be called.
872 void IncreaseSendWindowSize(int32 delta_window_size
);
874 // If session flow control is turned on, called by CreateDataFrame()
875 // (which is in turn called by a stream) to decrease this session's
876 // send window size by |delta_window_size|, which must be at least 1
877 // and at most kMaxSpdyFrameChunkSize. |delta_window_size| must not
878 // cause this session's send window size to go negative.
880 // If session flow control is turned off, this must not be called.
881 void DecreaseSendWindowSize(int32 delta_window_size
);
883 // Called when bytes are consumed by the delegate from a SpdyBuffer
884 // containing received data. Increases the receive window size
887 // If session flow control is turned off, this must not be called.
888 void OnReadBufferConsumed(size_t consume_size
,
889 SpdyBuffer::ConsumeSource consume_source
);
891 // Called by OnReadBufferConsume to increase this session's receive
892 // window size by |delta_window_size|, which must be at least 1 and
893 // must not cause this session's receive window size to overflow,
894 // possibly also sending a WINDOW_UPDATE frame. Also called during
895 // initialization to set the initial receive window size.
897 // If session flow control is turned off, this must not be called.
898 void IncreaseRecvWindowSize(int32 delta_window_size
);
900 // Called by OnStreamFrameData (which is in turn called by the
901 // framer) to decrease this session's receive window size by
902 // |delta_window_size|, which must be at least 1 and must not cause
903 // this session's receive window size to go negative.
905 // If session flow control is turned off, this must not be called.
906 void DecreaseRecvWindowSize(int32 delta_window_size
);
908 // Queue a send-stalled stream for possibly resuming once we're not
909 // send-stalled anymore.
910 void QueueSendStalledStream(const SpdyStream
& stream
);
912 // Go through the queue of send-stalled streams and try to resume as
914 void ResumeSendStalledStreams();
916 // Returns the next stream to possibly resume, or 0 if the queue is
918 SpdyStreamId
PopStreamToPossiblyResume();
920 // --------------------------
921 // Helper methods for testing
922 // --------------------------
924 void set_connection_at_risk_of_loss_time(base::TimeDelta duration
) {
925 connection_at_risk_of_loss_time_
= duration
;
928 void set_hung_interval(base::TimeDelta duration
) {
929 hung_interval_
= duration
;
932 void set_max_concurrent_pushed_streams(size_t value
) {
933 max_concurrent_pushed_streams_
= value
;
936 int64
pings_in_flight() const { return pings_in_flight_
; }
938 uint32
next_ping_id() const { return next_ping_id_
; }
940 base::TimeTicks
last_activity_time() const { return last_activity_time_
; }
942 bool check_ping_status_pending() const { return check_ping_status_pending_
; }
944 size_t max_concurrent_streams() const { return max_concurrent_streams_
; }
946 // Returns the SSLClientSocket that this SPDY session sits on top of,
947 // or NULL, if the transport is not SSL.
948 SSLClientSocket
* GetSSLClientSocket() const;
950 // Whether Do{Read,Write}Loop() is in the call stack. Useful for
951 // making sure we don't destroy ourselves prematurely in that case.
954 // The key used to identify this session.
955 const SpdySessionKey spdy_session_key_
;
957 // Set set of SpdySessionKeys for which this session has serviced
959 std::set
<SpdySessionKey
> pooled_aliases_
;
961 // |pool_| owns us, therefore its lifetime must exceed ours. We set
962 // this to NULL after we are removed from the pool.
963 SpdySessionPool
* pool_
;
964 const base::WeakPtr
<HttpServerProperties
> http_server_properties_
;
966 // The socket handle for this session.
967 scoped_ptr
<ClientSocketHandle
> connection_
;
969 // The read buffer used to read data from the socket.
970 scoped_refptr
<IOBuffer
> read_buffer_
;
972 SpdyStreamId stream_hi_water_mark_
; // The next stream id to use.
974 // Queue, for each priority, of pending stream requests that have
975 // not yet been satisfied.
976 PendingStreamRequestQueue pending_create_stream_queues_
[NUM_PRIORITIES
];
978 // Map from stream id to all active streams. Streams are active in the sense
979 // that they have a consumer (typically SpdyNetworkTransaction and regardless
980 // of whether or not there is currently any ongoing IO [might be waiting for
981 // the server to start pushing the stream]) or there are still network events
982 // incoming even though the consumer has already gone away (cancellation).
984 // |active_streams_| owns all its SpdyStream objects.
986 // TODO(willchan): Perhaps we should separate out cancelled streams and move
987 // them into a separate ActiveStreamMap, and not deliver network events to
989 ActiveStreamMap active_streams_
;
991 // (Bijective) map from the URL to the ID of the streams that have
992 // already started to be pushed by the server, but do not have
993 // consumers yet. Contains a subset of |active_streams_|.
994 PushedStreamMap unclaimed_pushed_streams_
;
996 // Set of all created streams but that have not yet sent any frames.
998 // |created_streams_| owns all its SpdyStream objects.
999 CreatedStreamSet created_streams_
;
1001 // Number of pushed streams. All active streams are stored in
1002 // |active_streams_|, but it's better to know the number of push streams
1003 // without traversing the whole collection.
1004 size_t num_pushed_streams_
;
1006 // Number of active pushed streams in |active_streams_|, i.e. not in reserved
1007 // remote state. Streams in reserved state are not counted towards any
1008 // concurrency limits.
1009 size_t num_active_pushed_streams_
;
1012 SpdyWriteQueue write_queue_
;
1014 // Data for the frame we are currently sending.
1016 // The buffer we're currently writing.
1017 scoped_ptr
<SpdyBuffer
> in_flight_write_
;
1018 // The type of the frame in |in_flight_write_|.
1019 SpdyFrameType in_flight_write_frame_type_
;
1020 // The size of the frame in |in_flight_write_|.
1021 size_t in_flight_write_frame_size_
;
1022 // The stream to notify when |in_flight_write_| has been written to
1023 // the socket completely.
1024 base::WeakPtr
<SpdyStream
> in_flight_write_stream_
;
1026 // Flag if we're using an SSL connection for this SpdySession.
1029 // Certificate error code when using a secure connection.
1030 int certificate_error_code_
;
1032 // Spdy Frame state.
1033 scoped_ptr
<BufferedSpdyFramer
> buffered_spdy_framer_
;
1035 // The state variables.
1036 AvailabilityState availability_state_
;
1037 ReadState read_state_
;
1038 WriteState write_state_
;
1040 // If the session is closing (i.e., |availability_state_| is STATE_DRAINING),
1041 // then |error_on_close_| holds the error with which it was closed, which
1042 // may be OK (upon a polite GOAWAY) or an error < ERR_IO_PENDING otherwise.
1043 // Initialized to OK.
1044 Error error_on_close_
;
1047 size_t max_concurrent_streams_
; // 0 if no limit
1048 size_t max_concurrent_streams_limit_
;
1049 size_t max_concurrent_pushed_streams_
;
1051 // Some statistics counters for the session.
1052 int streams_initiated_count_
;
1053 int streams_pushed_count_
;
1054 int streams_pushed_and_claimed_count_
;
1055 int streams_abandoned_count_
;
1057 // |total_bytes_received_| keeps track of all the bytes read by the
1058 // SpdySession. It is used by the |Net.SpdySettingsCwnd...| histograms.
1059 int total_bytes_received_
;
1061 bool sent_settings_
; // Did this session send settings when it started.
1062 bool received_settings_
; // Did this session receive at least one settings
1064 int stalled_streams_
; // Count of streams that were ever stalled.
1066 // Count of all pings on the wire, for which we have not gotten a response.
1067 int64 pings_in_flight_
;
1069 // This is the next ping_id (unique_id) to be sent in PING frame.
1070 uint32 next_ping_id_
;
1072 // This is the last time we have sent a PING.
1073 base::TimeTicks last_ping_sent_time_
;
1075 // This is the last time we had activity in the session.
1076 base::TimeTicks last_activity_time_
;
1078 // This is the length of the last compressed frame.
1079 size_t last_compressed_frame_len_
;
1081 // This is the next time that unclaimed push streams should be checked for
1083 base::TimeTicks next_unclaimed_push_stream_sweep_time_
;
1085 // Indicate if we have already scheduled a delayed task to check the ping
1087 bool check_ping_status_pending_
;
1089 // Whether to send the (HTTP/2) connection header prefix.
1090 bool send_connection_header_prefix_
;
1092 // The (version-dependent) flow control state.
1093 FlowControlState flow_control_state_
;
1095 // Initial send window size for this session's streams. Can be
1096 // changed by an arriving SETTINGS frame. Newly created streams use
1097 // this value for the initial send window size.
1098 int32 stream_initial_send_window_size_
;
1100 // Initial receive window size for this session's streams. There are
1101 // plans to add a command line switch that would cause a SETTINGS
1102 // frame with window size announcement to be sent on startup. Newly
1103 // created streams will use this value for the initial receive
1105 int32 stream_initial_recv_window_size_
;
1107 // Session flow control variables. All zero unless session flow
1108 // control is turned on.
1109 int32 session_send_window_size_
;
1110 int32 session_recv_window_size_
;
1111 int32 session_unacked_recv_window_bytes_
;
1113 // A queue of stream IDs that have been send-stalled at some point
1115 std::deque
<SpdyStreamId
> stream_send_unstall_queue_
[NUM_PRIORITIES
];
1117 BoundNetLog net_log_
;
1119 // Outside of tests, these should always be true.
1120 bool verify_domain_authentication_
;
1121 bool enable_sending_initial_data_
;
1122 bool enable_compression_
;
1123 bool enable_ping_based_connection_checking_
;
1125 // The SPDY protocol used. Always between kProtoSPDYMinimumVersion and
1126 // kProtoSPDYMaximumVersion.
1127 NextProto protocol_
;
1129 // |connection_at_risk_of_loss_time_| is an optimization to avoid sending
1130 // wasteful preface pings (when we just got some data).
1132 // If it is zero (the most conservative figure), then we always send the
1133 // preface ping (when none are in flight).
1135 // It is common for TCP/IP sessions to time out in about 3-5 minutes.
1136 // Certainly if it has been more than 3 minutes, we do want to send a preface
1139 // We don't think any connection will time out in under about 10 seconds. So
1140 // this might as well be set to something conservative like 10 seconds. Later,
1141 // we could adjust it to send fewer pings perhaps.
1142 base::TimeDelta connection_at_risk_of_loss_time_
;
1144 // The amount of time that we are willing to tolerate with no activity (of any
1145 // form), while there is a ping in flight, before we declare the connection to
1146 // be hung. TODO(rtenneti): When hung, instead of resetting connection, race
1147 // to build a new connection, and see if that completes before we (finally)
1148 // get a PING response (http://crbug.com/127812).
1149 base::TimeDelta hung_interval_
;
1151 // This SPDY proxy is allowed to push resources from origins that are
1152 // different from those of their associated streams.
1153 HostPortPair trusted_spdy_proxy_
;
1155 TimeFunc time_func_
;
1157 // Used for posting asynchronous IO tasks. We use this even though
1158 // SpdySession is refcounted because we don't need to keep the SpdySession
1159 // alive if the last reference is within a RunnableMethod. Just revoke the
1161 base::WeakPtrFactory
<SpdySession
> weak_factory_
;
1166 #endif // NET_SPDY_SPDY_SESSION_H_