• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 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 // This class is useful for building a simple URLRequestContext. Most creators
6 // of new URLRequestContexts should use this helper class to construct it. Call
7 // any configuration params, and when done, invoke Build() to construct the
8 // URLRequestContext. This URLRequestContext will own all its own storage.
9 //
10 // URLRequestContextBuilder and its associated params classes are initially
11 // populated with "sane" default values. Read through the comments to figure out
12 // what these are.
13 
14 #ifndef NET_URL_REQUEST_URL_REQUEST_CONTEXT_BUILDER_H_
15 #define NET_URL_REQUEST_URL_REQUEST_CONTEXT_BUILDER_H_
16 
17 #include <stdint.h>
18 
19 #include <map>
20 #include <memory>
21 #include <string>
22 #include <utility>
23 #include <vector>
24 
25 #include "base/files/file_path.h"
26 #include "base/functional/callback.h"
27 #include "base/memory/raw_ptr.h"
28 #include "base/memory/scoped_refptr.h"
29 #include "base/task/task_traits.h"
30 #include "build/build_config.h"
31 #include "build/buildflag.h"
32 #include "net/base/net_export.h"
33 #include "net/base/network_delegate.h"
34 #include "net/base/network_handle.h"
35 #include "net/base/proxy_delegate.h"
36 #include "net/disk_cache/disk_cache.h"
37 #include "net/dns/host_resolver.h"
38 #include "net/http/http_network_session.h"
39 #include "net/net_buildflags.h"
40 #include "net/network_error_logging/network_error_logging_service.h"
41 #include "net/proxy_resolution/proxy_config_service.h"
42 #include "net/proxy_resolution/proxy_resolution_service.h"
43 #include "net/socket/client_socket_factory.h"
44 #include "net/ssl/ssl_config_service.h"
45 #include "net/third_party/quiche/src/quiche/quic/core/quic_packets.h"
46 #include "net/url_request/url_request_job_factory.h"
47 
48 namespace base::android {
49 class ApplicationStatusListener;
50 }  // namespace base::android
51 
52 namespace net {
53 
54 class CertVerifier;
55 class ClientSocketFactory;
56 class CookieStore;
57 class CTPolicyEnforcer;
58 class HttpAuthHandlerFactory;
59 class HttpTransactionFactory;
60 class HttpUserAgentSettings;
61 class HttpServerProperties;
62 class HostResolverManager;
63 class NetworkQualityEstimator;
64 class ProxyConfigService;
65 class URLRequestContext;
66 
67 #if BUILDFLAG(ENABLE_REPORTING)
68 struct ReportingPolicy;
69 class PersistentReportingAndNelStore;
70 #endif  // BUILDFLAG(ENABLE_REPORTING)
71 
72 // A URLRequestContextBuilder creates a single URLRequestContext. It provides
73 // methods to manage various URLRequestContext components which should be called
74 // before creating the Context. Once configuration is complete, calling Build()
75 // will create a URLRequestContext with the specified configuration. Components
76 // that are not explicitly configured will use reasonable in-memory defaults.
77 //
78 // The returned URLRequestContext is self-contained: Deleting it will safely
79 // shut down all of the URLRequests owned by its internal components, and then
80 // tear down those components. The only exception to this are objects not owned
81 // by URLRequestContext. This includes components passed in to the methods that
82 // take raw pointers, and objects that components passed in to the Builder have
83 // raw pointers to.
84 //
85 // A Builder should be destroyed after calling Build, and there is no need to
86 // keep it around for the lifetime of the created URLRequestContext. Each
87 // Builder may be used to create only a single URLRequestContext.
88 class NET_EXPORT URLRequestContextBuilder {
89  public:
90   // Creates an HttpNetworkTransactionFactory given an HttpNetworkSession. Does
91   // not take ownership of the session.
92   using CreateHttpTransactionFactoryCallback =
93       base::OnceCallback<std::unique_ptr<HttpTransactionFactory>(
94           HttpNetworkSession* session)>;
95 
96   struct NET_EXPORT HttpCacheParams {
97     enum Type {
98       // In-memory cache.
99       IN_MEMORY,
100       // Disk cache using "default" backend.
101       DISK,
102       // Disk cache using "blockfile" backend (BackendImpl).
103       DISK_BLOCKFILE,
104       // Disk cache using "simple" backend (SimpleBackendImpl).
105       DISK_SIMPLE,
106     };
107 
108     HttpCacheParams();
109     ~HttpCacheParams();
110 
111     // The type of HTTP cache. Default is IN_MEMORY.
112     Type type = IN_MEMORY;
113 
114     // The max size of the cache in bytes. Default is algorithmically determined
115     // based off available disk space.
116     int max_size = 0;
117 
118     // Whether or not we need to reset the cache due to an experiment change.
119     bool reset_cache = false;
120 
121     // The cache path (when type is DISK).
122     base::FilePath path;
123 
124     // A factory to broker file operations. This is needed for network process
125     // sandboxing in some platforms.
126     scoped_refptr<disk_cache::BackendFileOperationsFactory>
127         file_operations_factory;
128 
129 #if BUILDFLAG(IS_ANDROID)
130     // If this is set, will override the default ApplicationStatusListener. This
131     // is useful if the cache will not be in the main process.
132     raw_ptr<base::android::ApplicationStatusListener> app_status_listener =
133         nullptr;
134 #endif
135   };
136 
137   URLRequestContextBuilder();
138 
139   URLRequestContextBuilder(const URLRequestContextBuilder&) = delete;
140   URLRequestContextBuilder& operator=(const URLRequestContextBuilder&) = delete;
141 
142   virtual ~URLRequestContextBuilder();
143 
144   // Sets whether Brotli compression is enabled.  Disabled by default;
set_enable_brotli(bool enable_brotli)145   void set_enable_brotli(bool enable_brotli) { enable_brotli_ = enable_brotli; }
146 
147   // Sets the |check_cleartext_permitted| flag, which controls whether to check
148   // system policy before allowing a cleartext http or ws request.
set_check_cleartext_permitted(bool value)149   void set_check_cleartext_permitted(bool value) {
150     check_cleartext_permitted_ = value;
151   }
152 
set_require_network_isolation_key(bool value)153   void set_require_network_isolation_key(bool value) {
154     require_network_isolation_key_ = value;
155   }
156 
157   // Unlike most other setters, the builder does not take ownership of the
158   // NetworkQualityEstimator.
set_network_quality_estimator(NetworkQualityEstimator * network_quality_estimator)159   void set_network_quality_estimator(
160       NetworkQualityEstimator* network_quality_estimator) {
161     network_quality_estimator_ = network_quality_estimator;
162   }
163 
164   // These functions are mutually exclusive.  The ProxyConfigService, if
165   // set, will be used to construct a ConfiguredProxyResolutionService.
set_proxy_config_service(std::unique_ptr<ProxyConfigService> proxy_config_service)166   void set_proxy_config_service(
167       std::unique_ptr<ProxyConfigService> proxy_config_service) {
168     proxy_config_service_ = std::move(proxy_config_service);
169   }
170 
171   // Sets whether quick PAC checks are enabled. Defaults to true. Ignored if
172   // a ConfiguredProxyResolutionService is set directly.
set_pac_quick_check_enabled(bool pac_quick_check_enabled)173   void set_pac_quick_check_enabled(bool pac_quick_check_enabled) {
174     pac_quick_check_enabled_ = pac_quick_check_enabled;
175   }
176 
177   // Sets the proxy service. If one is not provided, by default, uses system
178   // libraries to evaluate PAC scripts, if available (And if not, skips PAC
179   // resolution). Subclasses may override CreateProxyResolutionService for
180   // different default behavior.
set_proxy_resolution_service(std::unique_ptr<ProxyResolutionService> proxy_resolution_service)181   void set_proxy_resolution_service(
182       std::unique_ptr<ProxyResolutionService> proxy_resolution_service) {
183     proxy_resolution_service_ = std::move(proxy_resolution_service);
184   }
185 
set_ssl_config_service(std::unique_ptr<SSLConfigService> ssl_config_service)186   void set_ssl_config_service(
187       std::unique_ptr<SSLConfigService> ssl_config_service) {
188     ssl_config_service_ = std::move(ssl_config_service);
189   }
190 
191   // Call these functions to specify hard-coded Accept-Language
192   // or User-Agent header values for all requests that don't
193   // have the headers already set.
194   void set_accept_language(const std::string& accept_language);
195   void set_user_agent(const std::string& user_agent);
196 
197   // Makes the created URLRequestContext use a particular HttpUserAgentSettings
198   // object. Not compatible with set_accept_language() / set_user_agent().
199   //
200   // The object will be live until the URLRequestContext is destroyed.
201   void set_http_user_agent_settings(
202       std::unique_ptr<HttpUserAgentSettings> http_user_agent_settings);
203 
204   // Sets a valid ProtocolHandler for a scheme.
205   // A ProtocolHandler already exists for |scheme| will be overwritten.
206   void SetProtocolHandler(
207       const std::string& scheme,
208       std::unique_ptr<URLRequestJobFactory::ProtocolHandler> protocol_handler);
209 
210   // Unlike the other setters, the builder does not take ownership of the
211   // NetLog.
212   // TODO(mmenke):  Probably makes sense to get rid of this, and have consumers
213   // set their own NetLog::Observers instead.
set_net_log(NetLog * net_log)214   void set_net_log(NetLog* net_log) { net_log_ = net_log; }
215 
216   // Sets a HostResolver instance to be used instead of default construction.
217   // Should not be used if set_host_resolver_manager(),
218   // set_host_mapping_rules(), or set_host_resolver_factory() are used. On
219   // building the context, will call HostResolver::SetRequestContext, so
220   // |host_resolver| may not already be associated with a context.
221   void set_host_resolver(std::unique_ptr<HostResolver> host_resolver);
222 
223   // If set to non-empty, the mapping rules will be applied to requests to the
224   // created host resolver. See MappedHostResolver for details. Should not be
225   // used if set_host_resolver() is used.
226   void set_host_mapping_rules(std::string host_mapping_rules);
227 
228   // Sets a shared HostResolverManager to be used for created HostResolvers.
229   // Should not be used if set_host_resolver() is used. The consumer must ensure
230   // |manager| outlives the URLRequestContext returned by the builder.
231   void set_host_resolver_manager(HostResolverManager* manager);
232 
233   // Sets the factory used for any HostResolverCreation. By default, a default
234   // implementation will be used. Should not be used if set_host_resolver() is
235   // used.
236   void set_host_resolver_factory(HostResolver::Factory* factory);
237 
238   // Uses NetworkDelegateImpl by default. Note that calling Build will unset
239   // any custom delegate in builder, so this must be called each time before
240   // Build is called.
241   // Returns a raw pointer to the set delegate.
242   template <typename T>
set_network_delegate(std::unique_ptr<T> delegate)243   T* set_network_delegate(std::unique_ptr<T> delegate) {
244     network_delegate_ = std::move(delegate);
245     return static_cast<T*>(network_delegate_.get());
246   }
247 
248   // Sets the ProxyDelegate.
249   void set_proxy_delegate(std::unique_ptr<ProxyDelegate> proxy_delegate);
250 
251   // Sets a specific HttpAuthHandlerFactory to be used by the URLRequestContext
252   // rather than the default |HttpAuthHandlerRegistryFactory|. The builder
253   // takes ownership of the factory and will eventually transfer it to the new
254   // URLRequestContext.
255   void SetHttpAuthHandlerFactory(
256       std::unique_ptr<HttpAuthHandlerFactory> factory);
257 
258   // By default HttpCache is enabled with a default constructed HttpCacheParams.
259   void EnableHttpCache(const HttpCacheParams& params);
260   void DisableHttpCache();
261 
262   // Override default HttpNetworkSessionParams settings.
set_http_network_session_params(const HttpNetworkSessionParams & http_network_session_params)263   void set_http_network_session_params(
264       const HttpNetworkSessionParams& http_network_session_params) {
265     http_network_session_params_ = http_network_session_params;
266   }
267 
set_transport_security_persister_file_path(const base::FilePath & transport_security_persister_file_path)268   void set_transport_security_persister_file_path(
269       const base::FilePath& transport_security_persister_file_path) {
270     transport_security_persister_file_path_ =
271         transport_security_persister_file_path;
272   }
273 
set_hsts_policy_bypass_list(const std::vector<std::string> & hsts_policy_bypass_list)274   void set_hsts_policy_bypass_list(
275       const std::vector<std::string>& hsts_policy_bypass_list) {
276     hsts_policy_bypass_list_ = hsts_policy_bypass_list;
277   }
278 
279   void SetSpdyAndQuicEnabled(bool spdy_enabled, bool quic_enabled);
280 
set_throttling_enabled(bool throttling_enabled)281   void set_throttling_enabled(bool throttling_enabled) {
282     throttling_enabled_ = throttling_enabled;
283   }
284 
285   void set_ct_policy_enforcer(
286       std::unique_ptr<CTPolicyEnforcer> ct_policy_enforcer);
287   void set_sct_auditing_delegate(
288       std::unique_ptr<SCTAuditingDelegate> sct_auditing_delegate);
289   void set_quic_context(std::unique_ptr<QuicContext> quic_context);
290 
291   void SetCertVerifier(std::unique_ptr<CertVerifier> cert_verifier);
292 
293 #if BUILDFLAG(ENABLE_REPORTING)
294   void set_reporting_service(
295       std::unique_ptr<ReportingService> reporting_service);
296   void set_reporting_policy(std::unique_ptr<ReportingPolicy> reporting_policy);
297 
set_network_error_logging_enabled(bool network_error_logging_enabled)298   void set_network_error_logging_enabled(bool network_error_logging_enabled) {
299     network_error_logging_enabled_ = network_error_logging_enabled;
300   }
301 
302   template <typename T>
SetNetworkErrorLoggingServiceForTesting(std::unique_ptr<T> service)303   T* SetNetworkErrorLoggingServiceForTesting(std::unique_ptr<T> service) {
304     network_error_logging_service_ = std::move(service);
305     return static_cast<T*>(network_error_logging_service_.get());
306   }
307 
308   void set_persistent_reporting_and_nel_store(
309       std::unique_ptr<PersistentReportingAndNelStore>
310           persistent_reporting_and_nel_store);
311 #endif  // BUILDFLAG(ENABLE_REPORTING)
312 
313   // Override the default in-memory cookie store. If |cookie_store| is NULL,
314   // CookieStore will be disabled for this context.
315   void SetCookieStore(std::unique_ptr<CookieStore> cookie_store);
316 
317   // Sets a specific HttpServerProperties for use in the
318   // URLRequestContext rather than creating a default HttpServerPropertiesImpl.
319   void SetHttpServerProperties(
320       std::unique_ptr<HttpServerProperties> http_server_properties);
321 
322   // Sets a callback that will be used to create the
323   // HttpNetworkTransactionFactory. If a cache is enabled, the cache's
324   // HttpTransactionFactory will wrap the one this creates.
325   // TODO(mmenke): Get rid of this. See https://crbug.com/721408
326   void SetCreateHttpTransactionFactoryCallback(
327       CreateHttpTransactionFactoryCallback
328           create_http_network_transaction_factory);
329 
330   template <typename T>
SetHttpTransactionFactoryForTesting(std::unique_ptr<T> factory)331   T* SetHttpTransactionFactoryForTesting(std::unique_ptr<T> factory) {
332     create_http_network_transaction_factory_.Reset();
333     http_transaction_factory_ = std::move(factory);
334     return static_cast<T*>(http_transaction_factory_.get());
335   }
336 
337   // Sets a ClientSocketFactory so a test can mock out sockets. This must
338   // outlive the URLRequestContext that will be built.
set_client_socket_factory_for_testing(ClientSocketFactory * client_socket_factory_for_testing)339   void set_client_socket_factory_for_testing(
340       ClientSocketFactory* client_socket_factory_for_testing) {
341     set_client_socket_factory(client_socket_factory_for_testing);
342   }
343 
344   // Sets a ClientSocketFactory when the network service sandbox is enabled. The
345   // unique_ptr is moved to a URLRequestContext once Build() is called.
set_client_socket_factory(std::unique_ptr<ClientSocketFactory> client_socket_factory)346   void set_client_socket_factory(
347       std::unique_ptr<ClientSocketFactory> client_socket_factory) {
348     set_client_socket_factory(client_socket_factory.get());
349     client_socket_factory_ = std::move(client_socket_factory);
350   }
351 
352   // Binds the context to `network`. All requests scheduled through the context
353   // built by this builder will be sent using `network`. Requests will fail if
354   // `network` disconnects. `options` allows to specify the ManagerOptions that
355   // will be passed to the special purpose HostResolver created internally.
356   // This also imposes some limitations on the context capabilities:
357   // * By design, QUIC connection migration will be turned off.
358   // Only implemented for Android (API level > 23).
359   void BindToNetwork(
360       handles::NetworkHandle network,
361       absl::optional<HostResolver::ManagerOptions> options = absl::nullopt);
362 
363   // Creates a mostly self-contained URLRequestContext. May only be called once
364   // per URLRequestContextBuilder. After this is called, the Builder can be
365   // safely destroyed.
366   std::unique_ptr<URLRequestContext> Build();
367 
SuppressSettingSocketPerformanceWatcherFactoryForTesting()368   void SuppressSettingSocketPerformanceWatcherFactoryForTesting() {
369     suppress_setting_socket_performance_watcher_factory_for_testing_ = true;
370   }
371 
372  protected:
373   // Lets subclasses override ProxyResolutionService creation, using a
374   // ProxyResolutionService that uses the URLRequestContext itself to get PAC
375   // scripts. When this method is invoked, the URLRequestContext is not yet
376   // ready to service requests.
377   virtual std::unique_ptr<ProxyResolutionService> CreateProxyResolutionService(
378       std::unique_ptr<ProxyConfigService> proxy_config_service,
379       URLRequestContext* url_request_context,
380       HostResolver* host_resolver,
381       NetworkDelegate* network_delegate,
382       NetLog* net_log,
383       bool pac_quick_check_enabled);
384 
385  private:
386   // Extracts the component pointers required to construct an HttpNetworkSession
387   // and copies them into the HttpNetworkSession::Context used to create the
388   // session. This function should be used to ensure that a context and its
389   // associated HttpNetworkSession are consistent.
390   static void SetHttpNetworkSessionComponents(
391       const URLRequestContext* request_context,
392       HttpNetworkSessionContext* session_context,
393       bool suppress_setting_socket_performance_watcher_factory = false,
394       ClientSocketFactory* client_socket_factory = nullptr);
395 
396   // Factory that will be used to create all client sockets used by the
397   // URLRequestContext that will be built.
398   // `client_socket_factory` must outlive the context.
set_client_socket_factory(ClientSocketFactory * client_socket_factory)399   void set_client_socket_factory(ClientSocketFactory* client_socket_factory) {
400     client_socket_factory_raw_ = client_socket_factory;
401   }
402 
403   bool enable_brotli_ = false;
404   bool check_cleartext_permitted_ = false;
405   bool require_network_isolation_key_ = false;
406   raw_ptr<NetworkQualityEstimator> network_quality_estimator_ = nullptr;
407 
408   std::string accept_language_;
409   std::string user_agent_;
410   std::unique_ptr<HttpUserAgentSettings> http_user_agent_settings_;
411 
412   bool http_cache_enabled_ = true;
413   bool throttling_enabled_ = false;
414   bool cookie_store_set_by_client_ = false;
415   bool suppress_setting_socket_performance_watcher_factory_for_testing_ = false;
416 
417   handles::NetworkHandle bound_network_ = handles::kInvalidNetworkHandle;
418   // Used only if the context is bound to a network to customize the
419   // HostResolver created internally.
420   HostResolver::ManagerOptions manager_options_;
421 
422   HttpCacheParams http_cache_params_;
423   HttpNetworkSessionParams http_network_session_params_;
424   CreateHttpTransactionFactoryCallback create_http_network_transaction_factory_;
425   std::unique_ptr<HttpTransactionFactory> http_transaction_factory_;
426   base::FilePath transport_security_persister_file_path_;
427   std::vector<std::string> hsts_policy_bypass_list_;
428   raw_ptr<NetLog> net_log_ = nullptr;
429   std::unique_ptr<HostResolver> host_resolver_;
430   std::string host_mapping_rules_;
431   raw_ptr<HostResolverManager> host_resolver_manager_ = nullptr;
432   raw_ptr<HostResolver::Factory> host_resolver_factory_ = nullptr;
433   std::unique_ptr<ProxyConfigService> proxy_config_service_;
434   bool pac_quick_check_enabled_ = true;
435   std::unique_ptr<ProxyResolutionService> proxy_resolution_service_;
436   std::unique_ptr<SSLConfigService> ssl_config_service_;
437   std::unique_ptr<NetworkDelegate> network_delegate_;
438   std::unique_ptr<ProxyDelegate> proxy_delegate_;
439   std::unique_ptr<CookieStore> cookie_store_;
440   std::unique_ptr<HttpAuthHandlerFactory> http_auth_handler_factory_;
441   std::unique_ptr<CertVerifier> cert_verifier_;
442   std::unique_ptr<CTPolicyEnforcer> ct_policy_enforcer_;
443   std::unique_ptr<SCTAuditingDelegate> sct_auditing_delegate_;
444   std::unique_ptr<QuicContext> quic_context_;
445   std::unique_ptr<ClientSocketFactory> client_socket_factory_ = nullptr;
446 #if BUILDFLAG(ENABLE_REPORTING)
447   std::unique_ptr<ReportingService> reporting_service_;
448   std::unique_ptr<ReportingPolicy> reporting_policy_;
449   bool network_error_logging_enabled_ = false;
450   std::unique_ptr<NetworkErrorLoggingService> network_error_logging_service_;
451   std::unique_ptr<PersistentReportingAndNelStore>
452       persistent_reporting_and_nel_store_;
453 #endif  // BUILDFLAG(ENABLE_REPORTING)
454   std::unique_ptr<HttpServerProperties> http_server_properties_;
455   std::map<std::string, std::unique_ptr<URLRequestJobFactory::ProtocolHandler>>
456       protocol_handlers_;
457 
458   raw_ptr<ClientSocketFactory> client_socket_factory_raw_ = nullptr;
459 };
460 
461 }  // namespace net
462 
463 #endif  // NET_URL_REQUEST_URL_REQUEST_CONTEXT_BUILDER_H_
464