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/host_port_pair.h"
21 #include "net/base/http_user_agent_settings.h"
22 #include "net/cert/ct_policy_enforcer.h"
23 #include "net/cert/ct_policy_status.h"
24 #include "net/cert/mock_cert_verifier.h"
25 #include "net/cert/signed_certificate_timestamp_and_status.h"
26 #include "net/dns/host_resolver.h"
27 #include "net/dns/public/secure_dns_policy.h"
28 #include "net/http/http_cache.h"
29 #include "net/http/http_network_transaction.h"
30 #include "net/http/http_proxy_connect_job.h"
31 #include "net/log/net_log_with_source.h"
32 #include "net/proxy_resolution/configured_proxy_resolution_service.h"
33 #include "net/quic/quic_context.h"
34 #include "net/socket/client_socket_handle.h"
35 #include "net/socket/next_proto.h"
36 #include "net/socket/socket_tag.h"
37 #include "net/socket/socks_connect_job.h"
38 #include "net/socket/ssl_client_socket.h"
39 #include "net/socket/transport_client_socket_pool.h"
40 #include "net/spdy/buffered_spdy_framer.h"
41 #include "net/spdy/spdy_http_utils.h"
42 #include "net/spdy/spdy_stream.h"
43 #include "net/ssl/ssl_connection_status_flags.h"
44 #include "net/test/gtest_util.h"
45 #include "net/third_party/quiche/src/quiche/spdy/core/spdy_alt_svc_wire_format.h"
46 #include "net/third_party/quiche/src/quiche/spdy/core/spdy_framer.h"
47 #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
48 #include "net/url_request/static_http_user_agent_settings.h"
49 #include "net/url_request/url_request_context_builder.h"
50 #include "net/url_request/url_request_job_factory.h"
51 #include "net/url_request/url_request_test_util.h"
52 #include "testing/gmock/include/gmock/gmock.h"
53 #include "third_party/abseil-cpp/absl/types/optional.h"
54 #include "url/scheme_host_port.h"
55 #include "url/url_constants.h"
56
57 using net::test::IsError;
58 using net::test::IsOk;
59
60 namespace net {
61
62 namespace {
63
64 // Parses a URL into the scheme, host, and path components required for a
65 // SPDY request.
ParseUrl(base::StringPiece url,std::string * scheme,std::string * host,std::string * path)66 void ParseUrl(base::StringPiece url,
67 std::string* scheme,
68 std::string* host,
69 std::string* path) {
70 GURL gurl(url);
71 path->assign(gurl.PathForRequest());
72 scheme->assign(gurl.scheme());
73 host->assign(gurl.host());
74 if (gurl.has_port()) {
75 host->append(":");
76 host->append(gurl.port());
77 }
78 }
79
80 } // namespace
81
82 // Chop a frame into an array of MockWrites.
83 // |frame| is the frame to chop.
84 // |num_chunks| is the number of chunks to create.
ChopWriteFrame(const spdy::SpdySerializedFrame & frame,int num_chunks)85 std::unique_ptr<MockWrite[]> ChopWriteFrame(
86 const spdy::SpdySerializedFrame& frame,
87 int num_chunks) {
88 auto chunks = std::make_unique<MockWrite[]>(num_chunks);
89 int chunk_size = frame.size() / num_chunks;
90 for (int index = 0; index < num_chunks; index++) {
91 const char* ptr = frame.data() + (index * chunk_size);
92 if (index == num_chunks - 1)
93 chunk_size +=
94 frame.size() % chunk_size; // The last chunk takes the remainder.
95 chunks[index] = MockWrite(ASYNC, ptr, chunk_size);
96 }
97 return chunks;
98 }
99
100 // Adds headers and values to a map.
101 // |extra_headers| is an array of { name, value } pairs, arranged as strings
102 // where the even entries are the header names, and the odd entries are the
103 // header values.
104 // |headers| gets filled in from |extra_headers|.
AppendToHeaderBlock(const char * const extra_headers[],int extra_header_count,spdy::Http2HeaderBlock * headers)105 void AppendToHeaderBlock(const char* const extra_headers[],
106 int extra_header_count,
107 spdy::Http2HeaderBlock* headers) {
108 if (!extra_header_count)
109 return;
110
111 // Sanity check: Non-NULL header list.
112 DCHECK(extra_headers) << "NULL header value pair list";
113 // Sanity check: Non-NULL header map.
114 DCHECK(headers) << "NULL header map";
115
116 // Copy in the headers.
117 for (int i = 0; i < extra_header_count; i++) {
118 absl::string_view key(extra_headers[i * 2]);
119 absl::string_view value(extra_headers[i * 2 + 1]);
120 DCHECK(!key.empty()) << "Header key must not be empty.";
121 headers->AppendValueOrAddHeader(key, value);
122 }
123 }
124
125 // Create a MockWrite from the given spdy::SpdySerializedFrame.
CreateMockWrite(const spdy::SpdySerializedFrame & req)126 MockWrite CreateMockWrite(const spdy::SpdySerializedFrame& req) {
127 return MockWrite(ASYNC, req.data(), req.size());
128 }
129
130 // Create a MockWrite from the given spdy::SpdySerializedFrame and sequence
131 // number.
CreateMockWrite(const spdy::SpdySerializedFrame & req,int seq)132 MockWrite CreateMockWrite(const spdy::SpdySerializedFrame& req, int seq) {
133 return CreateMockWrite(req, seq, ASYNC);
134 }
135
136 // Create a MockWrite from the given spdy::SpdySerializedFrame and sequence
137 // number.
CreateMockWrite(const spdy::SpdySerializedFrame & req,int seq,IoMode mode)138 MockWrite CreateMockWrite(const spdy::SpdySerializedFrame& req,
139 int seq,
140 IoMode mode) {
141 return MockWrite(mode, req.data(), req.size(), seq);
142 }
143
144 // Create a MockRead from the given spdy::SpdySerializedFrame.
CreateMockRead(const spdy::SpdySerializedFrame & resp)145 MockRead CreateMockRead(const spdy::SpdySerializedFrame& resp) {
146 return MockRead(ASYNC, resp.data(), resp.size());
147 }
148
149 // Create a MockRead from the given spdy::SpdySerializedFrame and sequence
150 // number.
CreateMockRead(const spdy::SpdySerializedFrame & resp,int seq)151 MockRead CreateMockRead(const spdy::SpdySerializedFrame& resp, int seq) {
152 return CreateMockRead(resp, seq, ASYNC);
153 }
154
155 // Create a MockRead from the given spdy::SpdySerializedFrame and sequence
156 // number.
CreateMockRead(const spdy::SpdySerializedFrame & resp,int seq,IoMode mode)157 MockRead CreateMockRead(const spdy::SpdySerializedFrame& resp,
158 int seq,
159 IoMode mode) {
160 return MockRead(mode, resp.data(), resp.size(), seq);
161 }
162
163 // Combines the given vector of spdy::SpdySerializedFrame into a single frame.
CombineFrames(std::vector<const spdy::SpdySerializedFrame * > frames)164 spdy::SpdySerializedFrame CombineFrames(
165 std::vector<const spdy::SpdySerializedFrame*> frames) {
166 int total_size = 0;
167 for (const auto* frame : frames) {
168 total_size += frame->size();
169 }
170 auto data = std::make_unique<char[]>(total_size);
171 char* ptr = data.get();
172 for (const auto* frame : frames) {
173 memcpy(ptr, frame->data(), frame->size());
174 ptr += frame->size();
175 }
176 return spdy::SpdySerializedFrame(data.release(), total_size,
177 /* owns_buffer = */ true);
178 }
179
180 namespace {
181
182 class PriorityGetter : public BufferedSpdyFramerVisitorInterface {
183 public:
184 PriorityGetter() = default;
185 ~PriorityGetter() override = default;
186
priority() const187 spdy::SpdyPriority priority() const { return priority_; }
188
OnError(http2::Http2DecoderAdapter::SpdyFramerError spdy_framer_error)189 void OnError(
190 http2::Http2DecoderAdapter::SpdyFramerError spdy_framer_error) override {}
OnStreamError(spdy::SpdyStreamId stream_id,const std::string & description)191 void OnStreamError(spdy::SpdyStreamId stream_id,
192 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)193 void OnHeaders(spdy::SpdyStreamId stream_id,
194 bool has_priority,
195 int weight,
196 spdy::SpdyStreamId parent_stream_id,
197 bool exclusive,
198 bool fin,
199 spdy::Http2HeaderBlock headers,
200 base::TimeTicks recv_first_byte_time) override {
201 if (has_priority) {
202 priority_ = spdy::Http2WeightToSpdy3Priority(weight);
203 }
204 }
OnDataFrameHeader(spdy::SpdyStreamId stream_id,size_t length,bool fin)205 void OnDataFrameHeader(spdy::SpdyStreamId stream_id,
206 size_t length,
207 bool fin) override {}
OnStreamFrameData(spdy::SpdyStreamId stream_id,const char * data,size_t len)208 void OnStreamFrameData(spdy::SpdyStreamId stream_id,
209 const char* data,
210 size_t len) override {}
OnStreamEnd(spdy::SpdyStreamId stream_id)211 void OnStreamEnd(spdy::SpdyStreamId stream_id) override {}
OnStreamPadding(spdy::SpdyStreamId stream_id,size_t len)212 void OnStreamPadding(spdy::SpdyStreamId stream_id, size_t len) override {}
OnSettings()213 void OnSettings() override {}
OnSettingsAck()214 void OnSettingsAck() override {}
OnSetting(spdy::SpdySettingsId id,uint32_t value)215 void OnSetting(spdy::SpdySettingsId id, uint32_t value) override {}
OnSettingsEnd()216 void OnSettingsEnd() override {}
OnPing(spdy::SpdyPingId unique_id,bool is_ack)217 void OnPing(spdy::SpdyPingId unique_id, bool is_ack) override {}
OnRstStream(spdy::SpdyStreamId stream_id,spdy::SpdyErrorCode error_code)218 void OnRstStream(spdy::SpdyStreamId stream_id,
219 spdy::SpdyErrorCode error_code) override {}
OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,spdy::SpdyErrorCode error_code,base::StringPiece debug_data)220 void OnGoAway(spdy::SpdyStreamId last_accepted_stream_id,
221 spdy::SpdyErrorCode error_code,
222 base::StringPiece debug_data) override {}
OnWindowUpdate(spdy::SpdyStreamId stream_id,int delta_window_size)223 void OnWindowUpdate(spdy::SpdyStreamId stream_id,
224 int delta_window_size) override {}
OnPushPromise(spdy::SpdyStreamId stream_id,spdy::SpdyStreamId promised_stream_id,spdy::Http2HeaderBlock headers)225 void OnPushPromise(spdy::SpdyStreamId stream_id,
226 spdy::SpdyStreamId promised_stream_id,
227 spdy::Http2HeaderBlock headers) override {}
OnAltSvc(spdy::SpdyStreamId stream_id,base::StringPiece origin,const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector & altsvc_vector)228 void OnAltSvc(spdy::SpdyStreamId stream_id,
229 base::StringPiece origin,
230 const spdy::SpdyAltSvcWireFormat::AlternativeServiceVector&
231 altsvc_vector) override {}
OnUnknownFrame(spdy::SpdyStreamId stream_id,uint8_t frame_type)232 bool OnUnknownFrame(spdy::SpdyStreamId stream_id,
233 uint8_t frame_type) override {
234 return false;
235 }
236
237 private:
238 spdy::SpdyPriority priority_ = 0;
239 };
240
241 } // namespace
242
GetSpdyPriority(const spdy::SpdySerializedFrame & frame,spdy::SpdyPriority * priority)243 bool GetSpdyPriority(const spdy::SpdySerializedFrame& frame,
244 spdy::SpdyPriority* priority) {
245 NetLogWithSource net_log;
246 BufferedSpdyFramer framer(kMaxHeaderListSizeForTest, net_log);
247 PriorityGetter priority_getter;
248 framer.set_visitor(&priority_getter);
249 size_t frame_size = frame.size();
250 if (framer.ProcessInput(frame.data(), frame_size) != frame_size) {
251 return false;
252 }
253 *priority = priority_getter.priority();
254 return true;
255 }
256
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)257 base::WeakPtr<SpdyStream> CreateStreamSynchronously(
258 SpdyStreamType type,
259 const base::WeakPtr<SpdySession>& session,
260 const GURL& url,
261 RequestPriority priority,
262 const NetLogWithSource& net_log,
263 bool detect_broken_connection,
264 base::TimeDelta heartbeat_interval) {
265 SpdyStreamRequest stream_request;
266 int rv = stream_request.StartRequest(
267 type, session, url, false /* no early data */, priority, SocketTag(),
268 net_log, CompletionOnceCallback(), TRAFFIC_ANNOTATION_FOR_TESTS,
269 detect_broken_connection, heartbeat_interval);
270
271 return
272 (rv == OK) ? stream_request.ReleaseStream() : base::WeakPtr<SpdyStream>();
273 }
274
275 StreamReleaserCallback::StreamReleaserCallback() = default;
276
277 StreamReleaserCallback::~StreamReleaserCallback() = default;
278
MakeCallback(SpdyStreamRequest * request)279 CompletionOnceCallback StreamReleaserCallback::MakeCallback(
280 SpdyStreamRequest* request) {
281 return base::BindOnce(&StreamReleaserCallback::OnComplete,
282 base::Unretained(this), request);
283 }
284
OnComplete(SpdyStreamRequest * request,int result)285 void StreamReleaserCallback::OnComplete(
286 SpdyStreamRequest* request, int result) {
287 if (result == OK)
288 request->ReleaseStream()->Cancel(ERR_ABORTED);
289 SetResult(result);
290 }
291
SpdySessionDependencies()292 SpdySessionDependencies::SpdySessionDependencies()
293 : SpdySessionDependencies(
294 ConfiguredProxyResolutionService::CreateDirect()) {}
295
SpdySessionDependencies(std::unique_ptr<ProxyResolutionService> proxy_resolution_service)296 SpdySessionDependencies::SpdySessionDependencies(
297 std::unique_ptr<ProxyResolutionService> proxy_resolution_service)
298 : host_resolver(std::make_unique<MockCachingHostResolver>(
299 /*cache_invalidation_num=*/0,
300 MockHostResolverBase::RuleResolver::GetLocalhostResult())),
301 cert_verifier(std::make_unique<MockCertVerifier>()),
302 transport_security_state(std::make_unique<TransportSecurityState>()),
303 ct_policy_enforcer(std::make_unique<DefaultCTPolicyEnforcer>()),
304 proxy_resolution_service(std::move(proxy_resolution_service)),
305 ssl_config_service(std::make_unique<SSLConfigServiceDefaults>()),
306 socket_factory(std::make_unique<MockClientSocketFactory>()),
307 http_auth_handler_factory(HttpAuthHandlerFactory::CreateDefault()),
308 http_server_properties(std::make_unique<HttpServerProperties>()),
309 quic_context(std::make_unique<QuicContext>()),
310 time_func(&base::TimeTicks::Now) {
311 http2_settings[spdy::SETTINGS_INITIAL_WINDOW_SIZE] =
312 kDefaultInitialWindowSize;
313 }
314
315 SpdySessionDependencies::SpdySessionDependencies(SpdySessionDependencies&&) =
316 default;
317
318 SpdySessionDependencies::~SpdySessionDependencies() = default;
319
320 SpdySessionDependencies& SpdySessionDependencies::operator=(
321 SpdySessionDependencies&&) = default;
322
323 // static
SpdyCreateSession(SpdySessionDependencies * session_deps)324 std::unique_ptr<HttpNetworkSession> SpdySessionDependencies::SpdyCreateSession(
325 SpdySessionDependencies* session_deps) {
326 return SpdyCreateSessionWithSocketFactory(session_deps,
327 session_deps->socket_factory.get());
328 }
329
330 // static
331 std::unique_ptr<HttpNetworkSession>
SpdyCreateSessionWithSocketFactory(SpdySessionDependencies * session_deps,ClientSocketFactory * factory)332 SpdySessionDependencies::SpdyCreateSessionWithSocketFactory(
333 SpdySessionDependencies* session_deps,
334 ClientSocketFactory* factory) {
335 HttpNetworkSessionParams session_params = CreateSessionParams(session_deps);
336 HttpNetworkSessionContext session_context =
337 CreateSessionContext(session_deps);
338 session_context.client_socket_factory = factory;
339 auto http_session =
340 std::make_unique<HttpNetworkSession>(session_params, session_context);
341 SpdySessionPoolPeer pool_peer(http_session->spdy_session_pool());
342 pool_peer.SetEnableSendingInitialData(false);
343 return http_session;
344 }
345
346 // static
CreateSessionParams(SpdySessionDependencies * session_deps)347 HttpNetworkSessionParams SpdySessionDependencies::CreateSessionParams(
348 SpdySessionDependencies* session_deps) {
349 HttpNetworkSessionParams params;
350 params.enable_spdy_ping_based_connection_checking = session_deps->enable_ping;
351 params.enable_user_alternate_protocol_ports =
352 session_deps->enable_user_alternate_protocol_ports;
353 params.enable_quic = session_deps->enable_quic;
354 params.enable_server_push_cancellation =
355 session_deps->enable_server_push_cancellation;
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 /*ssl_config_for_proxy=*/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 ProxyServer::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
WasAlpnNegotiated() const536 bool WasAlpnNegotiated() const override {
537 ADD_FAILURE();
538 return false;
539 }
540
GetSSLInfo(SSLInfo * ssl_info)541 bool GetSSLInfo(SSLInfo* ssl_info) override {
542 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_3,
543 &ssl_info->connection_status);
544 SSLConnectionStatusSetCipherSuite(0x1301 /* TLS_CHACHA20_POLY1305_SHA256 */,
545 &ssl_info->connection_status);
546 return true;
547 }
548
GetTotalReceivedBytes() const549 int64_t GetTotalReceivedBytes() const override {
550 NOTIMPLEMENTED();
551 return 0;
552 }
553 };
554
555 } // namespace
556
CreateFakeSpdySession(SpdySessionPool * pool,const SpdySessionKey & key)557 base::WeakPtr<SpdySession> CreateFakeSpdySession(SpdySessionPool* pool,
558 const SpdySessionKey& key) {
559 EXPECT_FALSE(HasSpdySession(pool, key));
560 auto handle = std::make_unique<ClientSocketHandle>();
561 handle->SetSocket(std::make_unique<FakeSpdySessionClientSocket>());
562 base::WeakPtr<SpdySession> spdy_session;
563 int rv = pool->CreateAvailableSessionFromSocketHandle(
564 key, std::move(handle), NetLogWithSource(), &spdy_session);
565 // Failure is reported asynchronously.
566 EXPECT_THAT(rv, IsOk());
567 EXPECT_TRUE(spdy_session);
568 EXPECT_TRUE(HasSpdySession(pool, key));
569 // Disable the time-based receive window updates by setting the delay to
570 // the max time interval. This prevents time-based flakiness in the tests
571 // for any test not explicitly exercising the window update buffering.
572 spdy_session->SetTimeToBufferSmallWindowUpdates(base::TimeDelta::Max());
573 return spdy_session;
574 }
575
SpdySessionPoolPeer(SpdySessionPool * pool)576 SpdySessionPoolPeer::SpdySessionPoolPeer(SpdySessionPool* pool) : pool_(pool) {
577 }
578
RemoveAliases(const SpdySessionKey & key)579 void SpdySessionPoolPeer::RemoveAliases(const SpdySessionKey& key) {
580 pool_->RemoveAliases(key);
581 }
582
SetEnableSendingInitialData(bool enabled)583 void SpdySessionPoolPeer::SetEnableSendingInitialData(bool enabled) {
584 pool_->enable_sending_initial_data_ = enabled;
585 }
586
SpdyTestUtil()587 SpdyTestUtil::SpdyTestUtil()
588 : headerless_spdy_framer_(spdy::SpdyFramer::ENABLE_COMPRESSION),
589 request_spdy_framer_(spdy::SpdyFramer::ENABLE_COMPRESSION),
590 response_spdy_framer_(spdy::SpdyFramer::ENABLE_COMPRESSION),
591 default_url_(GURL(kDefaultUrl)) {}
592
593 SpdyTestUtil::~SpdyTestUtil() = default;
594
AddUrlToHeaderBlock(base::StringPiece url,spdy::Http2HeaderBlock * headers) const595 void SpdyTestUtil::AddUrlToHeaderBlock(base::StringPiece url,
596 spdy::Http2HeaderBlock* headers) const {
597 std::string scheme, host, path;
598 ParseUrl(url, &scheme, &host, &path);
599 (*headers)[spdy::kHttp2AuthorityHeader] = host;
600 (*headers)[spdy::kHttp2SchemeHeader] = scheme;
601 (*headers)[spdy::kHttp2PathHeader] = path;
602 }
603
604 // static
ConstructGetHeaderBlock(base::StringPiece url)605 spdy::Http2HeaderBlock SpdyTestUtil::ConstructGetHeaderBlock(
606 base::StringPiece url) {
607 return ConstructHeaderBlock("GET", url, nullptr);
608 }
609
610 // static
ConstructGetHeaderBlockForProxy(base::StringPiece url)611 spdy::Http2HeaderBlock SpdyTestUtil::ConstructGetHeaderBlockForProxy(
612 base::StringPiece url) {
613 return ConstructGetHeaderBlock(url);
614 }
615
616 // static
ConstructHeadHeaderBlock(base::StringPiece url,int64_t content_length)617 spdy::Http2HeaderBlock SpdyTestUtil::ConstructHeadHeaderBlock(
618 base::StringPiece url,
619 int64_t content_length) {
620 return ConstructHeaderBlock("HEAD", url, nullptr);
621 }
622
623 // static
ConstructPostHeaderBlock(base::StringPiece url,int64_t content_length)624 spdy::Http2HeaderBlock SpdyTestUtil::ConstructPostHeaderBlock(
625 base::StringPiece url,
626 int64_t content_length) {
627 return ConstructHeaderBlock("POST", url, &content_length);
628 }
629
630 // static
ConstructPutHeaderBlock(base::StringPiece url,int64_t content_length)631 spdy::Http2HeaderBlock SpdyTestUtil::ConstructPutHeaderBlock(
632 base::StringPiece url,
633 int64_t content_length) {
634 return ConstructHeaderBlock("PUT", url, &content_length);
635 }
636
ConstructSpdyReplyString(const spdy::Http2HeaderBlock & headers) const637 std::string SpdyTestUtil::ConstructSpdyReplyString(
638 const spdy::Http2HeaderBlock& headers) const {
639 std::string reply_string;
640 for (spdy::Http2HeaderBlock::const_iterator it = headers.begin();
641 it != headers.end(); ++it) {
642 auto key = std::string(it->first);
643 // Remove leading colon from pseudo headers.
644 if (key[0] == ':')
645 key = key.substr(1);
646 for (const std::string& value :
647 base::SplitString(it->second, base::StringPiece("\0", 1),
648 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
649 reply_string += key + ": " + value + "\n";
650 }
651 }
652 return reply_string;
653 }
654
655 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
656 // spdy::SpdySettingsIR).
ConstructSpdySettings(const spdy::SettingsMap & settings)657 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdySettings(
658 const spdy::SettingsMap& settings) {
659 spdy::SpdySettingsIR settings_ir;
660 for (const auto& setting : settings) {
661 settings_ir.AddSetting(setting.first, setting.second);
662 }
663 return spdy::SpdySerializedFrame(
664 headerless_spdy_framer_.SerializeFrame(settings_ir));
665 }
666
ConstructSpdySettingsAck()667 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdySettingsAck() {
668 spdy::SpdySettingsIR settings_ir;
669 settings_ir.set_is_ack(true);
670 return spdy::SpdySerializedFrame(
671 headerless_spdy_framer_.SerializeFrame(settings_ir));
672 }
673
ConstructSpdyPing(uint32_t ping_id,bool is_ack)674 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPing(uint32_t ping_id,
675 bool is_ack) {
676 spdy::SpdyPingIR ping_ir(ping_id);
677 ping_ir.set_is_ack(is_ack);
678 return spdy::SpdySerializedFrame(
679 headerless_spdy_framer_.SerializeFrame(ping_ir));
680 }
681
ConstructSpdyGoAway(spdy::SpdyStreamId last_good_stream_id)682 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGoAway(
683 spdy::SpdyStreamId last_good_stream_id) {
684 spdy::SpdyGoAwayIR go_ir(last_good_stream_id, spdy::ERROR_CODE_NO_ERROR,
685 "go away");
686 return spdy::SpdySerializedFrame(
687 headerless_spdy_framer_.SerializeFrame(go_ir));
688 }
689
ConstructSpdyGoAway(spdy::SpdyStreamId last_good_stream_id,spdy::SpdyErrorCode error_code,const std::string & desc)690 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGoAway(
691 spdy::SpdyStreamId last_good_stream_id,
692 spdy::SpdyErrorCode error_code,
693 const std::string& desc) {
694 spdy::SpdyGoAwayIR go_ir(last_good_stream_id, error_code, desc);
695 return spdy::SpdySerializedFrame(
696 headerless_spdy_framer_.SerializeFrame(go_ir));
697 }
698
ConstructSpdyWindowUpdate(const spdy::SpdyStreamId stream_id,uint32_t delta_window_size)699 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyWindowUpdate(
700 const spdy::SpdyStreamId stream_id,
701 uint32_t delta_window_size) {
702 spdy::SpdyWindowUpdateIR update_ir(stream_id, delta_window_size);
703 return spdy::SpdySerializedFrame(
704 headerless_spdy_framer_.SerializeFrame(update_ir));
705 }
706
707 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
708 // spdy::SpdyRstStreamIR).
ConstructSpdyRstStream(spdy::SpdyStreamId stream_id,spdy::SpdyErrorCode error_code)709 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyRstStream(
710 spdy::SpdyStreamId stream_id,
711 spdy::SpdyErrorCode error_code) {
712 spdy::SpdyRstStreamIR rst_ir(stream_id, error_code);
713 return spdy::SpdySerializedFrame(
714 headerless_spdy_framer_.SerializeRstStream(rst_ir));
715 }
716
717 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
718 // spdy::SpdyPriorityIR).
ConstructSpdyPriority(spdy::SpdyStreamId stream_id,spdy::SpdyStreamId parent_stream_id,RequestPriority request_priority,bool exclusive)719 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPriority(
720 spdy::SpdyStreamId stream_id,
721 spdy::SpdyStreamId parent_stream_id,
722 RequestPriority request_priority,
723 bool exclusive) {
724 int weight = spdy::Spdy3PriorityToHttp2Weight(
725 ConvertRequestPriorityToSpdyPriority(request_priority));
726 spdy::SpdyPriorityIR ir(stream_id, parent_stream_id, weight, exclusive);
727 return spdy::SpdySerializedFrame(
728 headerless_spdy_framer_.SerializePriority(ir));
729 }
730
ConstructSpdyGet(const char * const url,spdy::SpdyStreamId stream_id,RequestPriority request_priority)731 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGet(
732 const char* const url,
733 spdy::SpdyStreamId stream_id,
734 RequestPriority request_priority) {
735 spdy::Http2HeaderBlock block(ConstructGetHeaderBlock(url));
736 return ConstructSpdyHeaders(stream_id, std::move(block), request_priority,
737 true);
738 }
739
ConstructSpdyGet(const char * const extra_headers[],int extra_header_count,int stream_id,RequestPriority request_priority)740 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGet(
741 const char* const extra_headers[],
742 int extra_header_count,
743 int stream_id,
744 RequestPriority request_priority) {
745 spdy::Http2HeaderBlock block;
746 block[spdy::kHttp2MethodHeader] = "GET";
747 AddUrlToHeaderBlock(default_url_.spec(), &block);
748 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
749 return ConstructSpdyHeaders(stream_id, std::move(block), request_priority,
750 true);
751 }
752
ConstructSpdyConnect(const char * const extra_headers[],int extra_header_count,int stream_id,RequestPriority priority,const HostPortPair & host_port_pair)753 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyConnect(
754 const char* const extra_headers[],
755 int extra_header_count,
756 int stream_id,
757 RequestPriority priority,
758 const HostPortPair& host_port_pair) {
759 spdy::Http2HeaderBlock block;
760 block[spdy::kHttp2MethodHeader] = "CONNECT";
761 block[spdy::kHttp2AuthorityHeader] = host_port_pair.ToString();
762 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
763 return ConstructSpdyHeaders(stream_id, std::move(block), priority, false);
764 }
765
ConstructSpdyPush(const char * const extra_headers[],int extra_header_count,int stream_id,int associated_stream_id,const char * url)766 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPush(
767 const char* const extra_headers[],
768 int extra_header_count,
769 int stream_id,
770 int associated_stream_id,
771 const char* url) {
772 spdy::Http2HeaderBlock push_promise_header_block;
773 push_promise_header_block[spdy::kHttp2MethodHeader] = "GET";
774 AddUrlToHeaderBlock(url, &push_promise_header_block);
775 spdy::SpdySerializedFrame push_promise_frame(ConstructSpdyPushPromise(
776 associated_stream_id, stream_id, std::move(push_promise_header_block)));
777
778 spdy::Http2HeaderBlock headers_header_block;
779 headers_header_block[spdy::kHttp2StatusHeader] = "200";
780 headers_header_block["hello"] = "bye";
781 AppendToHeaderBlock(extra_headers, extra_header_count, &headers_header_block);
782 spdy::SpdyHeadersIR headers(stream_id, std::move(headers_header_block));
783 spdy::SpdySerializedFrame headers_frame(
784 response_spdy_framer_.SerializeFrame(headers));
785
786 return CombineFrames({&push_promise_frame, &headers_frame});
787 }
788
ConstructSpdyPush(const char * const extra_headers[],int extra_header_count,int stream_id,int associated_stream_id,const char * url,const char * status,const char * location)789 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPush(
790 const char* const extra_headers[],
791 int extra_header_count,
792 int stream_id,
793 int associated_stream_id,
794 const char* url,
795 const char* status,
796 const char* location) {
797 spdy::Http2HeaderBlock push_promise_header_block;
798 push_promise_header_block[spdy::kHttp2MethodHeader] = "GET";
799 AddUrlToHeaderBlock(url, &push_promise_header_block);
800 spdy::SpdySerializedFrame push_promise_frame(ConstructSpdyPushPromise(
801 associated_stream_id, stream_id, std::move(push_promise_header_block)));
802
803 spdy::Http2HeaderBlock headers_header_block;
804 headers_header_block["hello"] = "bye";
805 headers_header_block[spdy::kHttp2StatusHeader] = status;
806 headers_header_block["location"] = location;
807 AppendToHeaderBlock(extra_headers, extra_header_count, &headers_header_block);
808 spdy::SpdyHeadersIR headers(stream_id, std::move(headers_header_block));
809 spdy::SpdySerializedFrame headers_frame(
810 response_spdy_framer_.SerializeFrame(headers));
811
812 return CombineFrames({&push_promise_frame, &headers_frame});
813 }
814
ConstructSpdyPushPromise(spdy::SpdyStreamId associated_stream_id,spdy::SpdyStreamId stream_id,spdy::Http2HeaderBlock headers)815 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPushPromise(
816 spdy::SpdyStreamId associated_stream_id,
817 spdy::SpdyStreamId stream_id,
818 spdy::Http2HeaderBlock headers) {
819 spdy::SpdyPushPromiseIR push_promise(associated_stream_id, stream_id,
820 std::move(headers));
821 return spdy::SpdySerializedFrame(
822 response_spdy_framer_.SerializeFrame(push_promise));
823 }
824
ConstructSpdyPushHeaders(int stream_id,const char * const extra_headers[],int extra_header_count)825 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPushHeaders(
826 int stream_id,
827 const char* const extra_headers[],
828 int extra_header_count) {
829 spdy::Http2HeaderBlock header_block;
830 header_block[spdy::kHttp2StatusHeader] = "200";
831 AppendToHeaderBlock(extra_headers, extra_header_count, &header_block);
832 spdy::SpdyHeadersIR headers(stream_id, std::move(header_block));
833 return spdy::SpdySerializedFrame(
834 response_spdy_framer_.SerializeFrame(headers));
835 }
836
ConstructSpdyResponseHeaders(int stream_id,spdy::Http2HeaderBlock headers,bool fin)837 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyResponseHeaders(
838 int stream_id,
839 spdy::Http2HeaderBlock headers,
840 bool fin) {
841 spdy::SpdyHeadersIR spdy_headers(stream_id, std::move(headers));
842 spdy_headers.set_fin(fin);
843 return spdy::SpdySerializedFrame(
844 response_spdy_framer_.SerializeFrame(spdy_headers));
845 }
846
ConstructSpdyHeaders(int stream_id,spdy::Http2HeaderBlock block,RequestPriority priority,bool fin)847 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyHeaders(
848 int stream_id,
849 spdy::Http2HeaderBlock block,
850 RequestPriority priority,
851 bool fin) {
852 // Get the stream id of the next highest priority request
853 // (most recent request of the same priority, or last request of
854 // an earlier priority).
855 // Note that this is a duplicate of the logic in Http2PriorityDependencies
856 // (slightly transformed as this is based on RequestPriority and that logic
857 // on spdy::SpdyPriority, but only slightly transformed) and hence tests using
858 // this function do not effectively test that logic.
859 // That logic is tested by the Http2PriorityDependencies unit tests.
860 int parent_stream_id = 0;
861 for (int q = priority; q <= HIGHEST; ++q) {
862 if (!priority_to_stream_id_list_[q].empty()) {
863 parent_stream_id = priority_to_stream_id_list_[q].back();
864 break;
865 }
866 }
867
868 priority_to_stream_id_list_[priority].push_back(stream_id);
869
870 spdy::SpdyHeadersIR headers(stream_id, std::move(block));
871 headers.set_has_priority(true);
872 headers.set_weight(spdy::Spdy3PriorityToHttp2Weight(
873 ConvertRequestPriorityToSpdyPriority(priority)));
874 headers.set_parent_stream_id(parent_stream_id);
875 headers.set_exclusive(true);
876 headers.set_fin(fin);
877 return spdy::SpdySerializedFrame(
878 request_spdy_framer_.SerializeFrame(headers));
879 }
880
ConstructSpdyReply(int stream_id,spdy::Http2HeaderBlock headers)881 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyReply(
882 int stream_id,
883 spdy::Http2HeaderBlock headers) {
884 spdy::SpdyHeadersIR reply(stream_id, std::move(headers));
885 return spdy::SpdySerializedFrame(response_spdy_framer_.SerializeFrame(reply));
886 }
887
ConstructSpdyReplyError(const char * const status,const char * const * const extra_headers,int extra_header_count,int stream_id)888 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyReplyError(
889 const char* const status,
890 const char* const* const extra_headers,
891 int extra_header_count,
892 int stream_id) {
893 spdy::Http2HeaderBlock block;
894 block[spdy::kHttp2StatusHeader] = status;
895 block["hello"] = "bye";
896 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
897
898 spdy::SpdyHeadersIR reply(stream_id, std::move(block));
899 return spdy::SpdySerializedFrame(response_spdy_framer_.SerializeFrame(reply));
900 }
901
ConstructSpdyReplyError(int stream_id)902 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyReplyError(int stream_id) {
903 return ConstructSpdyReplyError("500", nullptr, 0, stream_id);
904 }
905
ConstructSpdyGetReply(const char * const extra_headers[],int extra_header_count,int stream_id)906 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyGetReply(
907 const char* const extra_headers[],
908 int extra_header_count,
909 int stream_id) {
910 spdy::Http2HeaderBlock block;
911 block[spdy::kHttp2StatusHeader] = "200";
912 block["hello"] = "bye";
913 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
914
915 return ConstructSpdyReply(stream_id, std::move(block));
916 }
917
ConstructSpdyPost(const char * url,spdy::SpdyStreamId stream_id,int64_t content_length,RequestPriority priority,const char * const extra_headers[],int extra_header_count)918 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPost(
919 const char* url,
920 spdy::SpdyStreamId stream_id,
921 int64_t content_length,
922 RequestPriority priority,
923 const char* const extra_headers[],
924 int extra_header_count) {
925 spdy::Http2HeaderBlock block(ConstructPostHeaderBlock(url, content_length));
926 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
927 return ConstructSpdyHeaders(stream_id, std::move(block), priority, false);
928 }
929
ConstructChunkedSpdyPost(const char * const extra_headers[],int extra_header_count)930 spdy::SpdySerializedFrame SpdyTestUtil::ConstructChunkedSpdyPost(
931 const char* const extra_headers[],
932 int extra_header_count) {
933 spdy::Http2HeaderBlock block;
934 block[spdy::kHttp2MethodHeader] = "POST";
935 AddUrlToHeaderBlock(default_url_.spec(), &block);
936 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
937 return ConstructSpdyHeaders(1, std::move(block), LOWEST, false);
938 }
939
ConstructSpdyPostReply(const char * const extra_headers[],int extra_header_count)940 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyPostReply(
941 const char* const extra_headers[],
942 int extra_header_count) {
943 // TODO(jgraettinger): Remove this method.
944 return ConstructSpdyGetReply(extra_headers, extra_header_count, 1);
945 }
946
ConstructSpdyDataFrame(int stream_id,bool fin)947 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyDataFrame(int stream_id,
948 bool fin) {
949 return ConstructSpdyDataFrame(stream_id, kUploadData, fin);
950 }
951
ConstructSpdyDataFrame(int stream_id,base::StringPiece data,bool fin)952 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyDataFrame(
953 int stream_id,
954 base::StringPiece data,
955 bool fin) {
956 spdy::SpdyDataIR data_ir(stream_id, data);
957 data_ir.set_fin(fin);
958 return spdy::SpdySerializedFrame(
959 headerless_spdy_framer_.SerializeData(data_ir));
960 }
961
ConstructSpdyDataFrame(int stream_id,base::StringPiece data,bool fin,int padding_length)962 spdy::SpdySerializedFrame SpdyTestUtil::ConstructSpdyDataFrame(
963 int stream_id,
964 base::StringPiece data,
965 bool fin,
966 int padding_length) {
967 spdy::SpdyDataIR data_ir(stream_id, data);
968 data_ir.set_fin(fin);
969 data_ir.set_padding_len(padding_length);
970 return spdy::SpdySerializedFrame(
971 headerless_spdy_framer_.SerializeData(data_ir));
972 }
973
ConstructWrappedSpdyFrame(const spdy::SpdySerializedFrame & frame,int stream_id)974 spdy::SpdySerializedFrame SpdyTestUtil::ConstructWrappedSpdyFrame(
975 const spdy::SpdySerializedFrame& frame,
976 int stream_id) {
977 return ConstructSpdyDataFrame(
978 stream_id, base::StringPiece(frame.data(), frame.size()), false);
979 }
980
SerializeFrame(const spdy::SpdyFrameIR & frame_ir)981 spdy::SpdySerializedFrame SpdyTestUtil::SerializeFrame(
982 const spdy::SpdyFrameIR& frame_ir) {
983 return headerless_spdy_framer_.SerializeFrame(frame_ir);
984 }
985
UpdateWithStreamDestruction(int stream_id)986 void SpdyTestUtil::UpdateWithStreamDestruction(int stream_id) {
987 for (auto& priority_it : priority_to_stream_id_list_) {
988 for (auto stream_it = priority_it.second.begin();
989 stream_it != priority_it.second.end(); ++stream_it) {
990 if (*stream_it == stream_id) {
991 priority_it.second.erase(stream_it);
992 return;
993 }
994 }
995 }
996 NOTREACHED();
997 }
998
999 // static
ConstructHeaderBlock(base::StringPiece method,base::StringPiece url,int64_t * content_length)1000 spdy::Http2HeaderBlock SpdyTestUtil::ConstructHeaderBlock(
1001 base::StringPiece method,
1002 base::StringPiece url,
1003 int64_t* content_length) {
1004 std::string scheme, host, path;
1005 ParseUrl(url, &scheme, &host, &path);
1006 spdy::Http2HeaderBlock headers;
1007 headers[spdy::kHttp2MethodHeader] = std::string(method);
1008 headers[spdy::kHttp2AuthorityHeader] = host.c_str();
1009 headers[spdy::kHttp2SchemeHeader] = scheme.c_str();
1010 headers[spdy::kHttp2PathHeader] = path.c_str();
1011 if (content_length) {
1012 std::string length_str = base::NumberToString(*content_length);
1013 headers["content-length"] = length_str;
1014 }
1015 return headers;
1016 }
1017
1018 namespace test {
GetTestHashValue(uint8_t label)1019 HashValue GetTestHashValue(uint8_t label) {
1020 HashValue hash_value(HASH_VALUE_SHA256);
1021 memset(hash_value.data(), label, hash_value.size());
1022 return hash_value;
1023 }
1024
1025 TestServerPushDelegate::TestServerPushDelegate() = default;
1026
1027 TestServerPushDelegate::~TestServerPushDelegate() = default;
1028
OnPush(std::unique_ptr<ServerPushHelper> push_helper,const NetLogWithSource & session_net_log)1029 void TestServerPushDelegate::OnPush(
1030 std::unique_ptr<ServerPushHelper> push_helper,
1031 const NetLogWithSource& session_net_log) {
1032 push_helpers[push_helper->GetURL()] = std::move(push_helper);
1033 }
1034
CancelPush(GURL url)1035 bool TestServerPushDelegate::CancelPush(GURL url) {
1036 auto itr = push_helpers.find(url);
1037 DCHECK(itr != push_helpers.end());
1038 itr->second->Cancel();
1039 push_helpers.erase(itr);
1040 return true;
1041 }
1042
1043 } // namespace test
1044 } // namespace net
1045