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 <optional> 22 #include <string> 23 #include <utility> 24 #include <vector> 25 26 #include "base/files/file_path.h" 27 #include "base/functional/callback.h" 28 #include "base/memory/raw_ptr.h" 29 #include "base/memory/scoped_refptr.h" 30 #include "base/task/task_traits.h" 31 #include "build/build_config.h" 32 #include "build/buildflag.h" 33 #include "net/base/net_export.h" 34 #include "net/base/network_delegate.h" 35 #include "net/base/network_handle.h" 36 #include "net/base/proxy_delegate.h" 37 #include "net/disk_cache/disk_cache.h" 38 #include "net/dns/host_resolver.h" 39 #include "net/http/http_network_session.h" 40 #include "net/net_buildflags.h" 41 #include "net/network_error_logging/network_error_logging_service.h" 42 #include "net/proxy_resolution/proxy_config_service.h" 43 #include "net/proxy_resolution/proxy_resolution_service.h" 44 #include "net/socket/client_socket_factory.h" 45 #include "net/ssl/ssl_config_service.h" 46 #include "net/third_party/quiche/src/quiche/quic/core/quic_packets.h" 47 #include "net/url_request/url_request_job_factory.h" 48 49 namespace net { 50 51 class CertVerifier; 52 class ClientSocketFactory; 53 class CookieStore; 54 class HttpAuthHandlerFactory; 55 class HttpTransactionFactory; 56 class HttpUserAgentSettings; 57 class HttpServerProperties; 58 class HostResolverManager; 59 class NetworkQualityEstimator; 60 class ProxyConfigService; 61 class URLRequestContext; 62 63 #if BUILDFLAG(ENABLE_REPORTING) 64 struct ReportingPolicy; 65 class PersistentReportingAndNelStore; 66 #endif // BUILDFLAG(ENABLE_REPORTING) 67 68 #if BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS) 69 class DeviceBoundSessionService; 70 #endif // BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS) 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 disk_cache::ApplicationStatusListenerGetter app_status_listener_getter; 133 #endif 134 }; 135 136 URLRequestContextBuilder(); 137 138 URLRequestContextBuilder(const URLRequestContextBuilder&) = delete; 139 URLRequestContextBuilder& operator=(const URLRequestContextBuilder&) = delete; 140 141 virtual ~URLRequestContextBuilder(); 142 143 // Sets whether Brotli compression is enabled. Disabled by default; set_enable_brotli(bool enable_brotli)144 void set_enable_brotli(bool enable_brotli) { enable_brotli_ = enable_brotli; } 145 146 // Sets whether Zstd compression is enabled. Disabled by default. set_enable_zstd(bool enable_zstd)147 void set_enable_zstd(bool enable_zstd) { enable_zstd_ = enable_zstd; } 148 149 // Sets the |check_cleartext_permitted| flag, which controls whether to check 150 // system policy before allowing a cleartext http or ws request. set_check_cleartext_permitted(bool value)151 void set_check_cleartext_permitted(bool value) { 152 check_cleartext_permitted_ = value; 153 } 154 set_require_network_anonymization_key(bool value)155 void set_require_network_anonymization_key(bool value) { 156 require_network_anonymization_key_ = value; 157 } 158 159 // Unlike most other setters, the builder does not take ownership of the 160 // NetworkQualityEstimator. set_network_quality_estimator(NetworkQualityEstimator * network_quality_estimator)161 void set_network_quality_estimator( 162 NetworkQualityEstimator* network_quality_estimator) { 163 network_quality_estimator_ = network_quality_estimator; 164 } 165 166 // These functions are mutually exclusive. The ProxyConfigService, if 167 // set, will be used to construct a ConfiguredProxyResolutionService. set_proxy_config_service(std::unique_ptr<ProxyConfigService> proxy_config_service)168 void set_proxy_config_service( 169 std::unique_ptr<ProxyConfigService> proxy_config_service) { 170 proxy_config_service_ = std::move(proxy_config_service); 171 } 172 173 // Sets whether quick PAC checks are enabled. Defaults to true. Ignored if 174 // a ConfiguredProxyResolutionService is set directly. set_pac_quick_check_enabled(bool pac_quick_check_enabled)175 void set_pac_quick_check_enabled(bool pac_quick_check_enabled) { 176 pac_quick_check_enabled_ = pac_quick_check_enabled; 177 } 178 179 // Sets the proxy service. If one is not provided, by default, uses system 180 // libraries to evaluate PAC scripts, if available (And if not, skips PAC 181 // resolution). Subclasses may override CreateProxyResolutionService for 182 // different default behavior. set_proxy_resolution_service(std::unique_ptr<ProxyResolutionService> proxy_resolution_service)183 void set_proxy_resolution_service( 184 std::unique_ptr<ProxyResolutionService> proxy_resolution_service) { 185 proxy_resolution_service_ = std::move(proxy_resolution_service); 186 } 187 set_ssl_config_service(std::unique_ptr<SSLConfigService> ssl_config_service)188 void set_ssl_config_service( 189 std::unique_ptr<SSLConfigService> ssl_config_service) { 190 ssl_config_service_ = std::move(ssl_config_service); 191 } 192 193 // Call these functions to specify hard-coded Accept-Language 194 // or User-Agent header values for all requests that don't 195 // have the headers already set. 196 void set_accept_language(const std::string& accept_language); 197 void set_user_agent(const std::string& user_agent); 198 199 // Makes the created URLRequestContext use a particular HttpUserAgentSettings 200 // object. Not compatible with set_accept_language() / set_user_agent(). 201 // 202 // The object will be live until the URLRequestContext is destroyed. 203 void set_http_user_agent_settings( 204 std::unique_ptr<HttpUserAgentSettings> http_user_agent_settings); 205 206 // Sets a valid ProtocolHandler for a scheme. 207 // A ProtocolHandler already exists for |scheme| will be overwritten. 208 void SetProtocolHandler( 209 const std::string& scheme, 210 std::unique_ptr<URLRequestJobFactory::ProtocolHandler> protocol_handler); 211 212 // Unlike the other setters, the builder does not take ownership of the 213 // NetLog. 214 // TODO(mmenke): Probably makes sense to get rid of this, and have consumers 215 // set their own NetLog::Observers instead. set_net_log(NetLog * net_log)216 void set_net_log(NetLog* net_log) { net_log_ = net_log; } 217 218 // Sets a HostResolver instance to be used instead of default construction. 219 // Should not be used if set_host_resolver_manager(), 220 // set_host_mapping_rules(), or set_host_resolver_factory() are used. On 221 // building the context, will call HostResolver::SetRequestContext, so 222 // |host_resolver| may not already be associated with a context. 223 void set_host_resolver(std::unique_ptr<HostResolver> host_resolver); 224 225 // If set to non-empty, the mapping rules will be applied to requests to the 226 // created host resolver. See MappedHostResolver for details. Should not be 227 // used if set_host_resolver() is used. 228 void set_host_mapping_rules(std::string host_mapping_rules); 229 230 // Sets a shared HostResolverManager to be used for created HostResolvers. 231 // Should not be used if set_host_resolver() is used. The consumer must ensure 232 // |manager| outlives the URLRequestContext returned by the builder. 233 void set_host_resolver_manager(HostResolverManager* manager); 234 235 // Sets the factory used for any HostResolverCreation. By default, a default 236 // implementation will be used. Should not be used if set_host_resolver() is 237 // used. 238 void set_host_resolver_factory(HostResolver::Factory* factory); 239 240 // Uses NetworkDelegateImpl by default. Note that calling Build will unset 241 // any custom delegate in builder, so this must be called each time before 242 // Build is called. 243 // Returns a raw pointer to the set delegate. 244 template <typename T> set_network_delegate(std::unique_ptr<T> delegate)245 T* set_network_delegate(std::unique_ptr<T> delegate) { 246 network_delegate_ = std::move(delegate); 247 return static_cast<T*>(network_delegate_.get()); 248 } 249 250 // Sets the ProxyDelegate. 251 void set_proxy_delegate(std::unique_ptr<ProxyDelegate> proxy_delegate); 252 253 // Sets a specific HttpAuthHandlerFactory to be used by the URLRequestContext 254 // rather than the default |HttpAuthHandlerRegistryFactory|. The builder 255 // takes ownership of the factory and will eventually transfer it to the new 256 // URLRequestContext. 257 void SetHttpAuthHandlerFactory( 258 std::unique_ptr<HttpAuthHandlerFactory> factory); 259 260 // By default HttpCache is enabled with a default constructed HttpCacheParams. 261 void EnableHttpCache(const HttpCacheParams& params); 262 void DisableHttpCache(); 263 264 // Override default HttpNetworkSessionParams settings. set_http_network_session_params(const HttpNetworkSessionParams & http_network_session_params)265 void set_http_network_session_params( 266 const HttpNetworkSessionParams& http_network_session_params) { 267 http_network_session_params_ = http_network_session_params; 268 } 269 set_transport_security_persister_file_path(const base::FilePath & transport_security_persister_file_path)270 void set_transport_security_persister_file_path( 271 const base::FilePath& transport_security_persister_file_path) { 272 transport_security_persister_file_path_ = 273 transport_security_persister_file_path; 274 } 275 set_hsts_policy_bypass_list(const std::vector<std::string> & hsts_policy_bypass_list)276 void set_hsts_policy_bypass_list( 277 const std::vector<std::string>& hsts_policy_bypass_list) { 278 hsts_policy_bypass_list_ = hsts_policy_bypass_list; 279 } 280 281 void SetSpdyAndQuicEnabled(bool spdy_enabled, bool quic_enabled); 282 283 void set_sct_auditing_delegate( 284 std::unique_ptr<SCTAuditingDelegate> sct_auditing_delegate); 285 void set_quic_context(std::unique_ptr<QuicContext> quic_context); 286 287 void SetCertVerifier(std::unique_ptr<CertVerifier> cert_verifier); 288 289 #if BUILDFLAG(ENABLE_REPORTING) 290 void set_reporting_service( 291 std::unique_ptr<ReportingService> reporting_service); 292 void set_reporting_policy(std::unique_ptr<ReportingPolicy> reporting_policy); 293 set_network_error_logging_enabled(bool network_error_logging_enabled)294 void set_network_error_logging_enabled(bool network_error_logging_enabled) { 295 network_error_logging_enabled_ = network_error_logging_enabled; 296 } 297 298 template <typename T> SetNetworkErrorLoggingServiceForTesting(std::unique_ptr<T> service)299 T* SetNetworkErrorLoggingServiceForTesting(std::unique_ptr<T> service) { 300 network_error_logging_service_ = std::move(service); 301 return static_cast<T*>(network_error_logging_service_.get()); 302 } 303 304 void set_persistent_reporting_and_nel_store( 305 std::unique_ptr<PersistentReportingAndNelStore> 306 persistent_reporting_and_nel_store); 307 #endif // BUILDFLAG(ENABLE_REPORTING) 308 309 // Override the default in-memory cookie store. If |cookie_store| is NULL, 310 // CookieStore will be disabled for this context. 311 void SetCookieStore(std::unique_ptr<CookieStore> cookie_store); 312 313 // Sets a specific HttpServerProperties for use in the 314 // URLRequestContext rather than creating a default HttpServerPropertiesImpl. 315 void SetHttpServerProperties( 316 std::unique_ptr<HttpServerProperties> http_server_properties); 317 318 // Sets a callback that will be used to create the 319 // HttpNetworkTransactionFactory. If a cache is enabled, the cache's 320 // HttpTransactionFactory will wrap the one this creates. 321 // TODO(mmenke): Get rid of this. See https://crbug.com/721408 322 void SetCreateHttpTransactionFactoryCallback( 323 CreateHttpTransactionFactoryCallback 324 create_http_network_transaction_factory); 325 326 template <typename T> SetHttpTransactionFactoryForTesting(std::unique_ptr<T> factory)327 T* SetHttpTransactionFactoryForTesting(std::unique_ptr<T> factory) { 328 create_http_network_transaction_factory_.Reset(); 329 http_transaction_factory_ = std::move(factory); 330 return static_cast<T*>(http_transaction_factory_.get()); 331 } 332 333 // Sets a ClientSocketFactory so a test can mock out sockets. This must 334 // outlive the URLRequestContext that will be built. set_client_socket_factory_for_testing(ClientSocketFactory * client_socket_factory_for_testing)335 void set_client_socket_factory_for_testing( 336 ClientSocketFactory* client_socket_factory_for_testing) { 337 set_client_socket_factory(client_socket_factory_for_testing); 338 } 339 340 // Sets a ClientSocketFactory when the network service sandbox is enabled. The 341 // unique_ptr is moved to a URLRequestContext once Build() is called. set_client_socket_factory(std::unique_ptr<ClientSocketFactory> client_socket_factory)342 void set_client_socket_factory( 343 std::unique_ptr<ClientSocketFactory> client_socket_factory) { 344 set_client_socket_factory(client_socket_factory.get()); 345 client_socket_factory_ = std::move(client_socket_factory); 346 } 347 set_cookie_deprecation_label(const std::string & label)348 void set_cookie_deprecation_label(const std::string& label) { 349 cookie_deprecation_label_ = label; 350 } 351 352 #if BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS) 353 void set_device_bound_session_service( 354 std::unique_ptr<DeviceBoundSessionService> device_bound_session_service); 355 #endif // BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS) 356 357 // Binds the context to `network`. All requests scheduled through the context 358 // built by this builder will be sent using `network`. Requests will fail if 359 // `network` disconnects. `options` allows to specify the ManagerOptions that 360 // will be passed to the special purpose HostResolver created internally. 361 // This also imposes some limitations on the context capabilities: 362 // * By design, QUIC connection migration will be turned off. 363 // Only implemented for Android (API level > 23). 364 void BindToNetwork( 365 handles::NetworkHandle network, 366 std::optional<HostResolver::ManagerOptions> options = std::nullopt); 367 368 // Creates a mostly self-contained URLRequestContext. May only be called once 369 // per URLRequestContextBuilder. After this is called, the Builder can be 370 // safely destroyed. 371 std::unique_ptr<URLRequestContext> Build(); 372 SuppressSettingSocketPerformanceWatcherFactoryForTesting()373 void SuppressSettingSocketPerformanceWatcherFactoryForTesting() { 374 suppress_setting_socket_performance_watcher_factory_for_testing_ = true; 375 } 376 377 protected: 378 // Lets subclasses override ProxyResolutionService creation, using a 379 // ProxyResolutionService that uses the URLRequestContext itself to get PAC 380 // scripts. When this method is invoked, the URLRequestContext is not yet 381 // ready to service requests. 382 virtual std::unique_ptr<ProxyResolutionService> CreateProxyResolutionService( 383 std::unique_ptr<ProxyConfigService> proxy_config_service, 384 URLRequestContext* url_request_context, 385 HostResolver* host_resolver, 386 NetworkDelegate* network_delegate, 387 NetLog* net_log, 388 bool pac_quick_check_enabled); 389 390 private: 391 // Extracts the component pointers required to construct an HttpNetworkSession 392 // and copies them into the HttpNetworkSession::Context used to create the 393 // session. This function should be used to ensure that a context and its 394 // associated HttpNetworkSession are consistent. 395 static void SetHttpNetworkSessionComponents( 396 const URLRequestContext* request_context, 397 HttpNetworkSessionContext* session_context, 398 bool suppress_setting_socket_performance_watcher_factory = false, 399 ClientSocketFactory* client_socket_factory = nullptr); 400 401 // Factory that will be used to create all client sockets used by the 402 // URLRequestContext that will be built. 403 // `client_socket_factory` must outlive the context. set_client_socket_factory(ClientSocketFactory * client_socket_factory)404 void set_client_socket_factory(ClientSocketFactory* client_socket_factory) { 405 client_socket_factory_raw_ = client_socket_factory; 406 } 407 408 bool enable_brotli_ = false; 409 bool enable_zstd_ = false; 410 bool check_cleartext_permitted_ = false; 411 bool require_network_anonymization_key_ = false; 412 raw_ptr<NetworkQualityEstimator> network_quality_estimator_ = nullptr; 413 414 std::string accept_language_; 415 std::string user_agent_; 416 std::unique_ptr<HttpUserAgentSettings> http_user_agent_settings_; 417 418 std::optional<std::string> cookie_deprecation_label_; 419 420 bool http_cache_enabled_ = true; 421 bool cookie_store_set_by_client_ = false; 422 bool suppress_setting_socket_performance_watcher_factory_for_testing_ = false; 423 424 handles::NetworkHandle bound_network_ = handles::kInvalidNetworkHandle; 425 // Used only if the context is bound to a network to customize the 426 // HostResolver created internally. 427 HostResolver::ManagerOptions manager_options_; 428 429 HttpCacheParams http_cache_params_; 430 HttpNetworkSessionParams http_network_session_params_; 431 CreateHttpTransactionFactoryCallback create_http_network_transaction_factory_; 432 std::unique_ptr<HttpTransactionFactory> http_transaction_factory_; 433 base::FilePath transport_security_persister_file_path_; 434 std::vector<std::string> hsts_policy_bypass_list_; 435 raw_ptr<NetLog> net_log_ = nullptr; 436 std::unique_ptr<HostResolver> host_resolver_; 437 std::string host_mapping_rules_; 438 raw_ptr<HostResolverManager> host_resolver_manager_ = nullptr; 439 raw_ptr<HostResolver::Factory> host_resolver_factory_ = nullptr; 440 std::unique_ptr<ProxyConfigService> proxy_config_service_; 441 bool pac_quick_check_enabled_ = true; 442 std::unique_ptr<ProxyResolutionService> proxy_resolution_service_; 443 std::unique_ptr<SSLConfigService> ssl_config_service_; 444 std::unique_ptr<NetworkDelegate> network_delegate_; 445 std::unique_ptr<ProxyDelegate> proxy_delegate_; 446 std::unique_ptr<CookieStore> cookie_store_; 447 std::unique_ptr<HttpAuthHandlerFactory> http_auth_handler_factory_; 448 std::unique_ptr<CertVerifier> cert_verifier_; 449 std::unique_ptr<SCTAuditingDelegate> sct_auditing_delegate_; 450 std::unique_ptr<QuicContext> quic_context_; 451 std::unique_ptr<ClientSocketFactory> client_socket_factory_ = nullptr; 452 #if BUILDFLAG(ENABLE_REPORTING) 453 std::unique_ptr<ReportingService> reporting_service_; 454 std::unique_ptr<ReportingPolicy> reporting_policy_; 455 bool network_error_logging_enabled_ = false; 456 std::unique_ptr<NetworkErrorLoggingService> network_error_logging_service_; 457 std::unique_ptr<PersistentReportingAndNelStore> 458 persistent_reporting_and_nel_store_; 459 #endif // BUILDFLAG(ENABLE_REPORTING) 460 std::unique_ptr<HttpServerProperties> http_server_properties_; 461 std::map<std::string, std::unique_ptr<URLRequestJobFactory::ProtocolHandler>> 462 protocol_handlers_; 463 #if BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS) 464 std::unique_ptr<DeviceBoundSessionService> device_bound_session_service_; 465 #endif // BUILDFLAG(ENABLE_DEVICE_BOUND_SESSIONS) 466 467 raw_ptr<ClientSocketFactory> client_socket_factory_raw_ = nullptr; 468 }; 469 470 } // namespace net 471 472 #endif // NET_URL_REQUEST_URL_REQUEST_CONTEXT_BUILDER_H_ 473