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