1 // Copyright (c) 2011 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 #pragma once 8 9 #include <deque> 10 #include <list> 11 #include <map> 12 #include <queue> 13 #include <string> 14 15 #include "base/gtest_prod_util.h" 16 #include "base/memory/linked_ptr.h" 17 #include "base/memory/ref_counted.h" 18 #include "base/task.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_log.h" 23 #include "net/base/request_priority.h" 24 #include "net/base/ssl_config_service.h" 25 #include "net/base/upload_data_stream.h" 26 #include "net/socket/client_socket.h" 27 #include "net/socket/client_socket_handle.h" 28 #include "net/spdy/spdy_framer.h" 29 #include "net/spdy/spdy_io_buffer.h" 30 #include "net/spdy/spdy_protocol.h" 31 #include "net/spdy/spdy_session_pool.h" 32 33 namespace net { 34 35 // This is somewhat arbitrary and not really fixed, but it will always work 36 // reasonably with ethernet. Chop the world into 2-packet chunks. This is 37 // somewhat arbitrary, but is reasonably small and ensures that we elicit 38 // ACKs quickly from TCP (because TCP tries to only ACK every other packet). 39 const int kMss = 1430; 40 const int kMaxSpdyFrameChunkSize = (2 * kMss) - spdy::SpdyFrame::size(); 41 42 class BoundNetLog; 43 class SpdySettingsStorage; 44 class SpdyStream; 45 class SSLInfo; 46 47 class SpdySession : public base::RefCounted<SpdySession>, 48 public spdy::SpdyFramerVisitorInterface { 49 public: 50 // Create a new SpdySession. 51 // |host_port_proxy_pair| is the host/port that this session connects to, and 52 // the proxy configuration settings that it's using. 53 // |spdy_session_pool| is the SpdySessionPool that owns us. Its lifetime must 54 // strictly be greater than |this|. 55 // |session| is the HttpNetworkSession. |net_log| is the NetLog that we log 56 // network events to. 57 SpdySession(const HostPortProxyPair& host_port_proxy_pair, 58 SpdySessionPool* spdy_session_pool, 59 SpdySettingsStorage* spdy_settings, 60 NetLog* net_log); 61 62 const HostPortPair& host_port_pair() const { 63 return host_port_proxy_pair_.first; 64 } 65 const HostPortProxyPair& host_port_proxy_pair() const { 66 return host_port_proxy_pair_; 67 } 68 69 // Get a pushed stream for a given |url|. 70 // If the server initiates a stream, it might already exist for a given path. 71 // The server might also not have initiated the stream yet, but indicated it 72 // will via X-Associated-Content. Writes the stream out to |spdy_stream|. 73 // Returns a net error code. 74 int GetPushStream( 75 const GURL& url, 76 scoped_refptr<SpdyStream>* spdy_stream, 77 const BoundNetLog& stream_net_log); 78 79 // Create a new stream for a given |url|. Writes it out to |spdy_stream|. 80 // Returns a net error code, possibly ERR_IO_PENDING. 81 int CreateStream( 82 const GURL& url, 83 RequestPriority priority, 84 scoped_refptr<SpdyStream>* spdy_stream, 85 const BoundNetLog& stream_net_log, 86 CompletionCallback* callback); 87 88 // Remove PendingCreateStream objects on transaction deletion 89 void CancelPendingCreateStreams(const scoped_refptr<SpdyStream>* spdy_stream); 90 91 // Used by SpdySessionPool to initialize with a pre-existing SSL socket. For 92 // testing, setting is_secure to false allows initialization with a 93 // pre-existing TCP socket. 94 // Returns OK on success, or an error on failure. 95 net::Error InitializeWithSocket(ClientSocketHandle* connection, 96 bool is_secure, 97 int certificate_error_code); 98 99 // Check to see if this SPDY session can support an additional domain. 100 // If the session is un-authenticated, then this call always returns true. 101 // For SSL-based sessions, verifies that the certificate in use by this 102 // session provides authentication for the domain. 103 // NOTE: This function can have false negatives on some platforms. 104 bool VerifyDomainAuthentication(const std::string& domain); 105 106 // Send the SYN frame for |stream_id|. 107 int WriteSynStream( 108 spdy::SpdyStreamId stream_id, 109 RequestPriority priority, 110 spdy::SpdyControlFlags flags, 111 const linked_ptr<spdy::SpdyHeaderBlock>& headers); 112 113 // Write a data frame to the stream. 114 // Used to create and queue a data frame for the given stream. 115 int WriteStreamData(spdy::SpdyStreamId stream_id, net::IOBuffer* data, 116 int len, 117 spdy::SpdyDataFlags flags); 118 119 // Close a stream. 120 void CloseStream(spdy::SpdyStreamId stream_id, int status); 121 122 // Reset a stream by sending a RST_STREAM frame with given status code. 123 // Also closes the stream. Was not piggybacked to CloseStream since not 124 // all of the calls to CloseStream necessitate sending a RST_STREAM. 125 void ResetStream(spdy::SpdyStreamId stream_id, spdy::SpdyStatusCodes status); 126 127 // Check if a stream is active. 128 bool IsStreamActive(spdy::SpdyStreamId stream_id) const; 129 130 // The LoadState is used for informing the user of the current network 131 // status, such as "resolving host", "connecting", etc. 132 LoadState GetLoadState() const; 133 134 // Fills SSL info in |ssl_info| and returns true when SSL is in use. 135 bool GetSSLInfo(SSLInfo* ssl_info, bool* was_npn_negotiated); 136 137 // Fills SSL Certificate Request info |cert_request_info| and returns 138 // true when SSL is in use. 139 bool GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info); 140 141 // Enable or disable SSL. 142 static void SetSSLMode(bool enable) { use_ssl_ = enable; } 143 static bool SSLMode() { return use_ssl_; } 144 145 // Enable or disable flow control. 146 static void set_flow_control(bool enable) { use_flow_control_ = enable; } 147 static bool flow_control() { return use_flow_control_; } 148 149 // Sets the max concurrent streams per session. 150 static void set_max_concurrent_streams(size_t value) { 151 max_concurrent_stream_limit_ = value; 152 } 153 static size_t max_concurrent_streams() { 154 return max_concurrent_stream_limit_; 155 } 156 157 // Send WINDOW_UPDATE frame, called by a stream whenever receive window 158 // size is increased. 159 void SendWindowUpdate(spdy::SpdyStreamId stream_id, int delta_window_size); 160 161 // If session is closed, no new streams/transactions should be created. 162 bool IsClosed() const { return state_ == CLOSED; } 163 164 // Closes this session. This will close all active streams and mark 165 // the session as permanently closed. 166 // |err| should not be OK; this function is intended to be called on 167 // error. 168 // |remove_from_pool| indicates whether to also remove the session from the 169 // session pool. 170 void CloseSessionOnError(net::Error err, bool remove_from_pool); 171 172 // Retrieves information on the current state of the SPDY session as a 173 // Value. Caller takes possession of the returned value. 174 Value* GetInfoAsValue() const; 175 176 // Indicates whether the session is being reused after having successfully 177 // used to send/receive data in the past. 178 bool IsReused() const { 179 return frames_received_ > 0; 180 } 181 182 // Returns true if the underlying transport socket ever had any reads or 183 // writes. 184 bool WasEverUsed() const { 185 return connection_->socket()->WasEverUsed(); 186 } 187 188 void set_spdy_session_pool(SpdySessionPool* pool) { 189 spdy_session_pool_ = NULL; 190 } 191 192 // Returns true if session is not currently active 193 bool is_active() const { 194 return !active_streams_.empty(); 195 } 196 197 // Access to the number of active and pending streams. These are primarily 198 // available for testing and diagnostics. 199 size_t num_active_streams() const { return active_streams_.size(); } 200 size_t num_unclaimed_pushed_streams() const { 201 return unclaimed_pushed_streams_.size(); 202 } 203 204 const BoundNetLog& net_log() const { return net_log_; } 205 206 int GetPeerAddress(AddressList* address) const; 207 int GetLocalAddress(IPEndPoint* address) const; 208 209 private: 210 friend class base::RefCounted<SpdySession>; 211 FRIEND_TEST_ALL_PREFIXES(SpdySessionTest, GetActivePushStream); 212 213 struct PendingCreateStream { 214 PendingCreateStream(const GURL& url, RequestPriority priority, 215 scoped_refptr<SpdyStream>* spdy_stream, 216 const BoundNetLog& stream_net_log, 217 CompletionCallback* callback) 218 : url(&url), priority(priority), spdy_stream(spdy_stream), 219 stream_net_log(&stream_net_log), callback(callback) { } 220 221 const GURL* url; 222 RequestPriority priority; 223 scoped_refptr<SpdyStream>* spdy_stream; 224 const BoundNetLog* stream_net_log; 225 CompletionCallback* callback; 226 }; 227 typedef std::queue<PendingCreateStream, std::list< PendingCreateStream> > 228 PendingCreateStreamQueue; 229 typedef std::map<int, scoped_refptr<SpdyStream> > ActiveStreamMap; 230 // Only HTTP push a stream. 231 typedef std::map<std::string, scoped_refptr<SpdyStream> > PushedStreamMap; 232 typedef std::priority_queue<SpdyIOBuffer> OutputQueue; 233 234 struct CallbackResultPair { 235 CallbackResultPair() : callback(NULL), result(OK) {} 236 CallbackResultPair(CompletionCallback* callback_in, int result_in) 237 : callback(callback_in), result(result_in) {} 238 239 CompletionCallback* callback; 240 int result; 241 }; 242 243 typedef std::map<const scoped_refptr<SpdyStream>*, CallbackResultPair> 244 PendingCallbackMap; 245 246 enum State { 247 IDLE, 248 CONNECTING, 249 CONNECTED, 250 CLOSED 251 }; 252 253 enum { kDefaultMaxConcurrentStreams = 10 }; 254 255 virtual ~SpdySession(); 256 257 void ProcessPendingCreateStreams(); 258 int CreateStreamImpl( 259 const GURL& url, 260 RequestPriority priority, 261 scoped_refptr<SpdyStream>* spdy_stream, 262 const BoundNetLog& stream_net_log); 263 264 // Control frame handlers. 265 void OnSyn(const spdy::SpdySynStreamControlFrame& frame, 266 const linked_ptr<spdy::SpdyHeaderBlock>& headers); 267 void OnSynReply(const spdy::SpdySynReplyControlFrame& frame, 268 const linked_ptr<spdy::SpdyHeaderBlock>& headers); 269 void OnHeaders(const spdy::SpdyHeadersControlFrame& frame, 270 const linked_ptr<spdy::SpdyHeaderBlock>& headers); 271 void OnRst(const spdy::SpdyRstStreamControlFrame& frame); 272 void OnGoAway(const spdy::SpdyGoAwayControlFrame& frame); 273 void OnSettings(const spdy::SpdySettingsControlFrame& frame); 274 void OnWindowUpdate(const spdy::SpdyWindowUpdateControlFrame& frame); 275 276 // IO Callbacks 277 void OnReadComplete(int result); 278 void OnWriteComplete(int result); 279 280 // Send relevant SETTINGS. This is generally called on connection setup. 281 void SendSettings(); 282 283 // Handle SETTINGS. Either when we send settings, or when we receive a 284 // SETTINGS ontrol frame, update our SpdySession accordingly. 285 void HandleSettings(const spdy::SpdySettings& settings); 286 287 // Start reading from the socket. 288 // Returns OK on success, or an error on failure. 289 net::Error ReadSocket(); 290 291 // Write current data to the socket. 292 void WriteSocketLater(); 293 void WriteSocket(); 294 295 // Get a new stream id. 296 int GetNewStreamId(); 297 298 // Queue a frame for sending. 299 // |frame| is the frame to send. 300 // |priority| is the priority for insertion into the queue. 301 // |stream| is the stream which this IO is associated with (or NULL). 302 void QueueFrame(spdy::SpdyFrame* frame, spdy::SpdyPriority priority, 303 SpdyStream* stream); 304 305 // Track active streams in the active stream list. 306 void ActivateStream(SpdyStream* stream); 307 void DeleteStream(spdy::SpdyStreamId id, int status); 308 309 // Removes this session from the session pool. 310 void RemoveFromPool(); 311 312 // Check if we have a pending pushed-stream for this url 313 // Returns the stream if found (and returns it from the pending 314 // list), returns NULL otherwise. 315 scoped_refptr<SpdyStream> GetActivePushStream(const std::string& url); 316 317 // Calls OnResponseReceived(). 318 // Returns true if successful. 319 bool Respond(const spdy::SpdyHeaderBlock& headers, 320 const scoped_refptr<SpdyStream> stream); 321 322 void RecordHistograms(); 323 324 // Closes all streams. Used as part of shutdown. 325 void CloseAllStreams(net::Error status); 326 327 // Invokes a user callback for stream creation. We provide this method so it 328 // can be deferred to the MessageLoop, so we avoid re-entrancy problems. 329 void InvokeUserStreamCreationCallback(scoped_refptr<SpdyStream>* stream); 330 331 // SpdyFramerVisitorInterface: 332 virtual void OnError(spdy::SpdyFramer*); 333 virtual void OnStreamFrameData(spdy::SpdyStreamId stream_id, 334 const char* data, 335 size_t len); 336 virtual void OnControl(const spdy::SpdyControlFrame* frame); 337 338 // Callbacks for the Spdy session. 339 CompletionCallbackImpl<SpdySession> read_callback_; 340 CompletionCallbackImpl<SpdySession> write_callback_; 341 342 // Used for posting asynchronous IO tasks. We use this even though 343 // SpdySession is refcounted because we don't need to keep the SpdySession 344 // alive if the last reference is within a RunnableMethod. Just revoke the 345 // method. 346 ScopedRunnableMethodFactory<SpdySession> method_factory_; 347 348 // Map of the SpdyStreams for which we have a pending Task to invoke a 349 // callback. This is necessary since, before we invoke said callback, it's 350 // possible that the request is cancelled. 351 PendingCallbackMap pending_callback_map_; 352 353 // The domain this session is connected to. 354 const HostPortProxyPair host_port_proxy_pair_; 355 356 // |spdy_session_pool_| owns us, therefore its lifetime must exceed ours. We 357 // set this to NULL after we are removed from the pool. 358 SpdySessionPool* spdy_session_pool_; 359 SpdySettingsStorage* const spdy_settings_; 360 361 // The socket handle for this session. 362 scoped_ptr<ClientSocketHandle> connection_; 363 364 // The read buffer used to read data from the socket. 365 scoped_refptr<IOBuffer> read_buffer_; 366 bool read_pending_; 367 368 int stream_hi_water_mark_; // The next stream id to use. 369 370 // Queue, for each priority, of pending Create Streams that have not 371 // yet been satisfied 372 PendingCreateStreamQueue create_stream_queues_[NUM_PRIORITIES]; 373 374 // Map from stream id to all active streams. Streams are active in the sense 375 // that they have a consumer (typically SpdyNetworkTransaction and regardless 376 // of whether or not there is currently any ongoing IO [might be waiting for 377 // the server to start pushing the stream]) or there are still network events 378 // incoming even though the consumer has already gone away (cancellation). 379 // TODO(willchan): Perhaps we should separate out cancelled streams and move 380 // them into a separate ActiveStreamMap, and not deliver network events to 381 // them? 382 ActiveStreamMap active_streams_; 383 // Map of all the streams that have already started to be pushed by the 384 // server, but do not have consumers yet. 385 PushedStreamMap unclaimed_pushed_streams_; 386 387 // As we gather data to be sent, we put it into the output queue. 388 OutputQueue queue_; 389 390 // The packet we are currently sending. 391 bool write_pending_; // Will be true when a write is in progress. 392 SpdyIOBuffer in_flight_write_; // This is the write buffer in progress. 393 394 // Flag if we have a pending message scheduled for WriteSocket. 395 bool delayed_write_pending_; 396 397 // Flag if we're using an SSL connection for this SpdySession. 398 bool is_secure_; 399 400 // Certificate error code when using a secure connection. 401 int certificate_error_code_; 402 403 // Spdy Frame state. 404 spdy::SpdyFramer spdy_framer_; 405 406 // If an error has occurred on the session, the session is effectively 407 // dead. Record this error here. When no error has occurred, |error_| will 408 // be OK. 409 net::Error error_; 410 State state_; 411 412 // Limits 413 size_t max_concurrent_streams_; // 0 if no limit 414 415 // Some statistics counters for the session. 416 int streams_initiated_count_; 417 int streams_pushed_count_; 418 int streams_pushed_and_claimed_count_; 419 int streams_abandoned_count_; 420 int frames_received_; 421 int bytes_received_; 422 bool sent_settings_; // Did this session send settings when it started. 423 bool received_settings_; // Did this session receive at least one settings 424 // frame. 425 int stalled_streams_; // Count of streams that were ever stalled. 426 427 // Initial send window size for the session; can be changed by an 428 // arriving SETTINGS frame; newly created streams use this value for the 429 // initial send window size. 430 int initial_send_window_size_; 431 432 // Initial receive window size for the session; there are plans to add a 433 // command line switch that would cause a SETTINGS frame with window size 434 // announcement to be sent on startup; newly created streams will use 435 // this value for the initial receive window size. 436 int initial_recv_window_size_; 437 438 BoundNetLog net_log_; 439 440 static bool use_ssl_; 441 static bool use_flow_control_; 442 static size_t max_concurrent_stream_limit_; 443 }; 444 445 class NetLogSpdySynParameter : public NetLog::EventParameters { 446 public: 447 NetLogSpdySynParameter(const linked_ptr<spdy::SpdyHeaderBlock>& headers, 448 spdy::SpdyControlFlags flags, 449 spdy::SpdyStreamId id, 450 spdy::SpdyStreamId associated_stream); 451 452 const linked_ptr<spdy::SpdyHeaderBlock>& GetHeaders() const { 453 return headers_; 454 } 455 456 virtual Value* ToValue() const; 457 458 private: 459 virtual ~NetLogSpdySynParameter(); 460 461 const linked_ptr<spdy::SpdyHeaderBlock> headers_; 462 const spdy::SpdyControlFlags flags_; 463 const spdy::SpdyStreamId id_; 464 const spdy::SpdyStreamId associated_stream_; 465 466 DISALLOW_COPY_AND_ASSIGN(NetLogSpdySynParameter); 467 }; 468 469 } // namespace net 470 471 #endif // NET_SPDY_SPDY_SESSION_H_ 472