spdy_session.h 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  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. #ifndef NET_SPDY_SPDY_SESSION_H_
  5. #define NET_SPDY_SPDY_SESSION_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <map>
  9. #include <memory>
  10. #include <set>
  11. #include <string>
  12. #include <vector>
  13. #include "base/containers/circular_deque.h"
  14. #include "base/gtest_prod_util.h"
  15. #include "base/memory/raw_ptr.h"
  16. #include "base/memory/ref_counted.h"
  17. #include "base/memory/scoped_refptr.h"
  18. #include "base/memory/weak_ptr.h"
  19. #include "base/strings/string_piece.h"
  20. #include "base/time/time.h"
  21. #include "base/timer/timer.h"
  22. #include "net/base/completion_once_callback.h"
  23. #include "net/base/host_port_pair.h"
  24. #include "net/base/io_buffer.h"
  25. #include "net/base/load_states.h"
  26. #include "net/base/load_timing_info.h"
  27. #include "net/base/net_errors.h"
  28. #include "net/base/net_export.h"
  29. #include "net/base/network_change_notifier.h"
  30. #include "net/base/request_priority.h"
  31. #include "net/log/net_log_source.h"
  32. #include "net/socket/client_socket_pool.h"
  33. #include "net/socket/next_proto.h"
  34. #include "net/socket/ssl_client_socket.h"
  35. #include "net/socket/stream_socket.h"
  36. #include "net/spdy/buffered_spdy_framer.h"
  37. #include "net/spdy/http2_priority_dependencies.h"
  38. #include "net/spdy/http2_push_promise_index.h"
  39. #include "net/spdy/multiplexed_session.h"
  40. #include "net/spdy/server_push_delegate.h"
  41. #include "net/spdy/spdy_buffer.h"
  42. #include "net/spdy/spdy_session_pool.h"
  43. #include "net/spdy/spdy_stream.h"
  44. #include "net/spdy/spdy_write_queue.h"
  45. #include "net/ssl/ssl_config_service.h"
  46. #include "net/third_party/quiche/src/quiche/spdy/core/http2_header_block.h"
  47. #include "net/third_party/quiche/src/quiche/spdy/core/spdy_alt_svc_wire_format.h"
  48. #include "net/third_party/quiche/src/quiche/spdy/core/spdy_framer.h"
  49. #include "net/third_party/quiche/src/quiche/spdy/core/spdy_protocol.h"
  50. #include "net/traffic_annotation/network_traffic_annotation.h"
  51. #include "third_party/abseil-cpp/absl/types/optional.h"
  52. #include "url/gurl.h"
  53. #include "url/origin.h"
  54. #include "url/scheme_host_port.h"
  55. namespace net {
  56. namespace test {
  57. class SpdyStreamTest;
  58. }
  59. // TLS and other layers will chunk data at 16KB. Making the max frame size too
  60. // small will lead to increased CPU/byte cost and overhead on both client/server
  61. // due to excessive frames to process. Making this larger has diminishing
  62. // returns as the data will be chunked elsewhere. We also want to ensure we are
  63. // >= 2860B (~2* MSS => 2 packets) to avoid delayed ACKs. We will also account
  64. // for the frame header size of 9B to prevent fragmentation when this is added.
  65. // As a result we will use a 16KB - 9B max data frame size.
  66. const int kMaxSpdyFrameChunkSize = (16 * 1024) - 9;
  67. // Default value of spdy::SETTINGS_INITIAL_WINDOW_SIZE per protocol
  68. // specification. A session is always created with this initial window size.
  69. const int32_t kDefaultInitialWindowSize = 65535;
  70. // Maximum number of concurrent streams we will create, unless the server
  71. // sends a SETTINGS frame with a different value.
  72. const size_t kInitialMaxConcurrentStreams = 100;
  73. // If more than this many bytes have been read or more than that many
  74. // milliseconds have passed, return ERR_IO_PENDING from ReadLoop.
  75. const int kYieldAfterBytesRead = 32 * 1024;
  76. const int kYieldAfterDurationMilliseconds = 20;
  77. // First and last valid stream IDs. As we always act as the client,
  78. // start at 1 for the first stream id.
  79. const spdy::SpdyStreamId kFirstStreamId = 1;
  80. const spdy::SpdyStreamId kLastStreamId = 0x7fffffff;
  81. // Maximum number of capped frames that can be queued at any time.
  82. // We measured how many queued capped frames were ever in the
  83. // SpdyWriteQueue at one given time between 2019-08 and 2020-02.
  84. // The numbers showed that in 99.94% of cases it would always
  85. // stay below 10, and that it would exceed 1000 only in
  86. // 10^-8 of cases. Therefore we picked 10000 as a number that will
  87. // virtually never be hit in practice, while still preventing an
  88. // attacker from growing this queue unboundedly.
  89. const int kSpdySessionMaxQueuedCappedFrames = 10000;
  90. // Default time to delay sending small receive window updates (can be
  91. // configured through SetTimeToBufferSmallWindowUpdates()). Usually window
  92. // updates are sent when half of the receive window has been processed by
  93. // the client but in the case of a client that consumes the data slowly,
  94. // this strategy alone would make servers consider the connection or stream
  95. // idle.
  96. constexpr base::TimeDelta kDefaultTimeToBufferSmallWindowUpdates =
  97. base::Seconds(5);
  98. class NetLog;
  99. class NetworkQualityEstimator;
  100. class SpdyStream;
  101. class SSLInfo;
  102. class TransportSecurityState;
  103. // NOTE: There is an enum called SpdyProtocolErrorDetails2 (also with numeric
  104. // suffixes) in tools/metrics/histograms/enums.xml. Be sure to add new values
  105. // there also.
  106. enum SpdyProtocolErrorDetails {
  107. // http2::Http2DecoderAdapter::SpdyFramerError mappings.
  108. SPDY_ERROR_NO_ERROR = 0,
  109. SPDY_ERROR_INVALID_STREAM_ID = 38,
  110. SPDY_ERROR_INVALID_CONTROL_FRAME = 1,
  111. SPDY_ERROR_CONTROL_PAYLOAD_TOO_LARGE = 2,
  112. SPDY_ERROR_DECOMPRESS_FAILURE = 5,
  113. SPDY_ERROR_INVALID_PADDING = 39,
  114. SPDY_ERROR_INVALID_DATA_FRAME_FLAGS = 8,
  115. SPDY_ERROR_UNEXPECTED_FRAME = 31,
  116. SPDY_ERROR_INTERNAL_FRAMER_ERROR = 41,
  117. SPDY_ERROR_INVALID_CONTROL_FRAME_SIZE = 37,
  118. SPDY_ERROR_OVERSIZED_PAYLOAD = 40,
  119. // HttpDecoder or HttpDecoderAdapter error.
  120. SPDY_ERROR_HPACK_INDEX_VARINT_ERROR = 43,
  121. SPDY_ERROR_HPACK_NAME_LENGTH_VARINT_ERROR = 44,
  122. SPDY_ERROR_HPACK_VALUE_LENGTH_VARINT_ERROR = 45,
  123. SPDY_ERROR_HPACK_NAME_TOO_LONG = 46,
  124. SPDY_ERROR_HPACK_VALUE_TOO_LONG = 47,
  125. SPDY_ERROR_HPACK_NAME_HUFFMAN_ERROR = 48,
  126. SPDY_ERROR_HPACK_VALUE_HUFFMAN_ERROR = 49,
  127. SPDY_ERROR_HPACK_MISSING_DYNAMIC_TABLE_SIZE_UPDATE = 50,
  128. SPDY_ERROR_HPACK_INVALID_INDEX = 51,
  129. SPDY_ERROR_HPACK_INVALID_NAME_INDEX = 52,
  130. SPDY_ERROR_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_NOT_ALLOWED = 53,
  131. SPDY_ERROR_HPACK_INITIAL_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_LOW_WATER_MARK =
  132. 54,
  133. SPDY_ERROR_HPACK_DYNAMIC_TABLE_SIZE_UPDATE_IS_ABOVE_ACKNOWLEDGED_SETTING = 55,
  134. SPDY_ERROR_HPACK_TRUNCATED_BLOCK = 56,
  135. SPDY_ERROR_HPACK_FRAGMENT_TOO_LONG = 57,
  136. SPDY_ERROR_HPACK_COMPRESSED_HEADER_SIZE_EXCEEDS_LIMIT = 58,
  137. SPDY_ERROR_STOP_PROCESSING = 59,
  138. // spdy::SpdyErrorCode mappings.
  139. STATUS_CODE_NO_ERROR = 41,
  140. STATUS_CODE_PROTOCOL_ERROR = 11,
  141. STATUS_CODE_INTERNAL_ERROR = 16,
  142. STATUS_CODE_FLOW_CONTROL_ERROR = 17,
  143. STATUS_CODE_SETTINGS_TIMEOUT = 32,
  144. STATUS_CODE_STREAM_CLOSED = 12,
  145. STATUS_CODE_FRAME_SIZE_ERROR = 21,
  146. STATUS_CODE_REFUSED_STREAM = 13,
  147. STATUS_CODE_CANCEL = 15,
  148. STATUS_CODE_COMPRESSION_ERROR = 42,
  149. STATUS_CODE_CONNECT_ERROR = 33,
  150. STATUS_CODE_ENHANCE_YOUR_CALM = 34,
  151. STATUS_CODE_INADEQUATE_SECURITY = 35,
  152. STATUS_CODE_HTTP_1_1_REQUIRED = 36,
  153. // Deprecated SpdyRstStrreamStatus mappings.
  154. STATUS_CODE_UNSUPPORTED_VERSION = 14,
  155. STATUS_CODE_STREAM_IN_USE = 18,
  156. STATUS_CODE_STREAM_ALREADY_CLOSED = 19,
  157. // SpdySession errors
  158. PROTOCOL_ERROR_UNEXPECTED_PING = 22,
  159. PROTOCOL_ERROR_RST_STREAM_FOR_NON_ACTIVE_STREAM = 23,
  160. PROTOCOL_ERROR_SPDY_COMPRESSION_FAILURE = 24,
  161. PROTOCOL_ERROR_REQUEST_FOR_SECURE_CONTENT_OVER_INSECURE_SESSION = 25,
  162. PROTOCOL_ERROR_SYN_REPLY_NOT_RECEIVED = 26,
  163. PROTOCOL_ERROR_INVALID_WINDOW_UPDATE_SIZE = 27,
  164. PROTOCOL_ERROR_RECEIVE_WINDOW_VIOLATION = 28,
  165. // Next free value.
  166. NUM_SPDY_PROTOCOL_ERROR_DETAILS = 60,
  167. };
  168. SpdyProtocolErrorDetails NET_EXPORT_PRIVATE MapFramerErrorToProtocolError(
  169. http2::Http2DecoderAdapter::SpdyFramerError error);
  170. Error NET_EXPORT_PRIVATE
  171. MapFramerErrorToNetError(http2::Http2DecoderAdapter::SpdyFramerError error);
  172. SpdyProtocolErrorDetails NET_EXPORT_PRIVATE
  173. MapRstStreamStatusToProtocolError(spdy::SpdyErrorCode error_code);
  174. spdy::SpdyErrorCode NET_EXPORT_PRIVATE MapNetErrorToGoAwayStatus(Error err);
  175. // There is an enum of the same name in tools/metrics/histograms/enums.xml.
  176. // Be sure to add new values there also.
  177. enum class SpdyPushedStreamFate {
  178. kTooManyPushedStreams = 0,
  179. kTimeout = 1,
  180. kPromisedStreamIdParityError = 2,
  181. kAssociatedStreamIdParityError = 3,
  182. kStreamIdOutOfOrder = 4,
  183. kGoingAway = 5,
  184. kInvalidUrl = 6,
  185. kInactiveAssociatedStream = 7,
  186. kNonHttpSchemeFromTrustedProxy = 8,
  187. kNonHttpsPushedScheme = 9,
  188. kNonHttpsAssociatedScheme = 10,
  189. kCertificateMismatch = 11,
  190. kDuplicateUrl = 12,
  191. kClientRequestNotRange = 13,
  192. kPushedRequestNotRange = 14,
  193. kRangeMismatch = 15,
  194. kVaryMismatch = 16,
  195. kAcceptedNoVary = 17,
  196. kAcceptedMatchingVary = 18,
  197. kPushDisabled = 19,
  198. kAlreadyInCache = 20,
  199. kUnsupportedStatusCode = 21,
  200. kMaxValue = kUnsupportedStatusCode
  201. };
  202. // If these compile asserts fail then SpdyProtocolErrorDetails needs
  203. // to be updated with new values, as do the mapping functions above.
  204. static_assert(28 == http2::Http2DecoderAdapter::LAST_ERROR,
  205. "SpdyProtocolErrorDetails / Spdy Errors mismatch");
  206. static_assert(13 == spdy::SpdyErrorCode::ERROR_CODE_MAX,
  207. "SpdyProtocolErrorDetails / spdy::SpdyErrorCode mismatch");
  208. // A helper class used to manage a request to create a stream.
  209. class NET_EXPORT_PRIVATE SpdyStreamRequest {
  210. public:
  211. SpdyStreamRequest();
  212. SpdyStreamRequest(const SpdyStreamRequest&) = delete;
  213. SpdyStreamRequest& operator=(const SpdyStreamRequest&) = delete;
  214. // Calls CancelRequest().
  215. ~SpdyStreamRequest();
  216. // Returns the time when ConfirmHandshake() completed, if this request had to
  217. // wait for ConfirmHandshake().
  218. base::TimeTicks confirm_handshake_end() const {
  219. return confirm_handshake_end_;
  220. }
  221. // Starts the request to create a stream. If OK is returned, then
  222. // ReleaseStream() may be called. If ERR_IO_PENDING is returned,
  223. // then when the stream is created, |callback| will be called, at
  224. // which point ReleaseStream() may be called. Otherwise, the stream
  225. // is not created, an error is returned, and ReleaseStream() may not
  226. // be called.
  227. //
  228. // If |can_send_early| is true, this request is allowed to be sent over
  229. // TLS 1.3 0RTT without confirming the handshake.
  230. //
  231. // If OK is returned, must not be called again without
  232. // ReleaseStream() being called first. If ERR_IO_PENDING is
  233. // returned, must not be called again without CancelRequest() or
  234. // ReleaseStream() being called first. Otherwise, in case of an
  235. // immediate error, this may be called again.
  236. int StartRequest(SpdyStreamType type,
  237. const base::WeakPtr<SpdySession>& session,
  238. const GURL& url,
  239. bool can_send_early,
  240. RequestPriority priority,
  241. const SocketTag& socket_tag,
  242. const NetLogWithSource& net_log,
  243. CompletionOnceCallback callback,
  244. const NetworkTrafficAnnotationTag& traffic_annotation,
  245. bool detect_broken_connection = false,
  246. base::TimeDelta heartbeat_interval = base::Seconds(0));
  247. // Cancels any pending stream creation request. May be called
  248. // repeatedly.
  249. void CancelRequest();
  250. // Transfers the created stream (guaranteed to not be NULL) to the
  251. // caller. Must be called at most once after StartRequest() returns
  252. // OK or |callback| is called with OK. The caller must immediately
  253. // set a delegate for the returned stream (except for test code).
  254. base::WeakPtr<SpdyStream> ReleaseStream();
  255. // Changes the priority of the stream, or changes the priority of the queued
  256. // request in the session.
  257. void SetPriority(RequestPriority priority);
  258. const NetworkTrafficAnnotationTag traffic_annotation() const {
  259. return NetworkTrafficAnnotationTag(traffic_annotation_);
  260. }
  261. private:
  262. friend class SpdySession;
  263. void OnConfirmHandshakeComplete(int rv);
  264. // Called by |session_| when the stream attempt has finished
  265. // successfully.
  266. void OnRequestCompleteSuccess(const base::WeakPtr<SpdyStream>& stream);
  267. // Called by |session_| when the stream attempt has finished with an
  268. // error. Also called with ERR_ABORTED if |session_| is destroyed
  269. // while the stream attempt is still pending.
  270. void OnRequestCompleteFailure(int rv);
  271. // Accessors called by |session_|.
  272. SpdyStreamType type() const { return type_; }
  273. const GURL& url() const { return url_; }
  274. RequestPriority priority() const { return priority_; }
  275. const NetLogWithSource& net_log() const { return net_log_; }
  276. void Reset();
  277. SpdyStreamType type_;
  278. base::WeakPtr<SpdySession> session_;
  279. base::WeakPtr<SpdyStream> stream_;
  280. GURL url_;
  281. RequestPriority priority_;
  282. SocketTag socket_tag_;
  283. NetLogWithSource net_log_;
  284. CompletionOnceCallback callback_;
  285. MutableNetworkTrafficAnnotationTag traffic_annotation_;
  286. base::TimeTicks confirm_handshake_end_;
  287. bool detect_broken_connection_;
  288. base::TimeDelta heartbeat_interval_;
  289. base::WeakPtrFactory<SpdyStreamRequest> weak_ptr_factory_{this};
  290. };
  291. class NET_EXPORT SpdySession
  292. : public BufferedSpdyFramerVisitorInterface,
  293. public spdy::SpdyFramerDebugVisitorInterface,
  294. public MultiplexedSession,
  295. public HigherLayeredPool,
  296. public NetworkChangeNotifier::DefaultNetworkActiveObserver,
  297. public Http2PushPromiseIndex::Delegate {
  298. public:
  299. // TODO(akalin): Use base::TickClock when it becomes available.
  300. typedef base::TimeTicks (*TimeFunc)();
  301. // Returns true if |new_hostname| can be pooled into an existing connection to
  302. // |old_hostname| associated with |ssl_info|.
  303. static bool CanPool(TransportSecurityState* transport_security_state,
  304. const SSLInfo& ssl_info,
  305. const SSLConfigService& ssl_config_service,
  306. const std::string& old_hostname,
  307. const std::string& new_hostname,
  308. const net::NetworkIsolationKey& network_isolation_key);
  309. // Create a new SpdySession.
  310. // |spdy_session_key| is the host/port that this session connects to, privacy
  311. // and proxy configuration settings that it's using.
  312. // |net_log| is the NetLog that we log network events to.
  313. SpdySession(const SpdySessionKey& spdy_session_key,
  314. HttpServerProperties* http_server_properties,
  315. TransportSecurityState* transport_security_state,
  316. SSLConfigService* ssl_config_service,
  317. const quic::ParsedQuicVersionVector& quic_supported_versions,
  318. bool enable_sending_initial_data,
  319. bool enable_ping_based_connection_checking,
  320. bool is_http_enabled,
  321. bool is_quic_enabled,
  322. size_t session_max_recv_window_size,
  323. int session_max_queued_capped_frames,
  324. const spdy::SettingsMap& initial_settings,
  325. bool enable_http2_settings_grease,
  326. const absl::optional<SpdySessionPool::GreasedHttp2Frame>&
  327. greased_http2_frame,
  328. bool http2_end_stream_with_data_frame,
  329. bool enable_priority_update,
  330. TimeFunc time_func,
  331. ServerPushDelegate* push_delegate,
  332. NetworkQualityEstimator* network_quality_estimator,
  333. NetLog* net_log);
  334. ~SpdySession() override;
  335. const HostPortPair& host_port_pair() const {
  336. return spdy_session_key_.host_port_proxy_pair().first;
  337. }
  338. const HostPortProxyPair& host_port_proxy_pair() const {
  339. return spdy_session_key_.host_port_proxy_pair();
  340. }
  341. const SpdySessionKey& spdy_session_key() const { return spdy_session_key_; }
  342. // Get a pushed stream for a given |url| with stream ID |pushed_stream_id|.
  343. // The caller must have already claimed the stream from Http2PushPromiseIndex.
  344. // |pushed_stream_id| must not be kNoPushedStreamFound.
  345. //
  346. // Returns ERR_CONNECTION_CLOSED if the connection is being closed.
  347. // Returns ERR_HTTP2_PUSHED_STREAM_NOT_AVAILABLE if the pushed stream is not
  348. // available any longer, for example, if the server has reset it.
  349. // Returns OK if the stream is still available, and returns the stream in
  350. // |*spdy_stream|. If the stream is still open, updates its priority to
  351. // |priority|.
  352. int GetPushedStream(const GURL& url,
  353. spdy::SpdyStreamId pushed_stream_id,
  354. RequestPriority priority,
  355. SpdyStream** spdy_stream);
  356. // Called when the pushed stream should be cancelled. If the pushed stream is
  357. // not claimed and active, sends RST to the server to cancel the stream.
  358. void CancelPush(const GURL& url);
  359. // Initialize the session with the given connection.
  360. //
  361. // |pool| is the SpdySessionPool that owns us. Its lifetime must
  362. // strictly be greater than |this|.
  363. //
  364. // The session begins reading from |client_socket_handle| on a subsequent
  365. // event loop iteration, so the SpdySession may close immediately afterwards
  366. // if the first read of |client_socket_handle| fails.
  367. void InitializeWithSocketHandle(
  368. std::unique_ptr<ClientSocketHandle> client_socket_handle,
  369. SpdySessionPool* pool);
  370. // Just like InitializeWithSocketHandle(), but for use when the session is not
  371. // on top of a socket pool, but instead directly on top of a socket, which the
  372. // session has sole ownership of, and is responsible for deleting directly
  373. // itself.
  374. void InitializeWithSocket(std::unique_ptr<StreamSocket> stream_socket,
  375. const LoadTimingInfo::ConnectTiming& connect_timing,
  376. SpdySessionPool* pool);
  377. // Parse ALPS application_data from TLS handshake.
  378. // Returns OK on success. Return a net error code on failure, and closes the
  379. // connection with the same error code.
  380. int ParseAlps();
  381. // Check to see if this SPDY session can support an additional domain.
  382. // If the session is un-authenticated, then this call always returns true.
  383. // For SSL-based sessions, verifies that the server certificate in use by
  384. // this session provides authentication for the domain and no client
  385. // certificate or channel ID was sent to the original server during the SSL
  386. // handshake. NOTE: This function can have false negatives on some
  387. // platforms.
  388. // TODO(wtc): rename this function and the Net.SpdyIPPoolDomainMatch
  389. // histogram because this function does more than verifying domain
  390. // authentication now.
  391. bool VerifyDomainAuthentication(const std::string& domain) const;
  392. // Pushes the given producer into the write queue for
  393. // |stream|. |stream| is guaranteed to be activated before the
  394. // producer is used to produce its frame.
  395. void EnqueueStreamWrite(const base::WeakPtr<SpdyStream>& stream,
  396. spdy::SpdyFrameType frame_type,
  397. std::unique_ptr<SpdyBufferProducer> producer);
  398. // Returns true if this session is configured to send greased HTTP/2 frames.
  399. // For more details on greased frames, see
  400. // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
  401. bool GreasedFramesEnabled() const;
  402. // Returns true if HEADERS frames on request streams should not have the
  403. // END_STREAM flag set, but instead an empty DATA frame with END_STREAM should
  404. // be sent afterwards to close the stream. Does not apply to bidirectional or
  405. // proxy streams.
  406. bool EndStreamWithDataFrame() const {
  407. return http2_end_stream_with_data_frame_;
  408. }
  409. // Send greased frame, that is, a frame of reserved type.
  410. void EnqueueGreasedFrame(const base::WeakPtr<SpdyStream>& stream);
  411. // Returns whether HTTP/2 style priority information (stream dependency and
  412. // weight fields in HEADERS frames, and PRIORITY frames) should be sent. True
  413. // unless |enable_priority_update_| is true and
  414. // SETTINGS_DEPRECATE_HTTP2_PRIORITIES with value 1 has been received from
  415. // server. In particular, if it returns false, it will always return false
  416. // afterwards.
  417. bool ShouldSendHttp2Priority() const;
  418. // Returns whether PRIORITY_UPDATE frames should be sent. False if
  419. // |enable_priority_update_| is false. Otherwise, true before SETTINGS frame
  420. // is received from server, and true after SETTINGS frame is received if it
  421. // contained SETTINGS_DEPRECATE_HTTP2_PRIORITIES with value 1. In particular,
  422. // if it returns false, it will always return false afterwards.
  423. bool ShouldSendPriorityUpdate() const;
  424. // Runs the handshake to completion to confirm the handshake with the server.
  425. // If ERR_IO_PENDING is returned, then when the handshake is confirmed,
  426. // |callback| will be called.
  427. int ConfirmHandshake(CompletionOnceCallback callback);
  428. // Creates and returns a HEADERS frame for |stream_id|.
  429. std::unique_ptr<spdy::SpdySerializedFrame> CreateHeaders(
  430. spdy::SpdyStreamId stream_id,
  431. RequestPriority priority,
  432. spdy::SpdyControlFlags flags,
  433. spdy::Http2HeaderBlock headers,
  434. NetLogSource source_dependency);
  435. // Creates and returns a SpdyBuffer holding a data frame with the given data.
  436. // Sets |*effective_len| to number of bytes sent, and |*end_stream| to the
  437. // value of the END_STREAM (also known as fin) flag. Returns nullptr if
  438. // session is draining or if session or stream is stalled by flow control.
  439. std::unique_ptr<SpdyBuffer> CreateDataBuffer(spdy::SpdyStreamId stream_id,
  440. IOBuffer* data,
  441. int len,
  442. spdy::SpdyDataFlags flags,
  443. int* effective_len,
  444. bool* end_stream);
  445. // Send PRIORITY frames according to the new priority of an existing stream.
  446. void UpdateStreamPriority(SpdyStream* stream,
  447. RequestPriority old_priority,
  448. RequestPriority new_priority);
  449. // Close the stream with the given ID, which must exist and be
  450. // active. Note that that stream may hold the last reference to the
  451. // session.
  452. void CloseActiveStream(spdy::SpdyStreamId stream_id, int status);
  453. // Close the given created stream, which must exist but not yet be
  454. // active. Note that |stream| may hold the last reference to the
  455. // session.
  456. void CloseCreatedStream(const base::WeakPtr<SpdyStream>& stream, int status);
  457. // Send a RST_STREAM frame with the given status code and close the
  458. // stream with the given ID, which must exist and be active. Note
  459. // that that stream may hold the last reference to the session.
  460. void ResetStream(spdy::SpdyStreamId stream_id,
  461. int error,
  462. const std::string& description);
  463. // Check if a stream is active.
  464. bool IsStreamActive(spdy::SpdyStreamId stream_id) const;
  465. // The LoadState is used for informing the user of the current network
  466. // status, such as "resolving host", "connecting", etc.
  467. LoadState GetLoadState() const;
  468. // MultiplexedSession methods:
  469. int GetRemoteEndpoint(IPEndPoint* endpoint) override;
  470. bool GetSSLInfo(SSLInfo* ssl_info) const override;
  471. base::StringPiece GetAcceptChViaAlps(
  472. const url::SchemeHostPort& scheme_host_port) const override;
  473. // Returns true if ALPN was negotiated for the underlying socket.
  474. bool WasAlpnNegotiated() const;
  475. // Returns the protocol negotiated via ALPN for the underlying socket.
  476. NextProto GetNegotiatedProtocol() const;
  477. // Send a WINDOW_UPDATE frame for a stream. Called by a stream
  478. // whenever receive window size is increased.
  479. void SendStreamWindowUpdate(spdy::SpdyStreamId stream_id,
  480. uint32_t delta_window_size);
  481. // Configure the amount of time that small receive window updates should
  482. // be accumulated over (defaults to kDefaultTimeToBufferSmallWindowUpdates).
  483. void SetTimeToBufferSmallWindowUpdates(const base::TimeDelta buffer_time) {
  484. time_to_buffer_small_window_updates_ = buffer_time;
  485. }
  486. // Returns the configured time that small receive window updates should
  487. // be accumulated over.
  488. base::TimeDelta TimeToBufferSmallWindowUpdates() const {
  489. return time_to_buffer_small_window_updates_;
  490. }
  491. // Accessors for the session's availability state.
  492. bool IsAvailable() const { return availability_state_ == STATE_AVAILABLE; }
  493. bool IsGoingAway() const { return availability_state_ == STATE_GOING_AWAY; }
  494. bool IsDraining() const { return availability_state_ == STATE_DRAINING; }
  495. // Closes this session. This will close all active streams and mark
  496. // the session as permanently closed. Callers must assume that the
  497. // session is destroyed after this is called. (However, it may not
  498. // be destroyed right away, e.g. when a SpdySession function is
  499. // present in the call stack.)
  500. //
  501. // |err| should be < ERR_IO_PENDING; this function is intended to be
  502. // called on error.
  503. // |description| indicates the reason for the error.
  504. void CloseSessionOnError(Error err, const std::string& description);
  505. // Mark this session as unavailable, meaning that it will not be used to
  506. // service new streams. Unlike when a GOAWAY frame is received, this function
  507. // will not close any streams.
  508. void MakeUnavailable();
  509. // Closes all active streams with stream id's greater than
  510. // |last_good_stream_id|, as well as any created or pending
  511. // streams. Must be called only when |availability_state_| >=
  512. // STATE_GOING_AWAY. After this function, DcheckGoingAway() will
  513. // pass. May be called multiple times.
  514. void StartGoingAway(spdy::SpdyStreamId last_good_stream_id, Error status);
  515. // Must be called only when going away (i.e., DcheckGoingAway()
  516. // passes). If there are no more active streams and the session
  517. // isn't closed yet, close it.
  518. void MaybeFinishGoingAway();
  519. // Retrieves information on the current state of the SPDY session as a
  520. // Value.
  521. base::Value GetInfoAsValue() const;
  522. // Indicates whether the session is being reused after having successfully
  523. // used to send/receive data in the past or if the underlying socket was idle
  524. // before being used for a SPDY session.
  525. bool IsReused() const;
  526. // Returns true if the underlying transport socket ever had any reads or
  527. // writes.
  528. bool WasEverUsed() const { return socket_->WasEverUsed(); }
  529. // Returns the load timing information from the perspective of the given
  530. // stream. If it's not the first stream, the connection is considered reused
  531. // for that stream.
  532. //
  533. // This uses a different notion of reuse than IsReused(). This function
  534. // sets |socket_reused| to false only if |stream_id| is the ID of the first
  535. // stream using the session. IsReused(), on the other hand, indicates if the
  536. // session has been used to send/receive data at all.
  537. bool GetLoadTimingInfo(spdy::SpdyStreamId stream_id,
  538. LoadTimingInfo* load_timing_info) const;
  539. // Returns true if session is currently active.
  540. bool is_active() const {
  541. return !active_streams_.empty() || !created_streams_.empty();
  542. }
  543. // True if the server supports WebSocket protocol.
  544. bool support_websocket() const { return support_websocket_; }
  545. // Returns true if no stream in the session can send data due to
  546. // session flow control.
  547. bool IsSendStalled() const { return session_send_window_size_ == 0; }
  548. const NetLogWithSource& net_log() const { return net_log_; }
  549. int GetPeerAddress(IPEndPoint* address) const;
  550. int GetLocalAddress(IPEndPoint* address) const;
  551. // Adds |alias| to set of aliases associated with this session.
  552. void AddPooledAlias(const SpdySessionKey& alias_key);
  553. // Removes |alias| from set of aliases associated with this session.
  554. void RemovePooledAlias(const SpdySessionKey& alias_key);
  555. // Returns the set of aliases associated with this session.
  556. const std::set<SpdySessionKey>& pooled_aliases() const {
  557. return pooled_aliases_;
  558. }
  559. // https://http2.github.io/http2-spec/#TLSUsage mandates minimum security
  560. // standards for TLS.
  561. bool HasAcceptableTransportSecurity() const;
  562. // Must be used only by |pool_| (including |pool_.push_promise_index_|).
  563. base::WeakPtr<SpdySession> GetWeakPtr();
  564. // HigherLayeredPool implementation:
  565. bool CloseOneIdleConnection() override;
  566. // Http2PushPromiseIndex::Delegate implementation:
  567. bool ValidatePushedStream(spdy::SpdyStreamId stream_id,
  568. const GURL& url,
  569. const HttpRequestInfo& request_info,
  570. const SpdySessionKey& key) const override;
  571. base::WeakPtr<SpdySession> GetWeakPtrToSession() override;
  572. // Change this session's socket tag to |new_tag|. Returns true on success.
  573. bool ChangeSocketTag(const SocketTag& new_tag);
  574. // Whether connection status monitoring is active or not.
  575. bool IsBrokenConnectionDetectionEnabled() const;
  576. static void RecordSpdyPushedStreamFateHistogram(SpdyPushedStreamFate value);
  577. private:
  578. friend class test::SpdyStreamTest;
  579. friend class base::RefCounted<SpdySession>;
  580. friend class HttpNetworkTransactionTest;
  581. friend class HttpProxyClientSocketPoolTest;
  582. friend class SpdyHttpStreamTest;
  583. friend class SpdyNetworkTransactionTest;
  584. friend class SpdyProxyClientSocketTest;
  585. friend class SpdySessionPoolTest;
  586. friend class SpdySessionTest;
  587. friend class SpdyStreamRequest;
  588. FRIEND_TEST_ALL_PREFIXES(RecordPushedStreamHistogramTest, VaryResponseHeader);
  589. using PendingStreamRequestQueue =
  590. base::circular_deque<base::WeakPtr<SpdyStreamRequest>>;
  591. using ActiveStreamMap = std::map<spdy::SpdyStreamId, SpdyStream*>;
  592. using CreatedStreamSet = std::set<SpdyStream*>;
  593. enum AvailabilityState {
  594. // The session is available in its socket pool and can be used
  595. // freely.
  596. STATE_AVAILABLE,
  597. // The session can process data on existing streams but will
  598. // refuse to create new ones.
  599. STATE_GOING_AWAY,
  600. // The session is draining its write queue in preparation of closing.
  601. // Further writes will not be queued, and further reads will not be issued
  602. // (though the remainder of a current read may be processed). The session
  603. // will be destroyed by its write loop once the write queue is drained.
  604. STATE_DRAINING,
  605. };
  606. enum ReadState {
  607. READ_STATE_DO_READ,
  608. READ_STATE_DO_READ_COMPLETE,
  609. };
  610. enum WriteState {
  611. // There is no in-flight write and the write queue is empty.
  612. WRITE_STATE_IDLE,
  613. WRITE_STATE_DO_WRITE,
  614. WRITE_STATE_DO_WRITE_COMPLETE,
  615. };
  616. // Has the shared logic for the other two Initialize methods that call it.
  617. void InitializeInternal(SpdySessionPool* pool);
  618. // Called by SpdyStreamRequest to start a request to create a
  619. // stream. If OK is returned, then |stream| will be filled in with a
  620. // valid stream. If ERR_IO_PENDING is returned, then
  621. // |request->OnRequestComplete{Success,Failure}()| will be called
  622. // when the stream is created (unless it is cancelled). Otherwise,
  623. // no stream is created and the error is returned.
  624. int TryCreateStream(const base::WeakPtr<SpdyStreamRequest>& request,
  625. base::WeakPtr<SpdyStream>* stream);
  626. // Actually create a stream into |stream|. Returns OK if successful;
  627. // otherwise, returns an error and |stream| is not filled.
  628. int CreateStream(const SpdyStreamRequest& request,
  629. base::WeakPtr<SpdyStream>* stream);
  630. // Called by SpdyStreamRequest to remove |request| from the stream
  631. // creation queue. Returns whether a request was removed from the queue.
  632. bool CancelStreamRequest(const base::WeakPtr<SpdyStreamRequest>& request);
  633. // Removes |request| from the stream creation queue and reinserts it into the
  634. // queue at the new |priority|.
  635. void ChangeStreamRequestPriority(
  636. const base::WeakPtr<SpdyStreamRequest>& request,
  637. RequestPriority priority);
  638. // Returns the next pending stream request to process, or NULL if
  639. // there is none.
  640. base::WeakPtr<SpdyStreamRequest> GetNextPendingStreamRequest();
  641. // Called when there is room to create more streams (e.g., a stream
  642. // was closed). Processes as many pending stream requests as
  643. // possible.
  644. void ProcessPendingStreamRequests();
  645. void TryCreatePushStream(spdy::SpdyStreamId stream_id,
  646. spdy::SpdyStreamId associated_stream_id,
  647. spdy::Http2HeaderBlock headers);
  648. // Close the stream pointed to by the given iterator. Note that that
  649. // stream may hold the last reference to the session.
  650. void CloseActiveStreamIterator(ActiveStreamMap::iterator it, int status);
  651. // Close the stream pointed to by the given iterator. Note that that
  652. // stream may hold the last reference to the session.
  653. void CloseCreatedStreamIterator(CreatedStreamSet::iterator it, int status);
  654. // Calls EnqueueResetStreamFrame() and then
  655. // CloseActiveStreamIterator().
  656. void ResetStreamIterator(ActiveStreamMap::iterator it,
  657. int status,
  658. const std::string& description);
  659. // Send a RST_STREAM frame with the given parameters. There should
  660. // either be no active stream with the given ID, or that active
  661. // stream should be closed shortly after this function is called.
  662. void EnqueueResetStreamFrame(spdy::SpdyStreamId stream_id,
  663. RequestPriority priority,
  664. spdy::SpdyErrorCode error_code,
  665. const std::string& description);
  666. // Send a PRIORITY frame with the given parameters.
  667. void EnqueuePriorityFrame(spdy::SpdyStreamId stream_id,
  668. spdy::SpdyStreamId dependency_id,
  669. int weight,
  670. bool exclusive);
  671. // Calls DoReadLoop. Use this function instead of DoReadLoop when
  672. // posting a task to pump the read loop.
  673. void PumpReadLoop(ReadState expected_read_state, int result);
  674. // Advance the ReadState state machine. |expected_read_state| is the
  675. // expected starting read state.
  676. //
  677. // This function must always be called via PumpReadLoop().
  678. int DoReadLoop(ReadState expected_read_state, int result);
  679. // The implementations of the states of the ReadState state machine.
  680. int DoRead();
  681. int DoReadComplete(int result);
  682. // Calls DoWriteLoop. If |availability_state_| is STATE_DRAINING and no
  683. // writes remain, the session is removed from the session pool and
  684. // destroyed.
  685. //
  686. // Use this function instead of DoWriteLoop when posting a task to
  687. // pump the write loop.
  688. void PumpWriteLoop(WriteState expected_write_state, int result);
  689. // Iff the write loop is not currently active, posts a callback into
  690. // PumpWriteLoop().
  691. void MaybePostWriteLoop();
  692. // Advance the WriteState state machine. |expected_write_state| is
  693. // the expected starting write state.
  694. //
  695. // This function must always be called via PumpWriteLoop().
  696. int DoWriteLoop(WriteState expected_write_state, int result);
  697. // The implementations of the states of the WriteState state machine.
  698. int DoWrite();
  699. int DoWriteComplete(int result);
  700. void NotifyRequestsOfConfirmation(int rv);
  701. // TODO(akalin): Rename the Send* and Write* functions below to
  702. // Enqueue*.
  703. // Send initial data. Called when a connection is successfully
  704. // established in InitializeWithSocket() and
  705. // |enable_sending_initial_data_| is true.
  706. void SendInitialData();
  707. // Handle SETTING. Either when we send settings, or when we receive a
  708. // SETTINGS control frame, update our SpdySession accordingly.
  709. void HandleSetting(uint32_t id, uint32_t value);
  710. // Adjust the send window size of all ActiveStreams and PendingStreamRequests.
  711. void UpdateStreamsSendWindowSize(int32_t delta_window_size);
  712. // Checks the connection status in an energy efficient manner:
  713. // * If the radio is in full power mode, send the PING immediately
  714. // * If the radio is in standby, record the event and send the PING once the
  715. // radio wakes up
  716. // The radio status check is currently only implemented for Android devices,
  717. // on all other platforms the radio is assumed to be always active (i.e., no
  718. // batching happens).
  719. void MaybeCheckConnectionStatus();
  720. // Always checks the connection status and schedules the next check.
  721. void CheckConnectionStatus();
  722. // Send PING frame if all previous PING frames have been ACKed,
  723. // all posted CheckPingStatus() tasks have been executed,
  724. // and too long time has passed since last read from server.
  725. void MaybeSendPrefacePing();
  726. // Send a single WINDOW_UPDATE frame.
  727. void SendWindowUpdateFrame(spdy::SpdyStreamId stream_id,
  728. uint32_t delta_window_size,
  729. RequestPriority priority);
  730. // Send the PING frame.
  731. void WritePingFrame(spdy::SpdyPingId unique_id, bool is_ack);
  732. // Post a CheckPingStatus call after delay. Don't post if there is already
  733. // CheckPingStatus running.
  734. void PlanToCheckPingStatus();
  735. // Check the status of the connection. It calls |CloseSessionOnError| if we
  736. // haven't received any data in |kHungInterval| time period.
  737. void CheckPingStatus(base::TimeTicks last_check_time);
  738. // Get a new stream id.
  739. spdy::SpdyStreamId GetNewStreamId();
  740. // Pushes the given frame with the given priority into the write
  741. // queue for the session.
  742. void EnqueueSessionWrite(RequestPriority priority,
  743. spdy::SpdyFrameType frame_type,
  744. std::unique_ptr<spdy::SpdySerializedFrame> frame);
  745. // Puts |producer| associated with |stream| onto the write queue
  746. // with the given priority.
  747. void EnqueueWrite(RequestPriority priority,
  748. spdy::SpdyFrameType frame_type,
  749. std::unique_ptr<SpdyBufferProducer> producer,
  750. const base::WeakPtr<SpdyStream>& stream,
  751. const NetworkTrafficAnnotationTag& traffic_annotation);
  752. // Inserts a newly-created stream into |created_streams_|.
  753. void InsertCreatedStream(std::unique_ptr<SpdyStream> stream);
  754. // Activates |stream| (which must be in |created_streams_|) by
  755. // assigning it an ID and returns it.
  756. std::unique_ptr<SpdyStream> ActivateCreatedStream(SpdyStream* stream);
  757. // Inserts a newly-activated stream into |active_streams_|.
  758. void InsertActivatedStream(std::unique_ptr<SpdyStream> stream);
  759. // Remove all internal references to |stream|, call OnClose() on it,
  760. // and process any pending stream requests before deleting it. Note
  761. // that |stream| may hold the last reference to the session.
  762. void DeleteStream(std::unique_ptr<SpdyStream> stream, int status);
  763. void RecordHistograms();
  764. void RecordProtocolErrorHistogram(SpdyProtocolErrorDetails details);
  765. static void RecordPushedStreamVaryResponseHeaderHistogram(
  766. const spdy::Http2HeaderBlock& headers);
  767. // DCHECKs that |availability_state_| >= STATE_GOING_AWAY, that
  768. // there are no pending stream creation requests, and that there are
  769. // no created streams.
  770. void DcheckGoingAway() const;
  771. // Calls DcheckGoingAway(), then DCHECKs that |availability_state_|
  772. // == STATE_DRAINING, |error_on_close_| has a valid value, and that there
  773. // are no active streams or unclaimed pushed streams.
  774. void DcheckDraining() const;
  775. // If the session is already draining, does nothing. Otherwise, moves
  776. // the session to the draining state.
  777. void DoDrainSession(Error err, const std::string& description);
  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. // Called right before closing an active stream for a reason other
  782. // than being requested to by the stream.
  783. void LogAbandonedActiveStream(ActiveStreamMap::const_iterator it,
  784. Error status);
  785. // Invokes a user callback for stream creation. We provide this method so it
  786. // can be deferred to the MessageLoop, so we avoid re-entrancy problems.
  787. void CompleteStreamRequest(
  788. const base::WeakPtr<SpdyStreamRequest>& pending_request);
  789. // Cancel pushed stream with |stream_id|, if still unclaimed. Identifying a
  790. // pushed stream by GURL instead of stream ID could result in incorrect
  791. // behavior if a pushed stream was claimed but later another stream was pushed
  792. // for the same GURL.
  793. void CancelPushedStreamIfUnclaimed(spdy::SpdyStreamId stream_id);
  794. // BufferedSpdyFramerVisitorInterface:
  795. void OnError(
  796. http2::Http2DecoderAdapter::SpdyFramerError spdy_framer_error) override;
  797. void OnStreamError(spdy::SpdyStreamId stream_id,
  798. const std::string& description) override;
  799. void OnPing(spdy::SpdyPingId unique_id, bool is_ack) override;
  800. void OnRstStream(spdy::SpdyStreamId stream_id,
  801. spdy::SpdyErrorCode error_code) override;
  802. void OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,
  803. spdy::SpdyErrorCode error_code,
  804. base::StringPiece debug_data) override;
  805. void OnDataFrameHeader(spdy::SpdyStreamId stream_id,
  806. size_t length,
  807. bool fin) override;
  808. void OnStreamFrameData(spdy::SpdyStreamId stream_id,
  809. const char* data,
  810. size_t len) override;
  811. void OnStreamEnd(spdy::SpdyStreamId stream_id) override;
  812. void OnStreamPadding(spdy::SpdyStreamId stream_id, size_t len) override;
  813. void OnSettings() override;
  814. void OnSettingsAck() override;
  815. void OnSetting(spdy::SpdySettingsId id, uint32_t value) override;
  816. void OnSettingsEnd() override;
  817. void OnWindowUpdate(spdy::SpdyStreamId stream_id,
  818. int delta_window_size) override;
  819. void OnPushPromise(spdy::SpdyStreamId stream_id,
  820. spdy::SpdyStreamId promised_stream_id,
  821. spdy::Http2HeaderBlock headers) override;
  822. void OnHeaders(spdy::SpdyStreamId stream_id,
  823. bool has_priority,
  824. int weight,
  825. spdy::SpdyStreamId parent_stream_id,
  826. bool exclusive,
  827. bool fin,
  828. spdy::Http2HeaderBlock headers,
  829. base::TimeTicks recv_first_byte_time) override;
  830. void OnAltSvc(spdy::SpdyStreamId stream_id,
  831. base::StringPiece origin,
  832. const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector&
  833. altsvc_vector) override;
  834. bool OnUnknownFrame(spdy::SpdyStreamId stream_id,
  835. uint8_t frame_type) override;
  836. // spdy::SpdyFramerDebugVisitorInterface
  837. void OnSendCompressedFrame(spdy::SpdyStreamId stream_id,
  838. spdy::SpdyFrameType type,
  839. size_t payload_len,
  840. size_t frame_len) override;
  841. void OnReceiveCompressedFrame(spdy::SpdyStreamId stream_id,
  842. spdy::SpdyFrameType type,
  843. size_t frame_len) override;
  844. // Called when bytes are consumed from a SpdyBuffer for a DATA frame
  845. // that is to be written or is being written. Increases the send
  846. // window size accordingly if some or all of the SpdyBuffer is being
  847. // discarded.
  848. //
  849. // If session flow control is turned off, this must not be called.
  850. void OnWriteBufferConsumed(size_t frame_payload_size,
  851. size_t consume_size,
  852. SpdyBuffer::ConsumeSource consume_source);
  853. // Called when the radio goes into full power mode. Currently implemented only
  854. // for Android devices.
  855. void OnDefaultNetworkActive() override;
  856. // Called by OnWindowUpdate() (which is in turn called by the
  857. // framer) to increase this session's send window size by
  858. // |delta_window_size| from a WINDOW_UPDATE frome, which must be at
  859. // least 1. If |delta_window_size| would cause this session's send
  860. // window size to overflow, does nothing.
  861. //
  862. // If session flow control is turned off, this must not be called.
  863. void IncreaseSendWindowSize(int delta_window_size);
  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_t delta_window_size);
  872. // Called when bytes are consumed by the delegate from a SpdyBuffer
  873. // containing received data. Increases the receive window size
  874. // accordingly.
  875. //
  876. // If session flow control is turned off, this must not be called.
  877. void OnReadBufferConsumed(size_t consume_size,
  878. SpdyBuffer::ConsumeSource consume_source);
  879. // Called by OnReadBufferConsume to increase this session's receive
  880. // window size by |delta_window_size|, which must be at least 1 and
  881. // must not cause this session's receive window size to overflow,
  882. // possibly also sending a WINDOW_UPDATE frame. Also called during
  883. // initialization to set the initial receive window size.
  884. //
  885. // If session flow control is turned off, this must not be called.
  886. void IncreaseRecvWindowSize(int32_t delta_window_size);
  887. // Called by OnStreamFrameData (which is in turn called by the
  888. // framer) to decrease this session's receive window size by
  889. // |delta_window_size|, which must be at least 1 and must not cause
  890. // this session's receive window size to go negative.
  891. //
  892. // If session flow control is turned off, this must not be called.
  893. void DecreaseRecvWindowSize(int32_t delta_window_size);
  894. // Queue a send-stalled stream for possibly resuming once we're not
  895. // send-stalled anymore.
  896. void QueueSendStalledStream(const SpdyStream& stream);
  897. // Go through the queue of send-stalled streams and try to resume as
  898. // many as possible.
  899. void ResumeSendStalledStreams();
  900. // Returns the next stream to possibly resume, or 0 if the queue is
  901. // empty.
  902. spdy::SpdyStreamId PopStreamToPossiblyResume();
  903. // Enables connection status monitoring, causing the session to periodically
  904. // send a PING frame.
  905. // This must be called at most once for each stream requiring it. If called,
  906. // MaybeDisableBrokenConnectionDetection() will need to be called before
  907. // closing the requesting stream.
  908. // Note: `heartbeat_interval` should be considered a suggestion. The
  909. // implementation, for example, could either:
  910. // * Avoid sending a PING, if one has recently been transmitted or is
  911. // already in flight
  912. // * Delay sending a PING, to avoid waking up the radio on mobile platforms
  913. // Only the first value of `heartbeat_interval` is taken into account.
  914. void EnableBrokenConnectionDetection(base::TimeDelta heartbeat_interval);
  915. // Requests to disable connection status monitoring. The service is disabled
  916. // only if no other active stream also requires it (an internal counter keeps
  917. // track of that).
  918. // This must be called once for each stream that requested it previously.
  919. void MaybeDisableBrokenConnectionDetection();
  920. // Whether Do{Read,Write}Loop() is in the call stack. Useful for
  921. // making sure we don't destroy ourselves prematurely in that case.
  922. bool in_io_loop_ = false;
  923. // The key used to identify this session.
  924. SpdySessionKey spdy_session_key_;
  925. // Set set of SpdySessionKeys for which this session has serviced
  926. // requests.
  927. std::set<SpdySessionKey> pooled_aliases_;
  928. // |pool_| owns us, therefore its lifetime must exceed ours.
  929. raw_ptr<SpdySessionPool> pool_ = nullptr;
  930. raw_ptr<HttpServerProperties> http_server_properties_;
  931. raw_ptr<TransportSecurityState> transport_security_state_;
  932. raw_ptr<SSLConfigService> ssl_config_service_;
  933. // One of these two owns the socket for this session, which is stored in
  934. // |socket_|. If |client_socket_handle_| is non-null, this session is on top
  935. // of a socket in a socket pool. If |owned_stream_socket_| is non-null, this
  936. // session is directly on top of a socket, which is not in a socket pool.
  937. std::unique_ptr<ClientSocketHandle> client_socket_handle_;
  938. std::unique_ptr<StreamSocket> owned_stream_socket_;
  939. // This is non-null only if |owned_stream_socket_| is non-null.
  940. std::unique_ptr<LoadTimingInfo::ConnectTiming> connect_timing_;
  941. // The socket for this session.
  942. raw_ptr<StreamSocket> socket_ = nullptr;
  943. // The read buffer used to read data from the socket.
  944. // Non-null if there is a Read() pending.
  945. scoped_refptr<IOBuffer> read_buffer_;
  946. spdy::SpdyStreamId stream_hi_water_mark_; // The next stream id to use.
  947. // Used to ensure the server increments push stream ids correctly.
  948. spdy::SpdyStreamId last_accepted_push_stream_id_ = 0;
  949. // Queue, for each priority, of pending stream requests that have
  950. // not yet been satisfied.
  951. PendingStreamRequestQueue pending_create_stream_queues_[NUM_PRIORITIES];
  952. // Map from stream id to all active streams. Streams are active in the sense
  953. // that they have a consumer (typically SpdyNetworkTransaction and regardless
  954. // of whether or not there is currently any ongoing IO [might be waiting for
  955. // the server to start pushing the stream]) or there are still network events
  956. // incoming even though the consumer has already gone away (cancellation).
  957. //
  958. // |active_streams_| owns all its SpdyStream objects.
  959. //
  960. // TODO(willchan): Perhaps we should separate out cancelled streams and move
  961. // them into a separate ActiveStreamMap, and not deliver network events to
  962. // them?
  963. ActiveStreamMap active_streams_;
  964. // Not owned. |push_delegate_| outlives the session and handles server pushes
  965. // received by session.
  966. raw_ptr<ServerPushDelegate> push_delegate_;
  967. // Set of all created streams but that have not yet sent any frames.
  968. //
  969. // |created_streams_| owns all its SpdyStream objects.
  970. CreatedStreamSet created_streams_;
  971. // Number of pushed streams. All active streams are stored in
  972. // |active_streams_|, but it's better to know the number of push streams
  973. // without traversing the whole collection.
  974. size_t num_pushed_streams_ = 0u;
  975. // Number of active pushed streams in |active_streams_|, i.e. not in reserved
  976. // remote state. Streams in reserved state are not counted towards any
  977. // concurrency limits.
  978. size_t num_active_pushed_streams_ = 0u;
  979. // Number of bytes that has been pushed by the server.
  980. uint64_t bytes_pushed_count_ = 0u;
  981. // Number of bytes that has been pushed by the server but never claimed.
  982. uint64_t bytes_pushed_and_unclaimed_count_ = 0u;
  983. // The write queue.
  984. SpdyWriteQueue write_queue_;
  985. // Data for the frame we are currently sending.
  986. // The buffer we're currently writing.
  987. std::unique_ptr<SpdyBuffer> in_flight_write_;
  988. // The type of the frame in |in_flight_write_|.
  989. spdy::SpdyFrameType in_flight_write_frame_type_ = spdy::SpdyFrameType::DATA;
  990. // The size of the frame in |in_flight_write_|.
  991. size_t in_flight_write_frame_size_ = 0;
  992. // The stream to notify when |in_flight_write_| has been written to
  993. // the socket completely.
  994. base::WeakPtr<SpdyStream> in_flight_write_stream_;
  995. // Traffic annotation for the write in progress.
  996. MutableNetworkTrafficAnnotationTag in_flight_write_traffic_annotation_;
  997. // Spdy Frame state.
  998. std::unique_ptr<BufferedSpdyFramer> buffered_spdy_framer_;
  999. // The state variables.
  1000. AvailabilityState availability_state_ = STATE_AVAILABLE;
  1001. ReadState read_state_ = READ_STATE_DO_READ;
  1002. WriteState write_state_ = WRITE_STATE_IDLE;
  1003. // If the session is closing (i.e., |availability_state_| is STATE_DRAINING),
  1004. // then |error_on_close_| holds the error with which it was closed, which
  1005. // may be OK (upon a polite GOAWAY) or an error < ERR_IO_PENDING otherwise.
  1006. // Initialized to OK.
  1007. Error error_on_close_ = OK;
  1008. // Settings that are sent in the initial SETTINGS frame
  1009. // (if |enable_sending_initial_data_| is true),
  1010. // and also control SpdySession parameters like initial receive window size
  1011. // and maximum HPACK dynamic table size.
  1012. const spdy::SettingsMap initial_settings_;
  1013. // If true, a setting parameter with reserved identifier will be sent in every
  1014. // initial SETTINGS frame, see
  1015. // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
  1016. // The setting identifier and value will be drawn independently for each
  1017. // connection to prevent tracking of the client.
  1018. const bool enable_http2_settings_grease_;
  1019. // If set, an HTTP/2 frame with a reserved frame type will be sent after
  1020. // every HTTP/2 SETTINGS frame and before every HTTP/2 DATA frame. See
  1021. // https://tools.ietf.org/html/draft-bishop-httpbis-grease-00.
  1022. const absl::optional<SpdySessionPool::GreasedHttp2Frame> greased_http2_frame_;
  1023. // If set, the HEADERS frame carrying a request without body will not have the
  1024. // END_STREAM flag set. The stream will be closed by a subsequent empty DATA
  1025. // frame with END_STREAM. Does not affect bidirectional or proxy streams.
  1026. // If unset, the HEADERS frame will have the END_STREAM flag set on.
  1027. // This is useful in conjuction with |greased_http2_frame_| so that a frame
  1028. // of reserved type can be sent out even on requests without a body.
  1029. const bool http2_end_stream_with_data_frame_;
  1030. // If true, enable sending PRIORITY_UPDATE frames until SETTINGS frame
  1031. // arrives. After SETTINGS frame arrives, do not send PRIORITY_UPDATE frames
  1032. // any longer if SETTINGS_DEPRECATE_HTTP2_PRIORITIES is missing or has zero 0,
  1033. // but continue and also stop sending HTTP/2-style priority information in
  1034. // HEADERS frames and PRIORITY frames if it has value 1.
  1035. const bool enable_priority_update_;
  1036. // The value of the last received SETTINGS_DEPRECATE_HTTP2_PRIORITIES, with 0
  1037. // mapping to false and 1 to true. Initial value is false.
  1038. bool deprecate_http2_priorities_ = false;
  1039. // True if at least one SETTINGS frame has been received.
  1040. bool settings_frame_received_ = false;
  1041. // The callbacks to notify a request that the handshake has been confirmed.
  1042. std::vector<CompletionOnceCallback> waiting_for_confirmation_callbacks_;
  1043. // True if there is an ongoing handshake confirmation with outstanding
  1044. // requests.
  1045. bool in_confirm_handshake_ = false;
  1046. // Limits
  1047. size_t max_concurrent_streams_;
  1048. size_t max_concurrent_pushed_streams_;
  1049. // Some statistics counters for the session.
  1050. int streams_initiated_count_ = 0;
  1051. int streams_pushed_count_ = 0;
  1052. int streams_pushed_and_claimed_count_ = 0;
  1053. int streams_abandoned_count_ = 0;
  1054. // True if there has been a ping sent for which we have not received a
  1055. // response yet. There is always at most one ping in flight.
  1056. bool ping_in_flight_ = false;
  1057. // Triggers periodic connection status checks.
  1058. base::OneShotTimer heartbeat_timer_;
  1059. // Period used by the connection status monitoring mechanism.
  1060. base::TimeDelta heartbeat_interval_;
  1061. // True if the connection status should be checked once the radio wakes up.
  1062. bool check_connection_on_radio_wakeup_ = false;
  1063. // This is the next ping_id (unique_id) to be sent in PING frame.
  1064. spdy::SpdyPingId next_ping_id_ = 1;
  1065. // This is the last time we have sent a PING.
  1066. base::TimeTicks last_ping_sent_time_;
  1067. // This is the last time we had read activity in the session.
  1068. base::TimeTicks last_read_time_;
  1069. // This is the length of the last compressed frame.
  1070. size_t last_compressed_frame_len_ = 0;
  1071. // True if there is a CheckPingStatus() task posted on the message loop.
  1072. bool check_ping_status_pending_ = false;
  1073. // Current send window size. Zero unless session flow control is turned on.
  1074. int32_t session_send_window_size_ = 0;
  1075. // Maximum receive window size. Each time a WINDOW_UPDATE is sent, it
  1076. // restores the receive window size to this value. Zero unless session flow
  1077. // control is turned on.
  1078. int32_t session_max_recv_window_size_;
  1079. // Maximum number of capped frames that can be queued at any time.
  1080. // Every time we try to enqueue a capped frame, we check that there aren't
  1081. // more than this amount already queued, and close the connection if so.
  1082. int session_max_queued_capped_frames_;
  1083. // Number of active requests which asked for connection status monitoring.
  1084. int broken_connection_detection_requests_ = 0;
  1085. // Sum of |session_unacked_recv_window_bytes_| and current receive window
  1086. // size. Zero unless session flow control is turned on.
  1087. // TODO(bnc): Rename or change semantics so that |window_size_| is actual
  1088. // window size.
  1089. int32_t session_recv_window_size_ = 0;
  1090. // When bytes are consumed, SpdyIOBuffer destructor calls back to SpdySession,
  1091. // and this member keeps count of them until the corresponding WINDOW_UPDATEs
  1092. // are sent. Zero unless session flow control is turned on.
  1093. int32_t session_unacked_recv_window_bytes_ = 0;
  1094. // Time of the last WINDOW_UPDATE for the receive window.
  1095. base::TimeTicks last_recv_window_update_;
  1096. // Time to accumilate small receive window updates for.
  1097. base::TimeDelta time_to_buffer_small_window_updates_;
  1098. // Initial send window size for this session's streams. Can be
  1099. // changed by an arriving SETTINGS frame. Newly created streams use
  1100. // this value for the initial send window size.
  1101. int32_t stream_initial_send_window_size_;
  1102. // The maximum HPACK dynamic table size the server is allowed to set.
  1103. uint32_t max_header_table_size_;
  1104. // Initial receive window size for this session's streams. There are
  1105. // plans to add a command line switch that would cause a SETTINGS
  1106. // frame with window size announcement to be sent on startup. Newly
  1107. // created streams will use this value for the initial receive
  1108. // window size.
  1109. int32_t stream_max_recv_window_size_;
  1110. // A queue of stream IDs that have been send-stalled at some point
  1111. // in the past.
  1112. base::circular_deque<spdy::SpdyStreamId>
  1113. stream_send_unstall_queue_[NUM_PRIORITIES];
  1114. NetLogWithSource net_log_;
  1115. // Versions of QUIC which may be used.
  1116. const quic::ParsedQuicVersionVector quic_supported_versions_;
  1117. // Outside of tests, these should always be true.
  1118. const bool enable_sending_initial_data_;
  1119. const bool enable_ping_based_connection_checking_;
  1120. const bool is_http2_enabled_;
  1121. const bool is_quic_enabled_;
  1122. // If true, accept pushed streams from server.
  1123. // If false, reset pushed streams immediately.
  1124. const bool enable_push_;
  1125. // True if the server has advertised WebSocket support via
  1126. // spdy::SETTINGS_ENABLE_CONNECT_PROTOCOL, see
  1127. // https://tools.ietf.org/html/draft-ietf-httpbis-h2-websockets-00.
  1128. bool support_websocket_ = false;
  1129. // |connection_at_risk_of_loss_time_| is an optimization to avoid sending
  1130. // wasteful preface pings (when we just got some data).
  1131. //
  1132. // If it is zero (the most conservative figure), then we always send the
  1133. // preface ping (when none are in flight).
  1134. //
  1135. // It is common for TCP/IP sessions to time out in about 3-5 minutes.
  1136. // Certainly if it has been more than 3 minutes, we do want to send a preface
  1137. // ping.
  1138. //
  1139. // We don't think any connection will time out in under about 10 seconds. So
  1140. // this might as well be set to something conservative like 10 seconds. Later,
  1141. // we could adjust it to send fewer pings perhaps.
  1142. base::TimeDelta connection_at_risk_of_loss_time_;
  1143. // The amount of time that we are willing to tolerate with no activity (of any
  1144. // form), while there is a ping in flight, before we declare the connection to
  1145. // be hung. TODO(rtenneti): When hung, instead of resetting connection, race
  1146. // to build a new connection, and see if that completes before we (finally)
  1147. // get a PING response (http://crbug.com/127812).
  1148. base::TimeDelta hung_interval_;
  1149. TimeFunc time_func_;
  1150. Http2PriorityDependencies priority_dependency_state_;
  1151. // Map of origin to Accept-CH header field values received via ALPS.
  1152. base::flat_map<url::SchemeHostPort, std::string>
  1153. accept_ch_entries_received_via_alps_;
  1154. // Network quality estimator to which the ping RTTs should be reported. May be
  1155. // nullptr.
  1156. raw_ptr<NetworkQualityEstimator> network_quality_estimator_;
  1157. // Used for accessing the SpdySession from asynchronous tasks. An asynchronous
  1158. // must check if its WeakPtr<SpdySession> is valid before accessing it, to
  1159. // correctly handle the case where it became unavailable and was deleted.
  1160. base::WeakPtrFactory<SpdySession> weak_factory_{this};
  1161. };
  1162. } // namespace net
  1163. #endif // NET_SPDY_SPDY_SESSION_H_