Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / net / spdy / spdy_session.h
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.
4
5 #ifndef NET_SPDY_SPDY_SESSION_H_
6 #define NET_SPDY_SPDY_SESSION_H_
7
8 #include <deque>
9 #include <map>
10 #include <set>
11 #include <string>
12
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"
38 #include "url/gurl.h"
39
40 namespace net {
41
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;
49
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;
53
54 // Specifies the maxiumum concurrent streams server could send (via push).
55 const int kMaxConcurrentPushedStreams = 1000;
56
57 // Specifies the maximum number of bytes to read synchronously before
58 // yielding.
59 const int kMaxReadBytesWithoutYielding = 32 * 1024;
60
61 // The initial receive window size for both streams and sessions.
62 const int32 kDefaultInitialRecvWindowSize = 10 * 1024 * 1024;  // 10MB
63
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;
68
69 class BoundNetLog;
70 struct LoadTimingInfo;
71 class SpdyStream;
72 class SSLInfo;
73 class TransportSecurityState;
74
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
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,
117
118   // Next free value.
119   NUM_SPDY_PROTOCOL_ERROR_DETAILS = 35,
120 };
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);
127
128 // If these compile asserts fail then SpdyProtocolErrorDetails needs
129 // to be updated with new values, as do the mapping functions above.
130 COMPILE_ASSERT(12 == SpdyFramer::LAST_ERROR,
131                SpdyProtocolErrorDetails_SpdyErrors_mismatch);
132 COMPILE_ASSERT(15 == RST_STREAM_NUM_STATUS_CODES,
133                SpdyProtocolErrorDetails_RstStreamStatus_mismatch);
134
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);
142
143 // A helper class used to manage a request to create a stream.
144 class NET_EXPORT_PRIVATE SpdyStreamRequest {
145  public:
146   SpdyStreamRequest();
147   // Calls CancelRequest().
148   ~SpdyStreamRequest();
149
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
155   // be called.
156   //
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,
164                    const GURL& url,
165                    RequestPriority priority,
166                    const BoundNetLog& net_log,
167                    const CompletionCallback& callback);
168
169   // Cancels any pending stream creation request. May be called
170   // repeatedly.
171   void CancelRequest();
172
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();
178
179  private:
180   friend class SpdySession;
181
182   // Called by |session_| when the stream attempt has finished
183   // successfully.
184   void OnRequestCompleteSuccess(const base::WeakPtr<SpdyStream>& stream);
185
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);
190
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_; }
196
197   void Reset();
198
199   SpdyStreamType type_;
200   base::WeakPtr<SpdySession> session_;
201   base::WeakPtr<SpdyStream> stream_;
202   GURL url_;
203   RequestPriority priority_;
204   BoundNetLog net_log_;
205   CompletionCallback callback_;
206
207   base::WeakPtrFactory<SpdyStreamRequest> weak_ptr_factory_;
208
209   DISALLOW_COPY_AND_ASSIGN(SpdyStreamRequest);
210 };
211
212 class NET_EXPORT SpdySession : public BufferedSpdyFramerVisitorInterface,
213                                public SpdyFramerDebugVisitorInterface,
214                                public HigherLayeredPool {
215  public:
216   // TODO(akalin): Use base::TickClock when it becomes available.
217   typedef base::TimeTicks (*TimeFunc)(void);
218
219   // How we handle flow control (version-dependent).
220   enum FlowControlState {
221     FLOW_CONTROL_NONE,
222     FLOW_CONTROL_STREAM,
223     FLOW_CONTROL_STREAM_AND_SESSION
224   };
225
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);
232
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 stream_initial_recv_window_size,
247               size_t initial_max_concurrent_streams,
248               size_t max_concurrent_streams_limit,
249               TimeFunc time_func,
250               const HostPortPair& trusted_spdy_proxy,
251               NetLog* net_log);
252
253   ~SpdySession() override;
254
255   const HostPortPair& host_port_pair() const {
256     return spdy_session_key_.host_port_proxy_pair().first;
257   }
258   const HostPortProxyPair& host_port_proxy_pair() const {
259     return spdy_session_key_.host_port_proxy_pair();
260   }
261   const SpdySessionKey& spdy_session_key() const {
262     return spdy_session_key_;
263   }
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|.
272   int GetPushStream(
273       const GURL& url,
274       base::WeakPtr<SpdyStream>* spdy_stream,
275       const BoundNetLog& stream_net_log);
276
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.
281   //
282   // |pool| is the SpdySessionPool that owns us.  Its lifetime must
283   // strictly be greater than |this|.
284   //
285   // |certificate_error_code| must either be OK or less than
286   // ERR_IO_PENDING.
287   //
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,
293                             bool is_secure,
294                             int certificate_error_code);
295
296   // Returns the protocol used by this session. Always between
297   // kProtoSPDYMinimumVersion and kProtoSPDYMaximumVersion.
298   NextProto protocol() const { return protocol_; }
299
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
306   // platforms.
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);
311
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);
318
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);
325
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,
329                                           IOBuffer* data,
330                                           int len,
331                                           SpdyDataFlags flags);
332
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
335   // session.
336   void CloseActiveStream(SpdyStreamId stream_id, int status);
337
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
340   // session.
341   void CloseCreatedStream(const base::WeakPtr<SpdyStream>& stream, int status);
342
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);
349
350   // Check if a stream is active.
351   bool IsStreamActive(SpdyStreamId stream_id) const;
352
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;
356
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);
361
362   // Fills SSL Certificate Request info |cert_request_info| and returns
363   // true when SSL is in use.
364   bool GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info);
365
366   // Send a WINDOW_UPDATE frame for a stream. Called by a stream
367   // whenever receive window size is increased.
368   void SendStreamWindowUpdate(SpdyStreamId stream_id,
369                               uint32 delta_window_size);
370
371   // Accessors for the session's availability state.
372   bool IsAvailable() const { return availability_state_ == STATE_AVAILABLE; }
373   bool IsGoingAway() const { return availability_state_ == STATE_GOING_AWAY; }
374   bool IsDraining() const { return availability_state_ == STATE_DRAINING; }
375
376   // Closes this session. This will close all active streams and mark
377   // the session as permanently closed. Callers must assume that the
378   // session is destroyed after this is called. (However, it may not
379   // be destroyed right away, e.g. when a SpdySession function is
380   // present in the call stack.)
381   //
382   // |err| should be < ERR_IO_PENDING; this function is intended to be
383   // called on error.
384   // |description| indicates the reason for the error.
385   void CloseSessionOnError(Error err, const std::string& description);
386
387   // Mark this session as unavailable, meaning that it will not be used to
388   // service new streams. Unlike when a GOAWAY frame is received, this function
389   // will not close any streams.
390   void MakeUnavailable();
391
392   // Closes all active streams with stream id's greater than
393   // |last_good_stream_id|, as well as any created or pending
394   // streams. Must be called only when |availability_state_| >=
395   // STATE_GOING_AWAY. After this function, DcheckGoingAway() will
396   // pass. May be called multiple times.
397   void StartGoingAway(SpdyStreamId last_good_stream_id, Error status);
398
399   // Must be called only when going away (i.e., DcheckGoingAway()
400   // passes). If there are no more active streams and the session
401   // isn't closed yet, close it.
402   void MaybeFinishGoingAway();
403
404   // Retrieves information on the current state of the SPDY session as a
405   // Value.  Caller takes possession of the returned value.
406   base::Value* GetInfoAsValue() const;
407
408   // Indicates whether the session is being reused after having successfully
409   // used to send/receive data in the past or if the underlying socket was idle
410   // before being used for a SPDY session.
411   bool IsReused() const;
412
413   // Returns true if the underlying transport socket ever had any reads or
414   // writes.
415   bool WasEverUsed() const {
416     return connection_->socket()->WasEverUsed();
417   }
418
419   // Returns the load timing information from the perspective of the given
420   // stream.  If it's not the first stream, the connection is considered reused
421   // for that stream.
422   //
423   // This uses a different notion of reuse than IsReused().  This function
424   // sets |socket_reused| to false only if |stream_id| is the ID of the first
425   // stream using the session.  IsReused(), on the other hand, indicates if the
426   // session has been used to send/receive data at all.
427   bool GetLoadTimingInfo(SpdyStreamId stream_id,
428                          LoadTimingInfo* load_timing_info) const;
429
430   // Returns true if session is not currently active
431   bool is_active() const {
432     return !active_streams_.empty() || !created_streams_.empty();
433   }
434
435   // Access to the number of active and pending streams.  These are primarily
436   // available for testing and diagnostics.
437   size_t num_active_streams() const { return active_streams_.size(); }
438   size_t num_unclaimed_pushed_streams() const {
439     return unclaimed_pushed_streams_.size();
440   }
441   size_t num_created_streams() const { return created_streams_.size(); }
442
443   size_t num_pushed_streams() const { return num_pushed_streams_; }
444   size_t num_active_pushed_streams() const {
445     return num_active_pushed_streams_;
446   }
447
448   size_t pending_create_stream_queue_size(RequestPriority priority) const {
449     DCHECK_GE(priority, MINIMUM_PRIORITY);
450     DCHECK_LE(priority, MAXIMUM_PRIORITY);
451     return pending_create_stream_queues_[priority].size();
452   }
453
454   // Returns the (version-dependent) flow control state.
455   FlowControlState flow_control_state() const {
456     return flow_control_state_;
457   }
458
459   // Returns the current |stream_initial_send_window_size_|.
460   int32 stream_initial_send_window_size() const {
461     return stream_initial_send_window_size_;
462   }
463
464   // Returns the current |stream_initial_recv_window_size_|.
465   int32 stream_initial_recv_window_size() const {
466     return stream_initial_recv_window_size_;
467   }
468
469   // Returns true if no stream in the session can send data due to
470   // session flow control.
471   bool IsSendStalled() const {
472     return
473         flow_control_state_ == FLOW_CONTROL_STREAM_AND_SESSION &&
474         session_send_window_size_ == 0;
475   }
476
477   const BoundNetLog& net_log() const { return net_log_; }
478
479   int GetPeerAddress(IPEndPoint* address) const;
480   int GetLocalAddress(IPEndPoint* address) const;
481
482   // Adds |alias| to set of aliases associated with this session.
483   void AddPooledAlias(const SpdySessionKey& alias_key);
484
485   // Returns the set of aliases associated with this session.
486   const std::set<SpdySessionKey>& pooled_aliases() const {
487     return pooled_aliases_;
488   }
489
490   SpdyMajorVersion GetProtocolVersion() const;
491
492   size_t GetDataFrameMinimumSize() const {
493     return buffered_spdy_framer_->GetDataFrameMinimumSize();
494   }
495
496   size_t GetControlFrameHeaderSize() const {
497     return buffered_spdy_framer_->GetControlFrameHeaderSize();
498   }
499
500   size_t GetFrameMinimumSize() const {
501     return buffered_spdy_framer_->GetFrameMinimumSize();
502   }
503
504   size_t GetFrameMaximumSize() const {
505     return buffered_spdy_framer_->GetFrameMaximumSize();
506   }
507
508   size_t GetDataFrameMaximumPayload() const {
509     return buffered_spdy_framer_->GetDataFrameMaximumPayload();
510   }
511
512   // https://http2.github.io/http2-spec/#TLSUsage mandates minimum security
513   // standards for TLS.
514   bool HasAcceptableTransportSecurity() const;
515
516   // Must be used only by |pool_|.
517   base::WeakPtr<SpdySession> GetWeakPtr();
518
519   // HigherLayeredPool implementation:
520   bool CloseOneIdleConnection() override;
521
522  private:
523   friend class base::RefCounted<SpdySession>;
524   friend class SpdyStreamRequest;
525   friend class SpdySessionTest;
526
527   // Allow tests to access our innards for testing purposes.
528   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, ClientPing);
529   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, FailedPing);
530   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, GetActivePushStream);
531   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, DeleteExpiredPushStreams);
532   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, ProtocolNegotiation);
533   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, ClearSettings);
534   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, AdjustRecvWindowSize);
535   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, AdjustSendWindowSize);
536   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, SessionFlowControlInactiveStream);
537   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, SessionFlowControlNoReceiveLeaks);
538   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, SessionFlowControlNoSendLeaks);
539   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, SessionFlowControlEndToEnd);
540   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, StreamIdSpaceExhausted);
541   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, UnstallRacesWithStreamCreation);
542   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, GoAwayOnSessionFlowControlError);
543   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest,
544                            RejectPushedStreamExceedingConcurrencyLimit);
545   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, IgnoreReservedRemoteStreamsCount);
546   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest,
547                            CancelReservedStreamOnHeadersReceived);
548   FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, RejectInvalidUnknownFrames);
549
550   typedef std::deque<base::WeakPtr<SpdyStreamRequest> >
551       PendingStreamRequestQueue;
552
553   struct ActiveStreamInfo {
554     ActiveStreamInfo();
555     explicit ActiveStreamInfo(SpdyStream* stream);
556     ~ActiveStreamInfo();
557
558     SpdyStream* stream;
559     bool waiting_for_syn_reply;
560   };
561   typedef std::map<SpdyStreamId, ActiveStreamInfo> ActiveStreamMap;
562
563   struct PushedStreamInfo {
564     PushedStreamInfo();
565     PushedStreamInfo(SpdyStreamId stream_id, base::TimeTicks creation_time);
566     ~PushedStreamInfo();
567
568     SpdyStreamId stream_id;
569     base::TimeTicks creation_time;
570   };
571   typedef std::map<GURL, PushedStreamInfo> PushedStreamMap;
572
573   typedef std::set<SpdyStream*> CreatedStreamSet;
574
575   enum AvailabilityState {
576     // The session is available in its socket pool and can be used
577     // freely.
578     STATE_AVAILABLE,
579     // The session can process data on existing streams but will
580     // refuse to create new ones.
581     STATE_GOING_AWAY,
582     // The session is draining its write queue in preparation of closing.
583     // Further writes will not be queued, and further reads will not be issued
584     // (though the remainder of a current read may be processed). The session
585     // will be destroyed by its write loop once the write queue is drained.
586     STATE_DRAINING,
587   };
588
589   enum ReadState {
590     READ_STATE_DO_READ,
591     READ_STATE_DO_READ_COMPLETE,
592   };
593
594   enum WriteState {
595     // There is no in-flight write and the write queue is empty.
596     WRITE_STATE_IDLE,
597     WRITE_STATE_DO_WRITE,
598     WRITE_STATE_DO_WRITE_COMPLETE,
599   };
600
601   // Checks whether a stream for the given |url| can be created or
602   // retrieved from the set of unclaimed push streams. Returns OK if
603   // so. Otherwise, the session is closed and an error <
604   // ERR_IO_PENDING is returned.
605   Error TryAccessStream(const GURL& url);
606
607   // Called by SpdyStreamRequest to start a request to create a
608   // stream. If OK is returned, then |stream| will be filled in with a
609   // valid stream. If ERR_IO_PENDING is returned, then
610   // |request->OnRequestComplete{Success,Failure}()| will be called
611   // when the stream is created (unless it is cancelled). Otherwise,
612   // no stream is created and the error is returned.
613   int TryCreateStream(const base::WeakPtr<SpdyStreamRequest>& request,
614                       base::WeakPtr<SpdyStream>* stream);
615
616   // Actually create a stream into |stream|. Returns OK if successful;
617   // otherwise, returns an error and |stream| is not filled.
618   int CreateStream(const SpdyStreamRequest& request,
619                    base::WeakPtr<SpdyStream>* stream);
620
621   // Called by SpdyStreamRequest to remove |request| from the stream
622   // creation queue.
623   void CancelStreamRequest(const base::WeakPtr<SpdyStreamRequest>& request);
624
625   // Returns the next pending stream request to process, or NULL if
626   // there is none.
627   base::WeakPtr<SpdyStreamRequest> GetNextPendingStreamRequest();
628
629   // Called when there is room to create more streams (e.g., a stream
630   // was closed). Processes as many pending stream requests as
631   // possible.
632   void ProcessPendingStreamRequests();
633
634   bool TryCreatePushStream(SpdyStreamId stream_id,
635                            SpdyStreamId associated_stream_id,
636                            SpdyPriority priority,
637                            const SpdyHeaderBlock& headers);
638
639   // Close the stream pointed to by the given iterator. Note that that
640   // stream may hold the last reference to the session.
641   void CloseActiveStreamIterator(ActiveStreamMap::iterator it, int status);
642
643   // Close the stream pointed to by the given iterator. Note that that
644   // stream may hold the last reference to the session.
645   void CloseCreatedStreamIterator(CreatedStreamSet::iterator it, int status);
646
647   // Calls EnqueueResetStreamFrame() and then
648   // CloseActiveStreamIterator().
649   void ResetStreamIterator(ActiveStreamMap::iterator it,
650                            SpdyRstStreamStatus status,
651                            const std::string& description);
652
653   // Send a RST_STREAM frame with the given parameters. There should
654   // either be no active stream with the given ID, or that active
655   // stream should be closed shortly after this function is called.
656   //
657   // TODO(akalin): Rename this to EnqueueResetStreamFrame().
658   void EnqueueResetStreamFrame(SpdyStreamId stream_id,
659                                RequestPriority priority,
660                                SpdyRstStreamStatus status,
661                                const std::string& description);
662
663   // Calls DoReadLoop. Use this function instead of DoReadLoop when
664   // posting a task to pump the read loop.
665   void PumpReadLoop(ReadState expected_read_state, int result);
666
667   // Advance the ReadState state machine. |expected_read_state| is the
668   // expected starting read state.
669   //
670   // This function must always be called via PumpReadLoop().
671   int DoReadLoop(ReadState expected_read_state, int result);
672   // The implementations of the states of the ReadState state machine.
673   int DoRead();
674   int DoReadComplete(int result);
675
676   // Calls DoWriteLoop. If |availability_state_| is STATE_DRAINING and no
677   // writes remain, the session is removed from the session pool and
678   // destroyed.
679   //
680   // Use this function instead of DoWriteLoop when posting a task to
681   // pump the write loop.
682   void PumpWriteLoop(WriteState expected_write_state, int result);
683
684   // Iff the write loop is not currently active, posts a callback into
685   // PumpWriteLoop().
686   void MaybePostWriteLoop();
687
688   // Advance the WriteState state machine. |expected_write_state| is
689   // the expected starting write state.
690   //
691   // This function must always be called via PumpWriteLoop().
692   int DoWriteLoop(WriteState expected_write_state, int result);
693   // The implementations of the states of the WriteState state machine.
694   int DoWrite();
695   int DoWriteComplete(int result);
696
697   // TODO(akalin): Rename the Send* and Write* functions below to
698   // Enqueue*.
699
700   // Send initial data. Called when a connection is successfully
701   // established in InitializeWithSocket() and
702   // |enable_sending_initial_data_| is true.
703   void SendInitialData();
704
705   // Helper method to send a SETTINGS frame.
706   void SendSettings(const SettingsMap& settings);
707
708   // Handle SETTING.  Either when we send settings, or when we receive a
709   // SETTINGS control frame, update our SpdySession accordingly.
710   void HandleSetting(uint32 id, uint32 value);
711
712   // Adjust the send window size of all ActiveStreams and PendingStreamRequests.
713   void UpdateStreamsSendWindowSize(int32 delta_window_size);
714
715   // Send the PING (preface-PING) frame.
716   void SendPrefacePingIfNoneInFlight();
717
718   // Send PING if there are no PINGs in flight and we haven't heard from server.
719   void SendPrefacePing();
720
721   // Send a single WINDOW_UPDATE frame.
722   void SendWindowUpdateFrame(SpdyStreamId stream_id, uint32 delta_window_size,
723                              RequestPriority priority);
724
725   // Send the PING frame.
726   void WritePingFrame(uint32 unique_id, bool is_ack);
727
728   // Post a CheckPingStatus call after delay. Don't post if there is already
729   // CheckPingStatus running.
730   void PlanToCheckPingStatus();
731
732   // Check the status of the connection. It calls |CloseSessionOnError| if we
733   // haven't received any data in |kHungInterval| time period.
734   void CheckPingStatus(base::TimeTicks last_check_time);
735
736   // Get a new stream id.
737   SpdyStreamId GetNewStreamId();
738
739   // Pushes the given frame with the given priority into the write
740   // queue for the session.
741   void EnqueueSessionWrite(RequestPriority priority,
742                            SpdyFrameType frame_type,
743                            scoped_ptr<SpdyFrame> frame);
744
745   // Puts |producer| associated with |stream| onto the write queue
746   // with the given priority.
747   void EnqueueWrite(RequestPriority priority,
748                     SpdyFrameType frame_type,
749                     scoped_ptr<SpdyBufferProducer> producer,
750                     const base::WeakPtr<SpdyStream>& stream);
751
752   // Inserts a newly-created stream into |created_streams_|.
753   void InsertCreatedStream(scoped_ptr<SpdyStream> stream);
754
755   // Activates |stream| (which must be in |created_streams_|) by
756   // assigning it an ID and returns it.
757   scoped_ptr<SpdyStream> ActivateCreatedStream(SpdyStream* stream);
758
759   // Inserts a newly-activated stream into |active_streams_|.
760   void InsertActivatedStream(scoped_ptr<SpdyStream> stream);
761
762   // Remove all internal references to |stream|, call OnClose() on it,
763   // and process any pending stream requests before deleting it.  Note
764   // that |stream| may hold the last reference to the session.
765   void DeleteStream(scoped_ptr<SpdyStream> stream, int status);
766
767   // Check if we have a pending pushed-stream for this url
768   // Returns the stream if found (and returns it from the pending
769   // list). Returns NULL otherwise.
770   base::WeakPtr<SpdyStream> GetActivePushStream(const GURL& url);
771
772   // Delegates to |stream->OnInitialResponseHeadersReceived()|. If an
773   // error is returned, the last reference to |this| may have been
774   // released.
775   int OnInitialResponseHeadersReceived(const SpdyHeaderBlock& response_headers,
776                                        base::Time response_time,
777                                        base::TimeTicks recv_first_byte_time,
778                                        SpdyStream* stream);
779
780   void RecordPingRTTHistogram(base::TimeDelta duration);
781   void RecordHistograms();
782   void RecordProtocolErrorHistogram(SpdyProtocolErrorDetails details);
783
784   // DCHECKs that |availability_state_| >= STATE_GOING_AWAY, that
785   // there are no pending stream creation requests, and that there are
786   // no created streams.
787   void DcheckGoingAway() const;
788
789   // Calls DcheckGoingAway(), then DCHECKs that |availability_state_|
790   // == STATE_DRAINING, |error_on_close_| has a valid value, and that there
791   // are no active streams or unclaimed pushed streams.
792   void DcheckDraining() const;
793
794   // If the session is already draining, does nothing. Otherwise, moves
795   // the session to the draining state.
796   void DoDrainSession(Error err, const std::string& description);
797
798   // Called right before closing a (possibly-inactive) stream for a
799   // reason other than being requested to by the stream.
800   void LogAbandonedStream(SpdyStream* stream, Error status);
801
802   // Called right before closing an active stream for a reason other
803   // than being requested to by the stream.
804   void LogAbandonedActiveStream(ActiveStreamMap::const_iterator it,
805                                 Error status);
806
807   // Invokes a user callback for stream creation.  We provide this method so it
808   // can be deferred to the MessageLoop, so we avoid re-entrancy problems.
809   void CompleteStreamRequest(
810       const base::WeakPtr<SpdyStreamRequest>& pending_request);
811
812   // Remove old unclaimed pushed streams.
813   void DeleteExpiredPushedStreams();
814
815   // BufferedSpdyFramerVisitorInterface:
816   void OnError(SpdyFramer::SpdyError error_code) override;
817   void OnStreamError(SpdyStreamId stream_id,
818                      const std::string& description) override;
819   void OnPing(SpdyPingId unique_id, bool is_ack) override;
820   void OnRstStream(SpdyStreamId stream_id, SpdyRstStreamStatus status) override;
821   void OnGoAway(SpdyStreamId last_accepted_stream_id,
822                 SpdyGoAwayStatus status) override;
823   void OnDataFrameHeader(SpdyStreamId stream_id,
824                          size_t length,
825                          bool fin) override;
826   void OnStreamFrameData(SpdyStreamId stream_id,
827                          const char* data,
828                          size_t len,
829                          bool fin) override;
830   void OnSettings(bool clear_persisted) override;
831   void OnSetting(SpdySettingsIds id, uint8 flags, uint32 value) override;
832   void OnWindowUpdate(SpdyStreamId stream_id,
833                       uint32 delta_window_size) override;
834   void OnPushPromise(SpdyStreamId stream_id,
835                      SpdyStreamId promised_stream_id,
836                      const SpdyHeaderBlock& headers) override;
837   void OnSynStream(SpdyStreamId stream_id,
838                    SpdyStreamId associated_stream_id,
839                    SpdyPriority priority,
840                    bool fin,
841                    bool unidirectional,
842                    const SpdyHeaderBlock& headers) override;
843   void OnSynReply(SpdyStreamId stream_id,
844                   bool fin,
845                   const SpdyHeaderBlock& headers) override;
846   void OnHeaders(SpdyStreamId stream_id,
847                  bool has_priority,
848                  SpdyPriority priority,
849                  bool fin,
850                  const SpdyHeaderBlock& headers) override;
851   bool OnUnknownFrame(SpdyStreamId stream_id, int frame_type) override;
852
853   // SpdyFramerDebugVisitorInterface
854   void OnSendCompressedFrame(SpdyStreamId stream_id,
855                              SpdyFrameType type,
856                              size_t payload_len,
857                              size_t frame_len) override;
858   void OnReceiveCompressedFrame(SpdyStreamId stream_id,
859                                 SpdyFrameType type,
860                                 size_t frame_len) override;
861
862   // Called when bytes are consumed from a SpdyBuffer for a DATA frame
863   // that is to be written or is being written. Increases the send
864   // window size accordingly if some or all of the SpdyBuffer is being
865   // discarded.
866   //
867   // If session flow control is turned off, this must not be called.
868   void OnWriteBufferConsumed(size_t frame_payload_size,
869                              size_t consume_size,
870                              SpdyBuffer::ConsumeSource consume_source);
871
872   // Called by OnWindowUpdate() (which is in turn called by the
873   // framer) to increase this session's send window size by
874   // |delta_window_size| from a WINDOW_UPDATE frome, which must be at
875   // least 1. If |delta_window_size| would cause this session's send
876   // window size to overflow, does nothing.
877   //
878   // If session flow control is turned off, this must not be called.
879   void IncreaseSendWindowSize(int32 delta_window_size);
880
881   // If session flow control is turned on, called by CreateDataFrame()
882   // (which is in turn called by a stream) to decrease this session's
883   // send window size by |delta_window_size|, which must be at least 1
884   // and at most kMaxSpdyFrameChunkSize.  |delta_window_size| must not
885   // cause this session's send window size to go negative.
886   //
887   // If session flow control is turned off, this must not be called.
888   void DecreaseSendWindowSize(int32 delta_window_size);
889
890   // Called when bytes are consumed by the delegate from a SpdyBuffer
891   // containing received data. Increases the receive window size
892   // accordingly.
893   //
894   // If session flow control is turned off, this must not be called.
895   void OnReadBufferConsumed(size_t consume_size,
896                             SpdyBuffer::ConsumeSource consume_source);
897
898   // Called by OnReadBufferConsume to increase this session's receive
899   // window size by |delta_window_size|, which must be at least 1 and
900   // must not cause this session's receive window size to overflow,
901   // possibly also sending a WINDOW_UPDATE frame. Also called during
902   // initialization to set the initial receive window size.
903   //
904   // If session flow control is turned off, this must not be called.
905   void IncreaseRecvWindowSize(int32 delta_window_size);
906
907   // Called by OnStreamFrameData (which is in turn called by the
908   // framer) to decrease this session's receive window size by
909   // |delta_window_size|, which must be at least 1 and must not cause
910   // this session's receive window size to go negative.
911   //
912   // If session flow control is turned off, this must not be called.
913   void DecreaseRecvWindowSize(int32 delta_window_size);
914
915   // Queue a send-stalled stream for possibly resuming once we're not
916   // send-stalled anymore.
917   void QueueSendStalledStream(const SpdyStream& stream);
918
919   // Go through the queue of send-stalled streams and try to resume as
920   // many as possible.
921   void ResumeSendStalledStreams();
922
923   // Returns the next stream to possibly resume, or 0 if the queue is
924   // empty.
925   SpdyStreamId PopStreamToPossiblyResume();
926
927   // --------------------------
928   // Helper methods for testing
929   // --------------------------
930
931   void set_connection_at_risk_of_loss_time(base::TimeDelta duration) {
932     connection_at_risk_of_loss_time_ = duration;
933   }
934
935   void set_hung_interval(base::TimeDelta duration) {
936     hung_interval_ = duration;
937   }
938
939   void set_max_concurrent_pushed_streams(size_t value) {
940     max_concurrent_pushed_streams_ = value;
941   }
942
943   int64 pings_in_flight() const { return pings_in_flight_; }
944
945   uint32 next_ping_id() const { return next_ping_id_; }
946
947   base::TimeTicks last_activity_time() const { return last_activity_time_; }
948
949   bool check_ping_status_pending() const { return check_ping_status_pending_; }
950
951   size_t max_concurrent_streams() const { return max_concurrent_streams_; }
952
953   // Returns the SSLClientSocket that this SPDY session sits on top of,
954   // or NULL, if the transport is not SSL.
955   SSLClientSocket* GetSSLClientSocket() const;
956
957   // Whether Do{Read,Write}Loop() is in the call stack. Useful for
958   // making sure we don't destroy ourselves prematurely in that case.
959   bool in_io_loop_;
960
961   // The key used to identify this session.
962   const SpdySessionKey spdy_session_key_;
963
964   // Set set of SpdySessionKeys for which this session has serviced
965   // requests.
966   std::set<SpdySessionKey> pooled_aliases_;
967
968   // |pool_| owns us, therefore its lifetime must exceed ours.  We set
969   // this to NULL after we are removed from the pool.
970   SpdySessionPool* pool_;
971   const base::WeakPtr<HttpServerProperties> http_server_properties_;
972
973   TransportSecurityState* transport_security_state_;
974
975   // The socket handle for this session.
976   scoped_ptr<ClientSocketHandle> connection_;
977
978   // The read buffer used to read data from the socket.
979   scoped_refptr<IOBuffer> read_buffer_;
980
981   SpdyStreamId stream_hi_water_mark_;  // The next stream id to use.
982
983   // Used to ensure the server increments push stream ids correctly.
984   SpdyStreamId last_accepted_push_stream_id_;
985
986   // Queue, for each priority, of pending stream requests that have
987   // not yet been satisfied.
988   PendingStreamRequestQueue pending_create_stream_queues_[NUM_PRIORITIES];
989
990   // Map from stream id to all active streams.  Streams are active in the sense
991   // that they have a consumer (typically SpdyNetworkTransaction and regardless
992   // of whether or not there is currently any ongoing IO [might be waiting for
993   // the server to start pushing the stream]) or there are still network events
994   // incoming even though the consumer has already gone away (cancellation).
995   //
996   // |active_streams_| owns all its SpdyStream objects.
997   //
998   // TODO(willchan): Perhaps we should separate out cancelled streams and move
999   // them into a separate ActiveStreamMap, and not deliver network events to
1000   // them?
1001   ActiveStreamMap active_streams_;
1002
1003   // (Bijective) map from the URL to the ID of the streams that have
1004   // already started to be pushed by the server, but do not have
1005   // consumers yet. Contains a subset of |active_streams_|.
1006   PushedStreamMap unclaimed_pushed_streams_;
1007
1008   // Set of all created streams but that have not yet sent any frames.
1009   //
1010   // |created_streams_| owns all its SpdyStream objects.
1011   CreatedStreamSet created_streams_;
1012
1013   // Number of pushed streams. All active streams are stored in
1014   // |active_streams_|, but it's better to know the number of push streams
1015   // without traversing the whole collection.
1016   size_t num_pushed_streams_;
1017
1018   // Number of active pushed streams in |active_streams_|, i.e. not in reserved
1019   // remote state. Streams in reserved state are not counted towards any
1020   // concurrency limits.
1021   size_t num_active_pushed_streams_;
1022
1023   // The write queue.
1024   SpdyWriteQueue write_queue_;
1025
1026   // Data for the frame we are currently sending.
1027
1028   // The buffer we're currently writing.
1029   scoped_ptr<SpdyBuffer> in_flight_write_;
1030   // The type of the frame in |in_flight_write_|.
1031   SpdyFrameType in_flight_write_frame_type_;
1032   // The size of the frame in |in_flight_write_|.
1033   size_t in_flight_write_frame_size_;
1034   // The stream to notify when |in_flight_write_| has been written to
1035   // the socket completely.
1036   base::WeakPtr<SpdyStream> in_flight_write_stream_;
1037
1038   // Flag if we're using an SSL connection for this SpdySession.
1039   bool is_secure_;
1040
1041   // Certificate error code when using a secure connection.
1042   int certificate_error_code_;
1043
1044   // Spdy Frame state.
1045   scoped_ptr<BufferedSpdyFramer> buffered_spdy_framer_;
1046
1047   // The state variables.
1048   AvailabilityState availability_state_;
1049   ReadState read_state_;
1050   WriteState write_state_;
1051
1052   // If the session is closing (i.e., |availability_state_| is STATE_DRAINING),
1053   // then |error_on_close_| holds the error with which it was closed, which
1054   // may be OK (upon a polite GOAWAY) or an error < ERR_IO_PENDING otherwise.
1055   // Initialized to OK.
1056   Error error_on_close_;
1057
1058   // Limits
1059   size_t max_concurrent_streams_;  // 0 if no limit
1060   size_t max_concurrent_streams_limit_;
1061   size_t max_concurrent_pushed_streams_;
1062
1063   // Some statistics counters for the session.
1064   int streams_initiated_count_;
1065   int streams_pushed_count_;
1066   int streams_pushed_and_claimed_count_;
1067   int streams_abandoned_count_;
1068
1069   // |total_bytes_received_| keeps track of all the bytes read by the
1070   // SpdySession. It is used by the |Net.SpdySettingsCwnd...| histograms.
1071   int total_bytes_received_;
1072
1073   bool sent_settings_;      // Did this session send settings when it started.
1074   bool received_settings_;  // Did this session receive at least one settings
1075                             // frame.
1076   int stalled_streams_;     // Count of streams that were ever stalled.
1077
1078   // Count of all pings on the wire, for which we have not gotten a response.
1079   int64 pings_in_flight_;
1080
1081   // This is the next ping_id (unique_id) to be sent in PING frame.
1082   uint32 next_ping_id_;
1083
1084   // This is the last time we have sent a PING.
1085   base::TimeTicks last_ping_sent_time_;
1086
1087   // This is the last time we had activity in the session.
1088   base::TimeTicks last_activity_time_;
1089
1090   // This is the length of the last compressed frame.
1091   size_t last_compressed_frame_len_;
1092
1093   // This is the next time that unclaimed push streams should be checked for
1094   // expirations.
1095   base::TimeTicks next_unclaimed_push_stream_sweep_time_;
1096
1097   // Indicate if we have already scheduled a delayed task to check the ping
1098   // status.
1099   bool check_ping_status_pending_;
1100
1101   // Whether to send the (HTTP/2) connection header prefix.
1102   bool send_connection_header_prefix_;
1103
1104   // The (version-dependent) flow control state.
1105   FlowControlState flow_control_state_;
1106
1107   // Initial send window size for this session's streams. Can be
1108   // changed by an arriving SETTINGS frame. Newly created streams use
1109   // this value for the initial send window size.
1110   int32 stream_initial_send_window_size_;
1111
1112   // Initial receive window size for this session's streams. There are
1113   // plans to add a command line switch that would cause a SETTINGS
1114   // frame with window size announcement to be sent on startup. Newly
1115   // created streams will use this value for the initial receive
1116   // window size.
1117   int32 stream_initial_recv_window_size_;
1118
1119   // Session flow control variables. All zero unless session flow
1120   // control is turned on.
1121   int32 session_send_window_size_;
1122   int32 session_recv_window_size_;
1123   int32 session_unacked_recv_window_bytes_;
1124
1125   // A queue of stream IDs that have been send-stalled at some point
1126   // in the past.
1127   std::deque<SpdyStreamId> stream_send_unstall_queue_[NUM_PRIORITIES];
1128
1129   BoundNetLog net_log_;
1130
1131   // Outside of tests, these should always be true.
1132   bool verify_domain_authentication_;
1133   bool enable_sending_initial_data_;
1134   bool enable_compression_;
1135   bool enable_ping_based_connection_checking_;
1136
1137   // The SPDY protocol used. Always between kProtoSPDYMinimumVersion and
1138   // kProtoSPDYMaximumVersion.
1139   NextProto protocol_;
1140
1141   // |connection_at_risk_of_loss_time_| is an optimization to avoid sending
1142   // wasteful preface pings (when we just got some data).
1143   //
1144   // If it is zero (the most conservative figure), then we always send the
1145   // preface ping (when none are in flight).
1146   //
1147   // It is common for TCP/IP sessions to time out in about 3-5 minutes.
1148   // Certainly if it has been more than 3 minutes, we do want to send a preface
1149   // ping.
1150   //
1151   // We don't think any connection will time out in under about 10 seconds. So
1152   // this might as well be set to something conservative like 10 seconds. Later,
1153   // we could adjust it to send fewer pings perhaps.
1154   base::TimeDelta connection_at_risk_of_loss_time_;
1155
1156   // The amount of time that we are willing to tolerate with no activity (of any
1157   // form), while there is a ping in flight, before we declare the connection to
1158   // be hung. TODO(rtenneti): When hung, instead of resetting connection, race
1159   // to build a new connection, and see if that completes before we (finally)
1160   // get a PING response (http://crbug.com/127812).
1161   base::TimeDelta hung_interval_;
1162
1163   // This SPDY proxy is allowed to push resources from origins that are
1164   // different from those of their associated streams.
1165   HostPortPair trusted_spdy_proxy_;
1166
1167   TimeFunc time_func_;
1168
1169   // Used for posting asynchronous IO tasks.  We use this even though
1170   // SpdySession is refcounted because we don't need to keep the SpdySession
1171   // alive if the last reference is within a RunnableMethod.  Just revoke the
1172   // method.
1173   base::WeakPtrFactory<SpdySession> weak_factory_;
1174 };
1175
1176 }  // namespace net
1177
1178 #endif  // NET_SPDY_SPDY_SESSION_H_