Debian Codegraph @

samples/chromium-sample/src/io_thread.cc

raw symbols SCIP
1 // Copyright (c) 2012 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.
4
5 #include "chrome/browser/io_thread.h"
6
7 #include <utility>
8 #include <vector>
9
10 #include "base/base64.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/command_line.h"
14 #include "base/compiler_specific.h"
15 #include "base/debug/leak_tracker.h"
16 #include "base/environment.h"
17 #include "base/files/file_path.h"
18 #include "base/logging.h"
19 #include "base/macros.h"
20 #include "base/memory/ptr_util.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram_macros.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/stl_util.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_piece.h"
27 #include "base/strings/string_split.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/utf_string_conversions.h"
30 #include "base/threading/sequenced_worker_pool.h"
31 #include "base/threading/thread.h"
32 #include "base/threading/worker_pool.h"
33 #include "base/time/time.h"
34 #include "base/trace_event/trace_event.h"
35 #include "build/build_config.h"
36 #include "chrome/browser/browser_process.h"
37 #include "chrome/browser/data_usage/tab_id_annotator.h"
38 #include "chrome/browser/net/async_dns_field_trial.h"
39 #include "chrome/browser/net/chrome_network_delegate.h"
40 #include "chrome/browser/net/connect_interceptor.h"
41 #include "chrome/browser/net/dns_probe_service.h"
42 #include "chrome/browser/net/proxy_service_factory.h"
43 #include "chrome/common/channel_info.h"
44 #include "chrome/common/chrome_content_client.h"
45 #include "chrome/common/chrome_switches.h"
46 #include "chrome/common/pref_names.h"
47 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h"
48 #include "components/data_usage/core/data_use_aggregator.h"
49 #include "components/data_usage/core/data_use_amortizer.h"
50 #include "components/data_usage/core/data_use_annotator.h"
51 #include "components/metrics/metrics_service.h"
52 #include "components/net_log/chrome_net_log.h"
53 #include "components/policy/core/common/policy_service.h"
54 #include "components/prefs/pref_registry_simple.h"
55 #include "components/prefs/pref_service.h"
56 #include "components/proxy_config/pref_proxy_config_tracker.h"
57 #include "components/variations/variations_associated_data.h"
58 #include "components/version_info/version_info.h"
59 #include "content/public/browser/browser_thread.h"
60 #include "content/public/browser/cookie_store_factory.h"
61 #include "content/public/common/content_features.h"
62 #include "content/public/common/content_switches.h"
63 #include "content/public/common/user_agent.h"
64 #include "net/base/host_mapping_rules.h"
65 #include "net/base/sdch_manager.h"
66 #include "net/cert/cert_verifier.h"
67 #include "net/cert/cert_verify_proc.h"
68 #include "net/cert/ct_known_logs.h"
69 #include "net/cert/ct_log_verifier.h"
70 #include "net/cert/ct_policy_enforcer.h"
71 #include "net/cert/ct_verifier.h"
72 #include "net/cert/multi_log_ct_verifier.h"
73 #include "net/cert/multi_threaded_cert_verifier.h"
74 #include "net/cookies/cookie_store.h"
75 #include "net/dns/host_cache.h"
76 #include "net/dns/host_resolver.h"
77 #include "net/dns/mapped_host_resolver.h"
78 #include "net/ftp/ftp_network_layer.h"
79 #include "net/http/http_auth_filter.h"
80 #include "net/http/http_auth_handler_factory.h"
81 #include "net/http/http_auth_preferences.h"
82 #include "net/http/http_network_layer.h"
83 #include "net/http/http_server_properties_impl.h"
84 #include "net/nqe/external_estimate_provider.h"
85 #include "net/nqe/network_quality_estimator.h"
86 #include "net/proxy/proxy_config_service.h"
87 #include "net/proxy/proxy_script_fetcher_impl.h"
88 #include "net/proxy/proxy_service.h"
89 #include "net/quic/crypto/crypto_protocol.h"
90 #include "net/quic/quic_protocol.h"
91 #include "net/quic/quic_utils.h"
92 #include "net/socket/ssl_client_socket.h"
93 #include "net/socket/tcp_client_socket.h"
94 #include "net/spdy/spdy_session.h"
95 #include "net/ssl/channel_id_service.h"
96 #include "net/ssl/default_channel_id_store.h"
97 #include "net/url_request/data_protocol_handler.h"
98 #include "net/url_request/file_protocol_handler.h"
99 #include "net/url_request/ftp_protocol_handler.h"
100 #include "net/url_request/static_http_user_agent_settings.h"
101 #include "net/url_request/url_fetcher.h"
102 #include "net/url_request/url_request_backoff_manager.h"
103 #include "net/url_request/url_request_context.h"
104 #include "net/url_request/url_request_context_builder.h"
105 #include "net/url_request/url_request_context_getter.h"
106 #include "net/url_request/url_request_job_factory_impl.h"
107 #include "policy/policy_constants.h"
108 #include "url/url_constants.h"
109
110 #if defined(ENABLE_EXTENSIONS)
111 #include "chrome/browser/extensions/event_router_forwarder.h"
112 #endif
113
114 #if defined(USE_NSS_CERTS)
115 #include "net/cert_net/nss_ocsp.h"
116 #endif
117
118 #if BUILDFLAG(ANDROID_JAVA_UI)
119 #include "base/android/build_info.h"
120 #include "chrome/browser/android/data_usage/external_data_use_observer.h"
121 #include "chrome/browser/android/net/external_estimate_provider_android.h"
122 #include "components/data_usage/android/traffic_stats_amortizer.h"
123 #endif
124
125 #if defined(OS_CHROMEOS)
126 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
127 #include "chromeos/network/host_resolver_impl_chromeos.h"
128 #endif
129
130 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
131 #include <openssl/cpu.h>
132 #include "crypto/openssl_util.h"
133 #endif
134
135 using content::BrowserThread;
136
137 class SafeBrowsingURLRequestContext;
138
139 // The IOThread object must outlive any tasks posted to the IO thread before the
140 // Quit task, so base::Bind() calls are not refcounted.
141
142 namespace {
143
144 const char kTCPFastOpenFieldTrialName[] = "TCPFastOpen";
145 const char kTCPFastOpenHttpsEnabledGroupName[] = "HttpsEnabled";
146
147 const char kQuicFieldTrialName[] = "QUIC";
148 const char kQuicFieldTrialEnabledGroupName[] = "Enabled";
149 const char kQuicFieldTrialHttpsEnabledGroupName[] = "HttpsEnabled";
150
151 // The SPDY trial composes two different trial plus control groups:
152 // * A "holdback" group with SPDY disabled, and corresponding control
153 // (SPDY/3.1). The primary purpose of the holdback group is to encourage site
154 // operators to do feature detection rather than UA-sniffing. As such, this
155 // trial runs continuously.
156 // * A SPDY/4 experiment, for SPDY/4 (aka HTTP/2) vs SPDY/3.1 comparisons and
157 // eventual SPDY/4 deployment.
158 const char kSpdyFieldTrialName[] = "SPDY";
159 const char kSpdyFieldTrialHoldbackGroupNamePrefix[] = "SpdyDisabled";
160 const char kSpdyFieldTrialSpdy31GroupNamePrefix[] = "Spdy31Enabled";
161 const char kSpdyFieldTrialSpdy4GroupNamePrefix[] = "Spdy4Enabled";
162 const char kSpdyFieldTrialParametrizedPrefix[] = "Parametrized";
163
164 // The AltSvc trial controls whether Alt-Svc headers are parsed.
165 // Disabled:
166 // Alt-Svc headers are not parsed.
167 // Alternate-Protocol headers are parsed.
168 // Enabled:
169 // Alt-Svc headers are parsed, but only same-host entries are used by
170 // default. (Use "enable_alternative_service_with_different_host" QUIC
171 // parameter to enable entries with different hosts.)
172 // Alternate-Protocol headers are ignored for responses that have an Alt-Svc
173 // header.
174 const char kAltSvcFieldTrialName[] = "ParseAltSvc";
175 const char kAltSvcFieldTrialDisabledPrefix[] = "AltSvcDisabled";
176 const char kAltSvcFieldTrialEnabledPrefix[] = "AltSvcEnabled";
177
178 // Field trial for network quality estimator. Seeds RTT and downstream
179 // throughput observations with values that correspond to the connection type
180 // determined by the operating system.
181 const char kNetworkQualityEstimatorFieldTrialName[] = "NetworkQualityEstimator";
182
183 // Field trial for NPN.
184 const char kNpnTrialName[] = "NPN";
185 const char kNpnTrialEnabledGroupNamePrefix[] = "Enable";
186 const char kNpnTrialDisabledGroupNamePrefix[] = "Disable";
187
188 // Field trial for priority dependencies.
189 const char kSpdyDependenciesFieldTrial[] = "SpdyEnableDependencies";
190 const char kSpdyDependenciesFieldTrialEnable[] = "Enable";
191 const char kSpdyDepencenciesFieldTrialDisable[] = "Disable";
192
193 #if defined(OS_MACOSX)
194 void ObserveKeychainEvents() {
195 DCHECK_CURRENTLY_ON(BrowserThread::UI);
196 net::CertDatabase::GetInstance()->SetMessageLoopForKeychainEvents();
197 }
198 #endif
199
200 // Gets file path into ssl_keylog_file from command line argument or
201 // environment variable. Command line argument has priority when
202 // both specified.
203 base::FilePath GetSSLKeyLogFile(const base::CommandLine& command_line) {
204 if (command_line.HasSwitch(switches::kSSLKeyLogFile)) {
205 base::FilePath path =
206 command_line.GetSwitchValuePath(switches::kSSLKeyLogFile);
207 if (!path.empty())
208 return path;
209 LOG(WARNING) << "ssl-key-log-file argument missing";
210 }
211
212 std::unique_ptr<base::Environment> env(base::Environment::Create());
213 std::string path_str;
214 env->GetVar("SSLKEYLOGFILE", &path_str);
215 #if defined(OS_WIN)
216 // base::Environment returns environment variables in UTF-8 on Windows.
217 return base::FilePath(base::UTF8ToUTF16(path_str));
218 #else
219 return base::FilePath(path_str);
220 #endif
221 }
222
223 // Used for the "system" URLRequestContext.
224 class SystemURLRequestContext : public net::URLRequestContext {
225 public:
226 SystemURLRequestContext() {
227 #if defined(USE_NSS_CERTS)
228 net::SetURLRequestContextForNSSHttpIO(this);
229 #endif
230 }
231
232 private:
233 ~SystemURLRequestContext() override {
234 AssertNoURLRequests();
235 #if defined(USE_NSS_CERTS)
236 net::SetURLRequestContextForNSSHttpIO(NULL);
237 #endif
238 }
239 };
240
241 std::unique_ptr<net::HostResolver> CreateGlobalHostResolver(
242 net::NetLog* net_log) {
243 TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver");
244 const base::CommandLine& command_line =
245 *base::CommandLine::ForCurrentProcess();
246
247 net::HostResolver::Options options;
248
249 // Use the retry attempts override from the command-line, if any.
250 if (command_line.HasSwitch(switches::kHostResolverRetryAttempts)) {
251 std::string s =
252 command_line.GetSwitchValueASCII(switches::kHostResolverRetryAttempts);
253 // Parse the switch (it should be a non-negative integer).
254 int n;
255 if (base::StringToInt(s, &n) && n >= 0) {
256 options.max_retry_attempts = static_cast<size_t>(n);
257 } else {
258 LOG(ERROR) << "Invalid switch for host resolver retry attempts: " << s;
259 }
260 }
261
262 std::unique_ptr<net::HostResolver> global_host_resolver;
263 #if defined OS_CHROMEOS
264 global_host_resolver =
265 chromeos::HostResolverImplChromeOS::CreateSystemResolver(options,
266 net_log);
267 #else
268 global_host_resolver =
269 net::HostResolver::CreateSystemResolver(options, net_log);
270 #endif
271
272 // If hostname remappings were specified on the command-line, layer these
273 // rules on top of the real host resolver. This allows forwarding all requests
274 // through a designated test server.
275 if (!command_line.HasSwitch(switches::kHostResolverRules))
276 return global_host_resolver;
277
278 std::unique_ptr<net::MappedHostResolver> remapped_resolver(
279 new net::MappedHostResolver(std::move(global_host_resolver)));
280 remapped_resolver->SetRulesFromString(
281 command_line.GetSwitchValueASCII(switches::kHostResolverRules));
282 return std::move(remapped_resolver);
283 }
284
285 int GetSwitchValueAsInt(const base::CommandLine& command_line,
286 const std::string& switch_name) {
287 int value;
288 if (!base::StringToInt(command_line.GetSwitchValueASCII(switch_name),
289 &value)) {
290 return 0;
291 }
292 return value;
293 }
294
295 // Returns the value associated with |key| in |params| or "" if the
296 // key is not present in the map.
297 const std::string& GetVariationParam(
298 const std::map<std::string, std::string>& params,
299 const std::string& key) {
300 std::map<std::string, std::string>::const_iterator it = params.find(key);
301 if (it == params.end())
302 return base::EmptyString();
303
304 return it->second;
305 }
306
307 } // namespace
308
309 class IOThread::LoggingNetworkChangeObserver
310 : public net::NetworkChangeNotifier::IPAddressObserver,
311 public net::NetworkChangeNotifier::ConnectionTypeObserver,
312 public net::NetworkChangeNotifier::NetworkChangeObserver {
313 public:
314 // |net_log| must remain valid throughout our lifetime.
315 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
316 : net_log_(net_log) {
317 net::NetworkChangeNotifier::AddIPAddressObserver(this);
318 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
319 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
320 }
321
322 ~LoggingNetworkChangeObserver() override {
323 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
324 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
325 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
326 }
327
328 // NetworkChangeNotifier::IPAddressObserver implementation.
329 void OnIPAddressChanged() override {
330 VLOG(1) << "Observed a change to the network IP addresses";
331
332 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
333 }
334
335 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
336 void OnConnectionTypeChanged(
337 net::NetworkChangeNotifier::ConnectionType type) override {
338 std::string type_as_string =
339 net::NetworkChangeNotifier::ConnectionTypeToString(type);
340
341 VLOG(1) << "Observed a change to network connectivity state "
342 << type_as_string;
343
344 net_log_->AddGlobalEntry(
345 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
346 net::NetLog::StringCallback("new_connection_type", &type_as_string));
347 }
348
349 // NetworkChangeNotifier::NetworkChangeObserver implementation.
350 void OnNetworkChanged(
351 net::NetworkChangeNotifier::ConnectionType type) override {
352 std::string type_as_string =
353 net::NetworkChangeNotifier::ConnectionTypeToString(type);
354
355 VLOG(1) << "Observed a network change to state " << type_as_string;
356
357 net_log_->AddGlobalEntry(
358 net::NetLog::TYPE_NETWORK_CHANGED,
359 net::NetLog::StringCallback("new_connection_type", &type_as_string));
360 }
361
362 private:
363 net::NetLog* net_log_;
364 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
365 };
366
367 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
368 public:
369 explicit SystemURLRequestContextGetter(IOThread* io_thread);
370
371 // Implementation for net::UrlRequestContextGetter.
372 net::URLRequestContext* GetURLRequestContext() override;
373 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
374 const override;
375
376 protected:
377 ~SystemURLRequestContextGetter() override;
378
379 private:
380 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
381 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
382
383 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
384 };
385
386 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
387 IOThread* io_thread)
388 : io_thread_(io_thread),
389 network_task_runner_(
390 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
391 }
392
393 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
394
395 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
396 DCHECK_CURRENTLY_ON(BrowserThread::IO);
397 DCHECK(io_thread_->globals()->system_request_context.get());
398
399 return io_thread_->globals()->system_request_context.get();
400 }
401
402 scoped_refptr<base::SingleThreadTaskRunner>
403 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
404 return network_task_runner_;
405 }
406
407 IOThread::Globals::
408 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
409 Globals* globals)
410 : globals_(globals) {
411 DCHECK(globals_);
412 }
413
414 IOThread::Globals::
415 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
416 if (globals_->system_request_context.get())
417 globals_->system_request_context->AssertNoURLRequests();
418 }
419
420 IOThread::Globals::Globals() : system_request_context_leak_checker(this),
421 enable_brotli(false) {}
422
423 IOThread::Globals::~Globals() {}
424
425 // |local_state| is passed in explicitly in order to (1) reduce implicit
426 // dependencies and (2) make IOThread more flexible for testing.
427 IOThread::IOThread(
428 PrefService* local_state,
429 policy::PolicyService* policy_service,
430 net_log::ChromeNetLog* net_log,
431 extensions::EventRouterForwarder* extension_event_router_forwarder)
432 : net_log_(net_log),
433 #if defined(ENABLE_EXTENSIONS)
434 extension_event_router_forwarder_(extension_event_router_forwarder),
435 #endif
436 globals_(NULL),
437 is_spdy_allowed_by_policy_(true),
438 is_quic_allowed_by_policy_(true),
439 creation_time_(base::TimeTicks::Now()),
440 weak_factory_(this) {
441 scoped_refptr<base::SingleThreadTaskRunner> io_thread_proxy =
442 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
443 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
444 negotiate_disable_cname_lookup_.Init(
445 prefs::kDisableAuthNegotiateCnameLookup, local_state,
446 base::Bind(&IOThread::UpdateNegotiateDisableCnameLookup,
447 base::Unretained(this)));
448 negotiate_disable_cname_lookup_.MoveToThread(io_thread_proxy);
449 negotiate_enable_port_.Init(
450 prefs::kEnableAuthNegotiatePort, local_state,
451 base::Bind(&IOThread::UpdateNegotiateEnablePort, base::Unretained(this)));
452 negotiate_enable_port_.MoveToThread(io_thread_proxy);
453 auth_server_whitelist_.Init(
454 prefs::kAuthServerWhitelist, local_state,
455 base::Bind(&IOThread::UpdateServerWhitelist, base::Unretained(this)));
456 auth_server_whitelist_.MoveToThread(io_thread_proxy);
457 auth_delegate_whitelist_.Init(
458 prefs::kAuthNegotiateDelegateWhitelist, local_state,
459 base::Bind(&IOThread::UpdateDelegateWhitelist, base::Unretained(this)));
460 auth_delegate_whitelist_.MoveToThread(io_thread_proxy);
461 #if defined(OS_ANDROID)
462 auth_android_negotiate_account_type_.Init(
463 prefs::kAuthAndroidNegotiateAccountType, local_state,
464 base::Bind(&IOThread::UpdateAndroidAuthNegotiateAccountType,
465 base::Unretained(this)));
466 auth_android_negotiate_account_type_.MoveToThread(io_thread_proxy);
467 #endif
468 #if defined(OS_POSIX) && !defined(OS_ANDROID)
469 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
470 #endif
471 pref_proxy_config_tracker_.reset(
472 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
473 local_state));
474 ChromeNetworkDelegate::InitializePrefsOnUIThread(
475 &system_enable_referrers_,
476 NULL,
477 NULL,
478 NULL,
479 local_state);
480 ssl_config_service_manager_.reset(
481 ssl_config::SSLConfigServiceManager::CreateDefaultManager(
482 local_state,
483 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
484
485 base::Value* dns_client_enabled_default = new base::FundamentalValue(
486 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
487 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
488 dns_client_enabled_default);
489 chrome_browser_net::LogAsyncDnsPrefSource(
490 local_state->FindPreference(prefs::kBuiltInDnsClientEnabled));
491
492 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
493 local_state,
494 base::Bind(&IOThread::UpdateDnsClientEnabled,
495 base::Unretained(this)));
496 dns_client_enabled_.MoveToThread(io_thread_proxy);
497
498 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
499 local_state);
500 quick_check_enabled_.MoveToThread(io_thread_proxy);
501
502 is_spdy_allowed_by_policy_ =
503 policy_service
504 ->GetPolicies(policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
505 std::string()))
506 .Get(policy::key::kDisableSpdy) == nullptr;
507
508 const base::Value* value = policy_service->GetPolicies(
509 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME,
510 std::string())).GetValue(policy::key::kQuicAllowed);
511 if (value)
512 value->GetAsBoolean(&is_quic_allowed_by_policy_);
513
514 // Some unit tests use IOThread but do not initialize MetricsService. In that
515 // case it is fine not to have |metrics_data_use_forwarder_|.
516 if (g_browser_process->metrics_service()) {
517 // Callback for updating data use prefs should be obtained on UI thread.
518 metrics_data_use_forwarder_ =
519 g_browser_process->metrics_service()->GetDataUseForwardingCallback();
520 }
521
522 BrowserThread::SetDelegate(BrowserThread::IO, this);
523 }
524
525 IOThread::~IOThread() {
526 // This isn't needed for production code, but in tests, IOThread may
527 // be multiply constructed.
528 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
529
530 pref_proxy_config_tracker_->DetachFromPrefService();
531 DCHECK(!globals_);
532 }
533
534 IOThread::Globals* IOThread::globals() {
535 DCHECK_CURRENTLY_ON(BrowserThread::IO);
536 return globals_;
537 }
538
539 void IOThread::SetGlobalsForTesting(Globals* globals) {
540 DCHECK_CURRENTLY_ON(BrowserThread::IO);
541 DCHECK(!globals || !globals_);
542 globals_ = globals;
543 }
544
545 net_log::ChromeNetLog* IOThread::net_log() {
546 return net_log_;
547 }
548
549 void IOThread::ChangedToOnTheRecord() {
550 DCHECK_CURRENTLY_ON(BrowserThread::UI);
551 BrowserThread::PostTask(
552 BrowserThread::IO,
553 FROM_HERE,
554 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
555 base::Unretained(this)));
556 }
557
558 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
559 DCHECK_CURRENTLY_ON(BrowserThread::UI);
560 if (!system_url_request_context_getter_.get()) {
561 InitSystemRequestContext();
562 }
563 return system_url_request_context_getter_.get();
564 }
565
566 void IOThread::Init() {
567 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
568 // is fixed.
569 tracked_objects::ScopedTracker tracking_profile1(
570 FROM_HERE_WITH_EXPLICIT_FUNCTION("466432 IOThread::InitAsync::Start"));
571 TRACE_EVENT0("startup", "IOThread::InitAsync");
572 DCHECK_CURRENTLY_ON(BrowserThread::IO);
573
574 #if defined(USE_NSS_CERTS)
575 net::SetMessageLoopForNSSHttpIO();
576 #endif
577
578 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
579 // is fixed.
580 tracked_objects::ScopedTracker tracking_profile2(
581 FROM_HERE_WITH_EXPLICIT_FUNCTION(
582 "466432 IOThread::InitAsync::CommandLineForCurrentProcess"));
583 const base::CommandLine& command_line =
584 *base::CommandLine::ForCurrentProcess();
585
586 // Export ssl keys if log file specified.
587 base::FilePath ssl_keylog_file = GetSSLKeyLogFile(command_line);
588 if (!ssl_keylog_file.empty()) {
589 net::SSLClientSocket::SetSSLKeyLogFile(
590 ssl_keylog_file,
591 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
592 }
593
594 DCHECK(!globals_);
595 globals_ = new Globals;
596
597 // Add an observer that will emit network change events to the ChromeNetLog.
598 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
599 // logging the network change before other IO thread consumers respond to it.
600 network_change_observer_.reset(
601 new LoggingNetworkChangeObserver(net_log_));
602
603 // Setup the HistogramWatcher to run on the IO thread.
604 net::NetworkChangeNotifier::InitHistogramWatcher();
605
606 #if defined(ENABLE_EXTENSIONS)
607 globals_->extension_event_router_forwarder =
608 extension_event_router_forwarder_;
609 #endif
610
611 std::unique_ptr<data_usage::DataUseAmortizer> data_use_amortizer;
612 #if BUILDFLAG(ANDROID_JAVA_UI)
613 data_use_amortizer.reset(new data_usage::android::TrafficStatsAmortizer());
614 #endif
615
616 globals_->data_use_aggregator.reset(new data_usage::DataUseAggregator(
617 std::unique_ptr<data_usage::DataUseAnnotator>(
618 new chrome_browser_data_usage::TabIdAnnotator()),
619 std::move(data_use_amortizer)));
620
621 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
622 // is fixed.
623 tracked_objects::ScopedTracker tracking_profile3(
624 FROM_HERE_WITH_EXPLICIT_FUNCTION(
625 "466432 IOThread::InitAsync::ChromeNetworkDelegate"));
626 std::unique_ptr<ChromeNetworkDelegate> chrome_network_delegate(
627 new ChromeNetworkDelegate(extension_event_router_forwarder(),
628 &system_enable_referrers_,
629 metrics_data_use_forwarder_));
630 // By default, data usage is considered off the record.
631 chrome_network_delegate->set_data_use_aggregator(
632 globals_->data_use_aggregator.get(),
633 true /* is_data_usage_off_the_record */);
634
635 #if BUILDFLAG(ANDROID_JAVA_UI)
636 globals_->external_data_use_observer.reset(
637 new chrome::android::ExternalDataUseObserver(
638 globals_->data_use_aggregator.get(),
639 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
640 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI)));
641 #endif
642
643 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
644 // is fixed.
645 tracked_objects::ScopedTracker tracking_profile4(
646 FROM_HERE_WITH_EXPLICIT_FUNCTION(
647 "466432 IOThread::InitAsync::CreateGlobalHostResolver"));
648 globals_->system_network_delegate = std::move(chrome_network_delegate);
649 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
650
651 std::map<std::string, std::string> network_quality_estimator_params;
652 variations::GetVariationParams(kNetworkQualityEstimatorFieldTrialName,
653 &network_quality_estimator_params);
654
655 std::unique_ptr<net::ExternalEstimateProvider> external_estimate_provider;
656 #if BUILDFLAG(ANDROID_JAVA_UI)
657 external_estimate_provider.reset(
658 new chrome::android::ExternalEstimateProviderAndroid());
659 #endif
660 // Pass ownership.
661 globals_->network_quality_estimator.reset(new net::NetworkQualityEstimator(
662 std::move(external_estimate_provider), network_quality_estimator_params));
663
664 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
665 // is fixed.
666 tracked_objects::ScopedTracker tracking_profile5(
667 FROM_HERE_WITH_EXPLICIT_FUNCTION(
668 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::Start"));
669 UpdateDnsClientEnabled();
670 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
671 // is fixed.
672 tracked_objects::ScopedTracker tracking_profile6(
673 FROM_HERE_WITH_EXPLICIT_FUNCTION(
674 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::End"));
675 #if defined(OS_CHROMEOS)
676 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
677 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
678 new chromeos::CertVerifyProcChromeOS()));
679 #else
680 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
681 net::CertVerifyProc::CreateDefault()));
682 #endif
683
684 globals_->transport_security_state.reset(new net::TransportSecurityState());
685
686 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
687 // is fixed.
688 tracked_objects::ScopedTracker tracking_profile8(
689 FROM_HERE_WITH_EXPLICIT_FUNCTION(
690 "466432 IOThread::InitAsync::CreateLogVerifiers::Start"));
691 std::vector<scoped_refptr<const net::CTLogVerifier>> ct_logs(
692 net::ct::CreateLogVerifiersForKnownLogs());
693
694 // Add logs from command line
695 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
696 std::string switch_value = command_line.GetSwitchValueASCII(
697 switches::kCertificateTransparencyLog);
698 for (const base::StringPiece& curr_log : base::SplitStringPiece(
699 switch_value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
700 std::vector<std::string> log_metadata = base::SplitString(
701 curr_log, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
702 CHECK_GE(log_metadata.size(), 3u)
703 << "CT log metadata missing: Switch format is "
704 << "'description:base64_key:url_without_schema'.";
705 std::string log_description(log_metadata[0]);
706 std::string log_url(std::string("https://") + log_metadata[2]);
707 std::string ct_public_key_data;
708 CHECK(base::Base64Decode(log_metadata[1], &ct_public_key_data))
709 << "Unable to decode CT public key.";
710 scoped_refptr<const net::CTLogVerifier> external_log_verifier(
711 net::CTLogVerifier::Create(ct_public_key_data, log_description,
712 log_url));
713 CHECK(external_log_verifier) << "Unable to parse CT public key.";
714 VLOG(1) << "Adding log with description " << log_description;
715 ct_logs.push_back(external_log_verifier);
716 }
717 }
718
719 globals_->ct_logs.assign(ct_logs.begin(), ct_logs.end());
720
721 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
722 // is fixed.
723 tracked_objects::ScopedTracker tracking_profile9(
724 FROM_HERE_WITH_EXPLICIT_FUNCTION(
725 "466432 IOThread::InitAsync::CreateLogVerifiers::End"));
726 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
727 // is fixed.
728 tracked_objects::ScopedTracker tracking_profile7(
729 FROM_HERE_WITH_EXPLICIT_FUNCTION(
730 "466432 IOThread::InitAsync::CreateMultiLogVerifier"));
731 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
732 globals_->cert_transparency_verifier.reset(ct_verifier);
733 // Add built-in logs
734 ct_verifier->AddLogs(globals_->ct_logs);
735
736 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
737 // is fixed.
738 tracked_objects::ScopedTracker tracking_profile10(
739 FROM_HERE_WITH_EXPLICIT_FUNCTION(
740 "466432 IOThread::InitAsync::CTPolicyEnforcer"));
741 globals_->ct_policy_enforcer.reset(new net::CTPolicyEnforcer());
742 params_.ct_policy_enforcer = globals_->ct_policy_enforcer.get();
743
744 globals_->ssl_config_service = GetSSLConfigService();
745
746 CreateDefaultAuthHandlerFactory();
747 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
748 // For the ProxyScriptFetcher, we use a direct ProxyService.
749 globals_->proxy_script_fetcher_proxy_service =
750 net::ProxyService::CreateDirectWithNetLog(net_log_);
751 // In-memory cookie store.
752 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
753 // is fixed.
754 tracked_objects::ScopedTracker tracking_profile11(
755 FROM_HERE_WITH_EXPLICIT_FUNCTION(
756 "466432 IOThread::InitAsync::CreateCookieStore::Start"));
757 globals_->system_cookie_store =
758 content::CreateCookieStore(content::CookieStoreConfig());
759 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
760 // is fixed.
761 tracked_objects::ScopedTracker tracking_profile12(
762 FROM_HERE_WITH_EXPLICIT_FUNCTION(
763 "466432 IOThread::InitAsync::CreateCookieStore::End"));
764 // In-memory channel ID store.
765 globals_->system_channel_id_service.reset(
766 new net::ChannelIDService(
767 new net::DefaultChannelIDStore(NULL),
768 base::WorkerPool::GetTaskRunner(true)));
769 globals_->system_cookie_store->SetChannelIDServiceID(
770 globals_->system_channel_id_service->GetUniqueID());
771 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
772 // is fixed.
773 tracked_objects::ScopedTracker tracking_profile12_1(
774 FROM_HERE_WITH_EXPLICIT_FUNCTION(
775 "466432 IOThread::InitAsync::CreateDnsProbeService"));
776 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
777 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
778 // is fixed.
779 tracked_objects::ScopedTracker tracking_profile12_2(
780 FROM_HERE_WITH_EXPLICIT_FUNCTION(
781 "466432 IOThread::InitAsync::CreateHostMappingRules"));
782 globals_->host_mapping_rules.reset(new net::HostMappingRules());
783 params_.host_mapping_rules = globals_->host_mapping_rules.get();
784 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
785 // is fixed.
786 tracked_objects::ScopedTracker tracking_profile12_3(
787 FROM_HERE_WITH_EXPLICIT_FUNCTION(
788 "466432 IOThread::InitAsync::CreateHTTPUserAgentSettings"));
789 globals_->http_user_agent_settings.reset(
790 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
791 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
792 // is fixed.
793 tracked_objects::ScopedTracker tracking_profile12_4(
794 FROM_HERE_WITH_EXPLICIT_FUNCTION(
795 "466432 IOThread::InitAsync::CommandLineConfiguration"));
796 if (command_line.HasSwitch(switches::kHostRules)) {
797 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
798 globals_->host_mapping_rules->SetRulesFromString(
799 command_line.GetSwitchValueASCII(switches::kHostRules));
800 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
801 }
802 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
803 // is fixed.
804 tracked_objects::ScopedTracker tracking_profile12_5(
805 FROM_HERE_WITH_EXPLICIT_FUNCTION(
806 "466432 IOThread::InitAsync::QuicConfiguration"));
807 if (command_line.HasSwitch(
808 switches::kEnableUserAlternateProtocolPorts)) {
809 params_.enable_user_alternate_protocol_ports = true;
810 }
811 globals_->enable_brotli =
812 base::FeatureList::IsEnabled(features::kBrotliEncoding);
813 params_.enable_token_binding =
814 base::FeatureList::IsEnabled(features::kTokenBinding);
815 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
816 // is fixed.
817 tracked_objects::ScopedTracker tracking_profile13(
818 FROM_HERE_WITH_EXPLICIT_FUNCTION(
819 "466432 IOThread::InitAsync::InitializeNetworkOptions"));
820 // TODO(rch): Make the client socket factory a per-network session instance,
821 // constructed from a NetworkSession::Params, to allow us to move this option
822 // to IOThread::Globals & HttpNetworkSession::Params.
823 network_session_configurator_.ParseFieldTrialsAndCommandLine(
824 is_spdy_allowed_by_policy_, is_quic_allowed_by_policy_, &params_);
825 bool always_enable_tfo_if_supported =
826 command_line.HasSwitch(switches::kEnableTcpFastOpen);
827 // Check for OS support of TCP FastOpen, and turn it on for all connections if
828 // indicated by user.
829 net::CheckSupportAndMaybeEnableTCPFastOpen(always_enable_tfo_if_supported);
830
831 TRACE_EVENT_BEGIN0("startup",
832 "IOThread::Init:ProxyScriptFetcherRequestContext");
833 globals_->proxy_script_fetcher_context.reset(
834 ConstructProxyScriptFetcherContext(globals_, params_, net_log_));
835 TRACE_EVENT_END0("startup",
836 "IOThread::Init:ProxyScriptFetcherRequestContext");
837
838 const version_info::Channel channel = chrome::GetChannel();
839 if (channel == version_info::Channel::UNKNOWN ||
840 channel == version_info::Channel::CANARY ||
841 channel == version_info::Channel::DEV) {
842 globals_->url_request_backoff_manager.reset(
843 new net::URLRequestBackoffManager());
844 }
845
846 #if defined(OS_MACOSX)
847 // Start observing Keychain events. This needs to be done on the UI thread,
848 // as Keychain services requires a CFRunLoop.
849 BrowserThread::PostTask(BrowserThread::UI,
850 FROM_HERE,
851 base::Bind(&ObserveKeychainEvents));
852 #endif
853
854 // InitSystemRequestContext turns right around and posts a task back
855 // to the IO thread, so we can't let it run until we know the IO
856 // thread has started.
857 //
858 // Note that since we are at BrowserThread::Init time, the UI thread
859 // is blocked waiting for the thread to start. Therefore, posting
860 // this task to the main thread's message loop here is guaranteed to
861 // get it onto the message loop while the IOThread object still
862 // exists. However, the message might not be processed on the UI
863 // thread until after IOThread is gone, so use a weak pointer.
864 BrowserThread::PostTask(BrowserThread::UI,
865 FROM_HERE,
866 base::Bind(&IOThread::InitSystemRequestContext,
867 weak_factory_.GetWeakPtr()));
868
869 #if defined(OS_ANDROID) && defined(ARCH_CPU_ARMEL)
870 // Record how common CPUs with broken NEON units are. See
871 // https://crbug.com/341598.
872 crypto::EnsureOpenSSLInit();
873 UMA_HISTOGRAM_BOOLEAN("Net.HasBrokenNEON", CRYPTO_has_broken_NEON());
874 #endif
875 }
876
877 void IOThread::CleanUp() {
878 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
879
880 #if defined(USE_NSS_CERTS)
881 net::ShutdownNSSHttpIO();
882 #endif
883
884 system_url_request_context_getter_ = NULL;
885
886 // Release objects that the net::URLRequestContext could have been pointing
887 // to.
888
889 // Shutdown the HistogramWatcher on the IO thread.
890 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
891
892 // This must be reset before the ChromeNetLog is destroyed.
893 network_change_observer_.reset();
894
895 system_proxy_config_service_.reset();
896 delete globals_;
897 globals_ = NULL;
898
899 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
900 }
901
902 // static
903 void IOThread::NetworkSessionConfigurator::ParseFieldTrials(
904 bool is_spdy_allowed_by_policy,
905 bool is_quic_allowed_by_policy,
906 net::HttpNetworkSession::Params* params) {
907 const base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
908 ParseFieldTrialsAndCommandLineInternal(command_line,
909 is_spdy_allowed_by_policy,
910 is_quic_allowed_by_policy, params);
911 }
912
913 // static
914 void IOThread::NetworkSessionConfigurator::ParseFieldTrialsAndCommandLine(
915 bool is_spdy_allowed_by_policy,
916 bool is_quic_allowed_by_policy,
917 net::HttpNetworkSession::Params* params) {
918 const base::CommandLine& command_line =
919 *base::CommandLine::ForCurrentProcess();
920 ParseFieldTrialsAndCommandLineInternal(command_line,
921 is_spdy_allowed_by_policy,
922 is_quic_allowed_by_policy, params);
923 }
924
925 // static
926 void IOThread::NetworkSessionConfigurator::
927 ParseFieldTrialsAndCommandLineInternal(
928 const base::CommandLine& command_line,
929 bool is_spdy_allowed_by_policy,
930 bool is_quic_allowed_by_policy,
931 net::HttpNetworkSession::Params* params) {
932 // Parameters only controlled by command line.
933 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
934 params->ignore_certificate_errors = true;
935 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
936 params->testing_fixed_http_port =
937 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
938 }
939 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
940 params->testing_fixed_https_port =
941 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
942 }
943
944 // Always fetch the field trial groups to ensure they are reported correctly.
945 // The command line flags will be associated with a group that is reported so
946 // long as trial is actually queried.
947
948 std::string altsvc_trial_group =
949 base::FieldTrialList::FindFullName(kAltSvcFieldTrialName);
950 ConfigureAltSvcParams(command_line, altsvc_trial_group, params);
951
952 std::string quic_trial_group =
953 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
954 VariationParameters quic_trial_params;
955 if (!variations::GetVariationParams(kQuicFieldTrialName, &quic_trial_params))
956 quic_trial_params.clear();
957 ConfigureQuicParams(command_line, quic_trial_group, quic_trial_params,
958 is_quic_allowed_by_policy, params);
959
960 if (!is_spdy_allowed_by_policy) {
961 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
962 if (trial)
963 trial->Disable();
964 }
965 std::string spdy_trial_group =
966 base::FieldTrialList::FindFullName(kSpdyFieldTrialName);
967 VariationParameters spdy_trial_params;
968 if (!variations::GetVariationParams(kSpdyFieldTrialName, &spdy_trial_params))
969 spdy_trial_params.clear();
970 ConfigureSpdyParams(command_line, spdy_trial_group, spdy_trial_params,
971 is_spdy_allowed_by_policy, params);
972
973 const std::string tfo_trial_group =
974 base::FieldTrialList::FindFullName(kTCPFastOpenFieldTrialName);
975 ConfigureTCPFastOpenParams(tfo_trial_group, params);
976
977 std::string npn_trial_group =
978 base::FieldTrialList::FindFullName(kNpnTrialName);
979 ConfigureNPNParams(command_line, npn_trial_group, params);
980
981 std::string priority_dependencies_trial_group =
982 base::FieldTrialList::FindFullName(kSpdyDependenciesFieldTrial);
983 ConfigurePriorityDependencies(priority_dependencies_trial_group, params);
984 }
985
986 // static
987 void IOThread::NetworkSessionConfigurator::ConfigureTCPFastOpenParams(
988 base::StringPiece tfo_trial_group,
989 net::HttpNetworkSession::Params* params) {
990 if (tfo_trial_group == kTCPFastOpenHttpsEnabledGroupName)
991 params->enable_tcp_fast_open_for_ssl = true;
992 }
993
994 // static
995 void IOThread::NetworkSessionConfigurator::ConfigureSpdyParams(
996 const base::CommandLine& command_line,
997 base::StringPiece spdy_trial_group,
998 const VariationParameters& spdy_trial_params,
999 bool is_spdy_allowed_by_policy,
1000 net::HttpNetworkSession::Params* params) {
1001 // Only handle SPDY field trial parameters and command line flags if
1002 // "spdy.disabled" preference is not forced via policy.
1003 if (!is_spdy_allowed_by_policy) {
1004 params->enable_spdy31 = false;
1005 params->enable_http2 = false;
1006 return;
1007 }
1008
1009 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
1010 net::URLFetcher::SetIgnoreCertificateRequests(true);
1011
1012 if (command_line.HasSwitch(switches::kDisableHttp2)) {
1013 params->enable_spdy31 = false;
1014 params->enable_http2 = false;
1015 return;
1016 }
1017
1018 if (spdy_trial_group.starts_with(kSpdyFieldTrialHoldbackGroupNamePrefix)) {
1019 net::HttpStreamFactory::set_spdy_enabled(false);
1020 return;
1021 }
1022 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy31GroupNamePrefix)) {
1023 params->enable_spdy31 = true;
1024 params->enable_http2 = false;
1025 return;
1026 }
1027 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy4GroupNamePrefix)) {
1028 params->enable_spdy31 = true;
1029 params->enable_http2 = true;
1030 return;
1031 }
1032 if (spdy_trial_group.starts_with(kSpdyFieldTrialParametrizedPrefix)) {
1033 bool spdy_enabled = false;
1034 params->enable_spdy31 = false;
1035 params->enable_http2 = false;
1036 if (base::LowerCaseEqualsASCII(
1037 GetVariationParam(spdy_trial_params, "enable_http2"), "true")) {
1038 spdy_enabled = true;
1039 params->enable_http2 = true;
1040 }
1041 if (base::LowerCaseEqualsASCII(
1042 GetVariationParam(spdy_trial_params, "enable_spdy31"), "true")) {
1043 spdy_enabled = true;
1044 params->enable_spdy31 = true;
1045 }
1046 // TODO(bnc): https://crbug.com/521597
1047 // HttpStreamFactory::spdy_enabled_ is redundant with params->enable_http2
1048 // and enable_spdy31, can it be eliminated?
1049 net::HttpStreamFactory::set_spdy_enabled(spdy_enabled);
1050 return;
1051 }
1052 }
1053
1054 // static
1055 void IOThread::NetworkSessionConfigurator::ConfigureAltSvcParams(
1056 const base::CommandLine& command_line,
1057 base::StringPiece altsvc_trial_group,
1058 net::HttpNetworkSession::Params* params) {
1059 if (command_line.HasSwitch(switches::kEnableAlternativeServices) ||
1060 altsvc_trial_group.starts_with(kAltSvcFieldTrialEnabledPrefix)) {
1061 params->parse_alternative_services = true;
1062 return;
1063 }
1064 if (altsvc_trial_group.starts_with(kAltSvcFieldTrialDisabledPrefix)) {
1065 params->parse_alternative_services = false;
1066 }
1067 }
1068
1069 // static
1070 void IOThread::NetworkSessionConfigurator::ConfigureNPNParams(
1071 const base::CommandLine& command_line,
1072 base::StringPiece npn_trial_group,
1073 net::HttpNetworkSession::Params* params) {
1074 if (npn_trial_group.starts_with(kNpnTrialEnabledGroupNamePrefix)) {
1075 params->enable_npn = true;
1076 } else if (npn_trial_group.starts_with(kNpnTrialDisabledGroupNamePrefix)) {
1077 params->enable_npn = false;
1078 }
1079 }
1080
1081 // static
1082 void IOThread::NetworkSessionConfigurator::ConfigurePriorityDependencies(
1083 base::StringPiece priority_dependencies_trial_group,
1084 net::HttpNetworkSession::Params* params) {
1085 if (priority_dependencies_trial_group.starts_with(
1086 kSpdyDependenciesFieldTrialEnable)) {
1087 params->enable_priority_dependencies = true;
1088 } else if (priority_dependencies_trial_group.starts_with(
1089 kSpdyDepencenciesFieldTrialDisable)) {
1090 params->enable_priority_dependencies = false;
1091 }
1092 }
1093
1094 // static
1095 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
1096 registry->RegisterStringPref(prefs::kAuthSchemes,
1097 "basic,digest,ntlm,negotiate");
1098 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
1099 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
1100 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
1101 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
1102 std::string());
1103 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
1104 registry->RegisterStringPref(prefs::kAuthAndroidNegotiateAccountType,
1105 std::string());
1106 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
1107 data_reduction_proxy::RegisterPrefs(registry);
1108 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
1109 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
1110 }
1111
1112 void IOThread::UpdateServerWhitelist() {
1113 globals_->http_auth_preferences->set_server_whitelist(
1114 auth_server_whitelist_.GetValue());
1115 }
1116
1117 void IOThread::UpdateDelegateWhitelist() {
1118 globals_->http_auth_preferences->set_delegate_whitelist(
1119 auth_delegate_whitelist_.GetValue());
1120 }
1121
1122 #if defined(OS_ANDROID)
1123 void IOThread::UpdateAndroidAuthNegotiateAccountType() {
1124 globals_->http_auth_preferences->set_auth_android_negotiate_account_type(
1125 auth_android_negotiate_account_type_.GetValue());
1126 }
1127 #endif
1128
1129 void IOThread::UpdateNegotiateDisableCnameLookup() {
1130 globals_->http_auth_preferences->set_negotiate_disable_cname_lookup(
1131 negotiate_disable_cname_lookup_.GetValue());
1132 }
1133
1134 void IOThread::UpdateNegotiateEnablePort() {
1135 globals_->http_auth_preferences->set_negotiate_enable_port(
1136 negotiate_enable_port_.GetValue());
1137 }
1138
1139 void IOThread::CreateDefaultAuthHandlerFactory() {
1140 std::vector<std::string> supported_schemes = base::SplitString(
1141 auth_schemes_, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
1142 globals_->http_auth_preferences.reset(new net::HttpAuthPreferences(
1143 supported_schemes
1144 #if defined(OS_POSIX) && !defined(OS_ANDROID)
1145 ,
1146 gssapi_library_name_
1147 #endif
1148 ));
1149 UpdateServerWhitelist();
1150 UpdateDelegateWhitelist();
1151 UpdateNegotiateDisableCnameLookup();
1152 UpdateNegotiateEnablePort();
1153 #if defined(OS_ANDROID)
1154 UpdateAndroidAuthNegotiateAccountType();
1155 #endif
1156 globals_->http_auth_handler_factory =
1157 net::HttpAuthHandlerRegistryFactory::Create(
1158 globals_->http_auth_preferences.get(), globals_->host_resolver.get());
1159 }
1160
1161 void IOThread::ClearHostCache() {
1162 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1163
1164 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
1165 if (host_cache)
1166 host_cache->clear();
1167 }
1168
1169 const net::HttpNetworkSession::Params& IOThread::NetworkSessionParams() const {
1170 return params_;
1171 }
1172
1173 base::TimeTicks IOThread::creation_time() const {
1174 return creation_time_;
1175 }
1176
1177 // static
1178 net::SSLConfigService* IOThread::GetSSLConfigService() {
1179 return ssl_config_service_manager_->Get();
1180 }
1181
1182 void IOThread::ChangedToOnTheRecordOnIOThread() {
1183 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1184
1185 // Clear the host cache to avoid showing entries from the OTR session
1186 // in about:net-internals.
1187 ClearHostCache();
1188 }
1189
1190 void IOThread::InitSystemRequestContext() {
1191 if (system_url_request_context_getter_.get())
1192 return;
1193 // If we're in unit_tests, IOThread may not be run.
1194 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1195 return;
1196 system_proxy_config_service_ = ProxyServiceFactory::CreateProxyConfigService(
1197 pref_proxy_config_tracker_.get());
1198 system_url_request_context_getter_ =
1199 new SystemURLRequestContextGetter(this);
1200 // Safe to post an unretained this pointer, since IOThread is
1201 // guaranteed to outlive the IO BrowserThread.
1202 BrowserThread::PostTask(
1203 BrowserThread::IO,
1204 FROM_HERE,
1205 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1206 base::Unretained(this)));
1207 }
1208
1209 void IOThread::InitSystemRequestContextOnIOThread() {
1210 DCHECK_CURRENTLY_ON(BrowserThread::IO);
1211 DCHECK(!globals_->system_proxy_service.get());
1212 DCHECK(system_proxy_config_service_.get());
1213
1214 const base::CommandLine& command_line =
1215 *base::CommandLine::ForCurrentProcess();
1216 globals_->system_proxy_service = ProxyServiceFactory::CreateProxyService(
1217 net_log_, globals_->proxy_script_fetcher_context.get(),
1218 globals_->system_network_delegate.get(),
1219 std::move(system_proxy_config_service_), command_line,
1220 quick_check_enabled_.GetValue());
1221
1222 globals_->system_request_context.reset(
1223 ConstructSystemRequestContext(globals_, params_, net_log_));
1224 }
1225
1226 void IOThread::UpdateDnsClientEnabled() {
1227 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1228 }
1229
1230 // static
1231 void IOThread::NetworkSessionConfigurator::ConfigureQuicParams(
1232 const base::CommandLine& command_line,
1233 base::StringPiece quic_trial_group,
1234 const VariationParameters& quic_trial_params,
1235 bool is_quic_allowed_by_policy,
1236 net::HttpNetworkSession::Params* params) {
1237 params->enable_quic = ShouldEnableQuic(command_line, quic_trial_group,
1238 is_quic_allowed_by_policy);
1239 params->disable_quic_on_timeout_with_open_streams =
1240 ShouldDisableQuicWhenConnectionTimesOutWithOpenStreams(quic_trial_params);
1241
1242 if (ShouldQuicEnableAlternativeServicesForDifferentHost(command_line,
1243 quic_trial_params)) {
1244 params->enable_alternative_service_with_different_host = true;
1245 params->parse_alternative_services = true;
1246 } else {
1247 params->enable_alternative_service_with_different_host = false;
1248 }
1249
1250 if (params->enable_quic) {
1251 params->quic_always_require_handshake_confirmation =
1252 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params);
1253 params->quic_disable_connection_pooling =
1254 ShouldQuicDisableConnectionPooling(quic_trial_params);
1255 int receive_buffer_size = GetQuicSocketReceiveBufferSize(quic_trial_params);
1256 if (receive_buffer_size != 0) {
1257 params->quic_socket_receive_buffer_size = receive_buffer_size;
1258 }
1259 float load_server_info_timeout_srtt_multiplier =
1260 GetQuicLoadServerInfoTimeoutSrttMultiplier(quic_trial_params);
1261 if (load_server_info_timeout_srtt_multiplier != 0) {
1262 params->quic_load_server_info_timeout_srtt_multiplier =
1263 load_server_info_timeout_srtt_multiplier;
1264 }
1265 params->quic_enable_connection_racing =
1266 ShouldQuicEnableConnectionRacing(quic_trial_params);
1267 params->quic_enable_non_blocking_io =
1268 ShouldQuicEnableNonBlockingIO(quic_trial_params);
1269 params->quic_disable_disk_cache =
1270 ShouldQuicDisableDiskCache(quic_trial_params);
1271 params->quic_prefer_aes = ShouldQuicPreferAes(quic_trial_params);
1272 int max_number_of_lossy_connections = GetQuicMaxNumberOfLossyConnections(
1273 quic_trial_params);
1274 if (max_number_of_lossy_connections != 0) {
1275 params->quic_max_number_of_lossy_connections =
1276 max_number_of_lossy_connections;
1277 }
1278 float packet_loss_threshold = GetQuicPacketLossThreshold(quic_trial_params);
1279 if (packet_loss_threshold != 0)
1280 params->quic_packet_loss_threshold = packet_loss_threshold;
1281 params->enable_quic_port_selection =
1282 ShouldEnableQuicPortSelection(command_line);
1283 params->quic_connection_options =
1284 GetQuicConnectionOptions(command_line, quic_trial_params);
1285 params->quic_close_sessions_on_ip_change =
1286 ShouldQuicCloseSessionsOnIpChange(quic_trial_params);
1287 int idle_connection_timeout_seconds = GetQuicIdleConnectionTimeoutSeconds(
1288 quic_trial_params);
1289 if (idle_connection_timeout_seconds != 0) {
1290 params->quic_idle_connection_timeout_seconds =
1291 idle_connection_timeout_seconds;
1292 }
1293 params->quic_disable_preconnect_if_0rtt =
1294 ShouldQuicDisablePreConnectIfZeroRtt(quic_trial_params);
1295 params->quic_host_whitelist =
1296 GetQuicHostWhitelist(command_line, quic_trial_params);
1297 params->quic_migrate_sessions_on_network_change =
1298 ShouldQuicMigrateSessionsOnNetworkChange(quic_trial_params);
1299 params->quic_migrate_sessions_early =
1300 ShouldQuicMigrateSessionsEarly(quic_trial_params);
1301 }
1302
1303 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1304 quic_trial_params);
1305 if (max_packet_length != 0) {
1306 params->quic_max_packet_length = max_packet_length;
1307 }
1308
1309 params->quic_user_agent_id = chrome::GetChannelString();
1310 if (!params->quic_user_agent_id.empty())
1311 params->quic_user_agent_id.push_back(' ');
1312 params->quic_user_agent_id.append(
1313 version_info::GetProductNameAndVersionForUserAgent());
1314 params->quic_user_agent_id.push_back(' ');
1315 params->quic_user_agent_id.append(content::BuildOSCpuInfo());
1316
1317 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1318 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1319 net::QuicVersionVector supported_versions;
1320 supported_versions.push_back(version);
1321 params->quic_supported_versions = supported_versions;
1322 }
1323
1324 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1325 std::string origins =
1326 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn);
1327 for (const std::string& host_port : base::SplitString(
1328 origins, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
1329 net::HostPortPair quic_origin = net::HostPortPair::FromString(host_port);
1330 if (!quic_origin.IsEmpty())
1331 params->origins_to_force_quic_on.insert(quic_origin);
1332 }
1333 }
1334 }
1335
1336 // static
1337 bool IOThread::NetworkSessionConfigurator::
1338 ShouldDisableQuicWhenConnectionTimesOutWithOpenStreams(
1339 const VariationParameters& quic_trial_params) {
1340 return base::LowerCaseEqualsASCII(
1341 GetVariationParam(quic_trial_params,
1342 "disable_quic_on_timeout_with_open_streams"),
1343 "true");
1344 }
1345
1346 // static
1347 bool IOThread::NetworkSessionConfigurator::ShouldEnableQuic(
1348 const base::CommandLine& command_line,
1349 base::StringPiece quic_trial_group,
1350 bool is_quic_allowed_by_policy) {
1351 if (command_line.HasSwitch(switches::kDisableQuic) ||
1352 !is_quic_allowed_by_policy)
1353 return false;
1354
1355 if (command_line.HasSwitch(switches::kEnableQuic))
1356 return true;
1357
1358 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1359 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1360 }
1361
1362 // static
1363 bool IOThread::NetworkSessionConfigurator::ShouldEnableQuicPortSelection(
1364 const base::CommandLine& command_line) {
1365 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1366 return false;
1367
1368 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1369 return true;
1370
1371 return false; // Default to disabling port selection on all channels.
1372 }
1373
1374 // static
1375 net::QuicTagVector
1376 IOThread::NetworkSessionConfigurator::GetQuicConnectionOptions(
1377 const base::CommandLine& command_line,
1378 const VariationParameters& quic_trial_params) {
1379 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1380 return net::QuicUtils::ParseQuicConnectionOptions(
1381 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1382 }
1383
1384 VariationParameters::const_iterator it =
1385 quic_trial_params.find("connection_options");
1386 if (it == quic_trial_params.end()) {
1387 return net::QuicTagVector();
1388 }
1389
1390 return net::QuicUtils::ParseQuicConnectionOptions(it->second);
1391 }
1392
1393 // static
1394 bool IOThread::NetworkSessionConfigurator::
1395 ShouldQuicAlwaysRequireHandshakeConfirmation(
1396 const VariationParameters& quic_trial_params) {
1397 return base::LowerCaseEqualsASCII(
1398 GetVariationParam(quic_trial_params,
1399 "always_require_handshake_confirmation"),
1400 "true");
1401 }
1402
1403 // static
1404 bool IOThread::NetworkSessionConfigurator::ShouldQuicDisableConnectionPooling(
1405 const VariationParameters& quic_trial_params) {
1406 return base::LowerCaseEqualsASCII(
1407 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1408 "true");
1409 }
1410
1411 // static
1412 float IOThread::NetworkSessionConfigurator::
1413 GetQuicLoadServerInfoTimeoutSrttMultiplier(
1414 const VariationParameters& quic_trial_params) {
1415 double value;
1416 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1417 "load_server_info_time_to_srtt"),
1418 &value)) {
1419 return static_cast<float>(value);
1420 }
1421 return 0.0f;
1422 }
1423
1424 // static
1425 bool IOThread::NetworkSessionConfigurator::ShouldQuicEnableConnectionRacing(
1426 const VariationParameters& quic_trial_params) {
1427 return base::LowerCaseEqualsASCII(
1428 GetVariationParam(quic_trial_params, "enable_connection_racing"),
1429 "true");
1430 }
1431
1432 // static
1433 bool IOThread::NetworkSessionConfigurator::ShouldQuicEnableNonBlockingIO(
1434 const VariationParameters& quic_trial_params) {
1435 return base::LowerCaseEqualsASCII(
1436 GetVariationParam(quic_trial_params, "enable_non_blocking_io"),
1437 "true");
1438 }
1439
1440 // static
1441 bool IOThread::NetworkSessionConfigurator::ShouldQuicDisableDiskCache(
1442 const VariationParameters& quic_trial_params) {
1443 return base::LowerCaseEqualsASCII(
1444 GetVariationParam(quic_trial_params, "disable_disk_cache"), "true");
1445 }
1446
1447 // static
1448 bool IOThread::NetworkSessionConfigurator::ShouldQuicPreferAes(
1449 const VariationParameters& quic_trial_params) {
1450 return base::LowerCaseEqualsASCII(
1451 GetVariationParam(quic_trial_params, "prefer_aes"), "true");
1452 }
1453
1454 // static
1455 bool IOThread::NetworkSessionConfigurator::
1456 ShouldQuicEnableAlternativeServicesForDifferentHost(
1457 const base::CommandLine& command_line,
1458 const VariationParameters& quic_trial_params) {
1459 // TODO(bnc): Remove inaccurately named "use_alternative_services" parameter.
1460 return command_line.HasSwitch(switches::kEnableAlternativeServices) ||
1461 base::LowerCaseEqualsASCII(
1462 GetVariationParam(quic_trial_params, "use_alternative_services"),
1463 "true") ||
1464 base::LowerCaseEqualsASCII(
1465 GetVariationParam(
1466 quic_trial_params,
1467 "enable_alternative_service_with_different_host"),
1468 "true");
1469 }
1470
1471 // static
1472 int IOThread::NetworkSessionConfigurator::GetQuicMaxNumberOfLossyConnections(
1473 const VariationParameters& quic_trial_params) {
1474 int value;
1475 if (base::StringToInt(GetVariationParam(quic_trial_params,
1476 "max_number_of_lossy_connections"),
1477 &value)) {
1478 return value;
1479 }
1480 return 0;
1481 }
1482
1483 // static
1484 float IOThread::NetworkSessionConfigurator::GetQuicPacketLossThreshold(
1485 const VariationParameters& quic_trial_params) {
1486 double value;
1487 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1488 "packet_loss_threshold"),
1489 &value)) {
1490 return static_cast<float>(value);
1491 }
1492 return 0.0f;
1493 }
1494
1495 // static
1496 int IOThread::NetworkSessionConfigurator::GetQuicSocketReceiveBufferSize(
1497 const VariationParameters& quic_trial_params) {
1498 int value;
1499 if (base::StringToInt(GetVariationParam(quic_trial_params,
1500 "receive_buffer_size"),
1501 &value)) {
1502 return value;
1503 }
1504 return 0;
1505 }
1506
1507 // static
1508 bool IOThread::NetworkSessionConfigurator::ShouldQuicCloseSessionsOnIpChange(
1509 const VariationParameters& quic_trial_params) {
1510 return base::LowerCaseEqualsASCII(
1511 GetVariationParam(quic_trial_params, "close_sessions_on_ip_change"),
1512 "true");
1513 }
1514
1515 // static
1516 int IOThread::NetworkSessionConfigurator::GetQuicIdleConnectionTimeoutSeconds(
1517 const VariationParameters& quic_trial_params) {
1518 int value;
1519 if (base::StringToInt(GetVariationParam(quic_trial_params,
1520 "idle_connection_timeout_seconds"),
1521 &value)) {
1522 return value;
1523 }
1524 return 0;
1525 }
1526
1527 // static
1528 bool IOThread::NetworkSessionConfigurator::ShouldQuicDisablePreConnectIfZeroRtt(
1529 const VariationParameters& quic_trial_params) {
1530 return base::LowerCaseEqualsASCII(
1531 GetVariationParam(quic_trial_params, "disable_preconnect_if_0rtt"),
1532 "true");
1533 }
1534
1535 // static
1536 std::unordered_set<std::string>
1537 IOThread::NetworkSessionConfigurator::GetQuicHostWhitelist(
1538 const base::CommandLine& command_line,
1539 const VariationParameters& quic_trial_params) {
1540 std::string whitelist;
1541 if (command_line.HasSwitch(switches::kQuicHostWhitelist)) {
1542 whitelist = command_line.GetSwitchValueASCII(switches::kQuicHostWhitelist);
1543 } else {
1544 whitelist = GetVariationParam(quic_trial_params, "quic_host_whitelist");
1545 }
1546 std::unordered_set<std::string> hosts;
1547 for (const std::string& host :base::SplitString(whitelist, ",",
1548 base::TRIM_WHITESPACE,
1549 base::SPLIT_WANT_ALL)) {
1550 hosts.insert(host);
1551 }
1552 return hosts;
1553 }
1554
1555 // static
1556 bool IOThread::NetworkSessionConfigurator::
1557 ShouldQuicMigrateSessionsOnNetworkChange(
1558 const VariationParameters& quic_trial_params) {
1559 return base::LowerCaseEqualsASCII(
1560 GetVariationParam(quic_trial_params,
1561 "migrate_sessions_on_network_change"),
1562 "true");
1563 }
1564
1565 // static
1566 bool IOThread::NetworkSessionConfigurator::ShouldQuicMigrateSessionsEarly(
1567 const VariationParameters& quic_trial_params) {
1568 return base::LowerCaseEqualsASCII(
1569 GetVariationParam(quic_trial_params, "migrate_sessions_early"), "true");
1570 }
1571
1572 // static
1573 size_t IOThread::NetworkSessionConfigurator::GetQuicMaxPacketLength(
1574 const base::CommandLine& command_line,
1575 const VariationParameters& quic_trial_params) {
1576 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1577 unsigned value;
1578 if (!base::StringToUint(
1579 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1580 &value)) {
1581 return 0;
1582 }
1583 return value;
1584 }
1585
1586 unsigned value;
1587 if (base::StringToUint(GetVariationParam(quic_trial_params,
1588 "max_packet_length"),
1589 &value)) {
1590 return value;
1591 }
1592 return 0;
1593 }
1594
1595 // static
1596 net::QuicVersion IOThread::NetworkSessionConfigurator::GetQuicVersion(
1597 const base::CommandLine& command_line,
1598 const VariationParameters& quic_trial_params) {
1599 if (command_line.HasSwitch(switches::kQuicVersion)) {
1600 return ParseQuicVersion(
1601 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1602 }
1603
1604 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1605 }
1606
1607 // static
1608 net::QuicVersion IOThread::NetworkSessionConfigurator::ParseQuicVersion(
1609 const std::string& quic_version) {
1610 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1611 for (size_t i = 0; i < supported_versions.size(); ++i) {
1612 net::QuicVersion version = supported_versions[i];
1613 if (net::QuicVersionToString(version) == quic_version) {
1614 return version;
1615 }
1616 }
1617
1618 return net::QUIC_VERSION_UNSUPPORTED;
1619 }
1620
1621 // static
1622 net::URLRequestContext* IOThread::ConstructSystemRequestContext(
1623 IOThread::Globals* globals,
1624 const net::HttpNetworkSession::Params& params,
1625 net::NetLog* net_log) {
1626 net::URLRequestContext* context = new SystemURLRequestContext;
1627 context->set_net_log(net_log);
1628 context->set_host_resolver(globals->host_resolver.get());
1629 context->set_cert_verifier(globals->cert_verifier.get());
1630 context->set_transport_security_state(
1631 globals->transport_security_state.get());
1632 context->set_cert_transparency_verifier(
1633 globals->cert_transparency_verifier.get());
1634 context->set_ssl_config_service(globals->ssl_config_service.get());
1635 context->set_http_auth_handler_factory(
1636 globals->http_auth_handler_factory.get());
1637 context->set_proxy_service(globals->system_proxy_service.get());
1638
1639 globals->system_url_request_job_factory.reset(
1640 new net::URLRequestJobFactoryImpl());
1641 context->set_job_factory(globals->system_url_request_job_factory.get());
1642
1643 context->set_cookie_store(globals->system_cookie_store.get());
1644 context->set_channel_id_service(
1645 globals->system_channel_id_service.get());
1646 context->set_network_delegate(globals->system_network_delegate.get());
1647 context->set_http_user_agent_settings(
1648 globals->http_user_agent_settings.get());
1649 context->set_network_quality_estimator(
1650 globals->network_quality_estimator.get());
1651 context->set_backoff_manager(globals->url_request_backoff_manager.get());
1652
1653 context->set_http_server_properties(
1654 globals->http_server_properties->GetWeakPtr());
1655
1656 context->set_enable_brotli(globals->enable_brotli);
1657
1658 net::HttpNetworkSession::Params system_params(params);
1659 net::URLRequestContextBuilder::SetHttpNetworkSessionComponents(
1660 context, &system_params);
1661
1662 globals->system_http_network_session.reset(
1663 new net::HttpNetworkSession(system_params));
1664 globals->system_http_transaction_factory.reset(
1665 new net::HttpNetworkLayer(globals->system_http_network_session.get()));
1666 context->set_http_transaction_factory(
1667 globals->system_http_transaction_factory.get());
1668
1669 return context;
1670 }
1671
1672 // static
1673 net::URLRequestContext* IOThread::ConstructProxyScriptFetcherContext(
1674 IOThread::Globals* globals,
1675 const net::HttpNetworkSession::Params& params,
1676 net::NetLog* net_log) {
1677 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
1678 // is fixed.
1679 tracked_objects::ScopedTracker tracking_profile1(
1680 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1681 "466432 IOThread::ConstructProxyScriptFetcherContext1"));
1682 net::URLRequestContext* context = new net::URLRequestContext;
1683 context->set_net_log(net_log);
1684 context->set_host_resolver(globals->host_resolver.get());
1685 context->set_cert_verifier(globals->cert_verifier.get());
1686 context->set_transport_security_state(
1687 globals->transport_security_state.get());
1688 context->set_cert_transparency_verifier(
1689 globals->cert_transparency_verifier.get());
1690 context->set_ssl_config_service(globals->ssl_config_service.get());
1691 context->set_http_auth_handler_factory(
1692 globals->http_auth_handler_factory.get());
1693 context->set_proxy_service(globals->proxy_script_fetcher_proxy_service.get());
1694
1695 context->set_job_factory(
1696 globals->proxy_script_fetcher_url_request_job_factory.get());
1697
1698 context->set_cookie_store(globals->system_cookie_store.get());
1699 context->set_channel_id_service(
1700 globals->system_channel_id_service.get());
1701 context->set_network_delegate(globals->system_network_delegate.get());
1702 context->set_http_user_agent_settings(
1703 globals->http_user_agent_settings.get());
1704 context->set_http_server_properties(
1705 globals->http_server_properties->GetWeakPtr());
1706
1707 context->set_enable_brotli(globals->enable_brotli);
1708
1709 net::HttpNetworkSession::Params session_params(params);
1710 net::URLRequestContextBuilder::SetHttpNetworkSessionComponents(
1711 context, &session_params);
1712
1713 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
1714 // is fixed.
1715 tracked_objects::ScopedTracker tracking_profile2(
1716 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1717 "466432 IOThread::ConstructProxyScriptFetcherContext2"));
1718 globals->proxy_script_fetcher_http_network_session.reset(
1719 new net::HttpNetworkSession(session_params));
1720 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
1721 // is fixed.
1722 tracked_objects::ScopedTracker tracking_profile3(
1723 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1724 "466432 IOThread::ConstructProxyScriptFetcherContext3"));
1725 globals->proxy_script_fetcher_http_transaction_factory.reset(
1726 new net::HttpNetworkLayer(
1727 globals->proxy_script_fetcher_http_network_session.get()));
1728 context->set_http_transaction_factory(
1729 globals->proxy_script_fetcher_http_transaction_factory.get());
1730
1731 std::unique_ptr<net::URLRequestJobFactoryImpl> job_factory(
1732 new net::URLRequestJobFactoryImpl());
1733
1734 job_factory->SetProtocolHandler(
1735 url::kDataScheme, base::WrapUnique(new net::DataProtocolHandler()));
1736 job_factory->SetProtocolHandler(
1737 url::kFileScheme,
1738 base::WrapUnique(new net::FileProtocolHandler(
1739 content::BrowserThread::GetBlockingPool()
1740 ->GetTaskRunnerWithShutdownBehavior(
1741 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));
1742 #if !defined(DISABLE_FTP_SUPPORT)
1743 globals->proxy_script_fetcher_ftp_transaction_factory.reset(
1744 new net::FtpNetworkLayer(globals->host_resolver.get()));
1745 job_factory->SetProtocolHandler(
1746 url::kFtpScheme,
1747 base::WrapUnique(new net::FtpProtocolHandler(
1748 globals->proxy_script_fetcher_ftp_transaction_factory.get())));
1749 #endif
1750 globals->proxy_script_fetcher_url_request_job_factory =
1751 std::move(job_factory);
1752
1753 context->set_job_factory(
1754 globals->proxy_script_fetcher_url_request_job_factory.get());
1755
1756 // TODO(rtenneti): We should probably use HttpServerPropertiesManager for the
1757 // system URLRequestContext too. There's no reason this should be tied to a
1758 // profile.
1759 return context;
1760 }
1761
1762 const metrics::UpdateUsagePrefCallbackType&
1763 IOThread::GetMetricsDataUseForwarder() {
1764 return metrics_data_use_forwarder_;
1765 }