Check USB device path access when prompting users to select a device.
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blobf75340776e030e74ba6aa96fae18bc06f28d43fa
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/logging.h"
16 #include "base/metrics/field_trial.h"
17 #include "base/prefs/pref_registry_simple.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/profiler/scoped_tracker.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 "base/trace_event/trace_event.h"
30 #include "build/build_config.h"
31 #include "chrome/browser/browser_process.h"
32 #include "chrome/browser/net/async_dns_field_trial.h"
33 #include "chrome/browser/net/chrome_net_log.h"
34 #include "chrome/browser/net/chrome_network_delegate.h"
35 #include "chrome/browser/net/connect_interceptor.h"
36 #include "chrome/browser/net/dns_probe_service.h"
37 #include "chrome/browser/net/pref_proxy_config_tracker.h"
38 #include "chrome/browser/net/proxy_service_factory.h"
39 #include "chrome/common/chrome_content_client.h"
40 #include "chrome/common/chrome_switches.h"
41 #include "chrome/common/chrome_version_info.h"
42 #include "chrome/common/pref_names.h"
43 #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h"
44 #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
45 #include "components/policy/core/common/policy_service.h"
46 #include "components/variations/variations_associated_data.h"
47 #include "content/public/browser/browser_thread.h"
48 #include "content/public/browser/cookie_store_factory.h"
49 #include "net/base/host_mapping_rules.h"
50 #include "net/base/net_util.h"
51 #include "net/base/sdch_manager.h"
52 #include "net/cert/cert_policy_enforcer.h"
53 #include "net/cert/cert_verifier.h"
54 #include "net/cert/cert_verify_proc.h"
55 #include "net/cert/ct_known_logs.h"
56 #include "net/cert/ct_known_logs_static.h"
57 #include "net/cert/ct_log_verifier.h"
58 #include "net/cert/ct_verifier.h"
59 #include "net/cert/multi_log_ct_verifier.h"
60 #include "net/cert/multi_threaded_cert_verifier.h"
61 #include "net/cookies/cookie_store.h"
62 #include "net/dns/host_cache.h"
63 #include "net/dns/host_resolver.h"
64 #include "net/dns/mapped_host_resolver.h"
65 #include "net/ftp/ftp_network_layer.h"
66 #include "net/http/http_auth_filter.h"
67 #include "net/http/http_auth_handler_factory.h"
68 #include "net/http/http_network_layer.h"
69 #include "net/http/http_server_properties_impl.h"
70 #include "net/proxy/proxy_config_service.h"
71 #include "net/proxy/proxy_script_fetcher_impl.h"
72 #include "net/proxy/proxy_service.h"
73 #include "net/quic/crypto/crypto_protocol.h"
74 #include "net/quic/quic_protocol.h"
75 #include "net/quic/quic_utils.h"
76 #include "net/socket/tcp_client_socket.h"
77 #include "net/spdy/spdy_session.h"
78 #include "net/ssl/channel_id_service.h"
79 #include "net/ssl/default_channel_id_store.h"
80 #include "net/url_request/data_protocol_handler.h"
81 #include "net/url_request/file_protocol_handler.h"
82 #include "net/url_request/ftp_protocol_handler.h"
83 #include "net/url_request/static_http_user_agent_settings.h"
84 #include "net/url_request/url_fetcher.h"
85 #include "net/url_request/url_request_context.h"
86 #include "net/url_request/url_request_context_getter.h"
87 #include "net/url_request/url_request_job_factory_impl.h"
88 #include "net/url_request/url_request_throttler_manager.h"
89 #include "url/url_constants.h"
91 #if defined(ENABLE_CONFIGURATION_POLICY)
92 #include "policy/policy_constants.h"
93 #endif
95 #if defined(ENABLE_EXTENSIONS)
96 #include "chrome/browser/extensions/event_router_forwarder.h"
97 #endif
99 #if defined(USE_NSS) || defined(OS_IOS)
100 #include "net/ocsp/nss_ocsp.h"
101 #endif
103 #if defined(OS_ANDROID)
104 #include "base/android/build_info.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 kSpdyFieldTrialSpdy31GroupNamePrefix[] = "Spdy31Enabled";
138 const char kSpdyFieldTrialSpdy4GroupNamePrefix[] = "Spdy4Enabled";
139 const char kSpdyFieldTrialParametrizedPrefix[] = "Parametrized";
141 // Field trial for Cache-Control: stale-while-revalidate directive.
142 const char kStaleWhileRevalidateFieldTrialName[] = "StaleWhileRevalidate";
144 #if defined(OS_MACOSX) && !defined(OS_IOS)
145 void ObserveKeychainEvents() {
146 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
147 net::CertDatabase::GetInstance()->SetMessageLoopForKeychainEvents();
149 #endif
151 // Used for the "system" URLRequestContext.
152 class SystemURLRequestContext : public net::URLRequestContext {
153 public:
154 SystemURLRequestContext() {
155 #if defined(USE_NSS) || defined(OS_IOS)
156 net::SetURLRequestContextForNSSHttpIO(this);
157 #endif
160 private:
161 ~SystemURLRequestContext() override {
162 AssertNoURLRequests();
163 #if defined(USE_NSS) || defined(OS_IOS)
164 net::SetURLRequestContextForNSSHttpIO(NULL);
165 #endif
169 scoped_ptr<net::HostResolver> CreateGlobalHostResolver(net::NetLog* net_log) {
170 TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver");
171 const base::CommandLine& command_line =
172 *base::CommandLine::ForCurrentProcess();
174 net::HostResolver::Options options;
176 // Use the retry attempts override from the command-line, if any.
177 if (command_line.HasSwitch(switches::kHostResolverRetryAttempts)) {
178 std::string s =
179 command_line.GetSwitchValueASCII(switches::kHostResolverRetryAttempts);
180 // Parse the switch (it should be a non-negative integer).
181 int n;
182 if (base::StringToInt(s, &n) && n >= 0) {
183 options.max_retry_attempts = static_cast<size_t>(n);
184 } else {
185 LOG(ERROR) << "Invalid switch for host resolver retry attempts: " << s;
189 scoped_ptr<net::HostResolver> global_host_resolver;
190 #if defined OS_CHROMEOS
191 global_host_resolver =
192 chromeos::HostResolverImplChromeOS::CreateSystemResolver(options,
193 net_log);
194 #else
195 global_host_resolver =
196 net::HostResolver::CreateSystemResolver(options, net_log);
197 #endif
199 // Determine if we should disable IPv6 support.
200 if (command_line.HasSwitch(switches::kEnableIPv6)) {
201 // Disable IPv6 probing.
202 global_host_resolver->SetDefaultAddressFamily(
203 net::ADDRESS_FAMILY_UNSPECIFIED);
204 } else if (command_line.HasSwitch(switches::kDisableIPv6)) {
205 global_host_resolver->SetDefaultAddressFamily(net::ADDRESS_FAMILY_IPV4);
208 // If hostname remappings were specified on the command-line, layer these
209 // rules on top of the real host resolver. This allows forwarding all requests
210 // through a designated test server.
211 if (!command_line.HasSwitch(switches::kHostResolverRules))
212 return global_host_resolver.Pass();
214 scoped_ptr<net::MappedHostResolver> remapped_resolver(
215 new net::MappedHostResolver(global_host_resolver.Pass()));
216 remapped_resolver->SetRulesFromString(
217 command_line.GetSwitchValueASCII(switches::kHostResolverRules));
218 return remapped_resolver.Pass();
221 // TODO(willchan): Remove proxy script fetcher context since it's not necessary
222 // now that I got rid of refcounting URLRequestContexts.
223 // See IOThread::Globals for details.
224 net::URLRequestContext*
225 ConstructProxyScriptFetcherContext(IOThread::Globals* globals,
226 net::NetLog* net_log) {
227 net::URLRequestContext* context = new net::URLRequestContext;
228 context->set_net_log(net_log);
229 context->set_host_resolver(globals->host_resolver.get());
230 context->set_cert_verifier(globals->cert_verifier.get());
231 context->set_transport_security_state(
232 globals->transport_security_state.get());
233 context->set_cert_transparency_verifier(
234 globals->cert_transparency_verifier.get());
235 context->set_http_auth_handler_factory(
236 globals->http_auth_handler_factory.get());
237 context->set_proxy_service(globals->proxy_script_fetcher_proxy_service.get());
238 context->set_http_transaction_factory(
239 globals->proxy_script_fetcher_http_transaction_factory.get());
240 context->set_job_factory(
241 globals->proxy_script_fetcher_url_request_job_factory.get());
242 context->set_cookie_store(globals->system_cookie_store.get());
243 context->set_channel_id_service(
244 globals->system_channel_id_service.get());
245 context->set_network_delegate(globals->system_network_delegate.get());
246 context->set_http_user_agent_settings(
247 globals->http_user_agent_settings.get());
248 // TODO(rtenneti): We should probably use HttpServerPropertiesManager for the
249 // system URLRequestContext too. There's no reason this should be tied to a
250 // profile.
251 return context;
254 net::URLRequestContext*
255 ConstructSystemRequestContext(IOThread::Globals* globals,
256 net::NetLog* net_log) {
257 net::URLRequestContext* context = new SystemURLRequestContext;
258 context->set_net_log(net_log);
259 context->set_host_resolver(globals->host_resolver.get());
260 context->set_cert_verifier(globals->cert_verifier.get());
261 context->set_transport_security_state(
262 globals->transport_security_state.get());
263 context->set_cert_transparency_verifier(
264 globals->cert_transparency_verifier.get());
265 context->set_http_auth_handler_factory(
266 globals->http_auth_handler_factory.get());
267 context->set_proxy_service(globals->system_proxy_service.get());
268 context->set_http_transaction_factory(
269 globals->system_http_transaction_factory.get());
270 context->set_job_factory(globals->system_url_request_job_factory.get());
271 context->set_cookie_store(globals->system_cookie_store.get());
272 context->set_channel_id_service(
273 globals->system_channel_id_service.get());
274 context->set_throttler_manager(globals->throttler_manager.get());
275 context->set_network_delegate(globals->system_network_delegate.get());
276 context->set_http_user_agent_settings(
277 globals->http_user_agent_settings.get());
278 return context;
281 int GetSwitchValueAsInt(const base::CommandLine& command_line,
282 const std::string& switch_name) {
283 int value;
284 if (!base::StringToInt(command_line.GetSwitchValueASCII(switch_name),
285 &value)) {
286 return 0;
288 return value;
291 // Returns the value associated with |key| in |params| or "" if the
292 // key is not present in the map.
293 const std::string& GetVariationParam(
294 const std::map<std::string, std::string>& params,
295 const std::string& key) {
296 std::map<std::string, std::string>::const_iterator it = params.find(key);
297 if (it == params.end())
298 return base::EmptyString();
300 return it->second;
303 // Return true if stale-while-revalidate support should be enabled.
304 bool IsStaleWhileRevalidateEnabled(const base::CommandLine& command_line) {
305 if (command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))
306 return true;
307 const std::string group_name =
308 base::FieldTrialList::FindFullName(kStaleWhileRevalidateFieldTrialName);
309 return group_name == "Enabled";
312 bool IsCertificateTransparencyRequiredForEV(
313 const base::CommandLine& command_line) {
314 const std::string group_name =
315 base::FieldTrialList::FindFullName("CTRequiredForEVTrial");
316 if (command_line.HasSwitch(
317 switches::kDisableCertificateTransparencyRequirementForEV))
318 return false;
320 return group_name == "RequirementEnforced";
323 // Parse kUseSpdy command line flag options, which may contain the following:
325 // "off" : Disables SPDY support entirely.
326 // "ssl" : Forces SPDY for all HTTPS requests.
327 // "no-ssl" : Forces SPDY for all HTTP requests.
328 // "no-ping" : Disables SPDY ping connection testing.
329 // "exclude=<host>" : Disables SPDY support for the host <host>.
330 // "no-compress" : Disables SPDY header compression.
331 // "no-alt-protocols : Disables alternate protocol support.
332 // "force-alt-protocols : Forces an alternate protocol of SPDY/3
333 // on port 443.
334 // "single-domain" : Forces all spdy traffic to a single domain.
335 // "init-max-streams=<limit>" : Specifies the maximum number of concurrent
336 // streams for a SPDY session, unless the
337 // specifies a different value via SETTINGS.
338 void ConfigureSpdyGlobalsFromUseSpdyArgument(const std::string& mode,
339 IOThread::Globals* globals) {
340 static const char kOff[] = "off";
341 static const char kSSL[] = "ssl";
342 static const char kDisableSSL[] = "no-ssl";
343 static const char kDisablePing[] = "no-ping";
344 static const char kExclude[] = "exclude"; // Hosts to exclude
345 static const char kDisableCompression[] = "no-compress";
346 static const char kDisableAltProtocols[] = "no-alt-protocols";
347 static const char kSingleDomain[] = "single-domain";
349 static const char kInitialMaxConcurrentStreams[] = "init-max-streams";
351 std::vector<std::string> spdy_options;
352 base::SplitString(mode, ',', &spdy_options);
354 for (const std::string& element : spdy_options) {
355 std::vector<std::string> name_value;
356 base::SplitString(element, '=', &name_value);
357 const std::string& option =
358 name_value.size() > 0 ? name_value[0] : std::string();
359 const std::string value =
360 name_value.size() > 1 ? name_value[1] : std::string();
362 if (option == kOff) {
363 net::HttpStreamFactory::set_spdy_enabled(false);
364 continue;
366 if (option == kDisableSSL) {
367 globals->spdy_default_protocol.set(net::kProtoSPDY31);
368 globals->force_spdy_over_ssl.set(false);
369 globals->force_spdy_always.set(true);
370 continue;
372 if (option == kSSL) {
373 globals->spdy_default_protocol.set(net::kProtoSPDY31);
374 globals->force_spdy_over_ssl.set(true);
375 globals->force_spdy_always.set(true);
376 continue;
378 if (option == kDisablePing) {
379 globals->enable_spdy_ping_based_connection_checking.set(false);
380 continue;
382 if (option == kExclude) {
383 globals->forced_spdy_exclusions.insert(
384 net::HostPortPair::FromURL(GURL(value)));
385 continue;
387 if (option == kDisableCompression) {
388 globals->enable_spdy_compression.set(false);
389 continue;
391 if (option == kDisableAltProtocols) {
392 globals->use_alternate_protocols.set(false);
393 continue;
395 if (option == kSingleDomain) {
396 DVLOG(1) << "FORCING SINGLE DOMAIN";
397 globals->force_spdy_single_domain.set(true);
398 continue;
400 if (option == kInitialMaxConcurrentStreams) {
401 int streams;
402 if (base::StringToInt(value, &streams)) {
403 globals->initial_max_spdy_concurrent_streams.set(streams);
404 continue;
407 LOG(DFATAL) << "Unrecognized spdy option: " << option;
411 } // namespace
413 class IOThread::LoggingNetworkChangeObserver
414 : public net::NetworkChangeNotifier::IPAddressObserver,
415 public net::NetworkChangeNotifier::ConnectionTypeObserver,
416 public net::NetworkChangeNotifier::NetworkChangeObserver {
417 public:
418 // |net_log| must remain valid throughout our lifetime.
419 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
420 : net_log_(net_log) {
421 net::NetworkChangeNotifier::AddIPAddressObserver(this);
422 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
423 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
426 ~LoggingNetworkChangeObserver() override {
427 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
428 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
429 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
432 // NetworkChangeNotifier::IPAddressObserver implementation.
433 void OnIPAddressChanged() override {
434 VLOG(1) << "Observed a change to the network IP addresses";
436 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
439 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
440 void OnConnectionTypeChanged(
441 net::NetworkChangeNotifier::ConnectionType type) override {
442 std::string type_as_string =
443 net::NetworkChangeNotifier::ConnectionTypeToString(type);
445 VLOG(1) << "Observed a change to network connectivity state "
446 << type_as_string;
448 net_log_->AddGlobalEntry(
449 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
450 net::NetLog::StringCallback("new_connection_type", &type_as_string));
453 // NetworkChangeNotifier::NetworkChangeObserver implementation.
454 void OnNetworkChanged(
455 net::NetworkChangeNotifier::ConnectionType type) override {
456 std::string type_as_string =
457 net::NetworkChangeNotifier::ConnectionTypeToString(type);
459 VLOG(1) << "Observed a network change to state " << type_as_string;
461 net_log_->AddGlobalEntry(
462 net::NetLog::TYPE_NETWORK_CHANGED,
463 net::NetLog::StringCallback("new_connection_type", &type_as_string));
466 private:
467 net::NetLog* net_log_;
468 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
471 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
472 public:
473 explicit SystemURLRequestContextGetter(IOThread* io_thread);
475 // Implementation for net::UrlRequestContextGetter.
476 net::URLRequestContext* GetURLRequestContext() override;
477 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
478 const override;
480 protected:
481 ~SystemURLRequestContextGetter() override;
483 private:
484 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
485 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
487 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
490 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
491 IOThread* io_thread)
492 : io_thread_(io_thread),
493 network_task_runner_(
494 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
497 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
499 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
500 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
501 DCHECK(io_thread_->globals()->system_request_context.get());
503 return io_thread_->globals()->system_request_context.get();
506 scoped_refptr<base::SingleThreadTaskRunner>
507 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
508 return network_task_runner_;
511 IOThread::Globals::
512 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
513 Globals* globals)
514 : globals_(globals) {
515 DCHECK(globals_);
518 IOThread::Globals::
519 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
520 if (globals_->system_request_context.get())
521 globals_->system_request_context->AssertNoURLRequests();
524 IOThread::Globals::Globals()
525 : system_request_context_leak_checker(this),
526 ignore_certificate_errors(false),
527 use_stale_while_revalidate(false),
528 testing_fixed_http_port(0),
529 testing_fixed_https_port(0),
530 enable_user_alternate_protocol_ports(false) {
533 IOThread::Globals::~Globals() {}
535 // |local_state| is passed in explicitly in order to (1) reduce implicit
536 // dependencies and (2) make IOThread more flexible for testing.
537 IOThread::IOThread(
538 PrefService* local_state,
539 policy::PolicyService* policy_service,
540 ChromeNetLog* net_log,
541 extensions::EventRouterForwarder* extension_event_router_forwarder)
542 : net_log_(net_log),
543 #if defined(ENABLE_EXTENSIONS)
544 extension_event_router_forwarder_(extension_event_router_forwarder),
545 #endif
546 globals_(NULL),
547 is_spdy_disabled_by_policy_(false),
548 creation_time_(base::TimeTicks::Now()),
549 weak_factory_(this) {
550 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
551 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
552 prefs::kDisableAuthNegotiateCnameLookup);
553 negotiate_enable_port_ = local_state->GetBoolean(
554 prefs::kEnableAuthNegotiatePort);
555 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
556 auth_delegate_whitelist_ = local_state->GetString(
557 prefs::kAuthNegotiateDelegateWhitelist);
558 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
559 pref_proxy_config_tracker_.reset(
560 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
561 local_state));
562 ChromeNetworkDelegate::InitializePrefsOnUIThread(
563 &system_enable_referrers_,
564 NULL,
565 NULL,
566 NULL,
567 NULL,
568 local_state);
569 ssl_config_service_manager_.reset(
570 SSLConfigServiceManager::CreateDefaultManager(local_state));
572 base::Value* dns_client_enabled_default = new base::FundamentalValue(
573 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
574 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
575 dns_client_enabled_default);
576 chrome_browser_net::LogAsyncDnsPrefSource(
577 local_state->FindPreference(prefs::kBuiltInDnsClientEnabled));
579 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
580 local_state,
581 base::Bind(&IOThread::UpdateDnsClientEnabled,
582 base::Unretained(this)));
583 dns_client_enabled_.MoveToThread(
584 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
586 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
587 local_state);
588 quick_check_enabled_.MoveToThread(
589 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
591 #if defined(ENABLE_CONFIGURATION_POLICY)
592 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
593 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
594 policy::key::kDisableSpdy) != NULL;
595 #endif // ENABLE_CONFIGURATION_POLICY
597 BrowserThread::SetDelegate(BrowserThread::IO, this);
600 IOThread::~IOThread() {
601 // This isn't needed for production code, but in tests, IOThread may
602 // be multiply constructed.
603 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
605 pref_proxy_config_tracker_->DetachFromPrefService();
606 DCHECK(!globals_);
609 IOThread::Globals* IOThread::globals() {
610 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
611 return globals_;
614 void IOThread::SetGlobalsForTesting(Globals* globals) {
615 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
616 DCHECK(!globals || !globals_);
617 globals_ = globals;
620 ChromeNetLog* IOThread::net_log() {
621 return net_log_;
624 void IOThread::ChangedToOnTheRecord() {
625 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
626 BrowserThread::PostTask(
627 BrowserThread::IO,
628 FROM_HERE,
629 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
630 base::Unretained(this)));
633 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
634 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
635 if (!system_url_request_context_getter_.get()) {
636 InitSystemRequestContext();
638 return system_url_request_context_getter_.get();
641 void IOThread::Init() {
642 // Prefer to use InitAsync unless you need initialization to block
643 // the UI thread
646 void IOThread::InitAsync() {
647 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
648 // is fixed.
649 tracked_objects::ScopedTracker tracking_profile1(
650 FROM_HERE_WITH_EXPLICIT_FUNCTION("466432 IOThread::InitAsync::Start"));
651 TRACE_EVENT0("startup", "IOThread::InitAsync");
652 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
654 #if defined(USE_NSS) || defined(OS_IOS)
655 net::SetMessageLoopForNSSHttpIO();
656 #endif
658 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
659 // is fixed.
660 tracked_objects::ScopedTracker tracking_profile2(
661 FROM_HERE_WITH_EXPLICIT_FUNCTION(
662 "466432 IOThread::InitAsync::CommandLineForCurrentProcess"));
663 const base::CommandLine& command_line =
664 *base::CommandLine::ForCurrentProcess();
666 DCHECK(!globals_);
667 globals_ = new Globals;
669 // Add an observer that will emit network change events to the ChromeNetLog.
670 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
671 // logging the network change before other IO thread consumers respond to it.
672 network_change_observer_.reset(
673 new LoggingNetworkChangeObserver(net_log_));
675 // Setup the HistogramWatcher to run on the IO thread.
676 net::NetworkChangeNotifier::InitHistogramWatcher();
678 #if defined(ENABLE_EXTENSIONS)
679 globals_->extension_event_router_forwarder =
680 extension_event_router_forwarder_;
681 #endif
683 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
684 // is fixed.
685 tracked_objects::ScopedTracker tracking_profile3(
686 FROM_HERE_WITH_EXPLICIT_FUNCTION(
687 "466432 IOThread::InitAsync::ChromeNetworkDelegate"));
688 scoped_ptr<ChromeNetworkDelegate> chrome_network_delegate(
689 new ChromeNetworkDelegate(extension_event_router_forwarder(),
690 &system_enable_referrers_));
692 #if defined(ENABLE_EXTENSIONS)
693 if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling))
694 chrome_network_delegate->NeverThrottleRequests();
695 #endif
697 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
698 // is fixed.
699 tracked_objects::ScopedTracker tracking_profile4(
700 FROM_HERE_WITH_EXPLICIT_FUNCTION(
701 "466432 IOThread::InitAsync::CreateGlobalHostResolver"));
702 globals_->system_network_delegate = chrome_network_delegate.Pass();
703 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
704 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
705 // is fixed.
706 tracked_objects::ScopedTracker tracking_profile5(
707 FROM_HERE_WITH_EXPLICIT_FUNCTION(
708 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::Start"));
709 UpdateDnsClientEnabled();
710 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
711 // is fixed.
712 tracked_objects::ScopedTracker tracking_profile6(
713 FROM_HERE_WITH_EXPLICIT_FUNCTION(
714 "466432 IOThread::InitAsync::UpdateDnsClientEnabled::End"));
715 #if defined(OS_CHROMEOS)
716 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
717 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
718 new chromeos::CertVerifyProcChromeOS()));
719 #else
720 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
721 net::CertVerifyProc::CreateDefault()));
722 #endif
724 globals_->transport_security_state.reset(new net::TransportSecurityState());
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);
734 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
735 // is fixed.
736 tracked_objects::ScopedTracker tracking_profile8(
737 FROM_HERE_WITH_EXPLICIT_FUNCTION(
738 "466432 IOThread::InitAsync::CreateLogVerifiers::Start"));
739 // Add built-in logs
740 ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
741 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
742 // is fixed.
743 tracked_objects::ScopedTracker tracking_profile9(
744 FROM_HERE_WITH_EXPLICIT_FUNCTION(
745 "466432 IOThread::InitAsync::CreateLogVerifiers::End"));
747 // Add logs from command line
748 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
749 std::string switch_value = command_line.GetSwitchValueASCII(
750 switches::kCertificateTransparencyLog);
751 std::vector<std::string> logs;
752 base::SplitString(switch_value, ',', &logs);
753 for (std::vector<std::string>::iterator it = logs.begin(); it != logs.end();
754 ++it) {
755 const std::string& curr_log = *it;
756 size_t delim_pos = curr_log.find(":");
757 CHECK(delim_pos != std::string::npos)
758 << "CT log description not provided (switch format"
759 " is 'description:base64_key')";
760 std::string log_description(curr_log.substr(0, delim_pos));
761 std::string ct_public_key_data;
762 CHECK(base::Base64Decode(curr_log.substr(delim_pos + 1),
763 &ct_public_key_data))
764 << "Unable to decode CT public key.";
765 scoped_ptr<net::CTLogVerifier> external_log_verifier(
766 net::CTLogVerifier::Create(ct_public_key_data, log_description));
767 CHECK(external_log_verifier) << "Unable to parse CT public key.";
768 VLOG(1) << "Adding log with description " << log_description;
769 ct_verifier->AddLog(external_log_verifier.Pass());
773 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
774 // is fixed.
775 tracked_objects::ScopedTracker tracking_profile10(
776 FROM_HERE_WITH_EXPLICIT_FUNCTION(
777 "466432 IOThread::InitAsync::CertPolicyEnforcer"));
778 net::CertPolicyEnforcer* policy_enforcer = NULL;
779 policy_enforcer = new net::CertPolicyEnforcer(
780 IsCertificateTransparencyRequiredForEV(command_line));
781 globals_->cert_policy_enforcer.reset(policy_enforcer);
783 globals_->ssl_config_service = GetSSLConfigService();
785 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
786 globals_->host_resolver.get()));
787 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
788 // For the ProxyScriptFetcher, we use a direct ProxyService.
789 globals_->proxy_script_fetcher_proxy_service.reset(
790 net::ProxyService::CreateDirectWithNetLog(net_log_));
791 // In-memory cookie store.
792 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
793 // is fixed.
794 tracked_objects::ScopedTracker tracking_profile11(
795 FROM_HERE_WITH_EXPLICIT_FUNCTION(
796 "466432 IOThread::InitAsync::CreateCookieStore::Start"));
797 globals_->system_cookie_store =
798 content::CreateCookieStore(content::CookieStoreConfig());
799 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
800 // is fixed.
801 tracked_objects::ScopedTracker tracking_profile12(
802 FROM_HERE_WITH_EXPLICIT_FUNCTION(
803 "466432 IOThread::InitAsync::CreateCookieStore::End"));
804 // In-memory channel ID store.
805 globals_->system_channel_id_service.reset(
806 new net::ChannelIDService(
807 new net::DefaultChannelIDStore(NULL),
808 base::WorkerPool::GetTaskRunner(true)));
809 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
810 globals_->host_mapping_rules.reset(new net::HostMappingRules());
811 globals_->http_user_agent_settings.reset(
812 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
813 if (command_line.HasSwitch(switches::kHostRules)) {
814 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
815 globals_->host_mapping_rules->SetRulesFromString(
816 command_line.GetSwitchValueASCII(switches::kHostRules));
817 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
819 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
820 globals_->ignore_certificate_errors = true;
821 globals_->use_stale_while_revalidate =
822 IsStaleWhileRevalidateEnabled(command_line);
823 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
824 globals_->testing_fixed_http_port =
825 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
827 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
828 globals_->testing_fixed_https_port =
829 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
831 ConfigureQuic(command_line);
832 if (command_line.HasSwitch(
833 switches::kEnableUserAlternateProtocolPorts)) {
834 globals_->enable_user_alternate_protocol_ports = true;
836 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
837 // is fixed.
838 tracked_objects::ScopedTracker tracking_profile13(
839 FROM_HERE_WITH_EXPLICIT_FUNCTION(
840 "466432 IOThread::InitAsync::InitializeNetworkOptions"));
841 InitializeNetworkOptions(command_line);
843 net::HttpNetworkSession::Params session_params;
844 InitializeNetworkSessionParams(&session_params);
845 session_params.net_log = net_log_;
846 session_params.proxy_service =
847 globals_->proxy_script_fetcher_proxy_service.get();
849 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
850 // is fixed.
851 tracked_objects::ScopedTracker tracking_profile14(
852 FROM_HERE_WITH_EXPLICIT_FUNCTION(
853 "466432 IOThread::InitAsync::HttpNetorkSession::Start"));
854 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession");
855 scoped_refptr<net::HttpNetworkSession> network_session(
856 new net::HttpNetworkSession(session_params));
857 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
858 // is fixed.
859 tracked_objects::ScopedTracker tracking_profile15(
860 FROM_HERE_WITH_EXPLICIT_FUNCTION(
861 "466432 IOThread::InitAsync::HttpNetorkSession::End"));
862 globals_->proxy_script_fetcher_http_transaction_factory
863 .reset(new net::HttpNetworkLayer(network_session.get()));
864 TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession");
865 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
866 new net::URLRequestJobFactoryImpl());
868 // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466432
869 // is fixed.
870 tracked_objects::ScopedTracker tracking_profile16(
871 FROM_HERE_WITH_EXPLICIT_FUNCTION(
872 "466432 IOThread::InitAsync::SetProtocolHandler"));
873 job_factory->SetProtocolHandler(url::kDataScheme,
874 new net::DataProtocolHandler());
875 job_factory->SetProtocolHandler(
876 url::kFileScheme,
877 new net::FileProtocolHandler(
878 content::BrowserThread::GetBlockingPool()->
879 GetTaskRunnerWithShutdownBehavior(
880 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
881 #if !defined(DISABLE_FTP_SUPPORT)
882 globals_->proxy_script_fetcher_ftp_transaction_factory.reset(
883 new net::FtpNetworkLayer(globals_->host_resolver.get()));
884 job_factory->SetProtocolHandler(
885 url::kFtpScheme,
886 new net::FtpProtocolHandler(
887 globals_->proxy_script_fetcher_ftp_transaction_factory.get()));
888 #endif
889 globals_->proxy_script_fetcher_url_request_job_factory = job_factory.Pass();
891 globals_->throttler_manager.reset(new net::URLRequestThrottlerManager());
892 globals_->throttler_manager->set_net_log(net_log_);
893 // Always done in production, disabled only for unit tests.
894 globals_->throttler_manager->set_enable_thread_checks(true);
896 globals_->proxy_script_fetcher_context.reset(
897 ConstructProxyScriptFetcherContext(globals_, net_log_));
899 #if defined(OS_MACOSX) && !defined(OS_IOS)
900 // Start observing Keychain events. This needs to be done on the UI thread,
901 // as Keychain services requires a CFRunLoop.
902 BrowserThread::PostTask(BrowserThread::UI,
903 FROM_HERE,
904 base::Bind(&ObserveKeychainEvents));
905 #endif
907 // InitSystemRequestContext turns right around and posts a task back
908 // to the IO thread, so we can't let it run until we know the IO
909 // thread has started.
911 // Note that since we are at BrowserThread::Init time, the UI thread
912 // is blocked waiting for the thread to start. Therefore, posting
913 // this task to the main thread's message loop here is guaranteed to
914 // get it onto the message loop while the IOThread object still
915 // exists. However, the message might not be processed on the UI
916 // thread until after IOThread is gone, so use a weak pointer.
917 BrowserThread::PostTask(BrowserThread::UI,
918 FROM_HERE,
919 base::Bind(&IOThread::InitSystemRequestContext,
920 weak_factory_.GetWeakPtr()));
923 void IOThread::CleanUp() {
924 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
926 #if defined(USE_NSS) || defined(OS_IOS)
927 net::ShutdownNSSHttpIO();
928 #endif
930 system_url_request_context_getter_ = NULL;
932 // Release objects that the net::URLRequestContext could have been pointing
933 // to.
935 // Shutdown the HistogramWatcher on the IO thread.
936 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
938 // This must be reset before the ChromeNetLog is destroyed.
939 network_change_observer_.reset();
941 system_proxy_config_service_.reset();
943 delete globals_;
944 globals_ = NULL;
946 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
949 void IOThread::InitializeNetworkOptions(const base::CommandLine& command_line) {
950 // Only handle use-spdy command line flags if "spdy.disabled" preference is
951 // not disabled via policy.
952 if (is_spdy_disabled_by_policy_) {
953 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
954 if (trial)
955 trial->Disable();
956 } else {
957 std::string group = base::FieldTrialList::FindFullName(kSpdyFieldTrialName);
958 VariationParameters params;
959 if (!variations::GetVariationParams(kSpdyFieldTrialName, &params)) {
960 params.clear();
962 ConfigureSpdyGlobals(command_line, group, params, globals_);
965 ConfigureTCPFastOpen(command_line);
966 ConfigureSdch();
968 // TODO(rch): Make the client socket factory a per-network session
969 // instance, constructed from a NetworkSession::Params, to allow us
970 // to move this option to IOThread::Globals &
971 // HttpNetworkSession::Params.
974 void IOThread::ConfigureTCPFastOpen(const base::CommandLine& command_line) {
975 const std::string trial_group =
976 base::FieldTrialList::FindFullName(kTCPFastOpenFieldTrialName);
977 if (trial_group == kTCPFastOpenHttpsEnabledGroupName)
978 globals_->enable_tcp_fast_open_for_ssl.set(true);
979 bool always_enable_if_supported =
980 command_line.HasSwitch(switches::kEnableTcpFastOpen);
981 // Check for OS support of TCP FastOpen, and turn it on for all connections
982 // if indicated by user.
983 net::CheckSupportAndMaybeEnableTCPFastOpen(always_enable_if_supported);
986 void IOThread::ConfigureSdch() {
987 // Check SDCH field trial. Default is now that everything is enabled,
988 // so provide options for disabling HTTPS or all of SDCH.
989 const char kSdchFieldTrialName[] = "SDCH";
990 const char kEnabledHttpOnlyGroupName[] = "EnabledHttpOnly";
991 const char kDisabledAllGroupName[] = "DisabledAll";
993 // Store in a string on return to keep underlying storage for
994 // StringPiece stable.
995 std::string sdch_trial_group_string =
996 base::FieldTrialList::FindFullName(kSdchFieldTrialName);
997 base::StringPiece sdch_trial_group(sdch_trial_group_string);
998 if (sdch_trial_group.starts_with(kEnabledHttpOnlyGroupName)) {
999 net::SdchManager::EnableSdchSupport(true);
1000 net::SdchManager::EnableSecureSchemeSupport(false);
1001 } else if (sdch_trial_group.starts_with(kDisabledAllGroupName)) {
1002 net::SdchManager::EnableSdchSupport(false);
1006 // static
1007 void IOThread::ConfigureSpdyGlobals(
1008 const base::CommandLine& command_line,
1009 base::StringPiece spdy_trial_group,
1010 const VariationParameters& spdy_trial_params,
1011 IOThread::Globals* globals) {
1012 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
1013 globals->trusted_spdy_proxy.set(
1014 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
1016 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
1017 net::URLFetcher::SetIgnoreCertificateRequests(true);
1019 if (command_line.HasSwitch(switches::kUseSpdy)) {
1020 std::string spdy_mode =
1021 command_line.GetSwitchValueASCII(switches::kUseSpdy);
1022 ConfigureSpdyGlobalsFromUseSpdyArgument(spdy_mode, globals);
1023 return;
1026 globals->next_protos.clear();
1027 globals->next_protos.push_back(net::kProtoHTTP11);
1028 bool enable_quic = false;
1029 globals->enable_quic.CopyToIfSet(&enable_quic);
1030 if (enable_quic) {
1031 globals->next_protos.push_back(net::kProtoQUIC1SPDY3);
1034 if (command_line.HasSwitch(switches::kEnableSpdy4)) {
1035 globals->next_protos.push_back(net::kProtoSPDY31);
1036 globals->next_protos.push_back(net::kProtoSPDY4_14);
1037 globals->next_protos.push_back(net::kProtoSPDY4);
1038 globals->use_alternate_protocols.set(true);
1039 return;
1041 if (command_line.HasSwitch(switches::kEnableNpnHttpOnly)) {
1042 globals->use_alternate_protocols.set(false);
1043 return;
1046 // No SPDY command-line flags have been specified. Examine trial groups.
1047 if (spdy_trial_group.starts_with(kSpdyFieldTrialHoldbackGroupNamePrefix)) {
1048 net::HttpStreamFactory::set_spdy_enabled(false);
1049 return;
1051 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy31GroupNamePrefix)) {
1052 globals->next_protos.push_back(net::kProtoSPDY31);
1053 globals->use_alternate_protocols.set(true);
1054 return;
1056 if (spdy_trial_group.starts_with(kSpdyFieldTrialSpdy4GroupNamePrefix)) {
1057 globals->next_protos.push_back(net::kProtoSPDY31);
1058 globals->next_protos.push_back(net::kProtoSPDY4_14);
1059 globals->next_protos.push_back(net::kProtoSPDY4);
1060 globals->use_alternate_protocols.set(true);
1061 return;
1063 if (spdy_trial_group.starts_with(kSpdyFieldTrialParametrizedPrefix)) {
1064 bool spdy_enabled = false;
1065 if (LowerCaseEqualsASCII(
1066 GetVariationParam(spdy_trial_params, "enable_spdy31"), "true")) {
1067 globals->next_protos.push_back(net::kProtoSPDY31);
1068 spdy_enabled = true;
1070 if (LowerCaseEqualsASCII(
1071 GetVariationParam(spdy_trial_params, "enable_http2_14"), "true")) {
1072 globals->next_protos.push_back(net::kProtoSPDY4_14);
1073 spdy_enabled = true;
1075 if (LowerCaseEqualsASCII(
1076 GetVariationParam(spdy_trial_params, "enable_http2"), "true")) {
1077 globals->next_protos.push_back(net::kProtoSPDY4);
1078 spdy_enabled = true;
1080 // TODO(bnc): HttpStreamFactory::spdy_enabled_ is redundant with
1081 // globals->next_protos, can it be eliminated?
1082 net::HttpStreamFactory::set_spdy_enabled(spdy_enabled);
1083 globals->use_alternate_protocols.set(true);
1084 return;
1087 // By default, enable HTTP/2.
1088 globals->next_protos.push_back(net::kProtoSPDY31);
1089 globals->next_protos.push_back(net::kProtoSPDY4_14);
1090 globals->next_protos.push_back(net::kProtoSPDY4);
1091 globals->use_alternate_protocols.set(true);
1094 // static
1095 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
1096 registry->RegisterStringPref(prefs::kAuthSchemes,
1097 "basic,digest,ntlm,negotiate,"
1098 "spdyproxy");
1099 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
1100 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
1101 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
1102 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
1103 std::string());
1104 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
1105 registry->RegisterStringPref(
1106 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
1107 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
1108 data_reduction_proxy::RegisterPrefs(registry);
1109 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
1110 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
1113 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
1114 net::HostResolver* resolver) {
1115 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
1116 if (!auth_server_whitelist_.empty()) {
1117 auth_filter_default_credentials =
1118 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
1120 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
1121 if (!auth_delegate_whitelist_.empty()) {
1122 auth_filter_delegate =
1123 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
1125 globals_->url_security_manager.reset(
1126 net::URLSecurityManager::Create(auth_filter_default_credentials,
1127 auth_filter_delegate));
1128 std::vector<std::string> supported_schemes;
1129 base::SplitString(auth_schemes_, ',', &supported_schemes);
1131 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
1132 net::HttpAuthHandlerRegistryFactory::Create(
1133 supported_schemes, globals_->url_security_manager.get(),
1134 resolver, gssapi_library_name_, negotiate_disable_cname_lookup_,
1135 negotiate_enable_port_));
1136 return registry_factory.release();
1139 void IOThread::ClearHostCache() {
1140 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1142 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
1143 if (host_cache)
1144 host_cache->clear();
1147 void IOThread::InitializeNetworkSessionParams(
1148 net::HttpNetworkSession::Params* params) {
1149 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
1152 // static
1153 void IOThread::InitializeNetworkSessionParamsFromGlobals(
1154 const IOThread::Globals& globals,
1155 net::HttpNetworkSession::Params* params) {
1156 params->host_resolver = globals.host_resolver.get();
1157 params->cert_verifier = globals.cert_verifier.get();
1158 params->cert_policy_enforcer = globals.cert_policy_enforcer.get();
1159 params->channel_id_service = globals.system_channel_id_service.get();
1160 params->transport_security_state = globals.transport_security_state.get();
1161 params->ssl_config_service = globals.ssl_config_service.get();
1162 params->http_auth_handler_factory = globals.http_auth_handler_factory.get();
1163 params->http_server_properties =
1164 globals.http_server_properties->GetWeakPtr();
1165 params->network_delegate = globals.system_network_delegate.get();
1166 params->host_mapping_rules = globals.host_mapping_rules.get();
1167 params->ignore_certificate_errors = globals.ignore_certificate_errors;
1168 params->use_stale_while_revalidate = globals.use_stale_while_revalidate;
1169 params->testing_fixed_http_port = globals.testing_fixed_http_port;
1170 params->testing_fixed_https_port = globals.testing_fixed_https_port;
1171 globals.enable_tcp_fast_open_for_ssl.CopyToIfSet(
1172 &params->enable_tcp_fast_open_for_ssl);
1174 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
1175 &params->spdy_initial_max_concurrent_streams);
1176 globals.force_spdy_single_domain.CopyToIfSet(
1177 &params->force_spdy_single_domain);
1178 globals.enable_spdy_compression.CopyToIfSet(
1179 &params->enable_spdy_compression);
1180 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1181 &params->enable_spdy_ping_based_connection_checking);
1182 globals.spdy_default_protocol.CopyToIfSet(
1183 &params->spdy_default_protocol);
1184 params->next_protos = globals.next_protos;
1185 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1186 globals.force_spdy_over_ssl.CopyToIfSet(&params->force_spdy_over_ssl);
1187 globals.force_spdy_always.CopyToIfSet(&params->force_spdy_always);
1188 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1189 globals.use_alternate_protocols.CopyToIfSet(
1190 &params->use_alternate_protocols);
1191 globals.alternate_protocol_probability_threshold.CopyToIfSet(
1192 &params->alternate_protocol_probability_threshold);
1194 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1195 globals.enable_quic_for_proxies.CopyToIfSet(&params->enable_quic_for_proxies);
1196 globals.quic_always_require_handshake_confirmation.CopyToIfSet(
1197 &params->quic_always_require_handshake_confirmation);
1198 globals.quic_disable_connection_pooling.CopyToIfSet(
1199 &params->quic_disable_connection_pooling);
1200 globals.quic_load_server_info_timeout_srtt_multiplier.CopyToIfSet(
1201 &params->quic_load_server_info_timeout_srtt_multiplier);
1202 globals.quic_enable_connection_racing.CopyToIfSet(
1203 &params->quic_enable_connection_racing);
1204 globals.quic_enable_non_blocking_io.CopyToIfSet(
1205 &params->quic_enable_non_blocking_io);
1206 globals.quic_disable_disk_cache.CopyToIfSet(
1207 &params->quic_disable_disk_cache);
1208 globals.quic_max_number_of_lossy_connections.CopyToIfSet(
1209 &params->quic_max_number_of_lossy_connections);
1210 globals.quic_packet_loss_threshold.CopyToIfSet(
1211 &params->quic_packet_loss_threshold);
1212 globals.quic_socket_receive_buffer_size.CopyToIfSet(
1213 &params->quic_socket_receive_buffer_size);
1214 globals.enable_quic_port_selection.CopyToIfSet(
1215 &params->enable_quic_port_selection);
1216 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1217 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1218 globals.quic_supported_versions.CopyToIfSet(
1219 &params->quic_supported_versions);
1220 params->quic_connection_options = globals.quic_connection_options;
1222 globals.origin_to_force_quic_on.CopyToIfSet(
1223 &params->origin_to_force_quic_on);
1224 params->enable_user_alternate_protocol_ports =
1225 globals.enable_user_alternate_protocol_ports;
1228 base::TimeTicks IOThread::creation_time() const {
1229 return creation_time_;
1232 net::SSLConfigService* IOThread::GetSSLConfigService() {
1233 return ssl_config_service_manager_->Get();
1236 void IOThread::ChangedToOnTheRecordOnIOThread() {
1237 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1239 // Clear the host cache to avoid showing entries from the OTR session
1240 // in about:net-internals.
1241 ClearHostCache();
1244 void IOThread::InitSystemRequestContext() {
1245 if (system_url_request_context_getter_.get())
1246 return;
1247 // If we're in unit_tests, IOThread may not be run.
1248 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1249 return;
1250 system_proxy_config_service_.reset(
1251 ProxyServiceFactory::CreateProxyConfigService(
1252 pref_proxy_config_tracker_.get()));
1253 system_url_request_context_getter_ =
1254 new SystemURLRequestContextGetter(this);
1255 // Safe to post an unretained this pointer, since IOThread is
1256 // guaranteed to outlive the IO BrowserThread.
1257 BrowserThread::PostTask(
1258 BrowserThread::IO,
1259 FROM_HERE,
1260 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1261 base::Unretained(this)));
1264 void IOThread::InitSystemRequestContextOnIOThread() {
1265 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1266 DCHECK(!globals_->system_proxy_service.get());
1267 DCHECK(system_proxy_config_service_.get());
1269 const base::CommandLine& command_line =
1270 *base::CommandLine::ForCurrentProcess();
1271 globals_->system_proxy_service.reset(
1272 ProxyServiceFactory::CreateProxyService(
1273 net_log_,
1274 globals_->proxy_script_fetcher_context.get(),
1275 globals_->system_network_delegate.get(),
1276 system_proxy_config_service_.release(),
1277 command_line,
1278 quick_check_enabled_.GetValue()));
1280 net::HttpNetworkSession::Params system_params;
1281 InitializeNetworkSessionParams(&system_params);
1282 system_params.net_log = net_log_;
1283 system_params.proxy_service = globals_->system_proxy_service.get();
1285 globals_->system_http_transaction_factory.reset(
1286 new net::HttpNetworkLayer(
1287 new net::HttpNetworkSession(system_params)));
1288 globals_->system_url_request_job_factory.reset(
1289 new net::URLRequestJobFactoryImpl());
1290 globals_->system_request_context.reset(
1291 ConstructSystemRequestContext(globals_, net_log_));
1292 globals_->system_request_context->set_ssl_config_service(
1293 globals_->ssl_config_service.get());
1294 globals_->system_request_context->set_http_server_properties(
1295 globals_->http_server_properties->GetWeakPtr());
1298 void IOThread::UpdateDnsClientEnabled() {
1299 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1302 void IOThread::ConfigureQuic(const base::CommandLine& command_line) {
1303 // Always fetch the field trial group to ensure it is reported correctly.
1304 // The command line flags will be associated with a group that is reported
1305 // so long as trial is actually queried.
1306 std::string group =
1307 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1308 VariationParameters params;
1309 if (!variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1310 params.clear();
1313 ConfigureQuicGlobals(command_line, group, params, globals_);
1316 // static
1317 void IOThread::ConfigureQuicGlobals(
1318 const base::CommandLine& command_line,
1319 base::StringPiece quic_trial_group,
1320 const VariationParameters& quic_trial_params,
1321 IOThread::Globals* globals) {
1322 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group);
1323 globals->enable_quic.set(enable_quic);
1324 bool enable_quic_for_proxies = ShouldEnableQuicForProxies(command_line,
1325 quic_trial_group);
1326 globals->enable_quic_for_proxies.set(enable_quic_for_proxies);
1327 if (enable_quic) {
1328 globals->quic_always_require_handshake_confirmation.set(
1329 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params));
1330 globals->quic_disable_connection_pooling.set(
1331 ShouldQuicDisableConnectionPooling(quic_trial_params));
1332 int receive_buffer_size = GetQuicSocketReceiveBufferSize(quic_trial_params);
1333 if (receive_buffer_size != 0) {
1334 globals->quic_socket_receive_buffer_size.set(receive_buffer_size);
1336 float load_server_info_timeout_srtt_multiplier =
1337 GetQuicLoadServerInfoTimeoutSrttMultiplier(quic_trial_params);
1338 if (load_server_info_timeout_srtt_multiplier != 0) {
1339 globals->quic_load_server_info_timeout_srtt_multiplier.set(
1340 load_server_info_timeout_srtt_multiplier);
1342 globals->quic_enable_connection_racing.set(
1343 ShouldQuicEnableConnectionRacing(quic_trial_params));
1344 globals->quic_enable_non_blocking_io.set(
1345 ShouldQuicEnableNonBlockingIO(quic_trial_params));
1346 globals->quic_disable_disk_cache.set(
1347 ShouldQuicDisableDiskCache(quic_trial_params));
1348 int max_number_of_lossy_connections = GetQuicMaxNumberOfLossyConnections(
1349 quic_trial_params);
1350 if (max_number_of_lossy_connections != 0) {
1351 globals->quic_max_number_of_lossy_connections.set(
1352 max_number_of_lossy_connections);
1354 float packet_loss_threshold = GetQuicPacketLossThreshold(quic_trial_params);
1355 if (packet_loss_threshold != 0)
1356 globals->quic_packet_loss_threshold.set(packet_loss_threshold);
1357 globals->enable_quic_port_selection.set(
1358 ShouldEnableQuicPortSelection(command_line));
1359 globals->quic_connection_options =
1360 GetQuicConnectionOptions(command_line, quic_trial_params);
1361 if (ShouldEnableQuicPacing(command_line, quic_trial_params)) {
1362 globals->quic_connection_options.push_back(net::kPACE);
1366 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1367 quic_trial_params);
1368 if (max_packet_length != 0) {
1369 globals->quic_max_packet_length.set(max_packet_length);
1372 std::string quic_user_agent_id =
1373 chrome::VersionInfo::GetVersionStringModifier();
1374 if (!quic_user_agent_id.empty())
1375 quic_user_agent_id.push_back(' ');
1376 chrome::VersionInfo version_info;
1377 quic_user_agent_id.append(version_info.ProductNameAndVersionForUserAgent());
1378 globals->quic_user_agent_id.set(quic_user_agent_id);
1380 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1381 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1382 net::QuicVersionVector supported_versions;
1383 supported_versions.push_back(version);
1384 globals->quic_supported_versions.set(supported_versions);
1387 double threshold =
1388 GetAlternateProtocolProbabilityThreshold(command_line, quic_trial_params);
1389 if (threshold >=0 && threshold <= 1) {
1390 globals->alternate_protocol_probability_threshold.set(threshold);
1391 globals->http_server_properties->SetAlternateProtocolProbabilityThreshold(
1392 threshold);
1395 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1396 net::HostPortPair quic_origin =
1397 net::HostPortPair::FromString(
1398 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1399 if (!quic_origin.IsEmpty()) {
1400 globals->origin_to_force_quic_on.set(quic_origin);
1405 bool IOThread::ShouldEnableQuic(const base::CommandLine& command_line,
1406 base::StringPiece quic_trial_group) {
1407 if (command_line.HasSwitch(switches::kDisableQuic))
1408 return false;
1410 if (command_line.HasSwitch(switches::kEnableQuic))
1411 return true;
1413 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1414 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1417 // static
1418 bool IOThread::ShouldEnableQuicForProxies(const base::CommandLine& command_line,
1419 base::StringPiece quic_trial_group) {
1420 return ShouldEnableQuic(command_line, quic_trial_group) ||
1421 ShouldEnableQuicForDataReductionProxy();
1424 // static
1425 bool IOThread::ShouldEnableQuicForDataReductionProxy() {
1426 const base::CommandLine& command_line =
1427 *base::CommandLine::ForCurrentProcess();
1429 if (command_line.HasSwitch(switches::kDisableQuic))
1430 return false;
1432 return data_reduction_proxy::DataReductionProxyParams::
1433 IsIncludedInQuicFieldTrial();
1436 bool IOThread::ShouldEnableQuicPortSelection(
1437 const base::CommandLine& command_line) {
1438 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1439 return false;
1441 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1442 return true;
1444 return false; // Default to disabling port selection on all channels.
1447 bool IOThread::ShouldEnableQuicPacing(
1448 const base::CommandLine& command_line,
1449 const VariationParameters& quic_trial_params) {
1450 if (command_line.HasSwitch(switches::kEnableQuicPacing))
1451 return true;
1453 if (command_line.HasSwitch(switches::kDisableQuicPacing))
1454 return false;
1456 return LowerCaseEqualsASCII(
1457 GetVariationParam(quic_trial_params, "enable_pacing"),
1458 "true");
1461 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1462 const base::CommandLine& command_line,
1463 const VariationParameters& quic_trial_params) {
1464 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1465 return net::QuicUtils::ParseQuicConnectionOptions(
1466 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1469 VariationParameters::const_iterator it =
1470 quic_trial_params.find("connection_options");
1471 if (it == quic_trial_params.end()) {
1472 return net::QuicTagVector();
1475 return net::QuicUtils::ParseQuicConnectionOptions(it->second);
1478 // static
1479 double IOThread::GetAlternateProtocolProbabilityThreshold(
1480 const base::CommandLine& command_line,
1481 const VariationParameters& quic_trial_params) {
1482 double value;
1483 if (command_line.HasSwitch(
1484 switches::kAlternateProtocolProbabilityThreshold)) {
1485 if (base::StringToDouble(
1486 command_line.GetSwitchValueASCII(
1487 switches::kAlternateProtocolProbabilityThreshold),
1488 &value)) {
1489 return value;
1492 if (command_line.HasSwitch(switches::kEnableQuic)) {
1493 return 0;
1495 if (base::StringToDouble(
1496 GetVariationParam(quic_trial_params,
1497 "alternate_protocol_probability_threshold"),
1498 &value)) {
1499 return value;
1501 return -1;
1504 // static
1505 bool IOThread::ShouldQuicAlwaysRequireHandshakeConfirmation(
1506 const VariationParameters& quic_trial_params) {
1507 return LowerCaseEqualsASCII(
1508 GetVariationParam(quic_trial_params,
1509 "always_require_handshake_confirmation"),
1510 "true");
1513 // static
1514 bool IOThread::ShouldQuicDisableConnectionPooling(
1515 const VariationParameters& quic_trial_params) {
1516 return LowerCaseEqualsASCII(
1517 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1518 "true");
1521 // static
1522 float IOThread::GetQuicLoadServerInfoTimeoutSrttMultiplier(
1523 const VariationParameters& quic_trial_params) {
1524 double value;
1525 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1526 "load_server_info_time_to_srtt"),
1527 &value)) {
1528 return (float)value;
1530 return 0.0f;
1533 // static
1534 bool IOThread::ShouldQuicEnableConnectionRacing(
1535 const VariationParameters& quic_trial_params) {
1536 return LowerCaseEqualsASCII(
1537 GetVariationParam(quic_trial_params, "enable_connection_racing"),
1538 "true");
1541 // static
1542 bool IOThread::ShouldQuicEnableNonBlockingIO(
1543 const VariationParameters& quic_trial_params) {
1544 return LowerCaseEqualsASCII(
1545 GetVariationParam(quic_trial_params, "enable_non_blocking_io"),
1546 "true");
1549 // static
1550 bool IOThread::ShouldQuicDisableDiskCache(
1551 const VariationParameters& quic_trial_params) {
1552 return LowerCaseEqualsASCII(
1553 GetVariationParam(quic_trial_params, "disable_disk_cache"), "true");
1556 // static
1557 int IOThread::GetQuicMaxNumberOfLossyConnections(
1558 const VariationParameters& quic_trial_params) {
1559 int value;
1560 if (base::StringToInt(GetVariationParam(quic_trial_params,
1561 "max_number_of_lossy_connections"),
1562 &value)) {
1563 return value;
1565 return 0;
1568 // static
1569 float IOThread::GetQuicPacketLossThreshold(
1570 const VariationParameters& quic_trial_params) {
1571 double value;
1572 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1573 "packet_loss_threshold"),
1574 &value)) {
1575 return (float)value;
1577 return 0.0f;
1580 // static
1581 int IOThread::GetQuicSocketReceiveBufferSize(
1582 const VariationParameters& quic_trial_params) {
1583 int value;
1584 if (base::StringToInt(GetVariationParam(quic_trial_params,
1585 "receive_buffer_size"),
1586 &value)) {
1587 return value;
1589 return 0;
1592 // static
1593 size_t IOThread::GetQuicMaxPacketLength(
1594 const base::CommandLine& command_line,
1595 const VariationParameters& quic_trial_params) {
1596 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1597 unsigned value;
1598 if (!base::StringToUint(
1599 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1600 &value)) {
1601 return 0;
1603 return value;
1606 unsigned value;
1607 if (base::StringToUint(GetVariationParam(quic_trial_params,
1608 "max_packet_length"),
1609 &value)) {
1610 return value;
1612 return 0;
1615 // static
1616 net::QuicVersion IOThread::GetQuicVersion(
1617 const base::CommandLine& command_line,
1618 const VariationParameters& quic_trial_params) {
1619 if (command_line.HasSwitch(switches::kQuicVersion)) {
1620 return ParseQuicVersion(
1621 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1624 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1627 // static
1628 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1629 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1630 for (size_t i = 0; i < supported_versions.size(); ++i) {
1631 net::QuicVersion version = supported_versions[i];
1632 if (net::QuicVersionToString(version) == quic_version) {
1633 return version;
1637 return net::QUIC_VERSION_UNSUPPORTED;