1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef NET_SPDY_SPDY_TEST_UTIL_COMMON_H_
6 #define NET_SPDY_SPDY_TEST_UTIL_COMMON_H_
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "crypto/ec_private_key.h"
14 #include "crypto/ec_signature_creator.h"
15 #include "net/base/completion_callback.h"
16 #include "net/base/request_priority.h"
17 #include "net/base/test_completion_callback.h"
18 #include "net/cert/cert_verifier.h"
19 #include "net/dns/mock_host_resolver.h"
20 #include "net/http/http_auth_handler_factory.h"
21 #include "net/http/http_network_session.h"
22 #include "net/http/http_response_info.h"
23 #include "net/http/http_server_properties_impl.h"
24 #include "net/http/transport_security_state.h"
25 #include "net/proxy/proxy_service.h"
26 #include "net/socket/next_proto.h"
27 #include "net/socket/socket_test_util.h"
28 #include "net/spdy/spdy_protocol.h"
29 #include "net/ssl/ssl_config_service_defaults.h"
30 #include "net/url_request/url_request_context.h"
31 #include "net/url_request/url_request_context_storage.h"
32 #include "testing/gtest/include/gtest/gtest.h"
41 class SpdySessionPool;
43 class SpdyStreamRequest;
45 // Default upload data used by both, mock objects and framer when creating
47 const char kDefaultURL[] = "http://www.google.com";
48 const char kUploadData[] = "hello!";
49 const int kUploadDataSize = arraysize(kUploadData)-1;
51 // SpdyNextProtos returns a vector of next protocols for negotiating
53 std::vector<NextProto> SpdyNextProtos();
55 // Chop a frame into an array of MockWrites.
56 // |data| is the frame to chop.
57 // |length| is the length of the frame to chop.
58 // |num_chunks| is the number of chunks to create.
59 MockWrite* ChopWriteFrame(const char* data, int length, int num_chunks);
61 // Chop a SpdyFrame into an array of MockWrites.
62 // |frame| is the frame to chop.
63 // |num_chunks| is the number of chunks to create.
64 MockWrite* ChopWriteFrame(const SpdyFrame& frame, int num_chunks);
66 // Chop a frame into an array of MockReads.
67 // |data| is the frame to chop.
68 // |length| is the length of the frame to chop.
69 // |num_chunks| is the number of chunks to create.
70 MockRead* ChopReadFrame(const char* data, int length, int num_chunks);
72 // Chop a SpdyFrame into an array of MockReads.
73 // |frame| is the frame to chop.
74 // |num_chunks| is the number of chunks to create.
75 MockRead* ChopReadFrame(const SpdyFrame& frame, int num_chunks);
77 // Adds headers and values to a map.
78 // |extra_headers| is an array of { name, value } pairs, arranged as strings
79 // where the even entries are the header names, and the odd entries are the
81 // |headers| gets filled in from |extra_headers|.
82 void AppendToHeaderBlock(const char* const extra_headers[],
83 int extra_header_count,
84 SpdyHeaderBlock* headers);
86 // Create an async MockWrite from the given SpdyFrame.
87 MockWrite CreateMockWrite(const SpdyFrame& req);
89 // Create an async MockWrite from the given SpdyFrame and sequence number.
90 MockWrite CreateMockWrite(const SpdyFrame& req, int seq);
92 MockWrite CreateMockWrite(const SpdyFrame& req, int seq, IoMode mode);
94 // Create a MockRead from the given SpdyFrame.
95 MockRead CreateMockRead(const SpdyFrame& resp);
97 // Create a MockRead from the given SpdyFrame and sequence number.
98 MockRead CreateMockRead(const SpdyFrame& resp, int seq);
100 MockRead CreateMockRead(const SpdyFrame& resp, int seq, IoMode mode);
102 // Combines the given SpdyFrames into the given char array and returns
104 int CombineFrames(const SpdyFrame** frames, int num_frames,
105 char* buff, int buff_len);
107 // Returns the SpdyPriority embedded in the given frame. Returns true
108 // and fills in |priority| on success.
109 bool GetSpdyPriority(SpdyMajorVersion version,
110 const SpdyFrame& frame,
111 SpdyPriority* priority);
113 // Tries to create a stream in |session| synchronously. Returns NULL
115 base::WeakPtr<SpdyStream> CreateStreamSynchronously(
117 const base::WeakPtr<SpdySession>& session,
119 RequestPriority priority,
120 const BoundNetLog& net_log);
122 // Helper class used by some tests to release a stream as soon as it's
124 class StreamReleaserCallback : public TestCompletionCallbackBase {
126 StreamReleaserCallback();
128 virtual ~StreamReleaserCallback();
130 // Returns a callback that releases |request|'s stream.
131 CompletionCallback MakeCallback(SpdyStreamRequest* request);
134 void OnComplete(SpdyStreamRequest* request, int result);
137 const size_t kSpdyCredentialSlotUnused = 0;
139 // This struct holds information used to construct spdy control and data frames.
140 struct SpdyHeaderInfo {
143 SpdyStreamId assoc_id;
144 SpdyPriority priority;
145 size_t credential_slot; // SPDY3 only
146 SpdyControlFlags control_flags;
148 SpdyRstStreamStatus status;
151 SpdyDataFlags data_flags;
154 // An ECSignatureCreator that returns deterministic signatures.
155 class MockECSignatureCreator : public crypto::ECSignatureCreator {
157 explicit MockECSignatureCreator(crypto::ECPrivateKey* key);
159 // crypto::ECSignatureCreator
160 virtual bool Sign(const uint8* data,
162 std::vector<uint8>* signature) OVERRIDE;
163 virtual bool DecodeSignature(const std::vector<uint8>& signature,
164 std::vector<uint8>* out_raw_sig) OVERRIDE;
167 crypto::ECPrivateKey* key_;
169 DISALLOW_COPY_AND_ASSIGN(MockECSignatureCreator);
172 // An ECSignatureCreatorFactory creates MockECSignatureCreator.
173 class MockECSignatureCreatorFactory : public crypto::ECSignatureCreatorFactory {
175 MockECSignatureCreatorFactory();
176 virtual ~MockECSignatureCreatorFactory();
178 // crypto::ECSignatureCreatorFactory
179 virtual crypto::ECSignatureCreator* Create(
180 crypto::ECPrivateKey* key) OVERRIDE;
183 DISALLOW_COPY_AND_ASSIGN(MockECSignatureCreatorFactory);
186 // Helper to manage the lifetimes of the dependencies for a
187 // HttpNetworkTransaction.
188 struct SpdySessionDependencies {
189 // Default set of dependencies -- "null" proxy service.
190 explicit SpdySessionDependencies(NextProto protocol);
192 // Custom proxy service dependency.
193 SpdySessionDependencies(NextProto protocol, ProxyService* proxy_service);
195 ~SpdySessionDependencies();
197 static HttpNetworkSession* SpdyCreateSession(
198 SpdySessionDependencies* session_deps);
199 static HttpNetworkSession* SpdyCreateSessionDeterministic(
200 SpdySessionDependencies* session_deps);
201 static HttpNetworkSession::Params CreateSessionParams(
202 SpdySessionDependencies* session_deps);
204 // NOTE: host_resolver must be ordered before http_auth_handler_factory.
205 scoped_ptr<MockHostResolverBase> host_resolver;
206 scoped_ptr<CertVerifier> cert_verifier;
207 scoped_ptr<TransportSecurityState> transport_security_state;
208 scoped_ptr<ProxyService> proxy_service;
209 scoped_refptr<SSLConfigService> ssl_config_service;
210 scoped_ptr<MockClientSocketFactory> socket_factory;
211 scoped_ptr<DeterministicMockClientSocketFactory> deterministic_socket_factory;
212 scoped_ptr<HttpAuthHandlerFactory> http_auth_handler_factory;
213 HttpServerPropertiesImpl http_server_properties;
214 bool enable_ip_pooling;
215 bool enable_compression;
217 bool enable_user_alternate_protocol_ports;
219 size_t stream_initial_recv_window_size;
220 SpdySession::TimeFunc time_func;
221 std::string trusted_spdy_proxy;
225 class SpdyURLRequestContext : public URLRequestContext {
227 explicit SpdyURLRequestContext(NextProto protocol);
228 virtual ~SpdyURLRequestContext();
230 MockClientSocketFactory& socket_factory() { return socket_factory_; }
233 MockClientSocketFactory socket_factory_;
234 net::URLRequestContextStorage storage_;
237 // Equivalent to pool->GetIfExists(spdy_session_key, BoundNetLog()) != NULL.
238 bool HasSpdySession(SpdySessionPool* pool, const SpdySessionKey& key);
240 // Creates a SPDY session for the given key and puts it in the SPDY
241 // session pool in |http_session|. A SPDY session for |key| must not
243 base::WeakPtr<SpdySession> CreateInsecureSpdySession(
244 const scoped_refptr<HttpNetworkSession>& http_session,
245 const SpdySessionKey& key,
246 const BoundNetLog& net_log);
248 // Tries to create a SPDY session for the given key but expects the
249 // attempt to fail with the given error. A SPDY session for |key| must
250 // not already exist. The session will be created but close in the
251 // next event loop iteration.
252 base::WeakPtr<SpdySession> TryCreateInsecureSpdySessionExpectingFailure(
253 const scoped_refptr<HttpNetworkSession>& http_session,
254 const SpdySessionKey& key,
255 Error expected_error,
256 const BoundNetLog& net_log);
258 // Like CreateInsecureSpdySession(), but uses TLS.
259 base::WeakPtr<SpdySession> CreateSecureSpdySession(
260 const scoped_refptr<HttpNetworkSession>& http_session,
261 const SpdySessionKey& key,
262 const BoundNetLog& net_log);
264 // Creates an insecure SPDY session for the given key and puts it in
265 // |pool|. The returned session will neither receive nor send any
266 // data. A SPDY session for |key| must not already exist.
267 base::WeakPtr<SpdySession> CreateFakeSpdySession(SpdySessionPool* pool,
268 const SpdySessionKey& key);
270 // Tries to create an insecure SPDY session for the given key but
271 // expects the attempt to fail with the given error. The session will
272 // neither receive nor send any data. A SPDY session for |key| must
273 // not already exist. The session will be created but close in the
274 // next event loop iteration.
275 base::WeakPtr<SpdySession> TryCreateFakeSpdySessionExpectingFailure(
276 SpdySessionPool* pool,
277 const SpdySessionKey& key,
278 Error expected_error);
280 class SpdySessionPoolPeer {
282 explicit SpdySessionPoolPeer(SpdySessionPool* pool);
284 void RemoveAliases(const SpdySessionKey& key);
285 void DisableDomainAuthenticationVerification();
286 void SetEnableSendingInitialData(bool enabled);
289 SpdySessionPool* const pool_;
291 DISALLOW_COPY_AND_ASSIGN(SpdySessionPoolPeer);
296 explicit SpdyTestUtil(NextProto protocol);
298 // Add the appropriate headers to put |url| into |block|.
299 void AddUrlToHeaderBlock(base::StringPiece url,
300 SpdyHeaderBlock* headers) const;
302 scoped_ptr<SpdyHeaderBlock> ConstructGetHeaderBlock(
303 base::StringPiece url) const;
304 scoped_ptr<SpdyHeaderBlock> ConstructGetHeaderBlockForProxy(
305 base::StringPiece url) const;
306 scoped_ptr<SpdyHeaderBlock> ConstructHeadHeaderBlock(
307 base::StringPiece url,
308 int64 content_length) const;
309 scoped_ptr<SpdyHeaderBlock> ConstructPostHeaderBlock(
310 base::StringPiece url,
311 int64 content_length) const;
312 scoped_ptr<SpdyHeaderBlock> ConstructPutHeaderBlock(
313 base::StringPiece url,
314 int64 content_length) const;
316 // Construct a SPDY frame. If it is a SYN_STREAM or SYN_REPLY frame (as
317 // specified in header_info.kind), the provided headers are included in the
319 SpdyFrame* ConstructSpdyFrame(
320 const SpdyHeaderInfo& header_info,
321 scoped_ptr<SpdyHeaderBlock> headers) const;
323 // Construct a SPDY frame. If it is a SYN_STREAM or SYN_REPLY frame (as
324 // specified in header_info.kind), the headers provided in extra_headers and
325 // (if non-NULL) tail_headers are concatenated and included in the frame.
326 // (extra_headers must always be non-NULL.)
327 SpdyFrame* ConstructSpdyFrame(const SpdyHeaderInfo& header_info,
328 const char* const extra_headers[],
329 int extra_header_count,
330 const char* const tail_headers[],
331 int tail_header_count) const;
333 // Construct a generic SpdyControlFrame.
334 SpdyFrame* ConstructSpdyControlFrame(
335 scoped_ptr<SpdyHeaderBlock> headers,
337 SpdyStreamId stream_id,
338 RequestPriority request_priority,
340 SpdyControlFlags flags,
341 SpdyStreamId associated_stream_id) const;
343 // Construct a generic SpdyControlFrame.
345 // Warning: extra_header_count is the number of header-value pairs in
346 // extra_headers (so half the number of elements), but tail_headers_size is
347 // the actual number of elements (both keys and values) in tail_headers.
348 // TODO(ttuttle): Fix this inconsistency.
349 SpdyFrame* ConstructSpdyControlFrame(
350 const char* const extra_headers[],
351 int extra_header_count,
353 SpdyStreamId stream_id,
354 RequestPriority request_priority,
356 SpdyControlFlags flags,
357 const char* const* tail_headers,
358 int tail_headers_size,
359 SpdyStreamId associated_stream_id) const;
361 // Construct an expected SPDY reply string from the given headers.
362 std::string ConstructSpdyReplyString(const SpdyHeaderBlock& headers) const;
364 // Construct an expected SPDY SETTINGS frame.
365 // |settings| are the settings to set.
366 // Returns the constructed frame. The caller takes ownership of the frame.
367 SpdyFrame* ConstructSpdySettings(const SettingsMap& settings) const;
369 // Construct a SPDY PING frame.
370 // Returns the constructed frame. The caller takes ownership of the frame.
371 SpdyFrame* ConstructSpdyPing(uint32 ping_id, bool is_ack) const;
373 // Construct a SPDY GOAWAY frame with last_good_stream_id = 0.
374 // Returns the constructed frame. The caller takes ownership of the frame.
375 SpdyFrame* ConstructSpdyGoAway() const;
377 // Construct a SPDY GOAWAY frame with the specified last_good_stream_id.
378 // Returns the constructed frame. The caller takes ownership of the frame.
379 SpdyFrame* ConstructSpdyGoAway(SpdyStreamId last_good_stream_id) const;
381 // Construct a SPDY WINDOW_UPDATE frame.
382 // Returns the constructed frame. The caller takes ownership of the frame.
383 SpdyFrame* ConstructSpdyWindowUpdate(
384 SpdyStreamId stream_id,
385 uint32 delta_window_size) const;
387 // Construct a SPDY RST_STREAM frame.
388 // Returns the constructed frame. The caller takes ownership of the frame.
389 SpdyFrame* ConstructSpdyRstStream(SpdyStreamId stream_id,
390 SpdyRstStreamStatus status) const;
392 // Constructs a standard SPDY GET SYN frame, optionally compressed
393 // for the url |url|.
394 // |extra_headers| are the extra header-value pairs, which typically
395 // will vary the most between calls.
396 // Returns a SpdyFrame.
397 SpdyFrame* ConstructSpdyGet(const char* const url,
399 SpdyStreamId stream_id,
400 RequestPriority request_priority) const;
402 SpdyFrame* ConstructSpdyGetForProxy(const char* const url,
404 SpdyStreamId stream_id,
405 RequestPriority request_priority) const;
407 // Constructs a standard SPDY GET SYN frame, optionally compressed.
408 // |extra_headers| are the extra header-value pairs, which typically
409 // will vary the most between calls. If |direct| is false, the
410 // the full url will be used instead of simply the path.
411 // Returns a SpdyFrame.
412 SpdyFrame* ConstructSpdyGet(const char* const extra_headers[],
413 int extra_header_count,
416 RequestPriority request_priority,
419 // Constructs a standard SPDY SYN_STREAM frame for a CONNECT request.
420 SpdyFrame* ConstructSpdyConnect(const char* const extra_headers[],
421 int extra_header_count,
423 RequestPriority priority) const;
425 // Constructs a standard SPDY push SYN frame.
426 // |extra_headers| are the extra header-value pairs, which typically
427 // will vary the most between calls.
428 // Returns a SpdyFrame.
429 SpdyFrame* ConstructSpdyPush(const char* const extra_headers[],
430 int extra_header_count,
432 int associated_stream_id,
434 SpdyFrame* ConstructSpdyPush(const char* const extra_headers[],
435 int extra_header_count,
437 int associated_stream_id,
440 const char* location);
442 SpdyFrame* ConstructSpdyPushHeaders(int stream_id,
443 const char* const extra_headers[],
444 int extra_header_count);
446 // Constructs a standard SPDY SYN_REPLY frame to match the SPDY GET.
447 // |extra_headers| are the extra header-value pairs, which typically
448 // will vary the most between calls.
449 // Returns a SpdyFrame.
450 SpdyFrame* ConstructSpdyGetSynReply(const char* const extra_headers[],
451 int extra_header_count,
454 // Constructs a standard SPDY SYN_REPLY frame to match the SPDY GET.
455 // |extra_headers| are the extra header-value pairs, which typically
456 // will vary the most between calls.
457 // Returns a SpdyFrame.
458 SpdyFrame* ConstructSpdyGetSynReplyRedirect(int stream_id);
460 // Constructs a standard SPDY SYN_REPLY frame with an Internal Server
461 // Error status code.
462 // Returns a SpdyFrame.
463 SpdyFrame* ConstructSpdySynReplyError(int stream_id);
465 // Constructs a standard SPDY SYN_REPLY frame with the specified status code.
466 // Returns a SpdyFrame.
467 SpdyFrame* ConstructSpdySynReplyError(const char* const status,
468 const char* const* const extra_headers,
469 int extra_header_count,
472 // Constructs a standard SPDY POST SYN frame.
473 // |extra_headers| are the extra header-value pairs, which typically
474 // will vary the most between calls.
475 // Returns a SpdyFrame.
476 SpdyFrame* ConstructSpdyPost(const char* url,
477 SpdyStreamId stream_id,
478 int64 content_length,
479 RequestPriority priority,
480 const char* const extra_headers[],
481 int extra_header_count);
483 // Constructs a chunked transfer SPDY POST SYN frame.
484 // |extra_headers| are the extra header-value pairs, which typically
485 // will vary the most between calls.
486 // Returns a SpdyFrame.
487 SpdyFrame* ConstructChunkedSpdyPost(const char* const extra_headers[],
488 int extra_header_count);
490 // Constructs a standard SPDY SYN_REPLY frame to match the SPDY POST.
491 // |extra_headers| are the extra header-value pairs, which typically
492 // will vary the most between calls.
493 // Returns a SpdyFrame.
494 SpdyFrame* ConstructSpdyPostSynReply(const char* const extra_headers[],
495 int extra_header_count);
497 // Constructs a single SPDY data frame with the contents "hello!"
498 SpdyFrame* ConstructSpdyBodyFrame(int stream_id,
501 // Constructs a single SPDY data frame with the given content.
502 SpdyFrame* ConstructSpdyBodyFrame(int stream_id, const char* data,
503 uint32 len, bool fin);
505 // Wraps |frame| in the payload of a data frame in stream |stream_id|.
506 SpdyFrame* ConstructWrappedSpdyFrame(const scoped_ptr<SpdyFrame>& frame,
509 const SpdyHeaderInfo MakeSpdyHeader(SpdyFrameType type);
511 // For versions below SPDY4, adds the version HTTP/1.1 header.
512 void MaybeAddVersionHeader(SpdyFrameWithNameValueBlockIR* frame_ir) const;
514 // Maps |priority| to SPDY version priority, and sets it on |frame_ir|.
515 void SetPriority(RequestPriority priority, SpdySynStreamIR* frame_ir) const;
517 NextProto protocol() const { return protocol_; }
518 SpdyMajorVersion spdy_version() const { return spdy_version_; }
519 bool is_spdy2() const { return protocol_ < kProtoSPDY3; }
520 bool include_version_header() const { return protocol_ < kProtoSPDY4; }
521 scoped_ptr<SpdyFramer> CreateFramer(bool compressed) const;
523 const char* GetMethodKey() const;
524 const char* GetStatusKey() const;
525 const char* GetHostKey() const;
526 const char* GetSchemeKey() const;
527 const char* GetVersionKey() const;
528 const char* GetPathKey() const;
531 // |content_length| may be NULL, in which case the content-length
532 // header will be omitted.
533 scoped_ptr<SpdyHeaderBlock> ConstructHeaderBlock(
534 base::StringPiece method,
535 base::StringPiece url,
536 int64* content_length) const;
538 const NextProto protocol_;
539 const SpdyMajorVersion spdy_version_;
544 #endif // NET_SPDY_SPDY_TEST_UTIL_COMMON_H_