1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/spdy/spdy_test_util_common.h"
6
7 #include <cstddef>
8 #include <utility>
9
10 #include "base/base64.h"
11 #include "base/check_op.h"
12 #include "base/compiler_specific.h"
13 #include "base/containers/span.h"
14 #include "base/functional/bind.h"
15 #include "base/notreached.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_piece.h"
18 #include "base/strings/string_split.h"
19 #include "build/build_config.h"
20 #include "net/base/features.h"
21 #include "net/base/host_port_pair.h"
22 #include "net/base/http_user_agent_settings.h"
23 #include "net/cert/ct_policy_enforcer.h"
24 #include "net/cert/ct_policy_status.h"
25 #include "net/cert/mock_cert_verifier.h"
26 #include "net/cert/signed_certificate_timestamp_and_status.h"
27 #include "net/dns/host_resolver.h"
28 #include "net/dns/public/secure_dns_policy.h"
29 #include "net/http/http_cache.h"
30 #include "net/http/http_network_transaction.h"
31 #include "net/http/http_proxy_connect_job.h"
32 #include "net/log/net_log_with_source.h"
33 #include "net/proxy_resolution/configured_proxy_resolution_service.h"
34 #include "net/quic/quic_context.h"
35 #include "net/quic/quic_http_utils.h"
36 #include "net/socket/client_socket_handle.h"
37 #include "net/socket/next_proto.h"
38 #include "net/socket/socket_tag.h"
39 #include "net/socket/socks_connect_job.h"
40 #include "net/socket/ssl_client_socket.h"
41 #include "net/socket/transport_client_socket_pool.h"
42 #include "net/spdy/buffered_spdy_framer.h"
43 #include "net/spdy/spdy_http_utils.h"
44 #include "net/spdy/spdy_stream.h"
45 #include "net/ssl/ssl_connection_status_flags.h"
46 #include "net/test/gtest_util.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/traffic_annotation/network_traffic_annotation_test_helper.h"
50 #include "net/url_request/static_http_user_agent_settings.h"
51 #include "net/url_request/url_request_context_builder.h"
52 #include "net/url_request/url_request_job_factory.h"
53 #include "net/url_request/url_request_test_util.h"
54 #include "testing/gmock/include/gmock/gmock.h"
55 #include "third_party/abseil-cpp/absl/types/optional.h"
56 #include "url/scheme_host_port.h"
57 #include "url/url_constants.h"
58
59 using net::test::IsError;
60 using net::test::IsOk;
61
62 namespace net {
63
64 namespace {
65
66 // Parses a URL into the scheme, host, and path components required for a
67 // SPDY request.
ParseUrl(base::StringPiece url,std::string * scheme,std::string * host,std::string * path)68 void ParseUrl(base::StringPiece url,
69 std::string* scheme,
70 std::string* host,
71 std::string* path) {
72 GURL gurl(url);
73 path->assign(gurl.PathForRequest());
74 scheme->assign(gurl.scheme());
75 host->assign(gurl.host());
76 if (gurl.has_port()) {
77 host->append(":");
78 host->append(gurl.port());
79 }
80 }
81
82 } // namespace
83
84 // Chop a frame into an array of MockWrites.
85 // |frame| is the frame to chop.
86 // |num_chunks| is the number of chunks to create.
ChopWriteFrame(const spdy::SpdySerializedFrame & frame,int num_chunks)87 std::unique_ptr<MockWrite[]> ChopWriteFrame(
88 const spdy::SpdySerializedFrame& frame,
89 int num_chunks) {
90 auto chunks = std::make_unique<MockWrite[]>(num_chunks);
91 int chunk_size = frame.size() / num_chunks;
92 for (int index = 0; index < num_chunks; index++) {
93 const char* ptr = frame.data() + (index * chunk_size);
94 if (index == num_chunks - 1)
95 chunk_size +=
96 frame.size() % chunk_size; // The last chunk takes the remainder.
97 chunks[index] = MockWrite(ASYNC, ptr, chunk_size);
98 }
99 return chunks;
100 }
101
102 // Adds headers and values to a map.
103 // |extra_headers| is an array of { name, value } pairs, arranged as strings
104 // where the even entries are the header names, and the odd entries are the
105 // header values.
106 // |headers| gets filled in from |extra_headers|.
AppendToHeaderBlock(const char * const extra_headers[],int extra_header_count,spdy::Http2HeaderBlock * headers)107 void AppendToHeaderBlock(const char* const extra_headers[],
108 int extra_header_count,
109 spdy::Http2HeaderBlock* headers) {
110 if (!extra_header_count)
111 return;
112
113 // Sanity check: Non-NULL header list.
114 DCHECK(extra_headers) << "NULL header value pair list";
115 // Sanity check: Non-NULL header map.
116 DCHECK(headers) << "NULL header map";
117
118 // Copy in the headers.
119 for (int i = 0; i < extra_header_count; i++) {
120 std::string_view key(extra_headers[i * 2]);
121 std::string_view value(extra_headers[i * 2 + 1]);
122 DCHECK(!key.empty()) << "Header key must not be empty.";
123 headers->AppendValueOrAddHeader(key, value);
124 }
125 }
126
127 // Create a MockWrite from the given spdy::SpdySerializedFrame.
CreateMockWrite(const spdy::SpdySerializedFrame & req)128 MockWrite CreateMockWrite(const spdy::SpdySerializedFrame& req) {
129 return MockWrite(ASYNC, req.data(), req.size());
130 }
131
132 // Create a MockWrite from the given spdy::SpdySerializedFrame and sequence
133 // number.
CreateMockWrite(const spdy::SpdySerializedFrame & req,int seq)134 MockWrite CreateMockWrite(const spdy::SpdySerializedFrame& req, int seq) {
135 return CreateMockWrite(req, seq, ASYNC);
136 }
137
138 // Create a MockWrite from the given spdy::SpdySerializedFrame and sequence
139 // number.
CreateMockWrite(const spdy::SpdySerializedFrame & req,int seq,IoMode mode)140 MockWrite CreateMockWrite(const spdy::SpdySerializedFrame& req,
141 int seq,
142 IoMode mode) {
143 return MockWrite(mode, req.data(), req.size(), seq);
144 }
145
146 // Create a MockRead from the given spdy::SpdySerializedFrame.
CreateMockRead(const spdy::SpdySerializedFrame & resp)147 MockRead CreateMockRead(const spdy::SpdySerializedFrame& resp) {
148 return MockRead(ASYNC, resp.data(), resp.size());
149 }
150
151 // Create a MockRead from the given spdy::SpdySerializedFrame and sequence
152 // number.
CreateMockRead(const spdy::SpdySerializedFrame & resp,int seq)153 MockRead CreateMockRead(const spdy::SpdySerializedFrame& resp, int seq) {
154 return CreateMockRead(resp, seq, ASYNC);
155 }
156
157 // Create a MockRead from the given spdy::SpdySerializedFrame and sequence
158 // number.
CreateMockRead(const spdy::SpdySerializedFrame & resp,int seq,IoMode mode)159 MockRead CreateMockRead(const spdy::SpdySerializedFrame& resp,
160 int seq,
161 IoMode mode) {
162 return MockRead(mode, resp.data(), resp.size(), seq);
163 }
164
165 // Combines the given vector of spdy::SpdySerializedFrame into a single frame.
CombineFrames(std::vector<const spdy::SpdySerializedFrame * > frames)166 spdy::SpdySerializedFrame CombineFrames(
167 std::vector<const spdy::SpdySerializedFrame*> frames) {
168 int total_size = 0;
169 for (const auto* frame : frames) {
170 total_size += frame->size();
171 }
172 auto data = std::make_unique<char[]>(total_size);
173 char* ptr = data.get();
174 for (const auto* frame : frames) {
175 memcpy(ptr, frame->data(), frame->size());
176 ptr += frame->size();
177 }
178 return spdy::SpdySerializedFrame(data.release(), total_size,
179 /* owns_buffer = */ true);
180 }
181
182 namespace {
183
184 class PriorityGetter : public BufferedSpdyFramerVisitorInterface {
185 public:
186 PriorityGetter() = default;
187 ~PriorityGetter() override = default;
188
priority() const189 spdy::SpdyPriority priority() const { return priority_; }
190
OnError(http2::Http2DecoderAdapter::SpdyFramerError spdy_framer_error)191 void OnError(
192 http2::Http2DecoderAdapter::SpdyFramerError spdy_framer_error) override {}
OnStreamError(spdy::SpdyStreamId stream_id,const std::string & description)193 void OnStreamError(spdy::SpdyStreamId stream_id,
194 const std::string& description) override {}
OnHeaders(spdy::SpdyStreamId stream_id,bool has_priority,int weight,spdy::SpdyStreamId parent_stream_id,bool exclusive,bool fin,spdy::Http2HeaderBlock headers,base::TimeTicks recv_first_byte_time)195 void OnHeaders(spdy::SpdyStreamId stream_id,
196 bool has_priority,
197 int weight,
198 spdy::SpdyStreamId parent_stream_id,
199 bool exclusive,
200 bool fin,
201 spdy::Http2HeaderBlock headers,
202 base::TimeTicks recv_first_byte_time) override {
203 if (has_priority) {
204 priority_ = spdy::Http2WeightToSpdy3Priority(weight);
205 }
206 }
OnDataFrameHeader(spdy::SpdyStreamId stream_id,size_t length,bool fin)207 void OnDataFrameHeader(spdy::SpdyStreamId stream_id,
208 size_t length,
209 bool fin) override {}
OnStreamFrameData(spdy::SpdyStreamId stream_id,const char * data,size_t len)210 void OnStreamFrameData(spdy::SpdyStreamId stream_id,
211 const char* data,
212 size_t len) override {}
OnStreamEnd(spdy::SpdyStreamId stream_id)213 void OnStreamEnd(spdy::SpdyStreamId stream_id) override {}
OnStreamPadding(spdy::SpdyStreamId stream_id,size_t len)214 void OnStreamPadding(spdy::SpdyStreamId stream_id, size_t len) override {}
OnSettings()215 void OnSettings() override {}
OnSettingsAck()216 void OnSettingsAck() override {}
OnSetting(spdy::SpdySettingsId id,uint32_t value)217 void OnSetting(spdy::SpdySettingsId id, uint32_t value) override {}
OnSettingsEnd()218 void OnSettingsEnd() override {}
OnPing(spdy::SpdyPingId unique_id,bool is_ack)219 void OnPing(spdy::SpdyPingId unique_id, bool is_ack) override {}
OnRstStream(spdy::SpdyStreamId stream_id,spdy::SpdyErrorCode error_code)220 void OnRstStream(spdy::SpdyStreamId stream_id,
221 spdy::SpdyErrorCode error_code) override {}
OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,spdy::SpdyErrorCode error_code,base::StringPiece debug_data)222 void OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,
223 spdy::SpdyErrorCode error_code,
224 base::StringPiece debug_data) override {}
OnWindowUpdate(spdy::SpdyStreamId stream_id,int delta_window_size)225 void OnWindowUpdate(spdy::SpdyStreamId stream_id,
226 int delta_window_size) override {}
OnPushPromise(spdy::SpdyStreamId stream_id,spdy::SpdyStreamId promised_stream_id,spdy::Http2HeaderBlock headers)227 void OnPushPromise(spdy::SpdyStreamId stream_id,
228 spdy::SpdyStreamId promised_stream_id,
229 spdy::Http2HeaderBlock headers) override {}
OnAltSvc(spdy::SpdyStreamId stream_id,base::StringPiece origin,const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector & altsvc_vector)230 void OnAltSvc(spdy::SpdyStreamId stream_id,
231 base::StringPiece origin,
232 const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector&
233 altsvc_vector) override {}
OnUnknownFrame(spdy::SpdyStreamId stream_id,uint8_t frame_type)234 bool OnUnknownFrame(spdy::SpdyStreamId stream_id,
235 uint8_t frame_type) override {
236 return false;
237 }
238
239 private:
240 spdy::SpdyPriority priority_ = 0;
241 };
242
243 } // namespace
244
GetSpdyPriority(const spdy::SpdySerializedFrame & frame,spdy::SpdyPriority * priority)245 bool GetSpdyPriority(const spdy::SpdySerializedFrame& frame,
246 spdy::SpdyPriority* priority) {
247 NetLogWithSource net_log;
248 BufferedSpdyFramer framer(kMaxHeaderListSizeForTest, net_log);
249 PriorityGetter priority_getter;
250 framer.set_visitor(&priority_getter);
251 size_t frame_size = frame.size();
252 if (framer.ProcessInput(frame.data(), frame_size) != frame_size) {
253 return false;
254 }
255 *priority = priority_getter.priority();
256 return true;
257 }
258
CreateStreamSynchronously(SpdyStreamType type,const base::WeakPtr<SpdySession> & session,const GURL & url,RequestPriority priority,const NetLogWithSource & net_log,bool detect_broken_connection,base::TimeDelta heartbeat_interval)259 base::WeakPtr<SpdyStream> CreateStreamSynchronously(
260 SpdyStreamType type,
261 const base::WeakPtr<SpdySession>& session,
262 const GURL& url,
263 RequestPriority priority,
264 const NetLogWithSource& net_log,
265 bool detect_broken_connection,
266 base::TimeDelta heartbeat_interval) {
267 SpdyStreamRequest stream_request;
268 int rv = stream_request.StartRequest(
269 type, session, url, false /* no early data */, priority, SocketTag(),
270 net_log, CompletionOnceCallback(), TRAFFIC_ANNOTATION_FOR_TESTS,
271 detect_broken_connection, heartbeat_interval);
272
273 return
274 (rv == OK) ? stream_request.ReleaseStream() : base::WeakPtr<SpdyStream>();
275 }
276
277 StreamReleaserCallback::StreamReleaserCallback() = default;
278
279 StreamReleaserCallback::~StreamReleaserCallback() = default;
280
MakeCallback(SpdyStreamRequest * request)281 CompletionOnceCallback StreamReleaserCallback::MakeCallback(
282 SpdyStreamRequest* request) {
283 return base::BindOnce(&StreamReleaserCallback::OnComplete,
284 base::Unretained(this), request);
285 }
286
OnComplete(SpdyStreamRequest * request,int result)287 void StreamReleaserCallback::OnComplete(
288 SpdyStreamRequest* request, int result) {
289 if (result == OK)
290 request->ReleaseStream()->Cancel(ERR_ABORTED);
291 SetResult(result);
292 }
293
SpdySessionDependencies()294 SpdySessionDependencies::SpdySessionDependencies()
295 : SpdySessionDependencies(
296 ConfiguredProxyResolutionService::CreateDirect()) {}
297
SpdySessionDependencies(std::unique_ptr<ProxyResolutionService> proxy_resolution_service)298 SpdySessionDependencies::SpdySessionDependencies(
299 std::unique_ptr<ProxyResolutionService> proxy_resolution_service)
300 : host_resolver(std::make_unique<MockCachingHostResolver>(
301 /*cache_invalidation_num=*/0,
302 MockHostResolverBase::RuleResolver::GetLocalhostResult())),
303 cert_verifier(std::make_unique<MockCertVerifier>()),
304 transport_security_state(std::make_unique<TransportSecurityState>()),
305 ct_policy_enforcer(std::make_unique<DefaultCTPolicyEnforcer>()),
306 proxy_resolution_service(std::move(proxy_resolution_service)),
307 ssl_config_service(std::make_unique<SSLConfigServiceDefaults>()),
308 socket_factory(std::make_unique<MockClientSocketFactory>()),
309 http_auth_handler_factory(HttpAuthHandlerFactory::CreateDefault()),
310 http_server_properties(std::make_unique<HttpServerProperties>()),
311 quic_context(std::make_unique<QuicContext>()),
312 time_func(&base::TimeTicks::Now) {
313 http2_settings[spdy::SETTINGS_INITIAL_WINDOW_SIZE] =
314 kDefaultInitialWindowSize;
315 }
316
317 SpdySessionDependencies::SpdySessionDependencies(SpdySessionDependencies&&) =
318 default;
319
320 SpdySessionDependencies::~SpdySessionDependencies() = default;
321
322 SpdySessionDependencies& SpdySessionDependencies::operator=(
323 SpdySessionDependencies&&) = default;
324
325 // static
SpdyCreateSession(SpdySessionDependencies * session_deps)326 std::unique_ptr<HttpNetworkSession> SpdySessionDependencies::SpdyCreateSession(
327 SpdySessionDependencies* session_deps) {
328 return SpdyCreateSessionWithSocketFactory(session_deps,
329 session_deps->socket_factory.get());
330 }
331
332 // static
333 std::unique_ptr<HttpNetworkSession>
SpdyCreateSessionWithSocketFactory(SpdySessionDependencies * session_deps,ClientSocketFactory * factory)334 SpdySessionDependencies::SpdyCreateSessionWithSocketFactory(
335 SpdySessionDependencies* session_deps,
336 ClientSocketFactory* factory) {
337 HttpNetworkSessionParams session_params = CreateSessionParams(session_deps);
338 HttpNetworkSessionContext session_context =
339 CreateSessionContext(session_deps);
340 session_context.client_socket_factory = factory;
341 auto http_session =
342 std::make_unique<HttpNetworkSession>(session_params, session_context);
343 SpdySessionPoolPeer pool_peer(http_session->spdy_session_pool());
344 pool_peer.SetEnableSendingInitialData(false);
345 return http_session;
346 }
347
348 // static
CreateSessionParams(SpdySessionDependencies * session_deps)349 HttpNetworkSessionParams SpdySessionDependencies::CreateSessionParams(
350 SpdySessionDependencies* session_deps) {
351 HttpNetworkSessionParams params;
352 params.enable_spdy_ping_based_connection_checking = session_deps->enable_ping;
353 params.enable_user_alternate_protocol_ports =
354 session_deps->enable_user_alternate_protocol_ports;
355 params.enable_quic = session_deps->enable_quic;
356 params.spdy_session_max_recv_window_size =
357 session_deps->session_max_recv_window_size;
358 params.spdy_session_max_queued_capped_frames =
359 session_deps->session_max_queued_capped_frames;
360 params.http2_settings = session_deps->http2_settings;
361 params.time_func = session_deps->time_func;
362 params.enable_http2_alternative_service =
363 session_deps->enable_http2_alternative_service;
364 params.enable_http2_settings_grease =
365 session_deps->enable_http2_settings_grease;
366 params.greased_http2_frame = session_deps->greased_http2_frame;
367 params.http2_end_stream_with_data_frame =
368 session_deps->http2_end_stream_with_data_frame;
369 params.disable_idle_sockets_close_on_memory_pressure =
370 session_deps->disable_idle_sockets_close_on_memory_pressure;
371 params.enable_early_data = session_deps->enable_early_data;
372 params.key_auth_cache_server_entries_by_network_anonymization_key =
373 session_deps->key_auth_cache_server_entries_by_network_anonymization_key;
374 params.enable_priority_update = session_deps->enable_priority_update;
375 params.spdy_go_away_on_ip_change = session_deps->go_away_on_ip_change;
376 params.ignore_ip_address_changes = session_deps->ignore_ip_address_changes;
377 return params;
378 }
379
CreateSessionContext(SpdySessionDependencies * session_deps)380 HttpNetworkSessionContext SpdySessionDependencies::CreateSessionContext(
381 SpdySessionDependencies* session_deps) {
382 HttpNetworkSessionContext context;
383 context.client_socket_factory = session_deps->socket_factory.get();
384 context.host_resolver = session_deps->GetHostResolver();
385 context.cert_verifier = session_deps->cert_verifier.get();
386 context.transport_security_state =
387 session_deps->transport_security_state.get();
388 context.ct_policy_enforcer = session_deps->ct_policy_enforcer.get();
389 context.proxy_resolution_service =
390 session_deps->proxy_resolution_service.get();
391 context.http_user_agent_settings =
392 session_deps->http_user_agent_settings.get();
393 context.ssl_config_service = session_deps->ssl_config_service.get();
394 context.http_auth_handler_factory =
395 session_deps->http_auth_handler_factory.get();
396 context.http_server_properties = session_deps->http_server_properties.get();
397 context.quic_context = session_deps->quic_context.get();
398 context.net_log = session_deps->net_log;
399 #if BUILDFLAG(ENABLE_REPORTING)
400 context.reporting_service = session_deps->reporting_service.get();
401 context.network_error_logging_service =
402 session_deps->network_error_logging_service.get();
403 #endif
404 return context;
405 }
406
407 std::unique_ptr<URLRequestContextBuilder>
CreateSpdyTestURLRequestContextBuilder(ClientSocketFactory * client_socket_factory)408 CreateSpdyTestURLRequestContextBuilder(
409 ClientSocketFactory* client_socket_factory) {
410 auto builder = CreateTestURLRequestContextBuilder();
411 builder->set_client_socket_factory_for_testing( // IN-TEST
412 client_socket_factory);
413 builder->set_host_resolver(std::make_unique<MockHostResolver>(
414 /*default_result=*/MockHostResolverBase::RuleResolver::
415 GetLocalhostResult()));
416 builder->SetCertVerifier(std::make_unique<MockCertVerifier>());
417 HttpNetworkSessionParams session_params;
418 session_params.enable_spdy_ping_based_connection_checking = false;
419 builder->set_http_network_session_params(session_params);
420 builder->set_http_user_agent_settings(
421 std::make_unique<StaticHttpUserAgentSettings>("", ""));
422 return builder;
423 }
424
HasSpdySession(SpdySessionPool * pool,const SpdySessionKey & key)425 bool HasSpdySession(SpdySessionPool* pool, const SpdySessionKey& key) {
426 return static_cast<bool>(pool->FindAvailableSession(
427 key, /* enable_ip_based_pooling = */ true,
428 /* is_websocket = */ false, NetLogWithSource()));
429 }
430
431 namespace {
432
CreateSpdySessionHelper(HttpNetworkSession * http_session,const SpdySessionKey & key,const NetLogWithSource & net_log,bool enable_ip_based_pooling)433 base::WeakPtr<SpdySession> CreateSpdySessionHelper(
434 HttpNetworkSession* http_session,
435 const SpdySessionKey& key,
436 const NetLogWithSource& net_log,
437 bool enable_ip_based_pooling) {
438 EXPECT_FALSE(http_session->spdy_session_pool()->FindAvailableSession(
439 key, enable_ip_based_pooling,
440 /*is_websocket=*/false, NetLogWithSource()));
441
442 auto connection = std::make_unique<ClientSocketHandle>();
443 TestCompletionCallback callback;
444
445 auto ssl_config = std::make_unique<SSLConfig>();
446 ssl_config->alpn_protos = http_session->GetAlpnProtos();
447 scoped_refptr<ClientSocketPool::SocketParams> socket_params =
448 base::MakeRefCounted<ClientSocketPool::SocketParams>(
449 /*ssl_config_for_origin=*/std::move(ssl_config),
450 /*base_ssl_config_for_proxies=*/nullptr);
451 int rv = connection->Init(
452 ClientSocketPool::GroupId(
453 url::SchemeHostPort(url::kHttpsScheme,
454 key.host_port_pair().HostForURL(),
455 key.host_port_pair().port()),
456 key.privacy_mode(), NetworkAnonymizationKey(),
457 SecureDnsPolicy::kAllow),
458 socket_params, /*proxy_annotation_tag=*/absl::nullopt, MEDIUM,
459 key.socket_tag(), ClientSocketPool::RespectLimits::ENABLED,
460 callback.callback(), ClientSocketPool::ProxyAuthCallback(),
461 http_session->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL,
462 ProxyChain::Direct()),
463 net_log);
464 rv = callback.GetResult(rv);
465 EXPECT_THAT(rv, IsOk());
466
467 base::WeakPtr<SpdySession> spdy_session;
468 rv =
469 http_session->spdy_session_pool()->CreateAvailableSessionFromSocketHandle(
470 key, std::move(connection), net_log, &spdy_session);
471 // Failure is reported asynchronously.
472 EXPECT_THAT(rv, IsOk());
473 EXPECT_TRUE(spdy_session);
474 EXPECT_TRUE(HasSpdySession(http_session->spdy_session_pool(), key));
475 // Disable the time-based receive window updates by setting the delay to
476 // the max time interval. This prevents time-based flakiness in the tests
477 // for any test not explicitly exercising the window update buffering.
478 spdy_session->SetTimeToBufferSmallWindowUpdates(base::TimeDelta::Max());
479 return spdy_session;
480 }
481
482 } // namespace
483
CreateSpdySession(HttpNetworkSession * http_session,const SpdySessionKey & key,const NetLogWithSource & net_log)484 base::WeakPtr<SpdySession> CreateSpdySession(HttpNetworkSession* http_session,
485 const SpdySessionKey& key,
486 const NetLogWithSource& net_log) {
487 return CreateSpdySessionHelper(http_session, key, net_log,
488 /* enable_ip_based_pooling = */ true);
489 }
490
CreateSpdySessionWithIpBasedPoolingDisabled(HttpNetworkSession * http_session,const SpdySessionKey & key,const NetLogWithSource & net_log)491 base::WeakPtr<SpdySession> CreateSpdySessionWithIpBasedPoolingDisabled(
492 HttpNetworkSession* http_session,
493 const SpdySessionKey& key,
494 const NetLogWithSource& net_log) {
495 return CreateSpdySessionHelper(http_session, key, net_log,
496 /* enable_ip_based_pooling = */ false);
497 }
498
499 namespace {
500
501 // A ClientSocket used for CreateFakeSpdySession() below.
502 class FakeSpdySessionClientSocket : public MockClientSocket {
503 public:
FakeSpdySessionClientSocket()504 FakeSpdySessionClientSocket() : MockClientSocket(NetLogWithSource()) {}
505
506 ~FakeSpdySessionClientSocket() override = default;
507
Read(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)508 int Read(IOBuffer* buf,
509 int buf_len,
510 CompletionOnceCallback callback) override {
511 return ERR_IO_PENDING;
512 }
513
Write(IOBuffer * buf,int buf_len,CompletionOnceCallback callback,const NetworkTrafficAnnotationTag & traffic_annotation)514 int Write(IOBuffer* buf,
515 int buf_len,
516 CompletionOnceCallback callback,
517 const NetworkTrafficAnnotationTag& traffic_annotation) override {
518 return ERR_IO_PENDING;
519 }
520
521 // Return kProtoUnknown to use the pool's default protocol.
GetNegotiatedProtocol() const522 NextProto GetNegotiatedProtocol() const override { return kProtoUnknown; }
523
524 // The functions below are not expected to be called.
525
Connect(CompletionOnceCallback callback)526 int Connect(CompletionOnceCallback callback) override {
527 ADD_FAILURE();
528 return ERR_UNEXPECTED;
529 }
530
WasEverUsed() const531 bool WasEverUsed() const override {
532 ADD_FAILURE();
533 return false;
534 }
535
GetSSLInfo(SSLInfo * ssl_info)536 bool GetSSLInfo(SSLInfo* ssl_info) override {
537 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_3,
538 &ssl_info->connection_status);
539 SSLConnectionStatusSetCipherSuite(0x1301 /* TLS_CHACHA20_POLY1305_SHA256 */,
540 &ssl_info->connection_status);
541 return true;
542 }
543
GetTotalReceivedBytes() const544 int64_t GetTotalReceivedBytes() const override {
545 NOTIMPLEMENTED();
546 return 0;
547 }
548 };
549
550 } // namespace
551
CreateFakeSpdySession(SpdySessionPool * pool,const SpdySessionKey & key)552 base::WeakPtr<SpdySession> CreateFakeSpdySession(SpdySessionPool* pool,
553 const SpdySessionKey& key) {
554 EXPECT_FALSE(HasSpdySession(pool, key));
555 auto handle = std::make_unique<ClientSocketHandle>();
556 handle->SetSocket(std::make_unique<FakeSpdySessionClientSocket>());
557 base::WeakPtr<SpdySession> spdy_session;
558 int rv = pool->CreateAvailableSessionFromSocketHandle(
559 key, std::move(handle), NetLogWithSource(), &spdy_session);
560 // Failure is reported asynchronously.
561 EXPECT_THAT(rv, IsOk());
562 EXPECT_TRUE(spdy_session);
563 EXPECT_TRUE(HasSpdySession(pool, key));
564 // Disable the time-based receive window updates by setting the delay to
565 // the max time interval. This prevents time-based flakiness in the tests
566 // for any test not explicitly exercising the window update buffering.
567 spdy_session->SetTimeToBufferSmallWindowUpdates(base::TimeDelta::Max());
568 return spdy_session;
569 }
570
SpdySessionPoolPeer(SpdySessionPool * pool)571 SpdySessionPoolPeer::SpdySessionPoolPeer(SpdySessionPool* pool) : pool_(pool) {
572 }
573
RemoveAliases(const SpdySessionKey & key)574 void SpdySessionPoolPeer::RemoveAliases(const SpdySessionKey& key) {
575 pool_->RemoveAliases(key);
576 }
577
SetEnableSendingInitialData(bool enabled)578 void SpdySessionPoolPeer::SetEnableSendingInitialData(bool enabled) {
579 pool_->enable_sending_initial_data_ = enabled;
580 }
581
SpdyTestUtil(bool use_priority_header)582 SpdyTestUtil::SpdyTestUtil(bool use_priority_header)
583 : headerless_spdy_framer_(spdy::SpdyFramer::ENABLE_COMPRESSION),
584 request_spdy_framer_(spdy::SpdyFramer::ENABLE_COMPRESSION),
585 response_spdy_framer_(spdy::SpdyFramer::ENABLE_COMPRESSION),
586 default_url_(GURL(kDefaultUrl)),
587 use_priority_header_(use_priority_header) {}
588
589 SpdyTestUtil::~SpdyTestUtil() = default;
590
AddUrlToHeaderBlock(base::StringPiece url,spdy::Http2HeaderBlock * headers) const591 void SpdyTestUtil::AddUrlToHeaderBlock(base::StringPiece url,
592 spdy::Http2HeaderBlock* headers) const {
593 std::string scheme, host, path;
594 ParseUrl(url, &scheme, &host, &path);
595 (*headers)[spdy::kHttp2AuthorityHeader] = host;
596 (*headers)[spdy::kHttp2SchemeHeader] = scheme;
597 (*headers)[spdy::kHttp2PathHeader] = path;
598 }
599
AddPriorityToHeaderBlock(RequestPriority request_priority,bool priority_incremental,spdy::Http2HeaderBlock * headers) const600 void SpdyTestUtil::AddPriorityToHeaderBlock(
601 RequestPriority request_priority,
602 bool priority_incremental,
603 spdy::Http2HeaderBlock* headers) const {
604 if (use_priority_header_ &&
605 base::FeatureList::IsEnabled(net::features::kPriorityHeader)) {
606 uint8_t urgency = ConvertRequestPriorityToQuicPriority(request_priority);
607 bool incremental = priority_incremental;
608 quic::HttpStreamPriority priority{urgency, incremental};
609 (*headers)[kHttp2PriorityHeader] =
610 quic::SerializePriorityFieldValue(priority);
611 }
612 }
613
614 // static
ConstructGetHeaderBlock(base::StringPiece url)615 spdy::Http2HeaderBlock SpdyTestUtil::ConstructGetHeaderBlock(
616 base::StringPiece url) {
617 return ConstructHeaderBlock("GET", url, nullptr);
618 }
619
620 // static
ConstructGetHeaderBlockForProxy(base::StringPiece url)621 spdy::Http2HeaderBlock SpdyTestUtil::ConstructGetHeaderBlockForProxy(
622 base::StringPiece url) {
623 return ConstructGetHeaderBlock(url);
624 }
625
626 // static
ConstructHeadHeaderBlock(base::StringPiece url,int64_t content_length)627 spdy::Http2HeaderBlock SpdyTestUtil::ConstructHeadHeaderBlock(
628 base::StringPiece url,
629 int64_t content_length) {
630 return ConstructHeaderBlock("HEAD", url, nullptr);
631 }
632
633 // static
ConstructPostHeaderBlock(base::StringPiece url,int64_t content_length)634 spdy::Http2HeaderBlock SpdyTestUtil::ConstructPostHeaderBlock(
635 base::StringPiece url,
636 int64_t content_length) {
637 return ConstructHeaderBlock("POST", url, &content_length);
638 }
639
640 // static
ConstructPutHeaderBlock(base::StringPiece url,int64_t content_length)641 spdy::Http2HeaderBlock SpdyTestUtil::ConstructPutHeaderBlock(
642 base::StringPiece url,
643 int64_t content_length) {
644 return ConstructHeaderBlock("PUT", url, &content_length);
645 }
646
ConstructSpdyReplyString(const spdy::Http2HeaderBlock & headers) const647 std::string SpdyTestUtil::ConstructSpdyReplyString(
648 const spdy::Http2HeaderBlock& headers) const {
649 std::string reply_string;
650 for (spdy::Http2HeaderBlock::const_iterator it = headers.begin();
651 it != headers.end(); ++it) {
652 auto key = std::string(it->first);
653 // Remove leading colon from pseudo headers.
654 if (key[0] == ':')
655 key = key.substr(1);
656 for (const std::string& value :
657 base::SplitString(it->second, base::StringPiece("\0", 1),
658 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
659 reply_string += key + ": " + value + "\n";
660 }
661 }
662 return reply_string;
663 }
664
665 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
666 // spdy::SpdySettingsIR).
ConstructSpdySettings(const spdy::SettingsMap & settings)667 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdySettings(
668 const spdy::SettingsMap& settings) {
669 spdy::SpdySettingsIR settings_ir;
670 for (const auto& setting : settings) {
671 settings_ir.AddSetting(setting.first, setting.second);
672 }
673 return spdy::SpdySerializedFrame(
674 headerless_spdy_framer_.SerializeFrame(settings_ir));
675 }
676
ConstructSpdySettingsAck()677 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdySettingsAck() {
678 spdy::SpdySettingsIR settings_ir;
679 settings_ir.set_is_ack(true);
680 return spdy::SpdySerializedFrame(
681 headerless_spdy_framer_.SerializeFrame(settings_ir));
682 }
683
ConstructSpdyPing(uint32_t ping_id,bool is_ack)684 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPing(uint32_t ping_id,
685 bool is_ack) {
686 spdy::SpdyPingIR ping_ir(ping_id);
687 ping_ir.set_is_ack(is_ack);
688 return spdy::SpdySerializedFrame(
689 headerless_spdy_framer_.SerializeFrame(ping_ir));
690 }
691
ConstructSpdyGoAway(spdy::SpdyStreamId last_good_stream_id)692 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGoAway(
693 spdy::SpdyStreamId last_good_stream_id) {
694 spdy::SpdyGoAwayIR go_ir(last_good_stream_id, spdy::ERROR_CODE_NO_ERROR,
695 "go away");
696 return spdy::SpdySerializedFrame(
697 headerless_spdy_framer_.SerializeFrame(go_ir));
698 }
699
ConstructSpdyGoAway(spdy::SpdyStreamId last_good_stream_id,spdy::SpdyErrorCode error_code,const std::string & desc)700 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGoAway(
701 spdy::SpdyStreamId last_good_stream_id,
702 spdy::SpdyErrorCode error_code,
703 const std::string& desc) {
704 spdy::SpdyGoAwayIR go_ir(last_good_stream_id, error_code, desc);
705 return spdy::SpdySerializedFrame(
706 headerless_spdy_framer_.SerializeFrame(go_ir));
707 }
708
ConstructSpdyWindowUpdate(const spdy::SpdyStreamId stream_id,uint32_t delta_window_size)709 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyWindowUpdate(
710 const spdy::SpdyStreamId stream_id,
711 uint32_t delta_window_size) {
712 spdy::SpdyWindowUpdateIR update_ir(stream_id, delta_window_size);
713 return spdy::SpdySerializedFrame(
714 headerless_spdy_framer_.SerializeFrame(update_ir));
715 }
716
717 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
718 // spdy::SpdyRstStreamIR).
ConstructSpdyRstStream(spdy::SpdyStreamId stream_id,spdy::SpdyErrorCode error_code)719 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyRstStream(
720 spdy::SpdyStreamId stream_id,
721 spdy::SpdyErrorCode error_code) {
722 spdy::SpdyRstStreamIR rst_ir(stream_id, error_code);
723 return spdy::SpdySerializedFrame(
724 headerless_spdy_framer_.SerializeRstStream(rst_ir));
725 }
726
727 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
728 // spdy::SpdyPriorityIR).
ConstructSpdyPriority(spdy::SpdyStreamId stream_id,spdy::SpdyStreamId parent_stream_id,RequestPriority request_priority,bool exclusive)729 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPriority(
730 spdy::SpdyStreamId stream_id,
731 spdy::SpdyStreamId parent_stream_id,
732 RequestPriority request_priority,
733 bool exclusive) {
734 int weight = spdy::Spdy3PriorityToHttp2Weight(
735 ConvertRequestPriorityToSpdyPriority(request_priority));
736 spdy::SpdyPriorityIR ir(stream_id, parent_stream_id, weight, exclusive);
737 return spdy::SpdySerializedFrame(
738 headerless_spdy_framer_.SerializePriority(ir));
739 }
740
ConstructSpdyGet(const char * const url,spdy::SpdyStreamId stream_id,RequestPriority request_priority,bool priority_incremental,absl::optional<RequestPriority> header_request_priority)741 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGet(
742 const char* const url,
743 spdy::SpdyStreamId stream_id,
744 RequestPriority request_priority,
745 bool priority_incremental,
746 absl::optional<RequestPriority> header_request_priority) {
747 spdy::Http2HeaderBlock block(ConstructGetHeaderBlock(url));
748 return ConstructSpdyHeaders(stream_id, std::move(block), request_priority,
749 true, priority_incremental,
750 header_request_priority);
751 }
752
ConstructSpdyGet(const char * const extra_headers[],int extra_header_count,int stream_id,RequestPriority request_priority,bool priority_incremental,absl::optional<RequestPriority> header_request_priority)753 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGet(
754 const char* const extra_headers[],
755 int extra_header_count,
756 int stream_id,
757 RequestPriority request_priority,
758 bool priority_incremental,
759 absl::optional<RequestPriority> header_request_priority) {
760 spdy::Http2HeaderBlock block;
761 block[spdy::kHttp2MethodHeader] = "GET";
762 AddUrlToHeaderBlock(default_url_.spec(), &block);
763 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
764 return ConstructSpdyHeaders(stream_id, std::move(block), request_priority,
765 true, priority_incremental,
766 header_request_priority);
767 }
768
ConstructSpdyConnect(const char * const extra_headers[],int extra_header_count,int stream_id,RequestPriority priority,const HostPortPair & host_port_pair)769 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyConnect(
770 const char* const extra_headers[],
771 int extra_header_count,
772 int stream_id,
773 RequestPriority priority,
774 const HostPortPair& host_port_pair) {
775 spdy::Http2HeaderBlock block;
776 block[spdy::kHttp2MethodHeader] = "CONNECT";
777 block[spdy::kHttp2AuthorityHeader] = host_port_pair.ToString();
778 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
779 return ConstructSpdyHeaders(stream_id, std::move(block), priority, false);
780 }
781
ConstructSpdyPushPromise(spdy::SpdyStreamId associated_stream_id,spdy::SpdyStreamId stream_id,spdy::Http2HeaderBlock headers)782 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPushPromise(
783 spdy::SpdyStreamId associated_stream_id,
784 spdy::SpdyStreamId stream_id,
785 spdy::Http2HeaderBlock headers) {
786 spdy::SpdyPushPromiseIR push_promise(associated_stream_id, stream_id,
787 std::move(headers));
788 return spdy::SpdySerializedFrame(
789 response_spdy_framer_.SerializeFrame(push_promise));
790 }
791
ConstructSpdyResponseHeaders(int stream_id,spdy::Http2HeaderBlock headers,bool fin)792 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyResponseHeaders(
793 int stream_id,
794 spdy::Http2HeaderBlock headers,
795 bool fin) {
796 spdy::SpdyHeadersIR spdy_headers(stream_id, std::move(headers));
797 spdy_headers.set_fin(fin);
798 return spdy::SpdySerializedFrame(
799 response_spdy_framer_.SerializeFrame(spdy_headers));
800 }
801
ConstructSpdyHeaders(int stream_id,spdy::Http2HeaderBlock block,RequestPriority priority,bool fin,bool priority_incremental,absl::optional<RequestPriority> header_request_priority)802 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyHeaders(
803 int stream_id,
804 spdy::Http2HeaderBlock block,
805 RequestPriority priority,
806 bool fin,
807 bool priority_incremental,
808 absl::optional<RequestPriority> header_request_priority) {
809 // Get the stream id of the next highest priority request
810 // (most recent request of the same priority, or last request of
811 // an earlier priority).
812 // Note that this is a duplicate of the logic in Http2PriorityDependencies
813 // (slightly transformed as this is based on RequestPriority and that logic
814 // on spdy::SpdyPriority, but only slightly transformed) and hence tests using
815 // this function do not effectively test that logic.
816 // That logic is tested by the Http2PriorityDependencies unit tests.
817 int parent_stream_id = 0;
818 for (int q = priority; q <= HIGHEST; ++q) {
819 if (!priority_to_stream_id_list_[q].empty()) {
820 parent_stream_id = priority_to_stream_id_list_[q].back();
821 break;
822 }
823 }
824
825 priority_to_stream_id_list_[priority].push_back(stream_id);
826
827 if (block[spdy::kHttp2MethodHeader] != "CONNECT") {
828 RequestPriority header_priority =
829 header_request_priority.value_or(priority);
830 AddPriorityToHeaderBlock(header_priority, priority_incremental, &block);
831 }
832
833 spdy::SpdyHeadersIR headers(stream_id, std::move(block));
834 headers.set_has_priority(true);
835 headers.set_weight(spdy::Spdy3PriorityToHttp2Weight(
836 ConvertRequestPriorityToSpdyPriority(priority)));
837 headers.set_parent_stream_id(parent_stream_id);
838 headers.set_exclusive(true);
839 headers.set_fin(fin);
840 return spdy::SpdySerializedFrame(
841 request_spdy_framer_.SerializeFrame(headers));
842 }
843
ConstructSpdyReply(int stream_id,spdy::Http2HeaderBlock headers)844 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyReply(
845 int stream_id,
846 spdy::Http2HeaderBlock headers) {
847 spdy::SpdyHeadersIR reply(stream_id, std::move(headers));
848 return spdy::SpdySerializedFrame(response_spdy_framer_.SerializeFrame(reply));
849 }
850
ConstructSpdyReplyError(const char * const status,const char * const * const extra_headers,int extra_header_count,int stream_id)851 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyReplyError(
852 const char* const status,
853 const char* const* const extra_headers,
854 int extra_header_count,
855 int stream_id) {
856 spdy::Http2HeaderBlock block;
857 block[spdy::kHttp2StatusHeader] = status;
858 block["hello"] = "bye";
859 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
860
861 spdy::SpdyHeadersIR reply(stream_id, std::move(block));
862 return spdy::SpdySerializedFrame(response_spdy_framer_.SerializeFrame(reply));
863 }
864
ConstructSpdyReplyError(int stream_id)865 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyReplyError(int stream_id) {
866 return ConstructSpdyReplyError("500", nullptr, 0, stream_id);
867 }
868
ConstructSpdyGetReply(const char * const extra_headers[],int extra_header_count,int stream_id)869 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGetReply(
870 const char* const extra_headers[],
871 int extra_header_count,
872 int stream_id) {
873 spdy::Http2HeaderBlock block;
874 block[spdy::kHttp2StatusHeader] = "200";
875 block["hello"] = "bye";
876 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
877
878 return ConstructSpdyReply(stream_id, std::move(block));
879 }
880
ConstructSpdyPost(const char * url,spdy::SpdyStreamId stream_id,int64_t content_length,RequestPriority request_priority,const char * const extra_headers[],int extra_header_count,bool priority_incremental)881 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPost(
882 const char* url,
883 spdy::SpdyStreamId stream_id,
884 int64_t content_length,
885 RequestPriority request_priority,
886 const char* const extra_headers[],
887 int extra_header_count,
888 bool priority_incremental) {
889 spdy::Http2HeaderBlock block(ConstructPostHeaderBlock(url, content_length));
890 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
891 return ConstructSpdyHeaders(stream_id, std::move(block), request_priority,
892 false, priority_incremental);
893 }
894
ConstructChunkedSpdyPost(const char * const extra_headers[],int extra_header_count,RequestPriority request_priority,bool priority_incremental)895 spdy::SpdySerializedFrame SpdyTestUtil::ConstructChunkedSpdyPost(
896 const char* const extra_headers[],
897 int extra_header_count,
898 RequestPriority request_priority,
899 bool priority_incremental) {
900 spdy::Http2HeaderBlock block;
901 block[spdy::kHttp2MethodHeader] = "POST";
902 AddUrlToHeaderBlock(default_url_.spec(), &block);
903 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
904 return ConstructSpdyHeaders(1, std::move(block), request_priority, false,
905 priority_incremental);
906 }
907
ConstructSpdyPostReply(const char * const extra_headers[],int extra_header_count)908 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPostReply(
909 const char* const extra_headers[],
910 int extra_header_count) {
911 // TODO(jgraettinger): Remove this method.
912 return ConstructSpdyGetReply(extra_headers, extra_header_count, 1);
913 }
914
ConstructSpdyDataFrame(int stream_id,bool fin)915 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyDataFrame(int stream_id,
916 bool fin) {
917 return ConstructSpdyDataFrame(stream_id, kUploadData, fin);
918 }
919
ConstructSpdyDataFrame(int stream_id,base::StringPiece data,bool fin)920 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyDataFrame(
921 int stream_id,
922 base::StringPiece data,
923 bool fin) {
924 spdy::SpdyDataIR data_ir(stream_id, data);
925 data_ir.set_fin(fin);
926 return spdy::SpdySerializedFrame(
927 headerless_spdy_framer_.SerializeData(data_ir));
928 }
929
ConstructSpdyDataFrame(int stream_id,base::StringPiece data,bool fin,int padding_length)930 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyDataFrame(
931 int stream_id,
932 base::StringPiece data,
933 bool fin,
934 int padding_length) {
935 spdy::SpdyDataIR data_ir(stream_id, data);
936 data_ir.set_fin(fin);
937 data_ir.set_padding_len(padding_length);
938 return spdy::SpdySerializedFrame(
939 headerless_spdy_framer_.SerializeData(data_ir));
940 }
941
ConstructWrappedSpdyFrame(const spdy::SpdySerializedFrame & frame,int stream_id)942 spdy::SpdySerializedFrame SpdyTestUtil::ConstructWrappedSpdyFrame(
943 const spdy::SpdySerializedFrame& frame,
944 int stream_id) {
945 return ConstructSpdyDataFrame(
946 stream_id, base::StringPiece(frame.data(), frame.size()), false);
947 }
948
SerializeFrame(const spdy::SpdyFrameIR & frame_ir)949 spdy::SpdySerializedFrame SpdyTestUtil::SerializeFrame(
950 const spdy::SpdyFrameIR& frame_ir) {
951 return headerless_spdy_framer_.SerializeFrame(frame_ir);
952 }
953
UpdateWithStreamDestruction(int stream_id)954 void SpdyTestUtil::UpdateWithStreamDestruction(int stream_id) {
955 for (auto& priority_it : priority_to_stream_id_list_) {
956 for (auto stream_it = priority_it.second.begin();
957 stream_it != priority_it.second.end(); ++stream_it) {
958 if (*stream_it == stream_id) {
959 priority_it.second.erase(stream_it);
960 return;
961 }
962 }
963 }
964 NOTREACHED();
965 }
966
967 // static
ConstructHeaderBlock(base::StringPiece method,base::StringPiece url,int64_t * content_length)968 spdy::Http2HeaderBlock SpdyTestUtil::ConstructHeaderBlock(
969 base::StringPiece method,
970 base::StringPiece url,
971 int64_t* content_length) {
972 std::string scheme, host, path;
973 ParseUrl(url, &scheme, &host, &path);
974 spdy::Http2HeaderBlock headers;
975 headers[spdy::kHttp2MethodHeader] = std::string(method);
976 headers[spdy::kHttp2AuthorityHeader] = host.c_str();
977 headers[spdy::kHttp2SchemeHeader] = scheme.c_str();
978 headers[spdy::kHttp2PathHeader] = path.c_str();
979 if (content_length) {
980 std::string length_str = base::NumberToString(*content_length);
981 headers["content-length"] = length_str;
982 }
983 return headers;
984 }
985
986 namespace test {
GetTestHashValue(uint8_t label)987 HashValue GetTestHashValue(uint8_t label) {
988 HashValue hash_value(HASH_VALUE_SHA256);
989 memset(hash_value.data(), label, hash_value.size());
990 return hash_value;
991 }
992
993 } // namespace test
994 } // namespace net
995