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 // If more than this many bytes have been read or more than that many
58 // milliseconds have passed, return ERR_IO_PENDING from ReadLoop.
59 const int kYieldAfterBytesRead
= 32 * 1024;
60 const int kYieldAfterDurationMilliseconds
= 50;
62 // First and last valid stream IDs. As we always act as the client,
63 // start at 1 for the first stream id.
64 const SpdyStreamId kFirstStreamId
= 1;
65 const SpdyStreamId kLastStreamId
= 0x7fffffff;
68 struct LoadTimingInfo
;
71 class TransportSecurityState
;
73 // NOTE: There's an enum of the same name (also with numeric suffixes)
74 // in histograms.xml. Be sure to add new values there also.
75 enum SpdyProtocolErrorDetails
{
76 // SpdyFramer::SpdyError mappings.
77 SPDY_ERROR_NO_ERROR
= 0,
78 SPDY_ERROR_INVALID_CONTROL_FRAME
= 1,
79 SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE
= 2,
80 SPDY_ERROR_ZLIB_INIT_FAILURE
= 3,
81 SPDY_ERROR_UNSUPPORTED_VERSION
= 4,
82 SPDY_ERROR_DECOMPRESS_FAILURE
= 5,
83 SPDY_ERROR_COMPRESS_FAILURE
= 6,
84 // SPDY_ERROR_CREDENTIAL_FRAME_CORRUPT = 7, (removed).
85 SPDY_ERROR_GOAWAY_FRAME_CORRUPT
= 29,
86 SPDY_ERROR_RST_STREAM_FRAME_CORRUPT
= 30,
87 SPDY_ERROR_INVALID_DATA_FRAME_FLAGS
= 8,
88 SPDY_ERROR_INVALID_CONTROL_FRAME_FLAGS
= 9,
89 SPDY_ERROR_UNEXPECTED_FRAME
= 31,
90 // SpdyRstStreamStatus mappings.
91 // RST_STREAM_INVALID not mapped.
92 STATUS_CODE_PROTOCOL_ERROR
= 11,
93 STATUS_CODE_INVALID_STREAM
= 12,
94 STATUS_CODE_REFUSED_STREAM
= 13,
95 STATUS_CODE_UNSUPPORTED_VERSION
= 14,
96 STATUS_CODE_CANCEL
= 15,
97 STATUS_CODE_INTERNAL_ERROR
= 16,
98 STATUS_CODE_FLOW_CONTROL_ERROR
= 17,
99 STATUS_CODE_STREAM_IN_USE
= 18,
100 STATUS_CODE_STREAM_ALREADY_CLOSED
= 19,
101 STATUS_CODE_INVALID_CREDENTIALS
= 20,
102 STATUS_CODE_FRAME_SIZE_ERROR
= 21,
103 STATUS_CODE_SETTINGS_TIMEOUT
= 32,
104 STATUS_CODE_CONNECT_ERROR
= 33,
105 STATUS_CODE_ENHANCE_YOUR_CALM
= 34,
106 STATUS_CODE_INADEQUATE_SECURITY
= 35,
107 STATUS_CODE_HTTP_1_1_REQUIRED
= 36,
109 // SpdySession errors
110 PROTOCOL_ERROR_UNEXPECTED_PING
= 22,
111 PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM
= 23,
112 PROTOCOL_ERROR_SPDY_COMPRESSION_FAILURE
= 24,
113 PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION
= 25,
114 PROTOCOL_ERROR_SYN_REPLY_NOT_RECEIVED
= 26,
115 PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
= 27,
116 PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION
= 28,
119 NUM_SPDY_PROTOCOL_ERROR_DETAILS
= 37,
121 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
122 MapFramerErrorToProtocolError(SpdyFramer::SpdyError error
);
123 Error NET_EXPORT_PRIVATE
MapFramerErrorToNetError(SpdyFramer::SpdyError error
);
124 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
125 MapRstStreamStatusToProtocolError(SpdyRstStreamStatus status
);
126 SpdyGoAwayStatus NET_EXPORT_PRIVATE
MapNetErrorToGoAwayStatus(Error err
);
128 // If these compile asserts fail then SpdyProtocolErrorDetails needs
129 // to be updated with new values, as do the mapping functions above.
130 static_assert(12 == SpdyFramer::LAST_ERROR
,
131 "SpdyProtocolErrorDetails / Spdy Errors mismatch");
132 static_assert(17 == RST_STREAM_NUM_STATUS_CODES
,
133 "SpdyProtocolErrorDetails / RstStreamStatus mismatch");
135 // Splits pushed |headers| into request and response parts. Request headers are
136 // the headers specifying resource URL.
137 void NET_EXPORT_PRIVATE
138 SplitPushedHeadersToRequestAndResponse(const SpdyHeaderBlock
& headers
,
139 SpdyMajorVersion protocol_version
,
140 SpdyHeaderBlock
* request_headers
,
141 SpdyHeaderBlock
* response_headers
);
143 // A helper class used to manage a request to create a stream.
144 class NET_EXPORT_PRIVATE SpdyStreamRequest
{
147 // Calls CancelRequest().
148 ~SpdyStreamRequest();
150 // Starts the request to create a stream. If OK is returned, then
151 // ReleaseStream() may be called. If ERR_IO_PENDING is returned,
152 // then when the stream is created, |callback| will be called, at
153 // which point ReleaseStream() may be called. Otherwise, the stream
154 // is not created, an error is returned, and ReleaseStream() may not
157 // If OK is returned, must not be called again without
158 // ReleaseStream() being called first. If ERR_IO_PENDING is
159 // returned, must not be called again without CancelRequest() or
160 // ReleaseStream() being called first. Otherwise, in case of an
161 // immediate error, this may be called again.
162 int StartRequest(SpdyStreamType type
,
163 const base::WeakPtr
<SpdySession
>& session
,
165 RequestPriority priority
,
166 const BoundNetLog
& net_log
,
167 const CompletionCallback
& callback
);
169 // Cancels any pending stream creation request. May be called
171 void CancelRequest();
173 // Transfers the created stream (guaranteed to not be NULL) to the
174 // caller. Must be called at most once after StartRequest() returns
175 // OK or |callback| is called with OK. The caller must immediately
176 // set a delegate for the returned stream (except for test code).
177 base::WeakPtr
<SpdyStream
> ReleaseStream();
180 friend class SpdySession
;
182 // Called by |session_| when the stream attempt has finished
184 void OnRequestCompleteSuccess(const base::WeakPtr
<SpdyStream
>& stream
);
186 // Called by |session_| when the stream attempt has finished with an
187 // error. Also called with ERR_ABORTED if |session_| is destroyed
188 // while the stream attempt is still pending.
189 void OnRequestCompleteFailure(int rv
);
191 // Accessors called by |session_|.
192 SpdyStreamType
type() const { return type_
; }
193 const GURL
& url() const { return url_
; }
194 RequestPriority
priority() const { return priority_
; }
195 const BoundNetLog
& net_log() const { return net_log_
; }
199 SpdyStreamType type_
;
200 base::WeakPtr
<SpdySession
> session_
;
201 base::WeakPtr
<SpdyStream
> stream_
;
203 RequestPriority priority_
;
204 BoundNetLog net_log_
;
205 CompletionCallback callback_
;
207 base::WeakPtrFactory
<SpdyStreamRequest
> weak_ptr_factory_
;
209 DISALLOW_COPY_AND_ASSIGN(SpdyStreamRequest
);
212 class NET_EXPORT SpdySession
: public BufferedSpdyFramerVisitorInterface
,
213 public SpdyFramerDebugVisitorInterface
,
214 public HigherLayeredPool
{
216 // TODO(akalin): Use base::TickClock when it becomes available.
217 typedef base::TimeTicks (*TimeFunc
)(void);
219 // How we handle flow control (version-dependent).
220 enum FlowControlState
{
223 FLOW_CONTROL_STREAM_AND_SESSION
226 // Returns true if |hostname| can be pooled into an existing connection
227 // associated with |ssl_info|.
228 static bool CanPool(TransportSecurityState
* transport_security_state
,
229 const SSLInfo
& ssl_info
,
230 const std::string
& old_hostname
,
231 const std::string
& new_hostname
);
233 // Create a new SpdySession.
234 // |spdy_session_key| is the host/port that this session connects to, privacy
235 // and proxy configuration settings that it's using.
236 // |session| is the HttpNetworkSession. |net_log| is the NetLog that we log
237 // network events to.
238 SpdySession(const SpdySessionKey
& spdy_session_key
,
239 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
240 TransportSecurityState
* transport_security_state
,
241 bool verify_domain_authentication
,
242 bool enable_sending_initial_data
,
243 bool enable_compression
,
244 bool enable_ping_based_connection_checking
,
245 NextProto default_protocol
,
246 size_t session_max_recv_window_size
,
247 size_t stream_max_recv_window_size
,
248 size_t initial_max_concurrent_streams
,
250 const HostPortPair
& trusted_spdy_proxy
,
253 ~SpdySession() override
;
255 const HostPortPair
& host_port_pair() const {
256 return spdy_session_key_
.host_port_proxy_pair().first
;
258 const HostPortProxyPair
& host_port_proxy_pair() const {
259 return spdy_session_key_
.host_port_proxy_pair();
261 const SpdySessionKey
& spdy_session_key() const {
262 return spdy_session_key_
;
264 // Get a pushed stream for a given |url|. If the server initiates a
265 // stream, it might already exist for a given path. The server
266 // might also not have initiated the stream yet, but indicated it
267 // will via X-Associated-Content. Returns OK if a stream was found
268 // and put into |spdy_stream|, or if one was not found but it is
269 // okay to create a new stream (in which case |spdy_stream| is
270 // reset). Returns an error (not ERR_IO_PENDING) otherwise, and
271 // resets |spdy_stream|.
274 base::WeakPtr
<SpdyStream
>* spdy_stream
,
275 const BoundNetLog
& stream_net_log
);
277 // Initialize the session with the given connection. |is_secure|
278 // must indicate whether |connection| uses an SSL socket or not; it
279 // is usually true, but it can be false for testing or when SPDY is
280 // configured to work with non-secure sockets.
282 // |pool| is the SpdySessionPool that owns us. Its lifetime must
283 // strictly be greater than |this|.
285 // |certificate_error_code| must either be OK or less than
288 // The session begins reading from |connection| on a subsequent event loop
289 // iteration, so the SpdySession may close immediately afterwards if the first
290 // read of |connection| fails.
291 void InitializeWithSocket(scoped_ptr
<ClientSocketHandle
> connection
,
292 SpdySessionPool
* pool
,
294 int certificate_error_code
);
296 // Returns the protocol used by this session. Always between
297 // kProtoSPDYMinimumVersion and kProtoSPDYMaximumVersion.
298 NextProto
protocol() const { return protocol_
; }
300 // Check to see if this SPDY session can support an additional domain.
301 // If the session is un-authenticated, then this call always returns true.
302 // For SSL-based sessions, verifies that the server certificate in use by
303 // this session provides authentication for the domain and no client
304 // certificate or channel ID was sent to the original server during the SSL
305 // handshake. NOTE: This function can have false negatives on some
307 // TODO(wtc): rename this function and the Net.SpdyIPPoolDomainMatch
308 // histogram because this function does more than verifying domain
309 // authentication now.
310 bool VerifyDomainAuthentication(const std::string
& domain
);
312 // Pushes the given producer into the write queue for
313 // |stream|. |stream| is guaranteed to be activated before the
314 // producer is used to produce its frame.
315 void EnqueueStreamWrite(const base::WeakPtr
<SpdyStream
>& stream
,
316 SpdyFrameType frame_type
,
317 scoped_ptr
<SpdyBufferProducer
> producer
);
319 // Creates and returns a SYN frame for |stream_id|.
320 scoped_ptr
<SpdyFrame
> CreateSynStream(
321 SpdyStreamId stream_id
,
322 RequestPriority priority
,
323 SpdyControlFlags flags
,
324 const SpdyHeaderBlock
& headers
);
326 // Creates and returns a SpdyBuffer holding a data frame with the
327 // given data. May return NULL if stalled by flow control.
328 scoped_ptr
<SpdyBuffer
> CreateDataBuffer(SpdyStreamId stream_id
,
331 SpdyDataFlags flags
);
333 // Close the stream with the given ID, which must exist and be
334 // active. Note that that stream may hold the last reference to the
336 void CloseActiveStream(SpdyStreamId stream_id
, int status
);
338 // Close the given created stream, which must exist but not yet be
339 // active. Note that |stream| may hold the last reference to the
341 void CloseCreatedStream(const base::WeakPtr
<SpdyStream
>& stream
, int status
);
343 // Send a RST_STREAM frame with the given status code and close the
344 // stream with the given ID, which must exist and be active. Note
345 // that that stream may hold the last reference to the session.
346 void ResetStream(SpdyStreamId stream_id
,
347 SpdyRstStreamStatus status
,
348 const std::string
& description
);
350 // Check if a stream is active.
351 bool IsStreamActive(SpdyStreamId stream_id
) const;
353 // The LoadState is used for informing the user of the current network
354 // status, such as "resolving host", "connecting", etc.
355 LoadState
GetLoadState() const;
357 // Fills SSL info in |ssl_info| and returns true when SSL is in use.
358 bool GetSSLInfo(SSLInfo
* ssl_info
,
359 bool* was_npn_negotiated
,
360 NextProto
* protocol_negotiated
);
362 // Send a WINDOW_UPDATE frame for a stream. Called by a stream
363 // whenever receive window size is increased.
364 void SendStreamWindowUpdate(SpdyStreamId stream_id
,
365 uint32 delta_window_size
);
367 // Accessors for the session's availability state.
368 bool IsAvailable() const { return availability_state_
== STATE_AVAILABLE
; }
369 bool IsGoingAway() const { return availability_state_
== STATE_GOING_AWAY
; }
370 bool IsDraining() const { return availability_state_
== STATE_DRAINING
; }
372 // Closes this session. This will close all active streams and mark
373 // the session as permanently closed. Callers must assume that the
374 // session is destroyed after this is called. (However, it may not
375 // be destroyed right away, e.g. when a SpdySession function is
376 // present in the call stack.)
378 // |err| should be < ERR_IO_PENDING; this function is intended to be
380 // |description| indicates the reason for the error.
381 void CloseSessionOnError(Error err
, const std::string
& description
);
383 // Mark this session as unavailable, meaning that it will not be used to
384 // service new streams. Unlike when a GOAWAY frame is received, this function
385 // will not close any streams.
386 void MakeUnavailable();
388 // Closes all active streams with stream id's greater than
389 // |last_good_stream_id|, as well as any created or pending
390 // streams. Must be called only when |availability_state_| >=
391 // STATE_GOING_AWAY. After this function, DcheckGoingAway() will
392 // pass. May be called multiple times.
393 void StartGoingAway(SpdyStreamId last_good_stream_id
, Error status
);
395 // Must be called only when going away (i.e., DcheckGoingAway()
396 // passes). If there are no more active streams and the session
397 // isn't closed yet, close it.
398 void MaybeFinishGoingAway();
400 // Retrieves information on the current state of the SPDY session as a
402 scoped_ptr
<base::Value
> GetInfoAsValue() const;
404 // Indicates whether the session is being reused after having successfully
405 // used to send/receive data in the past or if the underlying socket was idle
406 // before being used for a SPDY session.
407 bool IsReused() const;
409 // Returns true if the underlying transport socket ever had any reads or
411 bool WasEverUsed() const {
412 return connection_
->socket()->WasEverUsed();
415 // Returns the load timing information from the perspective of the given
416 // stream. If it's not the first stream, the connection is considered reused
419 // This uses a different notion of reuse than IsReused(). This function
420 // sets |socket_reused| to false only if |stream_id| is the ID of the first
421 // stream using the session. IsReused(), on the other hand, indicates if the
422 // session has been used to send/receive data at all.
423 bool GetLoadTimingInfo(SpdyStreamId stream_id
,
424 LoadTimingInfo
* load_timing_info
) const;
426 // Returns true if session is not currently active
427 bool is_active() const {
428 return !active_streams_
.empty() || !created_streams_
.empty();
431 // Access to the number of active and pending streams. These are primarily
432 // available for testing and diagnostics.
433 size_t num_active_streams() const { return active_streams_
.size(); }
434 size_t num_unclaimed_pushed_streams() const {
435 return unclaimed_pushed_streams_
.size();
437 size_t num_created_streams() const { return created_streams_
.size(); }
439 size_t num_pushed_streams() const { return num_pushed_streams_
; }
440 size_t num_active_pushed_streams() const {
441 return num_active_pushed_streams_
;
444 size_t pending_create_stream_queue_size(RequestPriority priority
) const {
445 DCHECK_GE(priority
, MINIMUM_PRIORITY
);
446 DCHECK_LE(priority
, MAXIMUM_PRIORITY
);
447 return pending_create_stream_queues_
[priority
].size();
450 // Returns the (version-dependent) flow control state.
451 FlowControlState
flow_control_state() const {
452 return flow_control_state_
;
455 // Returns the current |stream_initial_send_window_size_|.
456 int32
stream_initial_send_window_size() const {
457 return stream_initial_send_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 // Default value of SETTINGS_INITIAL_WINDOW_SIZE per protocol specification.
504 // A session is always created with this initial window size.
505 static int32
GetDefaultInitialWindowSize(NextProto protocol
) {
506 return protocol
< kProtoHTTP2
? 65536 : 65535;
509 // https://http2.github.io/http2-spec/#TLSUsage mandates minimum security
510 // standards for TLS.
511 bool HasAcceptableTransportSecurity() const;
513 // Must be used only by |pool_|.
514 base::WeakPtr
<SpdySession
> GetWeakPtr();
516 // HigherLayeredPool implementation:
517 bool CloseOneIdleConnection() override
;
520 friend class base::RefCounted
<SpdySession
>;
521 friend class SpdyStreamRequest
;
522 friend class SpdySessionTest
;
524 // Allow tests to access our innards for testing purposes.
525 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClientPing
);
526 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, FailedPing
);
527 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, GetActivePushStream
);
528 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, DeleteExpiredPushStreams
);
529 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ProtocolNegotiation
);
530 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClearSettings
);
531 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustRecvWindowSize
);
532 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustSendWindowSize
);
533 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlInactiveStream
);
534 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlPadding
);
535 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
,
536 SessionFlowControlTooMuchDataTwoDataFrames
);
537 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
,
538 StreamFlowControlTooMuchDataTwoDataFrames
);
539 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoReceiveLeaks
);
540 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoSendLeaks
);
541 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlEndToEnd
);
542 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, StreamIdSpaceExhausted
);
543 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, UnstallRacesWithStreamCreation
);
544 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, GoAwayOnSessionFlowControlError
);
545 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
,
546 RejectPushedStreamExceedingConcurrencyLimit
);
547 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, IgnoreReservedRemoteStreamsCount
);
548 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
,
549 CancelReservedStreamOnHeadersReceived
);
550 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, RejectInvalidUnknownFrames
);
552 typedef std::deque
<base::WeakPtr
<SpdyStreamRequest
> >
553 PendingStreamRequestQueue
;
555 struct ActiveStreamInfo
{
557 explicit ActiveStreamInfo(SpdyStream
* stream
);
561 bool waiting_for_syn_reply
;
563 typedef std::map
<SpdyStreamId
, ActiveStreamInfo
> ActiveStreamMap
;
565 struct PushedStreamInfo
{
567 PushedStreamInfo(SpdyStreamId stream_id
, base::TimeTicks creation_time
);
570 SpdyStreamId stream_id
;
571 base::TimeTicks creation_time
;
573 typedef std::map
<GURL
, PushedStreamInfo
> PushedStreamMap
;
575 typedef std::set
<SpdyStream
*> CreatedStreamSet
;
577 enum AvailabilityState
{
578 // The session is available in its socket pool and can be used
581 // The session can process data on existing streams but will
582 // refuse to create new ones.
584 // The session is draining its write queue in preparation of closing.
585 // Further writes will not be queued, and further reads will not be issued
586 // (though the remainder of a current read may be processed). The session
587 // will be destroyed by its write loop once the write queue is drained.
593 READ_STATE_DO_READ_COMPLETE
,
597 // There is no in-flight write and the write queue is empty.
599 WRITE_STATE_DO_WRITE
,
600 WRITE_STATE_DO_WRITE_COMPLETE
,
603 // Checks whether a stream for the given |url| can be created or
604 // retrieved from the set of unclaimed push streams. Returns OK if
605 // so. Otherwise, the session is closed and an error <
606 // ERR_IO_PENDING is returned.
607 Error
TryAccessStream(const GURL
& url
);
609 // Called by SpdyStreamRequest to start a request to create a
610 // stream. If OK is returned, then |stream| will be filled in with a
611 // valid stream. If ERR_IO_PENDING is returned, then
612 // |request->OnRequestComplete{Success,Failure}()| will be called
613 // when the stream is created (unless it is cancelled). Otherwise,
614 // no stream is created and the error is returned.
615 int TryCreateStream(const base::WeakPtr
<SpdyStreamRequest
>& request
,
616 base::WeakPtr
<SpdyStream
>* stream
);
618 // Actually create a stream into |stream|. Returns OK if successful;
619 // otherwise, returns an error and |stream| is not filled.
620 int CreateStream(const SpdyStreamRequest
& request
,
621 base::WeakPtr
<SpdyStream
>* stream
);
623 // Called by SpdyStreamRequest to remove |request| from the stream
625 void CancelStreamRequest(const base::WeakPtr
<SpdyStreamRequest
>& request
);
627 // Returns the next pending stream request to process, or NULL if
629 base::WeakPtr
<SpdyStreamRequest
> GetNextPendingStreamRequest();
631 // Called when there is room to create more streams (e.g., a stream
632 // was closed). Processes as many pending stream requests as
634 void ProcessPendingStreamRequests();
636 bool TryCreatePushStream(SpdyStreamId stream_id
,
637 SpdyStreamId associated_stream_id
,
638 SpdyPriority priority
,
639 const SpdyHeaderBlock
& headers
);
641 // Close the stream pointed to by the given iterator. Note that that
642 // stream may hold the last reference to the session.
643 void CloseActiveStreamIterator(ActiveStreamMap::iterator it
, int status
);
645 // Close the stream pointed to by the given iterator. Note that that
646 // stream may hold the last reference to the session.
647 void CloseCreatedStreamIterator(CreatedStreamSet::iterator it
, int status
);
649 // Calls EnqueueResetStreamFrame() and then
650 // CloseActiveStreamIterator().
651 void ResetStreamIterator(ActiveStreamMap::iterator it
,
652 SpdyRstStreamStatus status
,
653 const std::string
& description
);
655 // Send a RST_STREAM frame with the given parameters. There should
656 // either be no active stream with the given ID, or that active
657 // stream should be closed shortly after this function is called.
659 // TODO(akalin): Rename this to EnqueueResetStreamFrame().
660 void EnqueueResetStreamFrame(SpdyStreamId stream_id
,
661 RequestPriority priority
,
662 SpdyRstStreamStatus status
,
663 const std::string
& description
);
665 // Calls DoReadLoop. Use this function instead of DoReadLoop when
666 // posting a task to pump the read loop.
667 void PumpReadLoop(ReadState expected_read_state
, int result
);
669 // Advance the ReadState state machine. |expected_read_state| is the
670 // expected starting read state.
672 // This function must always be called via PumpReadLoop().
673 int DoReadLoop(ReadState expected_read_state
, int result
);
674 // The implementations of the states of the ReadState state machine.
676 int DoReadComplete(int result
);
678 // Calls DoWriteLoop. If |availability_state_| is STATE_DRAINING and no
679 // writes remain, the session is removed from the session pool and
682 // Use this function instead of DoWriteLoop when posting a task to
683 // pump the write loop.
684 void PumpWriteLoop(WriteState expected_write_state
, int result
);
686 // Iff the write loop is not currently active, posts a callback into
688 void MaybePostWriteLoop();
690 // Advance the WriteState state machine. |expected_write_state| is
691 // the expected starting write state.
693 // This function must always be called via PumpWriteLoop().
694 int DoWriteLoop(WriteState expected_write_state
, int result
);
695 // The implementations of the states of the WriteState state machine.
697 int DoWriteComplete(int result
);
699 // TODO(akalin): Rename the Send* and Write* functions below to
702 // Send initial data. Called when a connection is successfully
703 // established in InitializeWithSocket() and
704 // |enable_sending_initial_data_| is true.
705 void SendInitialData();
707 // Helper method to send a SETTINGS frame.
708 void SendSettings(const SettingsMap
& settings
);
710 // Handle SETTING. Either when we send settings, or when we receive a
711 // SETTINGS control frame, update our SpdySession accordingly.
712 void HandleSetting(uint32 id
, uint32 value
);
714 // Adjust the send window size of all ActiveStreams and PendingStreamRequests.
715 void UpdateStreamsSendWindowSize(int32 delta_window_size
);
717 // Send the PING (preface-PING) frame.
718 void SendPrefacePingIfNoneInFlight();
720 // Send PING if there are no PINGs in flight and we haven't heard from server.
721 void SendPrefacePing();
723 // Send a single WINDOW_UPDATE frame.
724 void SendWindowUpdateFrame(SpdyStreamId stream_id
, uint32 delta_window_size
,
725 RequestPriority priority
);
727 // Send the PING frame.
728 void WritePingFrame(SpdyPingId unique_id
, bool is_ack
);
730 // Post a CheckPingStatus call after delay. Don't post if there is already
731 // CheckPingStatus running.
732 void PlanToCheckPingStatus();
734 // Check the status of the connection. It calls |CloseSessionOnError| if we
735 // haven't received any data in |kHungInterval| time period.
736 void CheckPingStatus(base::TimeTicks last_check_time
);
738 // Get a new stream id.
739 SpdyStreamId
GetNewStreamId();
741 // Pushes the given frame with the given priority into the write
742 // queue for the session.
743 void EnqueueSessionWrite(RequestPriority priority
,
744 SpdyFrameType frame_type
,
745 scoped_ptr
<SpdyFrame
> frame
);
747 // Puts |producer| associated with |stream| onto the write queue
748 // with the given priority.
749 void EnqueueWrite(RequestPriority priority
,
750 SpdyFrameType frame_type
,
751 scoped_ptr
<SpdyBufferProducer
> producer
,
752 const base::WeakPtr
<SpdyStream
>& stream
);
754 // Inserts a newly-created stream into |created_streams_|.
755 void InsertCreatedStream(scoped_ptr
<SpdyStream
> stream
);
757 // Activates |stream| (which must be in |created_streams_|) by
758 // assigning it an ID and returns it.
759 scoped_ptr
<SpdyStream
> ActivateCreatedStream(SpdyStream
* stream
);
761 // Inserts a newly-activated stream into |active_streams_|.
762 void InsertActivatedStream(scoped_ptr
<SpdyStream
> stream
);
764 // Remove all internal references to |stream|, call OnClose() on it,
765 // and process any pending stream requests before deleting it. Note
766 // that |stream| may hold the last reference to the session.
767 void DeleteStream(scoped_ptr
<SpdyStream
> stream
, int status
);
769 // Check if we have a pending pushed-stream for this url
770 // Returns the stream if found (and returns it from the pending
771 // list). Returns NULL otherwise.
772 base::WeakPtr
<SpdyStream
> GetActivePushStream(const GURL
& url
);
774 // Delegates to |stream->OnInitialResponseHeadersReceived()|. If an
775 // error is returned, the last reference to |this| may have been
777 int OnInitialResponseHeadersReceived(const SpdyHeaderBlock
& response_headers
,
778 base::Time response_time
,
779 base::TimeTicks recv_first_byte_time
,
782 void RecordPingRTTHistogram(base::TimeDelta duration
);
783 void RecordHistograms();
784 void RecordProtocolErrorHistogram(SpdyProtocolErrorDetails details
);
786 // DCHECKs that |availability_state_| >= STATE_GOING_AWAY, that
787 // there are no pending stream creation requests, and that there are
788 // no created streams.
789 void DcheckGoingAway() const;
791 // Calls DcheckGoingAway(), then DCHECKs that |availability_state_|
792 // == STATE_DRAINING, |error_on_close_| has a valid value, and that there
793 // are no active streams or unclaimed pushed streams.
794 void DcheckDraining() const;
796 // If the session is already draining, does nothing. Otherwise, moves
797 // the session to the draining state.
798 void DoDrainSession(Error err
, const std::string
& description
);
800 // Called right before closing a (possibly-inactive) stream for a
801 // reason other than being requested to by the stream.
802 void LogAbandonedStream(SpdyStream
* stream
, Error status
);
804 // Called right before closing an active stream for a reason other
805 // than being requested to by the stream.
806 void LogAbandonedActiveStream(ActiveStreamMap::const_iterator it
,
809 // Invokes a user callback for stream creation. We provide this method so it
810 // can be deferred to the MessageLoop, so we avoid re-entrancy problems.
811 void CompleteStreamRequest(
812 const base::WeakPtr
<SpdyStreamRequest
>& pending_request
);
814 // Remove old unclaimed pushed streams.
815 void DeleteExpiredPushedStreams();
817 // BufferedSpdyFramerVisitorInterface:
818 void OnError(SpdyFramer::SpdyError error_code
) override
;
819 void OnStreamError(SpdyStreamId stream_id
,
820 const std::string
& description
) override
;
821 void OnPing(SpdyPingId unique_id
, bool is_ack
) override
;
822 void OnRstStream(SpdyStreamId stream_id
, SpdyRstStreamStatus status
) override
;
823 void OnGoAway(SpdyStreamId last_accepted_stream_id
,
824 SpdyGoAwayStatus status
) override
;
825 void OnDataFrameHeader(SpdyStreamId stream_id
,
828 void OnStreamFrameData(SpdyStreamId stream_id
,
832 void OnStreamPadding(SpdyStreamId stream_id
, size_t len
) override
;
833 void OnSettings(bool clear_persisted
) override
;
834 void OnSetting(SpdySettingsIds id
, uint8 flags
, uint32 value
) override
;
835 void OnWindowUpdate(SpdyStreamId stream_id
, int delta_window_size
) override
;
836 void OnPushPromise(SpdyStreamId stream_id
,
837 SpdyStreamId promised_stream_id
,
838 const SpdyHeaderBlock
& headers
) override
;
839 void OnSynStream(SpdyStreamId stream_id
,
840 SpdyStreamId associated_stream_id
,
841 SpdyPriority priority
,
844 const SpdyHeaderBlock
& headers
) override
;
845 void OnSynReply(SpdyStreamId stream_id
,
847 const SpdyHeaderBlock
& headers
) override
;
848 void OnHeaders(SpdyStreamId stream_id
,
850 SpdyPriority priority
,
851 SpdyStreamId parent_stream_id
,
854 const SpdyHeaderBlock
& headers
) override
;
855 bool OnUnknownFrame(SpdyStreamId stream_id
, int frame_type
) override
;
857 // SpdyFramerDebugVisitorInterface
858 void OnSendCompressedFrame(SpdyStreamId stream_id
,
861 size_t frame_len
) override
;
862 void OnReceiveCompressedFrame(SpdyStreamId stream_id
,
864 size_t frame_len
) override
;
866 // Called when bytes are consumed from a SpdyBuffer for a DATA frame
867 // that is to be written or is being written. Increases the send
868 // window size accordingly if some or all of the SpdyBuffer is being
871 // If session flow control is turned off, this must not be called.
872 void OnWriteBufferConsumed(size_t frame_payload_size
,
874 SpdyBuffer::ConsumeSource consume_source
);
876 // Called by OnWindowUpdate() (which is in turn called by the
877 // framer) to increase this session's send window size by
878 // |delta_window_size| from a WINDOW_UPDATE frome, which must be at
879 // least 1. If |delta_window_size| would cause this session's send
880 // window size to overflow, does nothing.
882 // If session flow control is turned off, this must not be called.
883 void IncreaseSendWindowSize(int delta_window_size
);
885 // If session flow control is turned on, called by CreateDataFrame()
886 // (which is in turn called by a stream) to decrease this session's
887 // send window size by |delta_window_size|, which must be at least 1
888 // and at most kMaxSpdyFrameChunkSize. |delta_window_size| must not
889 // cause this session's send window size to go negative.
891 // If session flow control is turned off, this must not be called.
892 void DecreaseSendWindowSize(int32 delta_window_size
);
894 // Called when bytes are consumed by the delegate from a SpdyBuffer
895 // containing received data. Increases the receive window size
898 // If session flow control is turned off, this must not be called.
899 void OnReadBufferConsumed(size_t consume_size
,
900 SpdyBuffer::ConsumeSource consume_source
);
902 // Called by OnReadBufferConsume to increase this session's receive
903 // window size by |delta_window_size|, which must be at least 1 and
904 // must not cause this session's receive window size to overflow,
905 // possibly also sending a WINDOW_UPDATE frame. Also called during
906 // initialization to set the initial receive window size.
908 // If session flow control is turned off, this must not be called.
909 void IncreaseRecvWindowSize(int32 delta_window_size
);
911 // Called by OnStreamFrameData (which is in turn called by the
912 // framer) to decrease this session's receive window size by
913 // |delta_window_size|, which must be at least 1 and must not cause
914 // this session's receive window size to go negative.
916 // If session flow control is turned off, this must not be called.
917 void DecreaseRecvWindowSize(int32 delta_window_size
);
919 // Queue a send-stalled stream for possibly resuming once we're not
920 // send-stalled anymore.
921 void QueueSendStalledStream(const SpdyStream
& stream
);
923 // Go through the queue of send-stalled streams and try to resume as
925 void ResumeSendStalledStreams();
927 // Returns the next stream to possibly resume, or 0 if the queue is
929 SpdyStreamId
PopStreamToPossiblyResume();
931 // --------------------------
932 // Helper methods for testing
933 // --------------------------
935 void set_connection_at_risk_of_loss_time(base::TimeDelta duration
) {
936 connection_at_risk_of_loss_time_
= duration
;
939 void set_hung_interval(base::TimeDelta duration
) {
940 hung_interval_
= duration
;
943 void set_max_concurrent_pushed_streams(size_t value
) {
944 max_concurrent_pushed_streams_
= value
;
947 int64
pings_in_flight() const { return pings_in_flight_
; }
949 SpdyPingId
next_ping_id() const { return next_ping_id_
; }
951 base::TimeTicks
last_activity_time() const { return last_activity_time_
; }
953 bool check_ping_status_pending() const { return check_ping_status_pending_
; }
955 size_t max_concurrent_streams() const { return max_concurrent_streams_
; }
957 // Returns the SSLClientSocket that this SPDY session sits on top of,
958 // or NULL, if the transport is not SSL.
959 SSLClientSocket
* GetSSLClientSocket() const;
961 // Whether Do{Read,Write}Loop() is in the call stack. Useful for
962 // making sure we don't destroy ourselves prematurely in that case.
965 // The key used to identify this session.
966 const SpdySessionKey spdy_session_key_
;
968 // Set set of SpdySessionKeys for which this session has serviced
970 std::set
<SpdySessionKey
> pooled_aliases_
;
972 // |pool_| owns us, therefore its lifetime must exceed ours. We set
973 // this to NULL after we are removed from the pool.
974 SpdySessionPool
* pool_
;
975 const base::WeakPtr
<HttpServerProperties
> http_server_properties_
;
977 TransportSecurityState
* transport_security_state_
;
979 // The socket handle for this session.
980 scoped_ptr
<ClientSocketHandle
> connection_
;
982 // The read buffer used to read data from the socket.
983 scoped_refptr
<IOBuffer
> read_buffer_
;
985 SpdyStreamId stream_hi_water_mark_
; // The next stream id to use.
987 // Used to ensure the server increments push stream ids correctly.
988 SpdyStreamId last_accepted_push_stream_id_
;
990 // Queue, for each priority, of pending stream requests that have
991 // not yet been satisfied.
992 PendingStreamRequestQueue pending_create_stream_queues_
[NUM_PRIORITIES
];
994 // Map from stream id to all active streams. Streams are active in the sense
995 // that they have a consumer (typically SpdyNetworkTransaction and regardless
996 // of whether or not there is currently any ongoing IO [might be waiting for
997 // the server to start pushing the stream]) or there are still network events
998 // incoming even though the consumer has already gone away (cancellation).
1000 // |active_streams_| owns all its SpdyStream objects.
1002 // TODO(willchan): Perhaps we should separate out cancelled streams and move
1003 // them into a separate ActiveStreamMap, and not deliver network events to
1005 ActiveStreamMap active_streams_
;
1007 // (Bijective) map from the URL to the ID of the streams that have
1008 // already started to be pushed by the server, but do not have
1009 // consumers yet. Contains a subset of |active_streams_|.
1010 PushedStreamMap unclaimed_pushed_streams_
;
1012 // Set of all created streams but that have not yet sent any frames.
1014 // |created_streams_| owns all its SpdyStream objects.
1015 CreatedStreamSet created_streams_
;
1017 // Number of pushed streams. All active streams are stored in
1018 // |active_streams_|, but it's better to know the number of push streams
1019 // without traversing the whole collection.
1020 size_t num_pushed_streams_
;
1022 // Number of active pushed streams in |active_streams_|, i.e. not in reserved
1023 // remote state. Streams in reserved state are not counted towards any
1024 // concurrency limits.
1025 size_t num_active_pushed_streams_
;
1028 SpdyWriteQueue write_queue_
;
1030 // Data for the frame we are currently sending.
1032 // The buffer we're currently writing.
1033 scoped_ptr
<SpdyBuffer
> in_flight_write_
;
1034 // The type of the frame in |in_flight_write_|.
1035 SpdyFrameType in_flight_write_frame_type_
;
1036 // The size of the frame in |in_flight_write_|.
1037 size_t in_flight_write_frame_size_
;
1038 // The stream to notify when |in_flight_write_| has been written to
1039 // the socket completely.
1040 base::WeakPtr
<SpdyStream
> in_flight_write_stream_
;
1042 // Flag if we're using an SSL connection for this SpdySession.
1045 // Certificate error code when using a secure connection.
1046 int certificate_error_code_
;
1048 // Spdy Frame state.
1049 scoped_ptr
<BufferedSpdyFramer
> buffered_spdy_framer_
;
1051 // The state variables.
1052 AvailabilityState availability_state_
;
1053 ReadState read_state_
;
1054 WriteState write_state_
;
1056 // If the session is closing (i.e., |availability_state_| is STATE_DRAINING),
1057 // then |error_on_close_| holds the error with which it was closed, which
1058 // may be OK (upon a polite GOAWAY) or an error < ERR_IO_PENDING otherwise.
1059 // Initialized to OK.
1060 Error error_on_close_
;
1063 size_t max_concurrent_streams_
; // 0 if no limit
1064 size_t max_concurrent_pushed_streams_
;
1066 // Some statistics counters for the session.
1067 int streams_initiated_count_
;
1068 int streams_pushed_count_
;
1069 int streams_pushed_and_claimed_count_
;
1070 int streams_abandoned_count_
;
1072 // |total_bytes_received_| keeps track of all the bytes read by the
1073 // SpdySession. It is used by the |Net.SpdySettingsCwnd...| histograms.
1074 int total_bytes_received_
;
1076 bool sent_settings_
; // Did this session send settings when it started.
1077 bool received_settings_
; // Did this session receive at least one settings
1079 int stalled_streams_
; // Count of streams that were ever stalled.
1081 // Count of all pings on the wire, for which we have not gotten a response.
1082 int64 pings_in_flight_
;
1084 // This is the next ping_id (unique_id) to be sent in PING frame.
1085 SpdyPingId next_ping_id_
;
1087 // This is the last time we have sent a PING.
1088 base::TimeTicks last_ping_sent_time_
;
1090 // This is the last time we had activity in the session.
1091 base::TimeTicks last_activity_time_
;
1093 // This is the length of the last compressed frame.
1094 size_t last_compressed_frame_len_
;
1096 // This is the next time that unclaimed push streams should be checked for
1098 base::TimeTicks next_unclaimed_push_stream_sweep_time_
;
1100 // Indicate if we have already scheduled a delayed task to check the ping
1102 bool check_ping_status_pending_
;
1104 // Whether to send the (HTTP/2) connection header prefix.
1105 bool send_connection_header_prefix_
;
1107 // The (version-dependent) flow control state.
1108 FlowControlState flow_control_state_
;
1110 // Current send window size. Zero unless session flow control is turned on.
1111 int32 session_send_window_size_
;
1113 // Maximum receive window size. Each time a WINDOW_UPDATE is sent, it
1114 // restores the receive window size to this value. Zero unless session flow
1115 // control is turned on.
1116 int32 session_max_recv_window_size_
;
1118 // Sum of |session_unacked_recv_window_bytes_| and current receive window
1119 // size. Zero unless session flow control is turned on.
1120 // TODO(bnc): Rename or change semantics so that |window_size_| is actual
1122 int32 session_recv_window_size_
;
1124 // When bytes are consumed, SpdyIOBuffer destructor calls back to SpdySession,
1125 // and this member keeps count of them until the corresponding WINDOW_UPDATEs
1126 // are sent. Zero unless session flow control is turned on.
1127 int32 session_unacked_recv_window_bytes_
;
1129 // Initial send window size for this session's streams. Can be
1130 // changed by an arriving SETTINGS frame. Newly created streams use
1131 // this value for the initial send window size.
1132 int32 stream_initial_send_window_size_
;
1134 // Initial receive window size for this session's streams. There are
1135 // plans to add a command line switch that would cause a SETTINGS
1136 // frame with window size announcement to be sent on startup. Newly
1137 // created streams will use this value for the initial receive
1139 int32 stream_max_recv_window_size_
;
1141 // A queue of stream IDs that have been send-stalled at some point
1143 std::deque
<SpdyStreamId
> stream_send_unstall_queue_
[NUM_PRIORITIES
];
1145 BoundNetLog net_log_
;
1147 // Outside of tests, these should always be true.
1148 bool verify_domain_authentication_
;
1149 bool enable_sending_initial_data_
;
1150 bool enable_compression_
;
1151 bool enable_ping_based_connection_checking_
;
1153 // The SPDY protocol used. Always between kProtoSPDYMinimumVersion and
1154 // kProtoSPDYMaximumVersion.
1155 NextProto protocol_
;
1157 // |connection_at_risk_of_loss_time_| is an optimization to avoid sending
1158 // wasteful preface pings (when we just got some data).
1160 // If it is zero (the most conservative figure), then we always send the
1161 // preface ping (when none are in flight).
1163 // It is common for TCP/IP sessions to time out in about 3-5 minutes.
1164 // Certainly if it has been more than 3 minutes, we do want to send a preface
1167 // We don't think any connection will time out in under about 10 seconds. So
1168 // this might as well be set to something conservative like 10 seconds. Later,
1169 // we could adjust it to send fewer pings perhaps.
1170 base::TimeDelta connection_at_risk_of_loss_time_
;
1172 // The amount of time that we are willing to tolerate with no activity (of any
1173 // form), while there is a ping in flight, before we declare the connection to
1174 // be hung. TODO(rtenneti): When hung, instead of resetting connection, race
1175 // to build a new connection, and see if that completes before we (finally)
1176 // get a PING response (http://crbug.com/127812).
1177 base::TimeDelta hung_interval_
;
1179 // This SPDY proxy is allowed to push resources from origins that are
1180 // different from those of their associated streams.
1181 HostPortPair trusted_spdy_proxy_
;
1183 TimeFunc time_func_
;
1185 // Used for posting asynchronous IO tasks. We use this even though
1186 // SpdySession is refcounted because we don't need to keep the SpdySession
1187 // alive if the last reference is within a RunnableMethod. Just revoke the
1189 base::WeakPtrFactory
<SpdySession
> weak_factory_
;
1194 #endif // NET_SPDY_SPDY_SESSION_H_