Roll src/third_party/WebKit 8b42d1d:744641d (svn 186770:186771)
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blob73f9f30c76fd0478ab167bc3d5d78f1ac7772f3b
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.
5 #include "chrome/browser/io_thread.h"
7 #include <vector>
9 #include "base/base64.h"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/command_line.h"
13 #include "base/compiler_specific.h"
14 #include "base/debug/leak_tracker.h"
15 #include "base/debug/trace_event.h"
16 #include "base/logging.h"
17 #include "base/metrics/field_trial.h"
18 #include "base/prefs/pref_registry_simple.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_piece.h"
23 #include "base/strings/string_split.h"
24 #include "base/strings/string_util.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "base/threading/thread.h"
27 #include "base/threading/worker_pool.h"
28 #include "base/time/time.h"
29 #include "build/build_config.h"
30 #include "chrome/browser/browser_process.h"
31 #include "chrome/browser/net/async_dns_field_trial.h"
32 #include "chrome/browser/net/chrome_net_log.h"
33 #include "chrome/browser/net/chrome_network_delegate.h"
34 #include "chrome/browser/net/connect_interceptor.h"
35 #include "chrome/browser/net/dns_probe_service.h"
36 #include "chrome/browser/net/pref_proxy_config_tracker.h"
37 #include "chrome/browser/net/proxy_service_factory.h"
38 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
39 #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
40 #include "chrome/common/chrome_content_client.h"
41 #include "chrome/common/chrome_switches.h"
42 #include "chrome/common/chrome_version_info.h"
43 #include "chrome/common/pref_names.h"
44 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_auth_request_handler.h"
45 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.h"
46 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h"
47 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_protocol.h"
48 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h"
49 #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
50 #include "components/policy/core/common/policy_service.h"
51 #include "components/variations/variations_associated_data.h"
52 #include "content/public/browser/browser_thread.h"
53 #include "content/public/browser/cookie_store_factory.h"
54 #include "net/base/host_mapping_rules.h"
55 #include "net/base/net_util.h"
56 #include "net/cert/cert_policy_enforcer.h"
57 #include "net/cert/cert_verifier.h"
58 #include "net/cert/cert_verify_proc.h"
59 #include "net/cert/ct_known_logs.h"
60 #include "net/cert/ct_known_logs_static.h"
61 #include "net/cert/ct_log_verifier.h"
62 #include "net/cert/ct_verifier.h"
63 #include "net/cert/multi_log_ct_verifier.h"
64 #include "net/cert/multi_threaded_cert_verifier.h"
65 #include "net/cookies/cookie_store.h"
66 #include "net/dns/host_cache.h"
67 #include "net/dns/host_resolver.h"
68 #include "net/dns/mapped_host_resolver.h"
69 #include "net/ftp/ftp_network_layer.h"
70 #include "net/http/http_auth_filter.h"
71 #include "net/http/http_auth_handler_factory.h"
72 #include "net/http/http_network_layer.h"
73 #include "net/http/http_server_properties_impl.h"
74 #include "net/proxy/proxy_config_service.h"
75 #include "net/proxy/proxy_script_fetcher_impl.h"
76 #include "net/proxy/proxy_service.h"
77 #include "net/quic/crypto/crypto_protocol.h"
78 #include "net/quic/quic_protocol.h"
79 #include "net/quic/quic_utils.h"
80 #include "net/socket/tcp_client_socket.h"
81 #include "net/spdy/spdy_session.h"
82 #include "net/ssl/channel_id_service.h"
83 #include "net/ssl/default_channel_id_store.h"
84 #include "net/url_request/data_protocol_handler.h"
85 #include "net/url_request/file_protocol_handler.h"
86 #include "net/url_request/ftp_protocol_handler.h"
87 #include "net/url_request/static_http_user_agent_settings.h"
88 #include "net/url_request/url_fetcher.h"
89 #include "net/url_request/url_request_context.h"
90 #include "net/url_request/url_request_context_getter.h"
91 #include "net/url_request/url_request_job_factory_impl.h"
92 #include "net/url_request/url_request_throttler_manager.h"
93 #include "url/url_constants.h"
95 #if defined(ENABLE_CONFIGURATION_POLICY)
96 #include "policy/policy_constants.h"
97 #endif
99 #if defined(ENABLE_EXTENSIONS)
100 #include "chrome/browser/extensions/event_router_forwarder.h"
101 #endif
103 #if defined(USE_NSS) || defined(OS_IOS)
104 #include "net/ocsp/nss_ocsp.h"
105 #endif
107 #if defined(OS_CHROMEOS)
108 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
109 #include "chromeos/network/host_resolver_impl_chromeos.h"
110 #endif
112 using content::BrowserThread;
114 class SafeBrowsingURLRequestContext;
116 // The IOThread object must outlive any tasks posted to the IO thread before the
117 // Quit task, so base::Bind() calls are not refcounted.
119 namespace {
121 const char kTCPFastOpenFieldTrialName[] = "TCPFastOpen";
122 const char kTCPFastOpenHttpsEnabledGroupName[] = "HttpsEnabled";
124 const char kQuicFieldTrialName[] = "QUIC";
125 const char kQuicFieldTrialEnabledGroupName[] = "Enabled";
126 const char kQuicFieldTrialHttpsEnabledGroupName[] = "HttpsEnabled";
128 // The SPDY trial composes two different trial plus control groups:
129 // * A "holdback" group with SPDY disabled, and corresponding control
130 // (SPDY/3.1). The primary purpose of the holdback group is to encourage site
131 // operators to do feature detection rather than UA-sniffing. As such, this
132 // trial runs continuously.
133 // * A SPDY/4 experiment, for SPDY/4 (aka HTTP/2) vs SPDY/3.1 comparisons and
134 // eventual SPDY/4 deployment.
135 const char kSpdyFieldTrialName[] = "SPDY";
136 const char kSpdyFieldTrialHoldbackGroupNamePrefix[] = "SpdyDisabled";
137 const char kSpdyFieldTrialHoldbackControlGroupName[] = "Control";
138 const char kSpdyFieldTrialSpdy31GroupNamePrefix[] = "Spdy31Enabled";
139 const char kSpdyFieldTrialSpdy4GroupNamePrefix[] = "Spdy4Enabled";
140 const char kSpdyFieldTrialSpdy4ControlGroupName[] = "Spdy4Control";
142 // Field trial for Cache-Control: stale-while-revalidate directive.
143 const char kStaleWhileRevalidateFieldTrialName[] = "StaleWhileRevalidate";
145 #if defined(OS_MACOSX) && !defined(OS_IOS)
146 void ObserveKeychainEvents() {
147 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
148 net::CertDatabase::GetInstance()->SetMessageLoopForKeychainEvents();
150 #endif
152 // Used for the "system" URLRequestContext.
153 class SystemURLRequestContext : public net::URLRequestContext {
154 public:
155 SystemURLRequestContext() {
156 #if defined(USE_NSS) || defined(OS_IOS)
157 net::SetURLRequestContextForNSSHttpIO(this);
158 #endif
161 private:
162 ~SystemURLRequestContext() override {
163 AssertNoURLRequests();
164 #if defined(USE_NSS) || defined(OS_IOS)
165 net::SetURLRequestContextForNSSHttpIO(NULL);
166 #endif
170 scoped_ptr<net::HostResolver> CreateGlobalHostResolver(net::NetLog* net_log) {
171 TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver");
172 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
174 net::HostResolver::Options options;
176 // Use the concurrency override from the command-line, if any.
177 if (command_line.HasSwitch(switches::kHostResolverParallelism)) {
178 std::string s =
179 command_line.GetSwitchValueASCII(switches::kHostResolverParallelism);
181 // Parse the switch (it should be a positive integer formatted as decimal).
182 int n;
183 if (base::StringToInt(s, &n) && n > 0) {
184 options.max_concurrent_resolves = static_cast<size_t>(n);
185 } else {
186 LOG(ERROR) << "Invalid switch for host resolver parallelism: " << s;
190 // Use the retry attempts override from the command-line, if any.
191 if (command_line.HasSwitch(switches::kHostResolverRetryAttempts)) {
192 std::string s =
193 command_line.GetSwitchValueASCII(switches::kHostResolverRetryAttempts);
194 // Parse the switch (it should be a non-negative integer).
195 int n;
196 if (base::StringToInt(s, &n) && n >= 0) {
197 options.max_retry_attempts = static_cast<size_t>(n);
198 } else {
199 LOG(ERROR) << "Invalid switch for host resolver retry attempts: " << s;
203 scoped_ptr<net::HostResolver> global_host_resolver;
204 #if defined OS_CHROMEOS
205 global_host_resolver =
206 chromeos::HostResolverImplChromeOS::CreateSystemResolver(options,
207 net_log);
208 #else
209 global_host_resolver =
210 net::HostResolver::CreateSystemResolver(options, net_log);
211 #endif
213 // Determine if we should disable IPv6 support.
214 if (command_line.HasSwitch(switches::kEnableIPv6)) {
215 // Disable IPv6 probing.
216 global_host_resolver->SetDefaultAddressFamily(
217 net::ADDRESS_FAMILY_UNSPECIFIED);
218 } else if (command_line.HasSwitch(switches::kDisableIPv6)) {
219 global_host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4);
222 // If hostname remappings were specified on the command-line, layer these
223 // rules on top of the real host resolver. This allows forwarding all requests
224 // through a designated test server.
225 if (!command_line.HasSwitch(switches::kHostResolverRules))
226 return global_host_resolver.Pass();
228 scoped_ptr<net::MappedHostResolver> remapped_resolver(
229 new net::MappedHostResolver(global_host_resolver.Pass()));
230 remapped_resolver->SetRulesFromString(
231 command_line.GetSwitchValueASCII(switches::kHostResolverRules));
232 return remapped_resolver.Pass();
235 // TODO(willchan): Remove proxy script fetcher context since it's not necessary
236 // now that I got rid of refcounting URLRequestContexts.
237 // See IOThread::Globals for details.
238 net::URLRequestContext*
239 ConstructProxyScriptFetcherContext(IOThread::Globals* globals,
240 net::NetLog* net_log) {
241 net::URLRequestContext* context = new net::URLRequestContext;
242 context->set_net_log(net_log);
243 context->set_host_resolver(globals->host_resolver.get());
244 context->set_cert_verifier(globals->cert_verifier.get());
245 context->set_transport_security_state(
246 globals->transport_security_state.get());
247 context->set_cert_transparency_verifier(
248 globals->cert_transparency_verifier.get());
249 context->set_http_auth_handler_factory(
250 globals->http_auth_handler_factory.get());
251 context->set_proxy_service(globals->proxy_script_fetcher_proxy_service.get());
252 context->set_http_transaction_factory(
253 globals->proxy_script_fetcher_http_transaction_factory.get());
254 context->set_job_factory(
255 globals->proxy_script_fetcher_url_request_job_factory.get());
256 context->set_cookie_store(globals->system_cookie_store.get());
257 context->set_channel_id_service(
258 globals->system_channel_id_service.get());
259 context->set_network_delegate(globals->system_network_delegate.get());
260 context->set_http_user_agent_settings(
261 globals->http_user_agent_settings.get());
262 // TODO(rtenneti): We should probably use HttpServerPropertiesManager for the
263 // system URLRequestContext too. There's no reason this should be tied to a
264 // profile.
265 return context;
268 net::URLRequestContext*
269 ConstructSystemRequestContext(IOThread::Globals* globals,
270 net::NetLog* net_log) {
271 net::URLRequestContext* context = new SystemURLRequestContext;
272 context->set_net_log(net_log);
273 context->set_host_resolver(globals->host_resolver.get());
274 context->set_cert_verifier(globals->cert_verifier.get());
275 context->set_transport_security_state(
276 globals->transport_security_state.get());
277 context->set_cert_transparency_verifier(
278 globals->cert_transparency_verifier.get());
279 context->set_http_auth_handler_factory(
280 globals->http_auth_handler_factory.get());
281 context->set_proxy_service(globals->system_proxy_service.get());
282 context->set_http_transaction_factory(
283 globals->system_http_transaction_factory.get());
284 context->set_job_factory(globals->system_url_request_job_factory.get());
285 context->set_cookie_store(globals->system_cookie_store.get());
286 context->set_channel_id_service(
287 globals->system_channel_id_service.get());
288 context->set_throttler_manager(globals->throttler_manager.get());
289 context->set_network_delegate(globals->system_network_delegate.get());
290 context->set_http_user_agent_settings(
291 globals->http_user_agent_settings.get());
292 return context;
295 int GetSwitchValueAsInt(const CommandLine& command_line,
296 const std::string& switch_name) {
297 int value;
298 if (!base::StringToInt(command_line.GetSwitchValueASCII(switch_name),
299 &value)) {
300 return 0;
302 return value;
305 // Returns the value associated with |key| in |params| or "" if the
306 // key is not present in the map.
307 const std::string& GetVariationParam(
308 const std::map<std::string, std::string>& params,
309 const std::string& key) {
310 std::map<std::string, std::string>::const_iterator it = params.find(key);
311 if (it == params.end())
312 return base::EmptyString();
314 return it->second;
317 // Return true if stale-while-revalidate support should be enabled.
318 bool IsStaleWhileRevalidateEnabled(const base::CommandLine& command_line) {
319 if (command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))
320 return true;
321 const std::string group_name =
322 base::FieldTrialList::FindFullName(kStaleWhileRevalidateFieldTrialName);
323 return group_name == "Enabled";
326 } // namespace
328 class IOThread::LoggingNetworkChangeObserver
329 : public net::NetworkChangeNotifier::IPAddressObserver,
330 public net::NetworkChangeNotifier::ConnectionTypeObserver,
331 public net::NetworkChangeNotifier::NetworkChangeObserver {
332 public:
333 // |net_log| must remain valid throughout our lifetime.
334 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
335 : net_log_(net_log) {
336 net::NetworkChangeNotifier::AddIPAddressObserver(this);
337 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
338 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
341 ~LoggingNetworkChangeObserver() override {
342 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
343 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
344 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
347 // NetworkChangeNotifier::IPAddressObserver implementation.
348 void OnIPAddressChanged() override {
349 VLOG(1) << "Observed a change to the network IP addresses";
351 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
354 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
355 void OnConnectionTypeChanged(
356 net::NetworkChangeNotifier::ConnectionType type) override {
357 std::string type_as_string =
358 net::NetworkChangeNotifier::ConnectionTypeToString(type);
360 VLOG(1) << "Observed a change to network connectivity state "
361 << type_as_string;
363 net_log_->AddGlobalEntry(
364 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
365 net::NetLog::StringCallback("new_connection_type", &type_as_string));
368 // NetworkChangeNotifier::NetworkChangeObserver implementation.
369 void OnNetworkChanged(
370 net::NetworkChangeNotifier::ConnectionType type) override {
371 std::string type_as_string =
372 net::NetworkChangeNotifier::ConnectionTypeToString(type);
374 VLOG(1) << "Observed a network change to state " << type_as_string;
376 net_log_->AddGlobalEntry(
377 net::NetLog::TYPE_NETWORK_CHANGED,
378 net::NetLog::StringCallback("new_connection_type", &type_as_string));
381 private:
382 net::NetLog* net_log_;
383 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
386 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
387 public:
388 explicit SystemURLRequestContextGetter(IOThread* io_thread);
390 // Implementation for net::UrlRequestContextGetter.
391 net::URLRequestContext* GetURLRequestContext() override;
392 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
393 const override;
395 protected:
396 ~SystemURLRequestContextGetter() override;
398 private:
399 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
400 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
402 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
405 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
406 IOThread* io_thread)
407 : io_thread_(io_thread),
408 network_task_runner_(
409 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
412 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
414 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
415 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
416 DCHECK(io_thread_->globals()->system_request_context.get());
418 return io_thread_->globals()->system_request_context.get();
421 scoped_refptr<base::SingleThreadTaskRunner>
422 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
423 return network_task_runner_;
426 IOThread::Globals::
427 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
428 Globals* globals)
429 : globals_(globals) {
430 DCHECK(globals_);
433 IOThread::Globals::
434 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
435 if (globals_->system_request_context.get())
436 globals_->system_request_context->AssertNoURLRequests();
439 IOThread::Globals::Globals()
440 : system_request_context_leak_checker(this),
441 enable_ssl_connect_job_waiting(false),
442 ignore_certificate_errors(false),
443 use_stale_while_revalidate(false),
444 testing_fixed_http_port(0),
445 testing_fixed_https_port(0),
446 enable_user_alternate_protocol_ports(false) {
449 IOThread::Globals::~Globals() {}
451 // |local_state| is passed in explicitly in order to (1) reduce implicit
452 // dependencies and (2) make IOThread more flexible for testing.
453 IOThread::IOThread(
454 PrefService* local_state,
455 policy::PolicyService* policy_service,
456 ChromeNetLog* net_log,
457 extensions::EventRouterForwarder* extension_event_router_forwarder)
458 : net_log_(net_log),
459 #if defined(ENABLE_EXTENSIONS)
460 extension_event_router_forwarder_(extension_event_router_forwarder),
461 #endif
462 globals_(NULL),
463 is_spdy_disabled_by_policy_(false),
464 creation_time_(base::TimeTicks::Now()),
465 weak_factory_(this) {
466 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
467 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
468 prefs::kDisableAuthNegotiateCnameLookup);
469 negotiate_enable_port_ = local_state->GetBoolean(
470 prefs::kEnableAuthNegotiatePort);
471 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
472 auth_delegate_whitelist_ = local_state->GetString(
473 prefs::kAuthNegotiateDelegateWhitelist);
474 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
475 pref_proxy_config_tracker_.reset(
476 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
477 local_state));
478 ChromeNetworkDelegate::InitializePrefsOnUIThread(
479 &system_enable_referrers_,
480 NULL,
481 NULL,
482 NULL,
483 NULL,
484 local_state);
485 ssl_config_service_manager_.reset(
486 SSLConfigServiceManager::CreateDefaultManager(local_state));
488 base::Value* dns_client_enabled_default = new base::FundamentalValue(
489 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
490 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
491 dns_client_enabled_default);
493 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
494 local_state,
495 base::Bind(&IOThread::UpdateDnsClientEnabled,
496 base::Unretained(this)));
497 dns_client_enabled_.MoveToThread(
498 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
500 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
501 local_state);
502 quick_check_enabled_.MoveToThread(
503 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
505 #if defined(ENABLE_CONFIGURATION_POLICY)
506 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
507 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
508 policy::key::kDisableSpdy) != NULL;
509 #endif // ENABLE_CONFIGURATION_POLICY
511 BrowserThread::SetDelegate(BrowserThread::IO, this);
514 IOThread::~IOThread() {
515 // This isn't needed for production code, but in tests, IOThread may
516 // be multiply constructed.
517 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
519 pref_proxy_config_tracker_->DetachFromPrefService();
520 DCHECK(!globals_);
523 IOThread::Globals* IOThread::globals() {
524 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
525 return globals_;
528 void IOThread::SetGlobalsForTesting(Globals* globals) {
529 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
530 DCHECK(!globals || !globals_);
531 globals_ = globals;
534 ChromeNetLog* IOThread::net_log() {
535 return net_log_;
538 void IOThread::ChangedToOnTheRecord() {
539 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
540 BrowserThread::PostTask(
541 BrowserThread::IO,
542 FROM_HERE,
543 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
544 base::Unretained(this)));
547 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
548 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
549 if (!system_url_request_context_getter_.get()) {
550 InitSystemRequestContext();
552 return system_url_request_context_getter_.get();
555 void IOThread::Init() {
556 // Prefer to use InitAsync unless you need initialization to block
557 // the UI thread
560 void IOThread::InitAsync() {
561 TRACE_EVENT0("startup", "IOThread::InitAsync");
562 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
564 #if defined(USE_NSS) || defined(OS_IOS)
565 net::SetMessageLoopForNSSHttpIO();
566 #endif
568 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
570 DCHECK(!globals_);
571 globals_ = new Globals;
573 // Add an observer that will emit network change events to the ChromeNetLog.
574 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
575 // logging the network change before other IO thread consumers respond to it.
576 network_change_observer_.reset(
577 new LoggingNetworkChangeObserver(net_log_));
579 // Setup the HistogramWatcher to run on the IO thread.
580 net::NetworkChangeNotifier::InitHistogramWatcher();
582 #if defined(ENABLE_EXTENSIONS)
583 globals_->extension_event_router_forwarder =
584 extension_event_router_forwarder_;
585 #endif
587 ChromeNetworkDelegate* network_delegate =
588 new ChromeNetworkDelegate(extension_event_router_forwarder(),
589 &system_enable_referrers_);
591 if (command_line.HasSwitch(switches::kEnableClientHints))
592 network_delegate->SetEnableClientHints();
594 #if defined(ENABLE_EXTENSIONS)
595 if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling))
596 network_delegate->NeverThrottleRequests();
597 #endif
599 globals_->system_network_delegate.reset(network_delegate);
600 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
601 UpdateDnsClientEnabled();
602 #if defined(OS_CHROMEOS)
603 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
604 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
605 new chromeos::CertVerifyProcChromeOS()));
606 #else
607 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
608 net::CertVerifyProc::CreateDefault()));
609 #endif
611 globals_->transport_security_state.reset(new net::TransportSecurityState());
613 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
614 globals_->cert_transparency_verifier.reset(ct_verifier);
616 // Add built-in logs
617 ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
619 // Add logs from command line
620 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
621 std::string switch_value = command_line.GetSwitchValueASCII(
622 switches::kCertificateTransparencyLog);
623 std::vector<std::string> logs;
624 base::SplitString(switch_value, ',', &logs);
625 for (std::vector<std::string>::iterator it = logs.begin(); it != logs.end();
626 ++it) {
627 const std::string& curr_log = *it;
628 size_t delim_pos = curr_log.find(":");
629 CHECK(delim_pos != std::string::npos)
630 << "CT log description not provided (switch format"
631 " is 'description:base64_key')";
632 std::string log_description(curr_log.substr(0, delim_pos));
633 std::string ct_public_key_data;
634 CHECK(base::Base64Decode(curr_log.substr(delim_pos + 1),
635 &ct_public_key_data))
636 << "Unable to decode CT public key.";
637 scoped_ptr<net::CTLogVerifier> external_log_verifier(
638 net::CTLogVerifier::Create(ct_public_key_data, log_description));
639 CHECK(external_log_verifier) << "Unable to parse CT public key.";
640 VLOG(1) << "Adding log with description " << log_description;
641 ct_verifier->AddLog(external_log_verifier.Pass());
645 net::CertPolicyEnforcer* policy_enforcer = NULL;
646 // TODO(eranm): Control with Finch, crbug.com/437766
647 if (command_line.HasSwitch(switches::kRequireCTForEV)) {
648 policy_enforcer = new net::CertPolicyEnforcer(kNumKnownCTLogs, true);
649 } else {
650 policy_enforcer = new net::CertPolicyEnforcer(kNumKnownCTLogs, false);
652 globals_->cert_policy_enforcer.reset(policy_enforcer);
654 globals_->ssl_config_service = GetSSLConfigService();
656 SetupDataReductionProxy(network_delegate);
658 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
659 globals_->host_resolver.get()));
660 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
661 // For the ProxyScriptFetcher, we use a direct ProxyService.
662 globals_->proxy_script_fetcher_proxy_service.reset(
663 net::ProxyService::CreateDirectWithNetLog(net_log_));
664 // In-memory cookie store.
665 globals_->system_cookie_store =
666 content::CreateCookieStore(content::CookieStoreConfig());
667 // In-memory channel ID store.
668 globals_->system_channel_id_service.reset(
669 new net::ChannelIDService(
670 new net::DefaultChannelIDStore(NULL),
671 base::WorkerPool::GetTaskRunner(true)));
672 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
673 globals_->host_mapping_rules.reset(new net::HostMappingRules());
674 globals_->http_user_agent_settings.reset(
675 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
676 if (command_line.HasSwitch(switches::kHostRules)) {
677 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
678 globals_->host_mapping_rules->SetRulesFromString(
679 command_line.GetSwitchValueASCII(switches::kHostRules));
680 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
682 if (command_line.HasSwitch(switches::kEnableSSLConnectJobWaiting))
683 globals_->enable_ssl_connect_job_waiting = true;
684 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
685 globals_->ignore_certificate_errors = true;
686 globals_->use_stale_while_revalidate =
687 IsStaleWhileRevalidateEnabled(command_line);
688 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
689 globals_->testing_fixed_http_port =
690 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
692 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
693 globals_->testing_fixed_https_port =
694 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
696 ConfigureQuic(command_line);
697 if (command_line.HasSwitch(
698 switches::kEnableUserAlternateProtocolPorts)) {
699 globals_->enable_user_alternate_protocol_ports = true;
701 InitializeNetworkOptions(command_line);
703 net::HttpNetworkSession::Params session_params;
704 InitializeNetworkSessionParams(&session_params);
705 session_params.net_log = net_log_;
706 session_params.proxy_service =
707 globals_->proxy_script_fetcher_proxy_service.get();
709 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession");
710 scoped_refptr<net::HttpNetworkSession> network_session(
711 new net::HttpNetworkSession(session_params));
712 globals_->proxy_script_fetcher_http_transaction_factory
713 .reset(new net::HttpNetworkLayer(network_session.get()));
714 TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession");
715 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
716 new net::URLRequestJobFactoryImpl());
717 job_factory->SetProtocolHandler(url::kDataScheme,
718 new net::DataProtocolHandler());
719 job_factory->SetProtocolHandler(
720 url::kFileScheme,
721 new net::FileProtocolHandler(
722 content::BrowserThread::GetBlockingPool()->
723 GetTaskRunnerWithShutdownBehavior(
724 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
725 #if !defined(DISABLE_FTP_SUPPORT)
726 globals_->proxy_script_fetcher_ftp_transaction_factory.reset(
727 new net::FtpNetworkLayer(globals_->host_resolver.get()));
728 job_factory->SetProtocolHandler(
729 url::kFtpScheme,
730 new net::FtpProtocolHandler(
731 globals_->proxy_script_fetcher_ftp_transaction_factory.get()));
732 #endif
733 globals_->proxy_script_fetcher_url_request_job_factory = job_factory.Pass();
735 globals_->throttler_manager.reset(new net::URLRequestThrottlerManager());
736 globals_->throttler_manager->set_net_log(net_log_);
737 // Always done in production, disabled only for unit tests.
738 globals_->throttler_manager->set_enable_thread_checks(true);
740 globals_->proxy_script_fetcher_context.reset(
741 ConstructProxyScriptFetcherContext(globals_, net_log_));
743 #if defined(OS_MACOSX) && !defined(OS_IOS)
744 // Start observing Keychain events. This needs to be done on the UI thread,
745 // as Keychain services requires a CFRunLoop.
746 BrowserThread::PostTask(BrowserThread::UI,
747 FROM_HERE,
748 base::Bind(&ObserveKeychainEvents));
749 #endif
751 // InitSystemRequestContext turns right around and posts a task back
752 // to the IO thread, so we can't let it run until we know the IO
753 // thread has started.
755 // Note that since we are at BrowserThread::Init time, the UI thread
756 // is blocked waiting for the thread to start. Therefore, posting
757 // this task to the main thread's message loop here is guaranteed to
758 // get it onto the message loop while the IOThread object still
759 // exists. However, the message might not be processed on the UI
760 // thread until after IOThread is gone, so use a weak pointer.
761 BrowserThread::PostTask(BrowserThread::UI,
762 FROM_HERE,
763 base::Bind(&IOThread::InitSystemRequestContext,
764 weak_factory_.GetWeakPtr()));
767 void IOThread::CleanUp() {
768 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
770 #if defined(USE_NSS) || defined(OS_IOS)
771 net::ShutdownNSSHttpIO();
772 #endif
774 system_url_request_context_getter_ = NULL;
776 // Release objects that the net::URLRequestContext could have been pointing
777 // to.
779 // Shutdown the HistogramWatcher on the IO thread.
780 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
782 // This must be reset before the ChromeNetLog is destroyed.
783 network_change_observer_.reset();
785 system_proxy_config_service_.reset();
787 delete globals_;
788 globals_ = NULL;
790 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
793 void IOThread::InitializeNetworkOptions(const CommandLine& command_line) {
794 // Only handle use-spdy command line flags if "spdy.disabled" preference is
795 // not disabled via policy.
796 if (is_spdy_disabled_by_policy_) {
797 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
798 if (trial)
799 trial->Disable();
800 } else {
801 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
802 globals_->trusted_spdy_proxy.set(
803 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
805 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
806 net::URLFetcher::SetIgnoreCertificateRequests(true);
808 if (command_line.HasSwitch(switches::kUseSpdy)) {
809 std::string spdy_mode =
810 command_line.GetSwitchValueASCII(switches::kUseSpdy);
811 EnableSpdy(spdy_mode);
812 } else if (command_line.HasSwitch(switches::kEnableSpdy4)) {
813 globals_->next_protos = net::NextProtosSpdy4Http2();
814 globals_->use_alternate_protocols.set(true);
815 } else if (command_line.HasSwitch(switches::kEnableNpnHttpOnly)) {
816 globals_->next_protos = net::NextProtosHttpOnly();
817 globals_->use_alternate_protocols.set(false);
818 } else {
819 // No SPDY command-line flags have been specified. Examine trial groups.
820 ConfigureSpdyFromTrial(
821 base::FieldTrialList::FindFullName(kSpdyFieldTrialName), globals_);
825 ConfigureTCPFastOpen(command_line);
827 // TODO(rch): Make the client socket factory a per-network session
828 // instance, constructed from a NetworkSession::Params, to allow us
829 // to move this option to IOThread::Globals &
830 // HttpNetworkSession::Params.
833 void IOThread::ConfigureTCPFastOpen(const CommandLine& command_line) {
834 const std::string trial_group =
835 base::FieldTrialList::FindFullName(kTCPFastOpenFieldTrialName);
836 if (trial_group == kTCPFastOpenHttpsEnabledGroupName)
837 globals_->enable_tcp_fast_open_for_ssl.set(true);
838 bool always_enable_if_supported =
839 command_line.HasSwitch(switches::kEnableTcpFastOpen);
840 // Check for OS support of TCP FastOpen, and turn it on for all connections
841 // if indicated by user.
842 net::CheckSupportAndMaybeEnableTCPFastOpen(always_enable_if_supported);
845 void IOThread::ConfigureSpdyFromTrial(base::StringPiece spdy_trial_group,
846 Globals* globals) {
847 if (spdy_trial_group.starts_with(kSpdyFieldTrialHoldbackGroupNamePrefix)) {
848 // TODO(jgraettinger): Use net::NextProtosHttpOnly() instead?
849 net::HttpStreamFactory::set_spdy_enabled(false);
850 } else if (spdy_trial_group == kSpdyFieldTrialHoldbackControlGroupName) {
851 // Use the current SPDY default (SPDY/3.1).
852 globals->next_protos = net::NextProtosSpdy31();
853 globals->use_alternate_protocols.set(true);
854 } else if (spdy_trial_group.starts_with(
855 kSpdyFieldTrialSpdy31GroupNamePrefix)) {
856 globals->next_protos = net::NextProtosSpdy31();
857 globals->use_alternate_protocols.set(true);
858 } else if (spdy_trial_group.starts_with(
859 kSpdyFieldTrialSpdy4GroupNamePrefix)) {
860 globals->next_protos = net::NextProtosSpdy4Http2();
861 globals->use_alternate_protocols.set(true);
862 } else if (spdy_trial_group == kSpdyFieldTrialSpdy4ControlGroupName) {
863 // This control group is pinned at SPDY/3.1.
864 globals->next_protos = net::NextProtosSpdy31();
865 globals->use_alternate_protocols.set(true);
866 } else {
867 // Use the current SPDY default (SPDY/3.1).
868 globals->next_protos = net::NextProtosSpdy31();
869 globals->use_alternate_protocols.set(true);
873 void IOThread::EnableSpdy(const std::string& mode) {
874 static const char kOff[] = "off";
875 static const char kSSL[] = "ssl";
876 static const char kDisableSSL[] = "no-ssl";
877 static const char kDisablePing[] = "no-ping";
878 static const char kExclude[] = "exclude"; // Hosts to exclude
879 static const char kDisableCompression[] = "no-compress";
880 static const char kDisableAltProtocols[] = "no-alt-protocols";
881 static const char kForceAltProtocols[] = "force-alt-protocols";
882 static const char kSingleDomain[] = "single-domain";
884 static const char kInitialMaxConcurrentStreams[] = "init-max-streams";
886 std::vector<std::string> spdy_options;
887 base::SplitString(mode, ',', &spdy_options);
889 for (std::vector<std::string>::iterator it = spdy_options.begin();
890 it != spdy_options.end(); ++it) {
891 const std::string& element = *it;
892 std::vector<std::string> name_value;
893 base::SplitString(element, '=', &name_value);
894 const std::string& option =
895 name_value.size() > 0 ? name_value[0] : std::string();
896 const std::string value =
897 name_value.size() > 1 ? name_value[1] : std::string();
899 if (option == kOff) {
900 net::HttpStreamFactory::set_spdy_enabled(false);
901 } else if (option == kDisableSSL) {
902 globals_->spdy_default_protocol.set(net::kProtoSPDY31);
903 globals_->force_spdy_over_ssl.set(false);
904 globals_->force_spdy_always.set(true);
905 } else if (option == kSSL) {
906 globals_->spdy_default_protocol.set(net::kProtoSPDY31);
907 globals_->force_spdy_over_ssl.set(true);
908 globals_->force_spdy_always.set(true);
909 } else if (option == kDisablePing) {
910 globals_->enable_spdy_ping_based_connection_checking.set(false);
911 } else if (option == kExclude) {
912 globals_->forced_spdy_exclusions.insert(
913 net::HostPortPair::FromURL(GURL(value)));
914 } else if (option == kDisableCompression) {
915 globals_->enable_spdy_compression.set(false);
916 } else if (option == kDisableAltProtocols) {
917 globals_->use_alternate_protocols.set(false);
918 } else if (option == kForceAltProtocols) {
919 net::AlternateProtocolInfo pair(443, net::NPN_SPDY_3, 1);
920 net::HttpServerPropertiesImpl::ForceAlternateProtocol(pair);
921 } else if (option == kSingleDomain) {
922 DVLOG(1) << "FORCING SINGLE DOMAIN";
923 globals_->force_spdy_single_domain.set(true);
924 } else if (option == kInitialMaxConcurrentStreams) {
925 int streams;
926 if (base::StringToInt(value, &streams))
927 globals_->initial_max_spdy_concurrent_streams.set(streams);
928 } else if (option.empty() && it == spdy_options.begin()) {
929 continue;
930 } else {
931 LOG(DFATAL) << "Unrecognized spdy option: " << option;
936 // static
937 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
938 registry->RegisterStringPref(prefs::kAuthSchemes,
939 "basic,digest,ntlm,negotiate,"
940 "spdyproxy");
941 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
942 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
943 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
944 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
945 std::string());
946 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
947 registry->RegisterStringPref(
948 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
949 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
950 data_reduction_proxy::RegisterPrefs(registry);
951 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
952 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
955 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
956 net::HostResolver* resolver) {
957 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
958 if (!auth_server_whitelist_.empty()) {
959 auth_filter_default_credentials =
960 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
962 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
963 if (!auth_delegate_whitelist_.empty()) {
964 auth_filter_delegate =
965 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
967 globals_->url_security_manager.reset(
968 net::URLSecurityManager::Create(auth_filter_default_credentials,
969 auth_filter_delegate));
970 std::vector<std::string> supported_schemes;
971 base::SplitString(auth_schemes_, ',', &supported_schemes);
973 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
974 net::HttpAuthHandlerRegistryFactory::Create(
975 supported_schemes, globals_->url_security_manager.get(),
976 resolver, gssapi_library_name_, negotiate_disable_cname_lookup_,
977 negotiate_enable_port_));
978 return registry_factory.release();
981 void IOThread::ClearHostCache() {
982 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
984 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
985 if (host_cache)
986 host_cache->clear();
989 void IOThread::InitializeNetworkSessionParams(
990 net::HttpNetworkSession::Params* params) {
991 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
994 // static
995 void IOThread::InitializeNetworkSessionParamsFromGlobals(
996 const IOThread::Globals& globals,
997 net::HttpNetworkSession::Params* params) {
998 params->host_resolver = globals.host_resolver.get();
999 params->cert_verifier = globals.cert_verifier.get();
1000 params->cert_policy_enforcer = globals.cert_policy_enforcer.get();
1001 params->channel_id_service = globals.system_channel_id_service.get();
1002 params->transport_security_state = globals.transport_security_state.get();
1003 params->ssl_config_service = globals.ssl_config_service.get();
1004 params->http_auth_handler_factory = globals.http_auth_handler_factory.get();
1005 params->http_server_properties =
1006 globals.http_server_properties->GetWeakPtr();
1007 params->network_delegate = globals.system_network_delegate.get();
1008 params->host_mapping_rules = globals.host_mapping_rules.get();
1009 params->enable_ssl_connect_job_waiting =
1010 globals.enable_ssl_connect_job_waiting;
1011 params->ignore_certificate_errors = globals.ignore_certificate_errors;
1012 params->use_stale_while_revalidate = globals.use_stale_while_revalidate;
1013 params->testing_fixed_http_port = globals.testing_fixed_http_port;
1014 params->testing_fixed_https_port = globals.testing_fixed_https_port;
1015 globals.enable_tcp_fast_open_for_ssl.CopyToIfSet(
1016 &params->enable_tcp_fast_open_for_ssl);
1018 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
1019 &params->spdy_initial_max_concurrent_streams);
1020 globals.force_spdy_single_domain.CopyToIfSet(
1021 &params->force_spdy_single_domain);
1022 globals.enable_spdy_compression.CopyToIfSet(
1023 &params->enable_spdy_compression);
1024 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1025 &params->enable_spdy_ping_based_connection_checking);
1026 globals.spdy_default_protocol.CopyToIfSet(
1027 &params->spdy_default_protocol);
1028 params->next_protos = globals.next_protos;
1029 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1030 globals.force_spdy_over_ssl.CopyToIfSet(&params->force_spdy_over_ssl);
1031 globals.force_spdy_always.CopyToIfSet(&params->force_spdy_always);
1032 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1033 globals.use_alternate_protocols.CopyToIfSet(
1034 &params->use_alternate_protocols);
1035 globals.alternate_protocol_probability_threshold.CopyToIfSet(
1036 &params->alternate_protocol_probability_threshold);
1038 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1039 globals.quic_always_require_handshake_confirmation.CopyToIfSet(
1040 &params->quic_always_require_handshake_confirmation);
1041 globals.quic_disable_connection_pooling.CopyToIfSet(
1042 &params->quic_disable_connection_pooling);
1043 globals.quic_load_server_info_timeout_ms.CopyToIfSet(
1044 &params->quic_load_server_info_timeout_ms);
1045 globals.enable_quic_port_selection.CopyToIfSet(
1046 &params->enable_quic_port_selection);
1047 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1048 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1049 globals.quic_supported_versions.CopyToIfSet(
1050 &params->quic_supported_versions);
1051 params->quic_connection_options = globals.quic_connection_options;
1053 globals.origin_to_force_quic_on.CopyToIfSet(
1054 &params->origin_to_force_quic_on);
1055 params->enable_user_alternate_protocol_ports =
1056 globals.enable_user_alternate_protocol_ports;
1057 params->proxy_delegate = globals.data_reduction_proxy_delegate.get();
1060 base::TimeTicks IOThread::creation_time() const {
1061 return creation_time_;
1064 net::SSLConfigService* IOThread::GetSSLConfigService() {
1065 return ssl_config_service_manager_->Get();
1068 void IOThread::ChangedToOnTheRecordOnIOThread() {
1069 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1071 // Clear the host cache to avoid showing entries from the OTR session
1072 // in about:net-internals.
1073 ClearHostCache();
1076 void IOThread::InitSystemRequestContext() {
1077 if (system_url_request_context_getter_.get())
1078 return;
1079 // If we're in unit_tests, IOThread may not be run.
1080 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1081 return;
1082 system_proxy_config_service_.reset(
1083 ProxyServiceFactory::CreateProxyConfigService(
1084 pref_proxy_config_tracker_.get()));
1085 system_url_request_context_getter_ =
1086 new SystemURLRequestContextGetter(this);
1087 // Safe to post an unretained this pointer, since IOThread is
1088 // guaranteed to outlive the IO BrowserThread.
1089 BrowserThread::PostTask(
1090 BrowserThread::IO,
1091 FROM_HERE,
1092 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1093 base::Unretained(this)));
1096 void IOThread::InitSystemRequestContextOnIOThread() {
1097 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1098 DCHECK(!globals_->system_proxy_service.get());
1099 DCHECK(system_proxy_config_service_.get());
1101 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
1102 globals_->system_proxy_service.reset(
1103 ProxyServiceFactory::CreateProxyService(
1104 net_log_,
1105 globals_->proxy_script_fetcher_context.get(),
1106 globals_->system_network_delegate.get(),
1107 system_proxy_config_service_.release(),
1108 command_line,
1109 quick_check_enabled_.GetValue()));
1110 DCHECK(globals_->data_reduction_proxy_params);
1112 net::HttpNetworkSession::Params system_params;
1113 InitializeNetworkSessionParams(&system_params);
1114 system_params.net_log = net_log_;
1115 system_params.proxy_service = globals_->system_proxy_service.get();
1117 globals_->system_http_transaction_factory.reset(
1118 new net::HttpNetworkLayer(
1119 new net::HttpNetworkSession(system_params)));
1120 globals_->system_url_request_job_factory.reset(
1121 new net::URLRequestJobFactoryImpl());
1122 globals_->system_request_context.reset(
1123 ConstructSystemRequestContext(globals_, net_log_));
1124 globals_->system_request_context->set_ssl_config_service(
1125 globals_->ssl_config_service.get());
1126 globals_->system_request_context->set_http_server_properties(
1127 globals_->http_server_properties->GetWeakPtr());
1130 void IOThread::UpdateDnsClientEnabled() {
1131 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1134 void IOThread::ConfigureQuic(const CommandLine& command_line) {
1135 // Always fetch the field trial group to ensure it is reported correctly.
1136 // The command line flags will be associated with a group that is reported
1137 // so long as trial is actually queried.
1138 std::string group =
1139 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1140 VariationParameters params;
1141 if (!variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1142 params.clear();
1145 ConfigureQuicGlobals(command_line, group, params, globals_);
1148 void IOThread::SetupDataReductionProxy(
1149 ChromeNetworkDelegate* network_delegate) {
1150 // TODO(kundaji): Move flags initialization to DataReductionProxyParams and
1151 // merge with flag initialization in
1152 // data_reduction_proxy_chrome_settings_factory.cc.
1153 int flags = data_reduction_proxy::DataReductionProxyParams::kAllowed |
1154 data_reduction_proxy::DataReductionProxyParams::kFallbackAllowed |
1155 data_reduction_proxy::DataReductionProxyParams::kAlternativeAllowed;
1156 if (data_reduction_proxy::DataReductionProxyParams::
1157 IsIncludedInPromoFieldTrial()) {
1158 flags |= data_reduction_proxy::DataReductionProxyParams::kPromoAllowed;
1160 if (data_reduction_proxy::DataReductionProxyParams::
1161 IsIncludedInHoldbackFieldTrial()) {
1162 flags |= data_reduction_proxy::DataReductionProxyParams::kHoldback;
1164 globals_->data_reduction_proxy_params.reset(
1165 new data_reduction_proxy::DataReductionProxyParams(flags));
1166 globals_->data_reduction_proxy_auth_request_handler.reset(
1167 new data_reduction_proxy::DataReductionProxyAuthRequestHandler(
1168 DataReductionProxyChromeSettings::GetClient(),
1169 globals_->data_reduction_proxy_params.get(),
1170 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
1171 globals_->data_reduction_proxy_delegate.reset(
1172 new data_reduction_proxy::DataReductionProxyDelegate(
1173 globals_->data_reduction_proxy_auth_request_handler.get(),
1174 globals_->data_reduction_proxy_params.get()));
1175 // This is the same as in ProfileImplIOData except that we do not collect
1176 // usage stats.
1177 network_delegate->set_data_reduction_proxy_params(
1178 globals_->data_reduction_proxy_params.get());
1179 network_delegate->set_data_reduction_proxy_auth_request_handler(
1180 globals_->data_reduction_proxy_auth_request_handler.get());
1181 network_delegate->set_on_resolve_proxy_handler(
1182 base::Bind(data_reduction_proxy::OnResolveProxyHandler));
1185 // static
1186 void IOThread::ConfigureQuicGlobals(
1187 const base::CommandLine& command_line,
1188 base::StringPiece quic_trial_group,
1189 const VariationParameters& quic_trial_params,
1190 IOThread::Globals* globals) {
1191 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group);
1192 globals->enable_quic.set(enable_quic);
1193 if (enable_quic) {
1194 globals->quic_always_require_handshake_confirmation.set(
1195 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params));
1196 globals->quic_disable_connection_pooling.set(
1197 ShouldQuicDisableConnectionPooling(quic_trial_params));
1198 int load_server_info_timeout_ms =
1199 GetQuicLoadServerInfoTimeout(quic_trial_params);
1200 if (load_server_info_timeout_ms != 0) {
1201 globals->quic_load_server_info_timeout_ms.set(
1202 load_server_info_timeout_ms);
1204 globals->enable_quic_port_selection.set(
1205 ShouldEnableQuicPortSelection(command_line));
1206 globals->quic_connection_options =
1207 GetQuicConnectionOptions(command_line, quic_trial_params);
1208 if (ShouldEnableQuicPacing(command_line, quic_trial_group,
1209 quic_trial_params)) {
1210 globals->quic_connection_options.push_back(net::kPACE);
1214 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1215 quic_trial_group,
1216 quic_trial_params);
1217 if (max_packet_length != 0) {
1218 globals->quic_max_packet_length.set(max_packet_length);
1221 std::string quic_user_agent_id =
1222 chrome::VersionInfo::GetVersionStringModifier();
1223 if (!quic_user_agent_id.empty())
1224 quic_user_agent_id.push_back(' ');
1225 chrome::VersionInfo version_info;
1226 quic_user_agent_id.append(version_info.ProductNameAndVersionForUserAgent());
1227 globals->quic_user_agent_id.set(quic_user_agent_id);
1229 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1230 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1231 net::QuicVersionVector supported_versions;
1232 supported_versions.push_back(version);
1233 globals->quic_supported_versions.set(supported_versions);
1236 double threshold =
1237 GetAlternateProtocolProbabilityThreshold(command_line, quic_trial_params);
1238 if (threshold >=0 && threshold <= 1) {
1239 globals->alternate_protocol_probability_threshold.set(threshold);
1240 globals->http_server_properties->SetAlternateProtocolProbabilityThreshold(
1241 threshold);
1244 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1245 net::HostPortPair quic_origin =
1246 net::HostPortPair::FromString(
1247 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1248 if (!quic_origin.IsEmpty()) {
1249 globals->origin_to_force_quic_on.set(quic_origin);
1254 bool IOThread::ShouldEnableQuic(const CommandLine& command_line,
1255 base::StringPiece quic_trial_group) {
1256 if (command_line.HasSwitch(switches::kDisableQuic))
1257 return false;
1259 if (command_line.HasSwitch(switches::kEnableQuic))
1260 return true;
1262 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1263 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1266 bool IOThread::ShouldEnableQuicPortSelection(
1267 const CommandLine& command_line) {
1268 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1269 return false;
1271 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1272 return true;
1274 return false; // Default to disabling port selection on all channels.
1277 bool IOThread::ShouldEnableQuicPacing(
1278 const CommandLine& command_line,
1279 base::StringPiece quic_trial_group,
1280 const VariationParameters& quic_trial_params) {
1281 if (command_line.HasSwitch(switches::kEnableQuicPacing))
1282 return true;
1284 if (command_line.HasSwitch(switches::kDisableQuicPacing))
1285 return false;
1287 return LowerCaseEqualsASCII(
1288 GetVariationParam(quic_trial_params, "enable_pacing"),
1289 "true");
1292 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1293 const CommandLine& command_line,
1294 const VariationParameters& quic_trial_params) {
1295 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1296 return net::QuicUtils::ParseQuicConnectionOptions(
1297 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1300 VariationParameters::const_iterator it =
1301 quic_trial_params.find("connection_options");
1302 if (it == quic_trial_params.end()) {
1303 // TODO(rch): remove support for deprecated congestion_options.
1304 it = quic_trial_params.find("congestion_options");
1305 if (it == quic_trial_params.end())
1306 return net::QuicTagVector();
1309 return net::QuicUtils::ParseQuicConnectionOptions(it->second);
1312 // static
1313 double IOThread::GetAlternateProtocolProbabilityThreshold(
1314 const base::CommandLine& command_line,
1315 const VariationParameters& quic_trial_params) {
1316 double value;
1317 if (command_line.HasSwitch(
1318 switches::kAlternateProtocolProbabilityThreshold)) {
1319 if (base::StringToDouble(
1320 command_line.GetSwitchValueASCII(
1321 switches::kAlternateProtocolProbabilityThreshold),
1322 &value)) {
1323 return value;
1326 if (command_line.HasSwitch(switches::kEnableQuic)) {
1327 return 0;
1329 if (base::StringToDouble(
1330 GetVariationParam(quic_trial_params,
1331 "alternate_protocol_probability_threshold"),
1332 &value)) {
1333 return value;
1335 return -1;
1338 // static
1339 bool IOThread::ShouldQuicAlwaysRequireHandshakeConfirmation(
1340 const VariationParameters& quic_trial_params) {
1341 return LowerCaseEqualsASCII(
1342 GetVariationParam(quic_trial_params,
1343 "always_require_handshake_confirmation"),
1344 "true");
1347 // static
1348 bool IOThread::ShouldQuicDisableConnectionPooling(
1349 const VariationParameters& quic_trial_params) {
1350 return LowerCaseEqualsASCII(
1351 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1352 "true");
1355 // static
1356 int IOThread::GetQuicLoadServerInfoTimeout(
1357 const VariationParameters& quic_trial_params) {
1358 int value;
1359 if (base::StringToInt(GetVariationParam(quic_trial_params,
1360 "load_server_info_timeout"),
1361 &value)) {
1362 return value;
1364 return 0;
1367 // static
1368 size_t IOThread::GetQuicMaxPacketLength(
1369 const CommandLine& command_line,
1370 base::StringPiece quic_trial_group,
1371 const VariationParameters& quic_trial_params) {
1372 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1373 unsigned value;
1374 if (!base::StringToUint(
1375 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1376 &value)) {
1377 return 0;
1379 return value;
1382 unsigned value;
1383 if (base::StringToUint(GetVariationParam(quic_trial_params,
1384 "max_packet_length"),
1385 &value)) {
1386 return value;
1388 return 0;
1391 // static
1392 net::QuicVersion IOThread::GetQuicVersion(
1393 const CommandLine& command_line,
1394 const VariationParameters& quic_trial_params) {
1395 if (command_line.HasSwitch(switches::kQuicVersion)) {
1396 return ParseQuicVersion(
1397 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1400 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1403 // static
1404 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1405 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1406 for (size_t i = 0; i < supported_versions.size(); ++i) {
1407 net::QuicVersion version = supported_versions[i];
1408 if (net::QuicVersionToString(version) == quic_version) {
1409 return version;
1413 return net::QUIC_VERSION_UNSUPPORTED;