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
;
73 class TransportSecurityState
;
75 // NOTE: There's an enum of the same name (also with numeric suffixes)
76 // in histograms.xml. Be sure to add new values there also.
77 enum SpdyProtocolErrorDetails
{
78 // SpdyFramer::SpdyError mappings.
79 SPDY_ERROR_NO_ERROR
= 0,
80 SPDY_ERROR_INVALID_CONTROL_FRAME
= 1,
81 SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE
= 2,
82 SPDY_ERROR_ZLIB_INIT_FAILURE
= 3,
83 SPDY_ERROR_UNSUPPORTED_VERSION
= 4,
84 SPDY_ERROR_DECOMPRESS_FAILURE
= 5,
85 SPDY_ERROR_COMPRESS_FAILURE
= 6,
86 // SPDY_ERROR_CREDENTIAL_FRAME_CORRUPT = 7, (removed).
87 SPDY_ERROR_GOAWAY_FRAME_CORRUPT
= 29,
88 SPDY_ERROR_RST_STREAM_FRAME_CORRUPT
= 30,
89 SPDY_ERROR_INVALID_DATA_FRAME_FLAGS
= 8,
90 SPDY_ERROR_INVALID_CONTROL_FRAME_FLAGS
= 9,
91 SPDY_ERROR_UNEXPECTED_FRAME
= 31,
92 // SpdyRstStreamStatus mappings.
93 // RST_STREAM_INVALID not mapped.
94 STATUS_CODE_PROTOCOL_ERROR
= 11,
95 STATUS_CODE_INVALID_STREAM
= 12,
96 STATUS_CODE_REFUSED_STREAM
= 13,
97 STATUS_CODE_UNSUPPORTED_VERSION
= 14,
98 STATUS_CODE_CANCEL
= 15,
99 STATUS_CODE_INTERNAL_ERROR
= 16,
100 STATUS_CODE_FLOW_CONTROL_ERROR
= 17,
101 STATUS_CODE_STREAM_IN_USE
= 18,
102 STATUS_CODE_STREAM_ALREADY_CLOSED
= 19,
103 STATUS_CODE_INVALID_CREDENTIALS
= 20,
104 STATUS_CODE_FRAME_SIZE_ERROR
= 21,
105 STATUS_CODE_SETTINGS_TIMEOUT
= 32,
106 STATUS_CODE_CONNECT_ERROR
= 33,
107 STATUS_CODE_ENHANCE_YOUR_CALM
= 34,
108 STATUS_CODE_INADEQUATE_SECURITY
= 35,
109 STATUS_CODE_HTTP_1_1_REQUIRED
= 36,
111 // SpdySession errors
112 PROTOCOL_ERROR_UNEXPECTED_PING
= 22,
113 PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM
= 23,
114 PROTOCOL_ERROR_SPDY_COMPRESSION_FAILURE
= 24,
115 PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION
= 25,
116 PROTOCOL_ERROR_SYN_REPLY_NOT_RECEIVED
= 26,
117 PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE
= 27,
118 PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION
= 28,
121 NUM_SPDY_PROTOCOL_ERROR_DETAILS
= 37,
123 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
124 MapFramerErrorToProtocolError(SpdyFramer::SpdyError error
);
125 Error NET_EXPORT_PRIVATE
MapFramerErrorToNetError(SpdyFramer::SpdyError error
);
126 SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
127 MapRstStreamStatusToProtocolError(SpdyRstStreamStatus status
);
128 SpdyGoAwayStatus NET_EXPORT_PRIVATE
MapNetErrorToGoAwayStatus(Error err
);
130 // If these compile asserts fail then SpdyProtocolErrorDetails needs
131 // to be updated with new values, as do the mapping functions above.
132 static_assert(12 == SpdyFramer::LAST_ERROR
,
133 "SpdyProtocolErrorDetails / Spdy Errors mismatch");
134 static_assert(17 == RST_STREAM_NUM_STATUS_CODES
,
135 "SpdyProtocolErrorDetails / RstStreamStatus mismatch");
137 // Splits pushed |headers| into request and response parts. Request headers are
138 // the headers specifying resource URL.
139 void NET_EXPORT_PRIVATE
140 SplitPushedHeadersToRequestAndResponse(const SpdyHeaderBlock
& headers
,
141 SpdyMajorVersion protocol_version
,
142 SpdyHeaderBlock
* request_headers
,
143 SpdyHeaderBlock
* response_headers
);
145 // A helper class used to manage a request to create a stream.
146 class NET_EXPORT_PRIVATE SpdyStreamRequest
{
149 // Calls CancelRequest().
150 ~SpdyStreamRequest();
152 // Starts the request to create a stream. If OK is returned, then
153 // ReleaseStream() may be called. If ERR_IO_PENDING is returned,
154 // then when the stream is created, |callback| will be called, at
155 // which point ReleaseStream() may be called. Otherwise, the stream
156 // is not created, an error is returned, and ReleaseStream() may not
159 // If OK is returned, must not be called again without
160 // ReleaseStream() being called first. If ERR_IO_PENDING is
161 // returned, must not be called again without CancelRequest() or
162 // ReleaseStream() being called first. Otherwise, in case of an
163 // immediate error, this may be called again.
164 int StartRequest(SpdyStreamType type
,
165 const base::WeakPtr
<SpdySession
>& session
,
167 RequestPriority priority
,
168 const BoundNetLog
& net_log
,
169 const CompletionCallback
& callback
);
171 // Cancels any pending stream creation request. May be called
173 void CancelRequest();
175 // Transfers the created stream (guaranteed to not be NULL) to the
176 // caller. Must be called at most once after StartRequest() returns
177 // OK or |callback| is called with OK. The caller must immediately
178 // set a delegate for the returned stream (except for test code).
179 base::WeakPtr
<SpdyStream
> ReleaseStream();
182 friend class SpdySession
;
184 // Called by |session_| when the stream attempt has finished
186 void OnRequestCompleteSuccess(const base::WeakPtr
<SpdyStream
>& stream
);
188 // Called by |session_| when the stream attempt has finished with an
189 // error. Also called with ERR_ABORTED if |session_| is destroyed
190 // while the stream attempt is still pending.
191 void OnRequestCompleteFailure(int rv
);
193 // Accessors called by |session_|.
194 SpdyStreamType
type() const { return type_
; }
195 const GURL
& url() const { return url_
; }
196 RequestPriority
priority() const { return priority_
; }
197 const BoundNetLog
& net_log() const { return net_log_
; }
201 SpdyStreamType type_
;
202 base::WeakPtr
<SpdySession
> session_
;
203 base::WeakPtr
<SpdyStream
> stream_
;
205 RequestPriority priority_
;
206 BoundNetLog net_log_
;
207 CompletionCallback callback_
;
209 base::WeakPtrFactory
<SpdyStreamRequest
> weak_ptr_factory_
;
211 DISALLOW_COPY_AND_ASSIGN(SpdyStreamRequest
);
214 class NET_EXPORT SpdySession
: public BufferedSpdyFramerVisitorInterface
,
215 public SpdyFramerDebugVisitorInterface
,
216 public HigherLayeredPool
{
218 // TODO(akalin): Use base::TickClock when it becomes available.
219 typedef base::TimeTicks (*TimeFunc
)(void);
221 // How we handle flow control (version-dependent).
222 enum FlowControlState
{
225 FLOW_CONTROL_STREAM_AND_SESSION
228 // Returns true if |hostname| can be pooled into an existing connection
229 // associated with |ssl_info|.
230 static bool CanPool(TransportSecurityState
* transport_security_state
,
231 const SSLInfo
& ssl_info
,
232 const std::string
& old_hostname
,
233 const std::string
& new_hostname
);
235 // Create a new SpdySession.
236 // |spdy_session_key| is the host/port that this session connects to, privacy
237 // and proxy configuration settings that it's using.
238 // |session| is the HttpNetworkSession. |net_log| is the NetLog that we log
239 // network events to.
240 SpdySession(const SpdySessionKey
& spdy_session_key
,
241 const base::WeakPtr
<HttpServerProperties
>& http_server_properties
,
242 TransportSecurityState
* transport_security_state
,
243 bool verify_domain_authentication
,
244 bool enable_sending_initial_data
,
245 bool enable_compression
,
246 bool enable_ping_based_connection_checking
,
247 NextProto default_protocol
,
248 size_t stream_initial_recv_window_size
,
249 size_t initial_max_concurrent_streams
,
250 size_t max_concurrent_streams_limit
,
252 const HostPortPair
& trusted_spdy_proxy
,
255 ~SpdySession() override
;
257 const HostPortPair
& host_port_pair() const {
258 return spdy_session_key_
.host_port_proxy_pair().first
;
260 const HostPortProxyPair
& host_port_proxy_pair() const {
261 return spdy_session_key_
.host_port_proxy_pair();
263 const SpdySessionKey
& spdy_session_key() const {
264 return spdy_session_key_
;
266 // Get a pushed stream for a given |url|. If the server initiates a
267 // stream, it might already exist for a given path. The server
268 // might also not have initiated the stream yet, but indicated it
269 // will via X-Associated-Content. Returns OK if a stream was found
270 // and put into |spdy_stream|, or if one was not found but it is
271 // okay to create a new stream (in which case |spdy_stream| is
272 // reset). Returns an error (not ERR_IO_PENDING) otherwise, and
273 // resets |spdy_stream|.
276 base::WeakPtr
<SpdyStream
>* spdy_stream
,
277 const BoundNetLog
& stream_net_log
);
279 // Initialize the session with the given connection. |is_secure|
280 // must indicate whether |connection| uses an SSL socket or not; it
281 // is usually true, but it can be false for testing or when SPDY is
282 // configured to work with non-secure sockets.
284 // |pool| is the SpdySessionPool that owns us. Its lifetime must
285 // strictly be greater than |this|.
287 // |certificate_error_code| must either be OK or less than
290 // The session begins reading from |connection| on a subsequent event loop
291 // iteration, so the SpdySession may close immediately afterwards if the first
292 // read of |connection| fails.
293 void InitializeWithSocket(scoped_ptr
<ClientSocketHandle
> connection
,
294 SpdySessionPool
* pool
,
296 int certificate_error_code
);
298 // Returns the protocol used by this session. Always between
299 // kProtoSPDYMinimumVersion and kProtoSPDYMaximumVersion.
300 NextProto
protocol() const { return protocol_
; }
302 // Check to see if this SPDY session can support an additional domain.
303 // If the session is un-authenticated, then this call always returns true.
304 // For SSL-based sessions, verifies that the server certificate in use by
305 // this session provides authentication for the domain and no client
306 // certificate or channel ID was sent to the original server during the SSL
307 // handshake. NOTE: This function can have false negatives on some
309 // TODO(wtc): rename this function and the Net.SpdyIPPoolDomainMatch
310 // histogram because this function does more than verifying domain
311 // authentication now.
312 bool VerifyDomainAuthentication(const std::string
& domain
);
314 // Pushes the given producer into the write queue for
315 // |stream|. |stream| is guaranteed to be activated before the
316 // producer is used to produce its frame.
317 void EnqueueStreamWrite(const base::WeakPtr
<SpdyStream
>& stream
,
318 SpdyFrameType frame_type
,
319 scoped_ptr
<SpdyBufferProducer
> producer
);
321 // Creates and returns a SYN frame for |stream_id|.
322 scoped_ptr
<SpdyFrame
> CreateSynStream(
323 SpdyStreamId stream_id
,
324 RequestPriority priority
,
325 SpdyControlFlags flags
,
326 const SpdyHeaderBlock
& headers
);
328 // Creates and returns a SpdyBuffer holding a data frame with the
329 // given data. May return NULL if stalled by flow control.
330 scoped_ptr
<SpdyBuffer
> CreateDataBuffer(SpdyStreamId stream_id
,
333 SpdyDataFlags flags
);
335 // Close the stream with the given ID, which must exist and be
336 // active. Note that that stream may hold the last reference to the
338 void CloseActiveStream(SpdyStreamId stream_id
, int status
);
340 // Close the given created stream, which must exist but not yet be
341 // active. Note that |stream| may hold the last reference to the
343 void CloseCreatedStream(const base::WeakPtr
<SpdyStream
>& stream
, int status
);
345 // Send a RST_STREAM frame with the given status code and close the
346 // stream with the given ID, which must exist and be active. Note
347 // that that stream may hold the last reference to the session.
348 void ResetStream(SpdyStreamId stream_id
,
349 SpdyRstStreamStatus status
,
350 const std::string
& description
);
352 // Check if a stream is active.
353 bool IsStreamActive(SpdyStreamId stream_id
) const;
355 // The LoadState is used for informing the user of the current network
356 // status, such as "resolving host", "connecting", etc.
357 LoadState
GetLoadState() const;
359 // Fills SSL info in |ssl_info| and returns true when SSL is in use.
360 bool GetSSLInfo(SSLInfo
* ssl_info
,
361 bool* was_npn_negotiated
,
362 NextProto
* protocol_negotiated
);
364 // Fills SSL Certificate Request info |cert_request_info| and returns
365 // true when SSL is in use.
366 bool GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
);
368 // Send a WINDOW_UPDATE frame for a stream. Called by a stream
369 // whenever receive window size is increased.
370 void SendStreamWindowUpdate(SpdyStreamId stream_id
,
371 uint32 delta_window_size
);
373 // Accessors for the session's availability state.
374 bool IsAvailable() const { return availability_state_
== STATE_AVAILABLE
; }
375 bool IsGoingAway() const { return availability_state_
== STATE_GOING_AWAY
; }
376 bool IsDraining() const { return availability_state_
== STATE_DRAINING
; }
378 // Closes this session. This will close all active streams and mark
379 // the session as permanently closed. Callers must assume that the
380 // session is destroyed after this is called. (However, it may not
381 // be destroyed right away, e.g. when a SpdySession function is
382 // present in the call stack.)
384 // |err| should be < ERR_IO_PENDING; this function is intended to be
386 // |description| indicates the reason for the error.
387 void CloseSessionOnError(Error err
, const std::string
& description
);
389 // Mark this session as unavailable, meaning that it will not be used to
390 // service new streams. Unlike when a GOAWAY frame is received, this function
391 // will not close any streams.
392 void MakeUnavailable();
394 // Closes all active streams with stream id's greater than
395 // |last_good_stream_id|, as well as any created or pending
396 // streams. Must be called only when |availability_state_| >=
397 // STATE_GOING_AWAY. After this function, DcheckGoingAway() will
398 // pass. May be called multiple times.
399 void StartGoingAway(SpdyStreamId last_good_stream_id
, Error status
);
401 // Must be called only when going away (i.e., DcheckGoingAway()
402 // passes). If there are no more active streams and the session
403 // isn't closed yet, close it.
404 void MaybeFinishGoingAway();
406 // Retrieves information on the current state of the SPDY session as a
407 // Value. Caller takes possession of the returned value.
408 base::Value
* GetInfoAsValue() const;
410 // Indicates whether the session is being reused after having successfully
411 // used to send/receive data in the past or if the underlying socket was idle
412 // before being used for a SPDY session.
413 bool IsReused() const;
415 // Returns true if the underlying transport socket ever had any reads or
417 bool WasEverUsed() const {
418 return connection_
->socket()->WasEverUsed();
421 // Returns the load timing information from the perspective of the given
422 // stream. If it's not the first stream, the connection is considered reused
425 // This uses a different notion of reuse than IsReused(). This function
426 // sets |socket_reused| to false only if |stream_id| is the ID of the first
427 // stream using the session. IsReused(), on the other hand, indicates if the
428 // session has been used to send/receive data at all.
429 bool GetLoadTimingInfo(SpdyStreamId stream_id
,
430 LoadTimingInfo
* load_timing_info
) const;
432 // Returns true if session is not currently active
433 bool is_active() const {
434 return !active_streams_
.empty() || !created_streams_
.empty();
437 // Access to the number of active and pending streams. These are primarily
438 // available for testing and diagnostics.
439 size_t num_active_streams() const { return active_streams_
.size(); }
440 size_t num_unclaimed_pushed_streams() const {
441 return unclaimed_pushed_streams_
.size();
443 size_t num_created_streams() const { return created_streams_
.size(); }
445 size_t num_pushed_streams() const { return num_pushed_streams_
; }
446 size_t num_active_pushed_streams() const {
447 return num_active_pushed_streams_
;
450 size_t pending_create_stream_queue_size(RequestPriority priority
) const {
451 DCHECK_GE(priority
, MINIMUM_PRIORITY
);
452 DCHECK_LE(priority
, MAXIMUM_PRIORITY
);
453 return pending_create_stream_queues_
[priority
].size();
456 // Returns the (version-dependent) flow control state.
457 FlowControlState
flow_control_state() const {
458 return flow_control_state_
;
461 // Returns the current |stream_initial_send_window_size_|.
462 int32
stream_initial_send_window_size() const {
463 return stream_initial_send_window_size_
;
466 // Returns the current |stream_initial_recv_window_size_|.
467 int32
stream_initial_recv_window_size() const {
468 return stream_initial_recv_window_size_
;
471 // Returns true if no stream in the session can send data due to
472 // session flow control.
473 bool IsSendStalled() const {
475 flow_control_state_
== FLOW_CONTROL_STREAM_AND_SESSION
&&
476 session_send_window_size_
== 0;
479 const BoundNetLog
& net_log() const { return net_log_
; }
481 int GetPeerAddress(IPEndPoint
* address
) const;
482 int GetLocalAddress(IPEndPoint
* address
) const;
484 // Adds |alias| to set of aliases associated with this session.
485 void AddPooledAlias(const SpdySessionKey
& alias_key
);
487 // Returns the set of aliases associated with this session.
488 const std::set
<SpdySessionKey
>& pooled_aliases() const {
489 return pooled_aliases_
;
492 SpdyMajorVersion
GetProtocolVersion() const;
494 size_t GetDataFrameMinimumSize() const {
495 return buffered_spdy_framer_
->GetDataFrameMinimumSize();
498 size_t GetControlFrameHeaderSize() const {
499 return buffered_spdy_framer_
->GetControlFrameHeaderSize();
502 size_t GetFrameMinimumSize() const {
503 return buffered_spdy_framer_
->GetFrameMinimumSize();
506 size_t GetFrameMaximumSize() const {
507 return buffered_spdy_framer_
->GetFrameMaximumSize();
510 size_t GetDataFrameMaximumPayload() const {
511 return buffered_spdy_framer_
->GetDataFrameMaximumPayload();
514 static int32
GetInitialWindowSize(NextProto protocol
) {
515 return protocol
< kProtoSPDY4MinimumVersion
? 65536 : 65535;
518 // https://http2.github.io/http2-spec/#TLSUsage mandates minimum security
519 // standards for TLS.
520 bool HasAcceptableTransportSecurity() const;
522 // Must be used only by |pool_|.
523 base::WeakPtr
<SpdySession
> GetWeakPtr();
525 // HigherLayeredPool implementation:
526 bool CloseOneIdleConnection() override
;
529 friend class base::RefCounted
<SpdySession
>;
530 friend class SpdyStreamRequest
;
531 friend class SpdySessionTest
;
533 // Allow tests to access our innards for testing purposes.
534 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClientPing
);
535 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, FailedPing
);
536 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, GetActivePushStream
);
537 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, DeleteExpiredPushStreams
);
538 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ProtocolNegotiation
);
539 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, ClearSettings
);
540 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustRecvWindowSize
);
541 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, AdjustSendWindowSize
);
542 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlInactiveStream
);
543 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlPadding
);
544 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoReceiveLeaks
);
545 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlNoSendLeaks
);
546 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, SessionFlowControlEndToEnd
);
547 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, StreamIdSpaceExhausted
);
548 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, UnstallRacesWithStreamCreation
);
549 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, GoAwayOnSessionFlowControlError
);
550 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
,
551 RejectPushedStreamExceedingConcurrencyLimit
);
552 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, IgnoreReservedRemoteStreamsCount
);
553 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
,
554 CancelReservedStreamOnHeadersReceived
);
555 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest
, RejectInvalidUnknownFrames
);
557 typedef std::deque
<base::WeakPtr
<SpdyStreamRequest
> >
558 PendingStreamRequestQueue
;
560 struct ActiveStreamInfo
{
562 explicit ActiveStreamInfo(SpdyStream
* stream
);
566 bool waiting_for_syn_reply
;
568 typedef std::map
<SpdyStreamId
, ActiveStreamInfo
> ActiveStreamMap
;
570 struct PushedStreamInfo
{
572 PushedStreamInfo(SpdyStreamId stream_id
, base::TimeTicks creation_time
);
575 SpdyStreamId stream_id
;
576 base::TimeTicks creation_time
;
578 typedef std::map
<GURL
, PushedStreamInfo
> PushedStreamMap
;
580 typedef std::set
<SpdyStream
*> CreatedStreamSet
;
582 enum AvailabilityState
{
583 // The session is available in its socket pool and can be used
586 // The session can process data on existing streams but will
587 // refuse to create new ones.
589 // The session is draining its write queue in preparation of closing.
590 // Further writes will not be queued, and further reads will not be issued
591 // (though the remainder of a current read may be processed). The session
592 // will be destroyed by its write loop once the write queue is drained.
598 READ_STATE_DO_READ_COMPLETE
,
602 // There is no in-flight write and the write queue is empty.
604 WRITE_STATE_DO_WRITE
,
605 WRITE_STATE_DO_WRITE_COMPLETE
,
608 // Checks whether a stream for the given |url| can be created or
609 // retrieved from the set of unclaimed push streams. Returns OK if
610 // so. Otherwise, the session is closed and an error <
611 // ERR_IO_PENDING is returned.
612 Error
TryAccessStream(const GURL
& url
);
614 // Called by SpdyStreamRequest to start a request to create a
615 // stream. If OK is returned, then |stream| will be filled in with a
616 // valid stream. If ERR_IO_PENDING is returned, then
617 // |request->OnRequestComplete{Success,Failure}()| will be called
618 // when the stream is created (unless it is cancelled). Otherwise,
619 // no stream is created and the error is returned.
620 int TryCreateStream(const base::WeakPtr
<SpdyStreamRequest
>& request
,
621 base::WeakPtr
<SpdyStream
>* stream
);
623 // Actually create a stream into |stream|. Returns OK if successful;
624 // otherwise, returns an error and |stream| is not filled.
625 int CreateStream(const SpdyStreamRequest
& request
,
626 base::WeakPtr
<SpdyStream
>* stream
);
628 // Called by SpdyStreamRequest to remove |request| from the stream
630 void CancelStreamRequest(const base::WeakPtr
<SpdyStreamRequest
>& request
);
632 // Returns the next pending stream request to process, or NULL if
634 base::WeakPtr
<SpdyStreamRequest
> GetNextPendingStreamRequest();
636 // Called when there is room to create more streams (e.g., a stream
637 // was closed). Processes as many pending stream requests as
639 void ProcessPendingStreamRequests();
641 bool TryCreatePushStream(SpdyStreamId stream_id
,
642 SpdyStreamId associated_stream_id
,
643 SpdyPriority priority
,
644 const SpdyHeaderBlock
& headers
);
646 // Close the stream pointed to by the given iterator. Note that that
647 // stream may hold the last reference to the session.
648 void CloseActiveStreamIterator(ActiveStreamMap::iterator it
, int status
);
650 // Close the stream pointed to by the given iterator. Note that that
651 // stream may hold the last reference to the session.
652 void CloseCreatedStreamIterator(CreatedStreamSet::iterator it
, int status
);
654 // Calls EnqueueResetStreamFrame() and then
655 // CloseActiveStreamIterator().
656 void ResetStreamIterator(ActiveStreamMap::iterator it
,
657 SpdyRstStreamStatus status
,
658 const std::string
& description
);
660 // Send a RST_STREAM frame with the given parameters. There should
661 // either be no active stream with the given ID, or that active
662 // stream should be closed shortly after this function is called.
664 // TODO(akalin): Rename this to EnqueueResetStreamFrame().
665 void EnqueueResetStreamFrame(SpdyStreamId stream_id
,
666 RequestPriority priority
,
667 SpdyRstStreamStatus status
,
668 const std::string
& description
);
670 // Calls DoReadLoop. Use this function instead of DoReadLoop when
671 // posting a task to pump the read loop.
672 void PumpReadLoop(ReadState expected_read_state
, int result
);
674 // Advance the ReadState state machine. |expected_read_state| is the
675 // expected starting read state.
677 // This function must always be called via PumpReadLoop().
678 int DoReadLoop(ReadState expected_read_state
, int result
);
679 // The implementations of the states of the ReadState state machine.
681 int DoReadComplete(int result
);
683 // Calls DoWriteLoop. If |availability_state_| is STATE_DRAINING and no
684 // writes remain, the session is removed from the session pool and
687 // Use this function instead of DoWriteLoop when posting a task to
688 // pump the write loop.
689 void PumpWriteLoop(WriteState expected_write_state
, int result
);
691 // Iff the write loop is not currently active, posts a callback into
693 void MaybePostWriteLoop();
695 // Advance the WriteState state machine. |expected_write_state| is
696 // the expected starting write state.
698 // This function must always be called via PumpWriteLoop().
699 int DoWriteLoop(WriteState expected_write_state
, int result
);
700 // The implementations of the states of the WriteState state machine.
702 int DoWriteComplete(int result
);
704 // TODO(akalin): Rename the Send* and Write* functions below to
707 // Send initial data. Called when a connection is successfully
708 // established in InitializeWithSocket() and
709 // |enable_sending_initial_data_| is true.
710 void SendInitialData();
712 // Helper method to send a SETTINGS frame.
713 void SendSettings(const SettingsMap
& settings
);
715 // Handle SETTING. Either when we send settings, or when we receive a
716 // SETTINGS control frame, update our SpdySession accordingly.
717 void HandleSetting(uint32 id
, uint32 value
);
719 // Adjust the send window size of all ActiveStreams and PendingStreamRequests.
720 void UpdateStreamsSendWindowSize(int32 delta_window_size
);
722 // Send the PING (preface-PING) frame.
723 void SendPrefacePingIfNoneInFlight();
725 // Send PING if there are no PINGs in flight and we haven't heard from server.
726 void SendPrefacePing();
728 // Send a single WINDOW_UPDATE frame.
729 void SendWindowUpdateFrame(SpdyStreamId stream_id
, uint32 delta_window_size
,
730 RequestPriority priority
);
732 // Send the PING frame.
733 void WritePingFrame(SpdyPingId unique_id
, bool is_ack
);
735 // Post a CheckPingStatus call after delay. Don't post if there is already
736 // CheckPingStatus running.
737 void PlanToCheckPingStatus();
739 // Check the status of the connection. It calls |CloseSessionOnError| if we
740 // haven't received any data in |kHungInterval| time period.
741 void CheckPingStatus(base::TimeTicks last_check_time
);
743 // Get a new stream id.
744 SpdyStreamId
GetNewStreamId();
746 // Pushes the given frame with the given priority into the write
747 // queue for the session.
748 void EnqueueSessionWrite(RequestPriority priority
,
749 SpdyFrameType frame_type
,
750 scoped_ptr
<SpdyFrame
> frame
);
752 // Puts |producer| associated with |stream| onto the write queue
753 // with the given priority.
754 void EnqueueWrite(RequestPriority priority
,
755 SpdyFrameType frame_type
,
756 scoped_ptr
<SpdyBufferProducer
> producer
,
757 const base::WeakPtr
<SpdyStream
>& stream
);
759 // Inserts a newly-created stream into |created_streams_|.
760 void InsertCreatedStream(scoped_ptr
<SpdyStream
> stream
);
762 // Activates |stream| (which must be in |created_streams_|) by
763 // assigning it an ID and returns it.
764 scoped_ptr
<SpdyStream
> ActivateCreatedStream(SpdyStream
* stream
);
766 // Inserts a newly-activated stream into |active_streams_|.
767 void InsertActivatedStream(scoped_ptr
<SpdyStream
> stream
);
769 // Remove all internal references to |stream|, call OnClose() on it,
770 // and process any pending stream requests before deleting it. Note
771 // that |stream| may hold the last reference to the session.
772 void DeleteStream(scoped_ptr
<SpdyStream
> stream
, int status
);
774 // Check if we have a pending pushed-stream for this url
775 // Returns the stream if found (and returns it from the pending
776 // list). Returns NULL otherwise.
777 base::WeakPtr
<SpdyStream
> GetActivePushStream(const GURL
& url
);
779 // Delegates to |stream->OnInitialResponseHeadersReceived()|. If an
780 // error is returned, the last reference to |this| may have been
782 int OnInitialResponseHeadersReceived(const SpdyHeaderBlock
& response_headers
,
783 base::Time response_time
,
784 base::TimeTicks recv_first_byte_time
,
787 void RecordPingRTTHistogram(base::TimeDelta duration
);
788 void RecordHistograms();
789 void RecordProtocolErrorHistogram(SpdyProtocolErrorDetails details
);
791 // DCHECKs that |availability_state_| >= STATE_GOING_AWAY, that
792 // there are no pending stream creation requests, and that there are
793 // no created streams.
794 void DcheckGoingAway() const;
796 // Calls DcheckGoingAway(), then DCHECKs that |availability_state_|
797 // == STATE_DRAINING, |error_on_close_| has a valid value, and that there
798 // are no active streams or unclaimed pushed streams.
799 void DcheckDraining() const;
801 // If the session is already draining, does nothing. Otherwise, moves
802 // the session to the draining state.
803 void DoDrainSession(Error err
, const std::string
& description
);
805 // Called right before closing a (possibly-inactive) stream for a
806 // reason other than being requested to by the stream.
807 void LogAbandonedStream(SpdyStream
* stream
, Error status
);
809 // Called right before closing an active stream for a reason other
810 // than being requested to by the stream.
811 void LogAbandonedActiveStream(ActiveStreamMap::const_iterator it
,
814 // Invokes a user callback for stream creation. We provide this method so it
815 // can be deferred to the MessageLoop, so we avoid re-entrancy problems.
816 void CompleteStreamRequest(
817 const base::WeakPtr
<SpdyStreamRequest
>& pending_request
);
819 // Remove old unclaimed pushed streams.
820 void DeleteExpiredPushedStreams();
822 // BufferedSpdyFramerVisitorInterface:
823 void OnError(SpdyFramer::SpdyError error_code
) override
;
824 void OnStreamError(SpdyStreamId stream_id
,
825 const std::string
& description
) override
;
826 void OnPing(SpdyPingId unique_id
, bool is_ack
) override
;
827 void OnRstStream(SpdyStreamId stream_id
, SpdyRstStreamStatus status
) override
;
828 void OnGoAway(SpdyStreamId last_accepted_stream_id
,
829 SpdyGoAwayStatus status
) override
;
830 void OnDataFrameHeader(SpdyStreamId stream_id
,
833 void OnStreamFrameData(SpdyStreamId stream_id
,
837 void OnStreamPadding(SpdyStreamId stream_id
, size_t len
) override
;
838 void OnSettings(bool clear_persisted
) override
;
839 void OnSetting(SpdySettingsIds id
, uint8 flags
, uint32 value
) override
;
840 void OnWindowUpdate(SpdyStreamId stream_id
,
841 uint32 delta_window_size
) override
;
842 void OnPushPromise(SpdyStreamId stream_id
,
843 SpdyStreamId promised_stream_id
,
844 const SpdyHeaderBlock
& headers
) override
;
845 void OnSynStream(SpdyStreamId stream_id
,
846 SpdyStreamId associated_stream_id
,
847 SpdyPriority priority
,
850 const SpdyHeaderBlock
& headers
) override
;
851 void OnSynReply(SpdyStreamId stream_id
,
853 const SpdyHeaderBlock
& headers
) override
;
854 void OnHeaders(SpdyStreamId stream_id
,
856 SpdyPriority priority
,
858 const SpdyHeaderBlock
& headers
) override
;
859 bool OnUnknownFrame(SpdyStreamId stream_id
, int frame_type
) override
;
861 // SpdyFramerDebugVisitorInterface
862 void OnSendCompressedFrame(SpdyStreamId stream_id
,
865 size_t frame_len
) override
;
866 void OnReceiveCompressedFrame(SpdyStreamId stream_id
,
868 size_t frame_len
) override
;
870 // Called when bytes are consumed from a SpdyBuffer for a DATA frame
871 // that is to be written or is being written. Increases the send
872 // window size accordingly if some or all of the SpdyBuffer is being
875 // If session flow control is turned off, this must not be called.
876 void OnWriteBufferConsumed(size_t frame_payload_size
,
878 SpdyBuffer::ConsumeSource consume_source
);
880 // Called by OnWindowUpdate() (which is in turn called by the
881 // framer) to increase this session's send window size by
882 // |delta_window_size| from a WINDOW_UPDATE frome, which must be at
883 // least 1. If |delta_window_size| would cause this session's send
884 // window size to overflow, does nothing.
886 // If session flow control is turned off, this must not be called.
887 void IncreaseSendWindowSize(int32 delta_window_size
);
889 // If session flow control is turned on, called by CreateDataFrame()
890 // (which is in turn called by a stream) to decrease this session's
891 // send window size by |delta_window_size|, which must be at least 1
892 // and at most kMaxSpdyFrameChunkSize. |delta_window_size| must not
893 // cause this session's send window size to go negative.
895 // If session flow control is turned off, this must not be called.
896 void DecreaseSendWindowSize(int32 delta_window_size
);
898 // Called when bytes are consumed by the delegate from a SpdyBuffer
899 // containing received data. Increases the receive window size
902 // If session flow control is turned off, this must not be called.
903 void OnReadBufferConsumed(size_t consume_size
,
904 SpdyBuffer::ConsumeSource consume_source
);
906 // Called by OnReadBufferConsume to increase this session's receive
907 // window size by |delta_window_size|, which must be at least 1 and
908 // must not cause this session's receive window size to overflow,
909 // possibly also sending a WINDOW_UPDATE frame. Also called during
910 // initialization to set the initial receive window size.
912 // If session flow control is turned off, this must not be called.
913 void IncreaseRecvWindowSize(int32 delta_window_size
);
915 // Called by OnStreamFrameData (which is in turn called by the
916 // framer) to decrease this session's receive window size by
917 // |delta_window_size|, which must be at least 1 and must not cause
918 // this session's receive window size to go negative.
920 // If session flow control is turned off, this must not be called.
921 void DecreaseRecvWindowSize(int32 delta_window_size
);
923 // Queue a send-stalled stream for possibly resuming once we're not
924 // send-stalled anymore.
925 void QueueSendStalledStream(const SpdyStream
& stream
);
927 // Go through the queue of send-stalled streams and try to resume as
929 void ResumeSendStalledStreams();
931 // Returns the next stream to possibly resume, or 0 if the queue is
933 SpdyStreamId
PopStreamToPossiblyResume();
935 // --------------------------
936 // Helper methods for testing
937 // --------------------------
939 void set_connection_at_risk_of_loss_time(base::TimeDelta duration
) {
940 connection_at_risk_of_loss_time_
= duration
;
943 void set_hung_interval(base::TimeDelta duration
) {
944 hung_interval_
= duration
;
947 void set_max_concurrent_pushed_streams(size_t value
) {
948 max_concurrent_pushed_streams_
= value
;
951 int64
pings_in_flight() const { return pings_in_flight_
; }
953 SpdyPingId
next_ping_id() const { return next_ping_id_
; }
955 base::TimeTicks
last_activity_time() const { return last_activity_time_
; }
957 bool check_ping_status_pending() const { return check_ping_status_pending_
; }
959 size_t max_concurrent_streams() const { return max_concurrent_streams_
; }
961 // Returns the SSLClientSocket that this SPDY session sits on top of,
962 // or NULL, if the transport is not SSL.
963 SSLClientSocket
* GetSSLClientSocket() const;
965 // Whether Do{Read,Write}Loop() is in the call stack. Useful for
966 // making sure we don't destroy ourselves prematurely in that case.
969 // The key used to identify this session.
970 const SpdySessionKey spdy_session_key_
;
972 // Set set of SpdySessionKeys for which this session has serviced
974 std::set
<SpdySessionKey
> pooled_aliases_
;
976 // |pool_| owns us, therefore its lifetime must exceed ours. We set
977 // this to NULL after we are removed from the pool.
978 SpdySessionPool
* pool_
;
979 const base::WeakPtr
<HttpServerProperties
> http_server_properties_
;
981 TransportSecurityState
* transport_security_state_
;
983 // The socket handle for this session.
984 scoped_ptr
<ClientSocketHandle
> connection_
;
986 // The read buffer used to read data from the socket.
987 scoped_refptr
<IOBuffer
> read_buffer_
;
989 SpdyStreamId stream_hi_water_mark_
; // The next stream id to use.
991 // Used to ensure the server increments push stream ids correctly.
992 SpdyStreamId last_accepted_push_stream_id_
;
994 // Queue, for each priority, of pending stream requests that have
995 // not yet been satisfied.
996 PendingStreamRequestQueue pending_create_stream_queues_
[NUM_PRIORITIES
];
998 // Map from stream id to all active streams. Streams are active in the sense
999 // that they have a consumer (typically SpdyNetworkTransaction and regardless
1000 // of whether or not there is currently any ongoing IO [might be waiting for
1001 // the server to start pushing the stream]) or there are still network events
1002 // incoming even though the consumer has already gone away (cancellation).
1004 // |active_streams_| owns all its SpdyStream objects.
1006 // TODO(willchan): Perhaps we should separate out cancelled streams and move
1007 // them into a separate ActiveStreamMap, and not deliver network events to
1009 ActiveStreamMap active_streams_
;
1011 // (Bijective) map from the URL to the ID of the streams that have
1012 // already started to be pushed by the server, but do not have
1013 // consumers yet. Contains a subset of |active_streams_|.
1014 PushedStreamMap unclaimed_pushed_streams_
;
1016 // Set of all created streams but that have not yet sent any frames.
1018 // |created_streams_| owns all its SpdyStream objects.
1019 CreatedStreamSet created_streams_
;
1021 // Number of pushed streams. All active streams are stored in
1022 // |active_streams_|, but it's better to know the number of push streams
1023 // without traversing the whole collection.
1024 size_t num_pushed_streams_
;
1026 // Number of active pushed streams in |active_streams_|, i.e. not in reserved
1027 // remote state. Streams in reserved state are not counted towards any
1028 // concurrency limits.
1029 size_t num_active_pushed_streams_
;
1032 SpdyWriteQueue write_queue_
;
1034 // Data for the frame we are currently sending.
1036 // The buffer we're currently writing.
1037 scoped_ptr
<SpdyBuffer
> in_flight_write_
;
1038 // The type of the frame in |in_flight_write_|.
1039 SpdyFrameType in_flight_write_frame_type_
;
1040 // The size of the frame in |in_flight_write_|.
1041 size_t in_flight_write_frame_size_
;
1042 // The stream to notify when |in_flight_write_| has been written to
1043 // the socket completely.
1044 base::WeakPtr
<SpdyStream
> in_flight_write_stream_
;
1046 // Flag if we're using an SSL connection for this SpdySession.
1049 // Certificate error code when using a secure connection.
1050 int certificate_error_code_
;
1052 // Spdy Frame state.
1053 scoped_ptr
<BufferedSpdyFramer
> buffered_spdy_framer_
;
1055 // The state variables.
1056 AvailabilityState availability_state_
;
1057 ReadState read_state_
;
1058 WriteState write_state_
;
1060 // If the session is closing (i.e., |availability_state_| is STATE_DRAINING),
1061 // then |error_on_close_| holds the error with which it was closed, which
1062 // may be OK (upon a polite GOAWAY) or an error < ERR_IO_PENDING otherwise.
1063 // Initialized to OK.
1064 Error error_on_close_
;
1067 size_t max_concurrent_streams_
; // 0 if no limit
1068 size_t max_concurrent_streams_limit_
;
1069 size_t max_concurrent_pushed_streams_
;
1071 // Some statistics counters for the session.
1072 int streams_initiated_count_
;
1073 int streams_pushed_count_
;
1074 int streams_pushed_and_claimed_count_
;
1075 int streams_abandoned_count_
;
1077 // |total_bytes_received_| keeps track of all the bytes read by the
1078 // SpdySession. It is used by the |Net.SpdySettingsCwnd...| histograms.
1079 int total_bytes_received_
;
1081 bool sent_settings_
; // Did this session send settings when it started.
1082 bool received_settings_
; // Did this session receive at least one settings
1084 int stalled_streams_
; // Count of streams that were ever stalled.
1086 // Count of all pings on the wire, for which we have not gotten a response.
1087 int64 pings_in_flight_
;
1089 // This is the next ping_id (unique_id) to be sent in PING frame.
1090 SpdyPingId next_ping_id_
;
1092 // This is the last time we have sent a PING.
1093 base::TimeTicks last_ping_sent_time_
;
1095 // This is the last time we had activity in the session.
1096 base::TimeTicks last_activity_time_
;
1098 // This is the length of the last compressed frame.
1099 size_t last_compressed_frame_len_
;
1101 // This is the next time that unclaimed push streams should be checked for
1103 base::TimeTicks next_unclaimed_push_stream_sweep_time_
;
1105 // Indicate if we have already scheduled a delayed task to check the ping
1107 bool check_ping_status_pending_
;
1109 // Whether to send the (HTTP/2) connection header prefix.
1110 bool send_connection_header_prefix_
;
1112 // The (version-dependent) flow control state.
1113 FlowControlState flow_control_state_
;
1115 // Initial send window size for this session's streams. Can be
1116 // changed by an arriving SETTINGS frame. Newly created streams use
1117 // this value for the initial send window size.
1118 int32 stream_initial_send_window_size_
;
1120 // Initial receive window size for this session's streams. There are
1121 // plans to add a command line switch that would cause a SETTINGS
1122 // frame with window size announcement to be sent on startup. Newly
1123 // created streams will use this value for the initial receive
1125 int32 stream_initial_recv_window_size_
;
1127 // Session flow control variables. All zero unless session flow
1128 // control is turned on.
1129 int32 session_send_window_size_
;
1130 int32 session_recv_window_size_
;
1131 int32 session_unacked_recv_window_bytes_
;
1133 // A queue of stream IDs that have been send-stalled at some point
1135 std::deque
<SpdyStreamId
> stream_send_unstall_queue_
[NUM_PRIORITIES
];
1137 BoundNetLog net_log_
;
1139 // Outside of tests, these should always be true.
1140 bool verify_domain_authentication_
;
1141 bool enable_sending_initial_data_
;
1142 bool enable_compression_
;
1143 bool enable_ping_based_connection_checking_
;
1145 // The SPDY protocol used. Always between kProtoSPDYMinimumVersion and
1146 // kProtoSPDYMaximumVersion.
1147 NextProto protocol_
;
1149 // |connection_at_risk_of_loss_time_| is an optimization to avoid sending
1150 // wasteful preface pings (when we just got some data).
1152 // If it is zero (the most conservative figure), then we always send the
1153 // preface ping (when none are in flight).
1155 // It is common for TCP/IP sessions to time out in about 3-5 minutes.
1156 // Certainly if it has been more than 3 minutes, we do want to send a preface
1159 // We don't think any connection will time out in under about 10 seconds. So
1160 // this might as well be set to something conservative like 10 seconds. Later,
1161 // we could adjust it to send fewer pings perhaps.
1162 base::TimeDelta connection_at_risk_of_loss_time_
;
1164 // The amount of time that we are willing to tolerate with no activity (of any
1165 // form), while there is a ping in flight, before we declare the connection to
1166 // be hung. TODO(rtenneti): When hung, instead of resetting connection, race
1167 // to build a new connection, and see if that completes before we (finally)
1168 // get a PING response (http://crbug.com/127812).
1169 base::TimeDelta hung_interval_
;
1171 // This SPDY proxy is allowed to push resources from origins that are
1172 // different from those of their associated streams.
1173 HostPortPair trusted_spdy_proxy_
;
1175 TimeFunc time_func_
;
1177 // Used for posting asynchronous IO tasks. We use this even though
1178 // SpdySession is refcounted because we don't need to keep the SpdySession
1179 // alive if the last reference is within a RunnableMethod. Just revoke the
1181 base::WeakPtrFactory
<SpdySession
> weak_factory_
;
1186 #endif // NET_SPDY_SPDY_SESSION_H_