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