Extract code handling PrinterProviderAPI from PrintPreviewHandler
[chromium-blink-merge.git] / chrome / browser / io_thread.cc
blob41d8709c78e96ec25425124e14cce21aea230a9f
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/metrics/user_metrics.h"
18 #include "base/prefs/pref_registry_simple.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/profiler/scoped_tracker.h"
21 #include "base/stl_util.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_piece.h"
24 #include "base/strings/string_split.h"
25 #include "base/strings/string_util.h"
26 #include "base/threading/sequenced_worker_pool.h"
27 #include "base/threading/thread.h"
28 #include "base/threading/worker_pool.h"
29 #include "base/time/time.h"
30 #include "base/trace_event/trace_event.h"
31 #include "build/build_config.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/net/async_dns_field_trial.h"
34 #include "chrome/browser/net/chrome_net_log.h"
35 #include "chrome/browser/net/chrome_network_delegate.h"
36 #include "chrome/browser/net/connect_interceptor.h"
37 #include "chrome/browser/net/dns_probe_service.h"
38 #include "chrome/browser/net/pref_proxy_config_tracker.h"
39 #include "chrome/browser/net/proxy_service_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_prefs.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/cert/cert_policy_enforcer.h"
52 #include "net/cert/cert_verifier.h"
53 #include "net/cert/cert_verify_proc.h"
54 #include "net/cert/ct_known_logs.h"
55 #include "net/cert/ct_known_logs_static.h"
56 #include "net/cert/ct_log_verifier.h"
57 #include "net/cert/ct_verifier.h"
58 #include "net/cert/multi_log_ct_verifier.h"
59 #include "net/cert/multi_threaded_cert_verifier.h"
60 #include "net/cookies/cookie_store.h"
61 #include "net/dns/host_cache.h"
62 #include "net/dns/host_resolver.h"
63 #include "net/dns/mapped_host_resolver.h"
64 #include "net/ftp/ftp_network_layer.h"
65 #include "net/http/http_auth_filter.h"
66 #include "net/http/http_auth_handler_factory.h"
67 #include "net/http/http_network_layer.h"
68 #include "net/http/http_server_properties_impl.h"
69 #include "net/proxy/proxy_config_service.h"
70 #include "net/proxy/proxy_script_fetcher_impl.h"
71 #include "net/proxy/proxy_service.h"
72 #include "net/quic/crypto/crypto_protocol.h"
73 #include "net/quic/quic_protocol.h"
74 #include "net/quic/quic_utils.h"
75 #include "net/socket/tcp_client_socket.h"
76 #include "net/spdy/spdy_session.h"
77 #include "net/ssl/channel_id_service.h"
78 #include "net/ssl/default_channel_id_store.h"
79 #include "net/url_request/data_protocol_handler.h"
80 #include "net/url_request/file_protocol_handler.h"
81 #include "net/url_request/ftp_protocol_handler.h"
82 #include "net/url_request/static_http_user_agent_settings.h"
83 #include "net/url_request/url_fetcher.h"
84 #include "net/url_request/url_request_context.h"
85 #include "net/url_request/url_request_context_getter.h"
86 #include "net/url_request/url_request_job_factory_impl.h"
87 #include "net/url_request/url_request_throttler_manager.h"
88 #include "url/url_constants.h"
90 #if defined(ENABLE_CONFIGURATION_POLICY)
91 #include "policy/policy_constants.h"
92 #endif
94 #if defined(ENABLE_EXTENSIONS)
95 #include "chrome/browser/extensions/event_router_forwarder.h"
96 #endif
98 #if defined(USE_NSS) || defined(OS_IOS)
99 #include "net/ocsp/nss_ocsp.h"
100 #endif
102 #if defined(OS_ANDROID)
103 #include "base/android/build_info.h"
104 #endif
106 #if defined(OS_CHROMEOS)
107 #include "chrome/browser/chromeos/net/cert_verify_proc_chromeos.h"
108 #include "chromeos/network/host_resolver_impl_chromeos.h"
109 #endif
111 using content::BrowserThread;
113 class SafeBrowsingURLRequestContext;
115 // The IOThread object must outlive any tasks posted to the IO thread before the
116 // Quit task, so base::Bind() calls are not refcounted.
118 namespace {
120 const char kTCPFastOpenFieldTrialName[] = "TCPFastOpen";
121 const char kTCPFastOpenHttpsEnabledGroupName[] = "HttpsEnabled";
123 const char kQuicFieldTrialName[] = "QUIC";
124 const char kQuicFieldTrialEnabledGroupName[] = "Enabled";
125 const char kQuicFieldTrialHttpsEnabledGroupName[] = "HttpsEnabled";
127 // The SPDY trial composes two different trial plus control groups:
128 // * A "holdback" group with SPDY disabled, and corresponding control
129 // (SPDY/3.1). The primary purpose of the holdback group is to encourage site
130 // operators to do feature detection rather than UA-sniffing. As such, this
131 // trial runs continuously.
132 // * A SPDY/4 experiment, for SPDY/4 (aka HTTP/2) vs SPDY/3.1 comparisons and
133 // eventual SPDY/4 deployment.
134 const char kSpdyFieldTrialName[] = "SPDY";
135 const char kSpdyFieldTrialHoldbackGroupNamePrefix[] = "SpdyDisabled";
136 const char kSpdyFieldTrialHoldbackControlGroupName[] = "Control";
137 const char kSpdyFieldTrialSpdy31GroupNamePrefix[] = "Spdy31Enabled";
138 const char kSpdyFieldTrialSpdy4GroupNamePrefix[] = "Spdy4Enabled";
139 const char kSpdyFieldTrialSpdy4ControlGroupName[] = "Spdy4Control";
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 // TODO(michaeln): Remove ScopedTracker below once crbug.com/454983 is fixed.
258 tracked_objects::ScopedTracker tracking_profile(
259 FROM_HERE_WITH_EXPLICIT_FUNCTION(
260 "454983 ConstructSystemRequestContext"));
261 net::URLRequestContext* context = new SystemURLRequestContext;
262 context->set_net_log(net_log);
263 context->set_host_resolver(globals->host_resolver.get());
264 context->set_cert_verifier(globals->cert_verifier.get());
265 context->set_transport_security_state(
266 globals->transport_security_state.get());
267 context->set_cert_transparency_verifier(
268 globals->cert_transparency_verifier.get());
269 context->set_http_auth_handler_factory(
270 globals->http_auth_handler_factory.get());
271 context->set_proxy_service(globals->system_proxy_service.get());
272 context->set_http_transaction_factory(
273 globals->system_http_transaction_factory.get());
274 context->set_job_factory(globals->system_url_request_job_factory.get());
275 context->set_cookie_store(globals->system_cookie_store.get());
276 context->set_channel_id_service(
277 globals->system_channel_id_service.get());
278 context->set_throttler_manager(globals->throttler_manager.get());
279 context->set_network_delegate(globals->system_network_delegate.get());
280 context->set_http_user_agent_settings(
281 globals->http_user_agent_settings.get());
282 return context;
285 int GetSwitchValueAsInt(const base::CommandLine& command_line,
286 const std::string& switch_name) {
287 int value;
288 if (!base::StringToInt(command_line.GetSwitchValueASCII(switch_name),
289 &value)) {
290 return 0;
292 return value;
295 // Returns the value associated with |key| in |params| or "" if the
296 // key is not present in the map.
297 const std::string& GetVariationParam(
298 const std::map<std::string, std::string>& params,
299 const std::string& key) {
300 std::map<std::string, std::string>::const_iterator it = params.find(key);
301 if (it == params.end())
302 return base::EmptyString();
304 return it->second;
307 // Return true if stale-while-revalidate support should be enabled.
308 bool IsStaleWhileRevalidateEnabled(const base::CommandLine& command_line) {
309 if (command_line.HasSwitch(switches::kEnableStaleWhileRevalidate))
310 return true;
311 const std::string group_name =
312 base::FieldTrialList::FindFullName(kStaleWhileRevalidateFieldTrialName);
313 return group_name == "Enabled";
316 bool IsCertificateTransparencyRequiredForEV(
317 const base::CommandLine& command_line) {
318 const std::string group_name =
319 base::FieldTrialList::FindFullName("CTRequiredForEVTrial");
321 if (command_line.HasSwitch(switches::kRequireCTForEV))
322 return true;
324 return group_name == "RequirementEnforced";
327 } // namespace
329 class IOThread::LoggingNetworkChangeObserver
330 : public net::NetworkChangeNotifier::IPAddressObserver,
331 public net::NetworkChangeNotifier::ConnectionTypeObserver,
332 public net::NetworkChangeNotifier::NetworkChangeObserver {
333 public:
334 // |net_log| must remain valid throughout our lifetime.
335 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
336 : net_log_(net_log) {
337 net::NetworkChangeNotifier::AddIPAddressObserver(this);
338 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
339 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
342 ~LoggingNetworkChangeObserver() override {
343 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
344 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
345 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
348 // NetworkChangeNotifier::IPAddressObserver implementation.
349 void OnIPAddressChanged() override {
350 VLOG(1) << "Observed a change to the network IP addresses";
352 net_log_->AddGlobalEntry(net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED);
355 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
356 void OnConnectionTypeChanged(
357 net::NetworkChangeNotifier::ConnectionType type) override {
358 std::string type_as_string =
359 net::NetworkChangeNotifier::ConnectionTypeToString(type);
361 VLOG(1) << "Observed a change to network connectivity state "
362 << type_as_string;
364 net_log_->AddGlobalEntry(
365 net::NetLog::TYPE_NETWORK_CONNECTIVITY_CHANGED,
366 net::NetLog::StringCallback("new_connection_type", &type_as_string));
369 // NetworkChangeNotifier::NetworkChangeObserver implementation.
370 void OnNetworkChanged(
371 net::NetworkChangeNotifier::ConnectionType type) override {
372 std::string type_as_string =
373 net::NetworkChangeNotifier::ConnectionTypeToString(type);
375 VLOG(1) << "Observed a network change to state " << type_as_string;
377 net_log_->AddGlobalEntry(
378 net::NetLog::TYPE_NETWORK_CHANGED,
379 net::NetLog::StringCallback("new_connection_type", &type_as_string));
382 private:
383 net::NetLog* net_log_;
384 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
387 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
388 public:
389 explicit SystemURLRequestContextGetter(IOThread* io_thread);
391 // Implementation for net::UrlRequestContextGetter.
392 net::URLRequestContext* GetURLRequestContext() override;
393 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
394 const override;
396 protected:
397 ~SystemURLRequestContextGetter() override;
399 private:
400 IOThread* const io_thread_; // Weak pointer, owned by BrowserProcess.
401 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
403 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
406 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
407 IOThread* io_thread)
408 : io_thread_(io_thread),
409 network_task_runner_(
410 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) {
413 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
415 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
416 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
417 DCHECK(io_thread_->globals()->system_request_context.get());
419 return io_thread_->globals()->system_request_context.get();
422 scoped_refptr<base::SingleThreadTaskRunner>
423 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
424 return network_task_runner_;
427 IOThread::Globals::
428 SystemRequestContextLeakChecker::SystemRequestContextLeakChecker(
429 Globals* globals)
430 : globals_(globals) {
431 DCHECK(globals_);
434 IOThread::Globals::
435 SystemRequestContextLeakChecker::~SystemRequestContextLeakChecker() {
436 if (globals_->system_request_context.get())
437 globals_->system_request_context->AssertNoURLRequests();
440 IOThread::Globals::Globals()
441 : system_request_context_leak_checker(this),
442 enable_ssl_connect_job_waiting(false),
443 ignore_certificate_errors(false),
444 use_stale_while_revalidate(false),
445 testing_fixed_http_port(0),
446 testing_fixed_https_port(0),
447 enable_user_alternate_protocol_ports(false) {
450 IOThread::Globals::~Globals() {}
452 // |local_state| is passed in explicitly in order to (1) reduce implicit
453 // dependencies and (2) make IOThread more flexible for testing.
454 IOThread::IOThread(
455 PrefService* local_state,
456 policy::PolicyService* policy_service,
457 ChromeNetLog* net_log,
458 extensions::EventRouterForwarder* extension_event_router_forwarder)
459 : net_log_(net_log),
460 #if defined(ENABLE_EXTENSIONS)
461 extension_event_router_forwarder_(extension_event_router_forwarder),
462 #endif
463 globals_(NULL),
464 is_spdy_disabled_by_policy_(false),
465 creation_time_(base::TimeTicks::Now()),
466 weak_factory_(this) {
467 auth_schemes_ = local_state->GetString(prefs::kAuthSchemes);
468 negotiate_disable_cname_lookup_ = local_state->GetBoolean(
469 prefs::kDisableAuthNegotiateCnameLookup);
470 negotiate_enable_port_ = local_state->GetBoolean(
471 prefs::kEnableAuthNegotiatePort);
472 auth_server_whitelist_ = local_state->GetString(prefs::kAuthServerWhitelist);
473 auth_delegate_whitelist_ = local_state->GetString(
474 prefs::kAuthNegotiateDelegateWhitelist);
475 gssapi_library_name_ = local_state->GetString(prefs::kGSSAPILibraryName);
476 pref_proxy_config_tracker_.reset(
477 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
478 local_state));
479 ChromeNetworkDelegate::InitializePrefsOnUIThread(
480 &system_enable_referrers_,
481 NULL,
482 NULL,
483 NULL,
484 NULL,
485 local_state);
486 ssl_config_service_manager_.reset(
487 SSLConfigServiceManager::CreateDefaultManager(local_state));
489 base::Value* dns_client_enabled_default = new base::FundamentalValue(
490 chrome_browser_net::ConfigureAsyncDnsFieldTrial());
491 local_state->SetDefaultPrefValue(prefs::kBuiltInDnsClientEnabled,
492 dns_client_enabled_default);
493 chrome_browser_net::LogAsyncDnsPrefSource(
494 local_state->FindPreference(prefs::kBuiltInDnsClientEnabled));
496 dns_client_enabled_.Init(prefs::kBuiltInDnsClientEnabled,
497 local_state,
498 base::Bind(&IOThread::UpdateDnsClientEnabled,
499 base::Unretained(this)));
500 dns_client_enabled_.MoveToThread(
501 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
503 quick_check_enabled_.Init(prefs::kQuickCheckEnabled,
504 local_state);
505 quick_check_enabled_.MoveToThread(
506 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
508 #if defined(ENABLE_CONFIGURATION_POLICY)
509 is_spdy_disabled_by_policy_ = policy_service->GetPolicies(
510 policy::PolicyNamespace(policy::POLICY_DOMAIN_CHROME, std::string())).Get(
511 policy::key::kDisableSpdy) != NULL;
512 #endif // ENABLE_CONFIGURATION_POLICY
514 BrowserThread::SetDelegate(BrowserThread::IO, this);
517 IOThread::~IOThread() {
518 // This isn't needed for production code, but in tests, IOThread may
519 // be multiply constructed.
520 BrowserThread::SetDelegate(BrowserThread::IO, NULL);
522 pref_proxy_config_tracker_->DetachFromPrefService();
523 DCHECK(!globals_);
526 IOThread::Globals* IOThread::globals() {
527 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
528 return globals_;
531 void IOThread::SetGlobalsForTesting(Globals* globals) {
532 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
533 DCHECK(!globals || !globals_);
534 globals_ = globals;
537 ChromeNetLog* IOThread::net_log() {
538 return net_log_;
541 void IOThread::ChangedToOnTheRecord() {
542 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
543 BrowserThread::PostTask(
544 BrowserThread::IO,
545 FROM_HERE,
546 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
547 base::Unretained(this)));
550 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
551 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
552 if (!system_url_request_context_getter_.get()) {
553 InitSystemRequestContext();
555 return system_url_request_context_getter_.get();
558 void IOThread::Init() {
559 // Prefer to use InitAsync unless you need initialization to block
560 // the UI thread
563 void IOThread::InitAsync() {
564 TRACE_EVENT0("startup", "IOThread::InitAsync");
565 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
567 #if defined(USE_NSS) || defined(OS_IOS)
568 net::SetMessageLoopForNSSHttpIO();
569 #endif
571 const base::CommandLine& command_line =
572 *base::CommandLine::ForCurrentProcess();
574 DCHECK(!globals_);
575 globals_ = new Globals;
577 // Add an observer that will emit network change events to the ChromeNetLog.
578 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
579 // logging the network change before other IO thread consumers respond to it.
580 network_change_observer_.reset(
581 new LoggingNetworkChangeObserver(net_log_));
583 // Setup the HistogramWatcher to run on the IO thread.
584 net::NetworkChangeNotifier::InitHistogramWatcher();
586 #if defined(ENABLE_EXTENSIONS)
587 globals_->extension_event_router_forwarder =
588 extension_event_router_forwarder_;
589 #endif
591 scoped_ptr<ChromeNetworkDelegate> chrome_network_delegate(
592 new ChromeNetworkDelegate(extension_event_router_forwarder(),
593 &system_enable_referrers_));
595 if (command_line.HasSwitch(switches::kEnableClientHints))
596 chrome_network_delegate->SetEnableClientHints();
598 #if defined(ENABLE_EXTENSIONS)
599 if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling))
600 chrome_network_delegate->NeverThrottleRequests();
601 #endif
603 globals_->system_network_delegate = chrome_network_delegate.Pass();
604 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
605 UpdateDnsClientEnabled();
606 #if defined(OS_CHROMEOS)
607 // Creates a CertVerifyProc that doesn't allow any profile-provided certs.
608 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
609 new chromeos::CertVerifyProcChromeOS()));
610 #else
611 globals_->cert_verifier.reset(new net::MultiThreadedCertVerifier(
612 net::CertVerifyProc::CreateDefault()));
613 #endif
615 globals_->transport_security_state.reset(new net::TransportSecurityState());
617 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
618 globals_->cert_transparency_verifier.reset(ct_verifier);
620 // Add built-in logs
621 ct_verifier->AddLogs(net::ct::CreateLogVerifiersForKnownLogs());
623 // Add logs from command line
624 if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) {
625 std::string switch_value = command_line.GetSwitchValueASCII(
626 switches::kCertificateTransparencyLog);
627 std::vector<std::string> logs;
628 base::SplitString(switch_value, ',', &logs);
629 for (std::vector<std::string>::iterator it = logs.begin(); it != logs.end();
630 ++it) {
631 const std::string& curr_log = *it;
632 size_t delim_pos = curr_log.find(":");
633 CHECK(delim_pos != std::string::npos)
634 << "CT log description not provided (switch format"
635 " is 'description:base64_key')";
636 std::string log_description(curr_log.substr(0, delim_pos));
637 std::string ct_public_key_data;
638 CHECK(base::Base64Decode(curr_log.substr(delim_pos + 1),
639 &ct_public_key_data))
640 << "Unable to decode CT public key.";
641 scoped_ptr<net::CTLogVerifier> external_log_verifier(
642 net::CTLogVerifier::Create(ct_public_key_data, log_description));
643 CHECK(external_log_verifier) << "Unable to parse CT public key.";
644 VLOG(1) << "Adding log with description " << log_description;
645 ct_verifier->AddLog(external_log_verifier.Pass());
649 net::CertPolicyEnforcer* policy_enforcer = NULL;
650 policy_enforcer = new net::CertPolicyEnforcer(
651 IsCertificateTransparencyRequiredForEV(command_line));
652 globals_->cert_policy_enforcer.reset(policy_enforcer);
654 globals_->ssl_config_service = GetSSLConfigService();
656 globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory(
657 globals_->host_resolver.get()));
658 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
659 // For the ProxyScriptFetcher, we use a direct ProxyService.
660 globals_->proxy_script_fetcher_proxy_service.reset(
661 net::ProxyService::CreateDirectWithNetLog(net_log_));
662 // In-memory cookie store.
663 globals_->system_cookie_store =
664 content::CreateCookieStore(content::CookieStoreConfig());
665 // In-memory channel ID store.
666 globals_->system_channel_id_service.reset(
667 new net::ChannelIDService(
668 new net::DefaultChannelIDStore(NULL),
669 base::WorkerPool::GetTaskRunner(true)));
670 globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService());
671 globals_->host_mapping_rules.reset(new net::HostMappingRules());
672 globals_->http_user_agent_settings.reset(
673 new net::StaticHttpUserAgentSettings(std::string(), GetUserAgent()));
674 if (command_line.HasSwitch(switches::kHostRules)) {
675 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:SetRulesFromString");
676 globals_->host_mapping_rules->SetRulesFromString(
677 command_line.GetSwitchValueASCII(switches::kHostRules));
678 TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString");
680 if (command_line.HasSwitch(switches::kEnableSSLConnectJobWaiting))
681 globals_->enable_ssl_connect_job_waiting = true;
682 if (command_line.HasSwitch(switches::kIgnoreCertificateErrors))
683 globals_->ignore_certificate_errors = true;
684 globals_->use_stale_while_revalidate =
685 IsStaleWhileRevalidateEnabled(command_line);
686 if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) {
687 globals_->testing_fixed_http_port =
688 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort);
690 if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) {
691 globals_->testing_fixed_https_port =
692 GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort);
694 ConfigureQuic(command_line);
695 if (command_line.HasSwitch(
696 switches::kEnableUserAlternateProtocolPorts)) {
697 globals_->enable_user_alternate_protocol_ports = true;
699 InitializeNetworkOptions(command_line);
701 net::HttpNetworkSession::Params session_params;
702 InitializeNetworkSessionParams(&session_params);
703 session_params.net_log = net_log_;
704 session_params.proxy_service =
705 globals_->proxy_script_fetcher_proxy_service.get();
707 TRACE_EVENT_BEGIN0("startup", "IOThread::InitAsync:HttpNetworkSession");
708 scoped_refptr<net::HttpNetworkSession> network_session(
709 new net::HttpNetworkSession(session_params));
710 globals_->proxy_script_fetcher_http_transaction_factory
711 .reset(new net::HttpNetworkLayer(network_session.get()));
712 TRACE_EVENT_END0("startup", "IOThread::InitAsync:HttpNetworkSession");
713 scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
714 new net::URLRequestJobFactoryImpl());
715 job_factory->SetProtocolHandler(url::kDataScheme,
716 new net::DataProtocolHandler());
717 job_factory->SetProtocolHandler(
718 url::kFileScheme,
719 new net::FileProtocolHandler(
720 content::BrowserThread::GetBlockingPool()->
721 GetTaskRunnerWithShutdownBehavior(
722 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)));
723 #if !defined(DISABLE_FTP_SUPPORT)
724 globals_->proxy_script_fetcher_ftp_transaction_factory.reset(
725 new net::FtpNetworkLayer(globals_->host_resolver.get()));
726 job_factory->SetProtocolHandler(
727 url::kFtpScheme,
728 new net::FtpProtocolHandler(
729 globals_->proxy_script_fetcher_ftp_transaction_factory.get()));
730 #endif
731 globals_->proxy_script_fetcher_url_request_job_factory = job_factory.Pass();
733 globals_->throttler_manager.reset(new net::URLRequestThrottlerManager());
734 globals_->throttler_manager->set_net_log(net_log_);
735 // Always done in production, disabled only for unit tests.
736 globals_->throttler_manager->set_enable_thread_checks(true);
738 globals_->proxy_script_fetcher_context.reset(
739 ConstructProxyScriptFetcherContext(globals_, net_log_));
741 #if defined(OS_MACOSX) && !defined(OS_IOS)
742 // Start observing Keychain events. This needs to be done on the UI thread,
743 // as Keychain services requires a CFRunLoop.
744 BrowserThread::PostTask(BrowserThread::UI,
745 FROM_HERE,
746 base::Bind(&ObserveKeychainEvents));
747 #endif
749 // InitSystemRequestContext turns right around and posts a task back
750 // to the IO thread, so we can't let it run until we know the IO
751 // thread has started.
753 // Note that since we are at BrowserThread::Init time, the UI thread
754 // is blocked waiting for the thread to start. Therefore, posting
755 // this task to the main thread's message loop here is guaranteed to
756 // get it onto the message loop while the IOThread object still
757 // exists. However, the message might not be processed on the UI
758 // thread until after IOThread is gone, so use a weak pointer.
759 BrowserThread::PostTask(BrowserThread::UI,
760 FROM_HERE,
761 base::Bind(&IOThread::InitSystemRequestContext,
762 weak_factory_.GetWeakPtr()));
765 void IOThread::CleanUp() {
766 base::debug::LeakTracker<SafeBrowsingURLRequestContext>::CheckForLeaks();
768 #if defined(USE_NSS) || defined(OS_IOS)
769 net::ShutdownNSSHttpIO();
770 #endif
772 system_url_request_context_getter_ = NULL;
774 // Release objects that the net::URLRequestContext could have been pointing
775 // to.
777 // Shutdown the HistogramWatcher on the IO thread.
778 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
780 // This must be reset before the ChromeNetLog is destroyed.
781 network_change_observer_.reset();
783 system_proxy_config_service_.reset();
785 delete globals_;
786 globals_ = NULL;
788 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
791 void IOThread::InitializeNetworkOptions(const base::CommandLine& command_line) {
792 // Only handle use-spdy command line flags if "spdy.disabled" preference is
793 // not disabled via policy.
794 if (is_spdy_disabled_by_policy_) {
795 base::FieldTrial* trial = base::FieldTrialList::Find(kSpdyFieldTrialName);
796 if (trial)
797 trial->Disable();
798 } else {
799 if (command_line.HasSwitch(switches::kTrustedSpdyProxy)) {
800 globals_->trusted_spdy_proxy.set(
801 command_line.GetSwitchValueASCII(switches::kTrustedSpdyProxy));
803 if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
804 net::URLFetcher::SetIgnoreCertificateRequests(true);
806 if (command_line.HasSwitch(switches::kUseSpdy)) {
807 std::string spdy_mode =
808 command_line.GetSwitchValueASCII(switches::kUseSpdy);
809 EnableSpdy(spdy_mode);
810 } else if (command_line.HasSwitch(switches::kEnableSpdy4)) {
811 globals_->next_protos = net::NextProtosSpdy4Http2();
812 globals_->use_alternate_protocols.set(true);
813 } else if (command_line.HasSwitch(switches::kEnableNpnHttpOnly)) {
814 globals_->next_protos = net::NextProtosHttpOnly();
815 globals_->use_alternate_protocols.set(false);
816 } else {
817 // No SPDY command-line flags have been specified. Examine trial groups.
818 ConfigureSpdyFromTrial(
819 base::FieldTrialList::FindFullName(kSpdyFieldTrialName), globals_);
823 ConfigureTCPFastOpen(command_line);
825 // TODO(rch): Make the client socket factory a per-network session
826 // instance, constructed from a NetworkSession::Params, to allow us
827 // to move this option to IOThread::Globals &
828 // HttpNetworkSession::Params.
831 void IOThread::ConfigureTCPFastOpen(const base::CommandLine& command_line) {
832 const std::string trial_group =
833 base::FieldTrialList::FindFullName(kTCPFastOpenFieldTrialName);
834 if (trial_group == kTCPFastOpenHttpsEnabledGroupName)
835 globals_->enable_tcp_fast_open_for_ssl.set(true);
836 bool always_enable_if_supported =
837 command_line.HasSwitch(switches::kEnableTcpFastOpen);
838 // Check for OS support of TCP FastOpen, and turn it on for all connections
839 // if indicated by user.
840 net::CheckSupportAndMaybeEnableTCPFastOpen(always_enable_if_supported);
843 void IOThread::ConfigureSpdyFromTrial(base::StringPiece spdy_trial_group,
844 Globals* globals) {
845 if (spdy_trial_group.starts_with(kSpdyFieldTrialHoldbackGroupNamePrefix)) {
846 // TODO(jgraettinger): Use net::NextProtosHttpOnly() instead?
847 net::HttpStreamFactory::set_spdy_enabled(false);
848 } else if (spdy_trial_group == kSpdyFieldTrialHoldbackControlGroupName) {
849 // Use the current SPDY default (SPDY/3.1).
850 globals->next_protos = net::NextProtosSpdy31();
851 globals->use_alternate_protocols.set(true);
852 } else if (spdy_trial_group.starts_with(
853 kSpdyFieldTrialSpdy31GroupNamePrefix)) {
854 globals->next_protos = net::NextProtosSpdy31();
855 globals->use_alternate_protocols.set(true);
856 } else if (spdy_trial_group.starts_with(
857 kSpdyFieldTrialSpdy4GroupNamePrefix)) {
858 globals->next_protos = net::NextProtosSpdy4Http2();
859 globals->use_alternate_protocols.set(true);
860 } else if (spdy_trial_group == kSpdyFieldTrialSpdy4ControlGroupName) {
861 // This control group is pinned at SPDY/3.1.
862 globals->next_protos = net::NextProtosSpdy31();
863 globals->use_alternate_protocols.set(true);
864 } else {
865 // By default, enable HTTP/2.
866 globals->next_protos = net::NextProtosSpdy4Http2();
867 globals->use_alternate_protocols.set(true);
871 void IOThread::EnableSpdy(const std::string& mode) {
872 static const char kOff[] = "off";
873 static const char kSSL[] = "ssl";
874 static const char kDisableSSL[] = "no-ssl";
875 static const char kDisablePing[] = "no-ping";
876 static const char kExclude[] = "exclude"; // Hosts to exclude
877 static const char kDisableCompression[] = "no-compress";
878 static const char kDisableAltProtocols[] = "no-alt-protocols";
879 static const char kForceAltProtocols[] = "force-alt-protocols";
880 static const char kSingleDomain[] = "single-domain";
882 static const char kInitialMaxConcurrentStreams[] = "init-max-streams";
884 std::vector<std::string> spdy_options;
885 base::SplitString(mode, ',', &spdy_options);
887 for (std::vector<std::string>::iterator it = spdy_options.begin();
888 it != spdy_options.end(); ++it) {
889 const std::string& element = *it;
890 std::vector<std::string> name_value;
891 base::SplitString(element, '=', &name_value);
892 const std::string& option =
893 name_value.size() > 0 ? name_value[0] : std::string();
894 const std::string value =
895 name_value.size() > 1 ? name_value[1] : std::string();
897 if (option == kOff) {
898 net::HttpStreamFactory::set_spdy_enabled(false);
899 } else if (option == kDisableSSL) {
900 globals_->spdy_default_protocol.set(net::kProtoSPDY31);
901 globals_->force_spdy_over_ssl.set(false);
902 globals_->force_spdy_always.set(true);
903 } else if (option == kSSL) {
904 globals_->spdy_default_protocol.set(net::kProtoSPDY31);
905 globals_->force_spdy_over_ssl.set(true);
906 globals_->force_spdy_always.set(true);
907 } else if (option == kDisablePing) {
908 globals_->enable_spdy_ping_based_connection_checking.set(false);
909 } else if (option == kExclude) {
910 globals_->forced_spdy_exclusions.insert(
911 net::HostPortPair::FromURL(GURL(value)));
912 } else if (option == kDisableCompression) {
913 globals_->enable_spdy_compression.set(false);
914 } else if (option == kDisableAltProtocols) {
915 globals_->use_alternate_protocols.set(false);
916 } else if (option == kForceAltProtocols) {
917 net::AlternateProtocolInfo pair(443, net::NPN_SPDY_3, 1);
918 base::RecordAction(base::UserMetricsAction("Net.ForceAlternateProtocol"));
919 net::HttpServerPropertiesImpl::ForceAlternateProtocol(pair);
920 } else if (option == kSingleDomain) {
921 DVLOG(1) << "FORCING SINGLE DOMAIN";
922 globals_->force_spdy_single_domain.set(true);
923 } else if (option == kInitialMaxConcurrentStreams) {
924 int streams;
925 if (base::StringToInt(value, &streams))
926 globals_->initial_max_spdy_concurrent_streams.set(streams);
927 } else if (option.empty() && it == spdy_options.begin()) {
928 continue;
929 } else {
930 LOG(DFATAL) << "Unrecognized spdy option: " << option;
935 // static
936 void IOThread::RegisterPrefs(PrefRegistrySimple* registry) {
937 registry->RegisterStringPref(prefs::kAuthSchemes,
938 "basic,digest,ntlm,negotiate,"
939 "spdyproxy");
940 registry->RegisterBooleanPref(prefs::kDisableAuthNegotiateCnameLookup, false);
941 registry->RegisterBooleanPref(prefs::kEnableAuthNegotiatePort, false);
942 registry->RegisterStringPref(prefs::kAuthServerWhitelist, std::string());
943 registry->RegisterStringPref(prefs::kAuthNegotiateDelegateWhitelist,
944 std::string());
945 registry->RegisterStringPref(prefs::kGSSAPILibraryName, std::string());
946 registry->RegisterStringPref(
947 data_reduction_proxy::prefs::kDataReductionProxy, std::string());
948 registry->RegisterBooleanPref(prefs::kEnableReferrers, true);
949 data_reduction_proxy::RegisterPrefs(registry);
950 registry->RegisterBooleanPref(prefs::kBuiltInDnsClientEnabled, true);
951 registry->RegisterBooleanPref(prefs::kQuickCheckEnabled, true);
954 net::HttpAuthHandlerFactory* IOThread::CreateDefaultAuthHandlerFactory(
955 net::HostResolver* resolver) {
956 net::HttpAuthFilterWhitelist* auth_filter_default_credentials = NULL;
957 if (!auth_server_whitelist_.empty()) {
958 auth_filter_default_credentials =
959 new net::HttpAuthFilterWhitelist(auth_server_whitelist_);
961 net::HttpAuthFilterWhitelist* auth_filter_delegate = NULL;
962 if (!auth_delegate_whitelist_.empty()) {
963 auth_filter_delegate =
964 new net::HttpAuthFilterWhitelist(auth_delegate_whitelist_);
966 globals_->url_security_manager.reset(
967 net::URLSecurityManager::Create(auth_filter_default_credentials,
968 auth_filter_delegate));
969 std::vector<std::string> supported_schemes;
970 base::SplitString(auth_schemes_, ',', &supported_schemes);
972 scoped_ptr<net::HttpAuthHandlerRegistryFactory> registry_factory(
973 net::HttpAuthHandlerRegistryFactory::Create(
974 supported_schemes, globals_->url_security_manager.get(),
975 resolver, gssapi_library_name_, negotiate_disable_cname_lookup_,
976 negotiate_enable_port_));
977 return registry_factory.release();
980 void IOThread::ClearHostCache() {
981 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
983 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
984 if (host_cache)
985 host_cache->clear();
988 void IOThread::InitializeNetworkSessionParams(
989 net::HttpNetworkSession::Params* params) {
990 // TODO(michaeln): Remove ScopedTracker below once crbug.com/454983 is fixed.
991 tracked_objects::ScopedTracker tracking_profile(
992 FROM_HERE_WITH_EXPLICIT_FUNCTION(
993 "454983 IOThread::InitializeNetworkSessionParams"));
994 InitializeNetworkSessionParamsFromGlobals(*globals_, params);
997 // static
998 void IOThread::InitializeNetworkSessionParamsFromGlobals(
999 const IOThread::Globals& globals,
1000 net::HttpNetworkSession::Params* params) {
1001 params->host_resolver = globals.host_resolver.get();
1002 params->cert_verifier = globals.cert_verifier.get();
1003 params->cert_policy_enforcer = globals.cert_policy_enforcer.get();
1004 params->channel_id_service = globals.system_channel_id_service.get();
1005 params->transport_security_state = globals.transport_security_state.get();
1006 params->ssl_config_service = globals.ssl_config_service.get();
1007 params->http_auth_handler_factory = globals.http_auth_handler_factory.get();
1008 params->http_server_properties =
1009 globals.http_server_properties->GetWeakPtr();
1010 params->network_delegate = globals.system_network_delegate.get();
1011 params->host_mapping_rules = globals.host_mapping_rules.get();
1012 params->enable_ssl_connect_job_waiting =
1013 globals.enable_ssl_connect_job_waiting;
1014 params->ignore_certificate_errors = globals.ignore_certificate_errors;
1015 params->use_stale_while_revalidate = globals.use_stale_while_revalidate;
1016 params->testing_fixed_http_port = globals.testing_fixed_http_port;
1017 params->testing_fixed_https_port = globals.testing_fixed_https_port;
1018 globals.enable_tcp_fast_open_for_ssl.CopyToIfSet(
1019 &params->enable_tcp_fast_open_for_ssl);
1021 globals.initial_max_spdy_concurrent_streams.CopyToIfSet(
1022 &params->spdy_initial_max_concurrent_streams);
1023 globals.force_spdy_single_domain.CopyToIfSet(
1024 &params->force_spdy_single_domain);
1025 globals.enable_spdy_compression.CopyToIfSet(
1026 &params->enable_spdy_compression);
1027 globals.enable_spdy_ping_based_connection_checking.CopyToIfSet(
1028 &params->enable_spdy_ping_based_connection_checking);
1029 globals.spdy_default_protocol.CopyToIfSet(
1030 &params->spdy_default_protocol);
1031 params->next_protos = globals.next_protos;
1032 globals.trusted_spdy_proxy.CopyToIfSet(&params->trusted_spdy_proxy);
1033 globals.force_spdy_over_ssl.CopyToIfSet(&params->force_spdy_over_ssl);
1034 globals.force_spdy_always.CopyToIfSet(&params->force_spdy_always);
1035 params->forced_spdy_exclusions = globals.forced_spdy_exclusions;
1036 globals.use_alternate_protocols.CopyToIfSet(
1037 &params->use_alternate_protocols);
1038 globals.alternate_protocol_probability_threshold.CopyToIfSet(
1039 &params->alternate_protocol_probability_threshold);
1041 globals.enable_quic.CopyToIfSet(&params->enable_quic);
1042 globals.quic_always_require_handshake_confirmation.CopyToIfSet(
1043 &params->quic_always_require_handshake_confirmation);
1044 globals.quic_disable_connection_pooling.CopyToIfSet(
1045 &params->quic_disable_connection_pooling);
1046 globals.quic_load_server_info_timeout_ms.CopyToIfSet(
1047 &params->quic_load_server_info_timeout_ms);
1048 globals.quic_load_server_info_timeout_srtt_multiplier.CopyToIfSet(
1049 &params->quic_load_server_info_timeout_srtt_multiplier);
1050 globals.quic_enable_truncated_connection_ids.CopyToIfSet(
1051 &params->quic_enable_truncated_connection_ids);
1052 globals.quic_enable_connection_racing.CopyToIfSet(
1053 &params->quic_enable_connection_racing);
1054 globals.enable_quic_port_selection.CopyToIfSet(
1055 &params->enable_quic_port_selection);
1056 globals.quic_max_packet_length.CopyToIfSet(&params->quic_max_packet_length);
1057 globals.quic_user_agent_id.CopyToIfSet(&params->quic_user_agent_id);
1058 globals.quic_supported_versions.CopyToIfSet(
1059 &params->quic_supported_versions);
1060 params->quic_connection_options = globals.quic_connection_options;
1062 globals.origin_to_force_quic_on.CopyToIfSet(
1063 &params->origin_to_force_quic_on);
1064 params->enable_user_alternate_protocol_ports =
1065 globals.enable_user_alternate_protocol_ports;
1068 base::TimeTicks IOThread::creation_time() const {
1069 return creation_time_;
1072 net::SSLConfigService* IOThread::GetSSLConfigService() {
1073 return ssl_config_service_manager_->Get();
1076 void IOThread::ChangedToOnTheRecordOnIOThread() {
1077 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1079 // Clear the host cache to avoid showing entries from the OTR session
1080 // in about:net-internals.
1081 ClearHostCache();
1084 void IOThread::InitSystemRequestContext() {
1085 if (system_url_request_context_getter_.get())
1086 return;
1087 // If we're in unit_tests, IOThread may not be run.
1088 if (!BrowserThread::IsMessageLoopValid(BrowserThread::IO))
1089 return;
1090 system_proxy_config_service_.reset(
1091 ProxyServiceFactory::CreateProxyConfigService(
1092 pref_proxy_config_tracker_.get()));
1093 system_url_request_context_getter_ =
1094 new SystemURLRequestContextGetter(this);
1095 // Safe to post an unretained this pointer, since IOThread is
1096 // guaranteed to outlive the IO BrowserThread.
1097 BrowserThread::PostTask(
1098 BrowserThread::IO,
1099 FROM_HERE,
1100 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
1101 base::Unretained(this)));
1104 void IOThread::InitSystemRequestContextOnIOThread() {
1105 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1106 DCHECK(!globals_->system_proxy_service.get());
1107 DCHECK(system_proxy_config_service_.get());
1109 const base::CommandLine& command_line =
1110 *base::CommandLine::ForCurrentProcess();
1111 globals_->system_proxy_service.reset(
1112 ProxyServiceFactory::CreateProxyService(
1113 net_log_,
1114 globals_->proxy_script_fetcher_context.get(),
1115 globals_->system_network_delegate.get(),
1116 system_proxy_config_service_.release(),
1117 command_line,
1118 quick_check_enabled_.GetValue()));
1120 net::HttpNetworkSession::Params system_params;
1121 InitializeNetworkSessionParams(&system_params);
1122 system_params.net_log = net_log_;
1123 system_params.proxy_service = globals_->system_proxy_service.get();
1126 // TODO(michaeln): Remove after crbug.com/454983 is fixed.
1127 tracked_objects::ScopedTracker tracking_profile(
1128 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1129 "454983 IOThread::InitSystemRequestContextOnIOThread"
1130 ".HttpNetworkSession"));
1131 globals_->system_http_transaction_factory.reset(
1132 new net::HttpNetworkLayer(
1133 new net::HttpNetworkSession(system_params)));
1135 globals_->system_url_request_job_factory.reset(
1136 new net::URLRequestJobFactoryImpl());
1137 globals_->system_request_context.reset(
1138 ConstructSystemRequestContext(globals_, net_log_));
1139 globals_->system_request_context->set_ssl_config_service(
1140 globals_->ssl_config_service.get());
1141 globals_->system_request_context->set_http_server_properties(
1142 globals_->http_server_properties->GetWeakPtr());
1145 void IOThread::UpdateDnsClientEnabled() {
1146 globals()->host_resolver->SetDnsClientEnabled(*dns_client_enabled_);
1149 void IOThread::ConfigureQuic(const base::CommandLine& command_line) {
1150 // Always fetch the field trial group to ensure it is reported correctly.
1151 // The command line flags will be associated with a group that is reported
1152 // so long as trial is actually queried.
1153 std::string group =
1154 base::FieldTrialList::FindFullName(kQuicFieldTrialName);
1155 VariationParameters params;
1156 if (!variations::GetVariationParams(kQuicFieldTrialName, &params)) {
1157 params.clear();
1160 ConfigureQuicGlobals(command_line, group, params, globals_);
1163 // static
1164 void IOThread::ConfigureQuicGlobals(
1165 const base::CommandLine& command_line,
1166 base::StringPiece quic_trial_group,
1167 const VariationParameters& quic_trial_params,
1168 IOThread::Globals* globals) {
1169 bool enable_quic = ShouldEnableQuic(command_line, quic_trial_group);
1170 globals->enable_quic.set(enable_quic);
1171 if (enable_quic) {
1172 globals->quic_always_require_handshake_confirmation.set(
1173 ShouldQuicAlwaysRequireHandshakeConfirmation(quic_trial_params));
1174 globals->quic_disable_connection_pooling.set(
1175 ShouldQuicDisableConnectionPooling(quic_trial_params));
1176 int load_server_info_timeout_ms =
1177 GetQuicLoadServerInfoTimeout(quic_trial_params);
1178 if (load_server_info_timeout_ms != 0) {
1179 globals->quic_load_server_info_timeout_ms.set(
1180 load_server_info_timeout_ms);
1182 float load_server_info_timeout_srtt_multiplier =
1183 GetQuicLoadServerInfoTimeoutSrttMultiplier(quic_trial_params);
1184 globals->quic_enable_truncated_connection_ids.set(
1185 ShouldQuicEnableTruncatedConnectionIds(quic_trial_params));
1186 globals->quic_enable_connection_racing.set(
1187 ShouldQuicEnableConnectionRacing(quic_trial_params));
1188 if (load_server_info_timeout_srtt_multiplier != 0) {
1189 globals->quic_load_server_info_timeout_srtt_multiplier.set(
1190 load_server_info_timeout_srtt_multiplier);
1192 globals->enable_quic_port_selection.set(
1193 ShouldEnableQuicPortSelection(command_line));
1194 globals->quic_connection_options =
1195 GetQuicConnectionOptions(command_line, quic_trial_params);
1196 if (ShouldEnableQuicPacing(command_line, quic_trial_params)) {
1197 globals->quic_connection_options.push_back(net::kPACE);
1201 size_t max_packet_length = GetQuicMaxPacketLength(command_line,
1202 quic_trial_params);
1203 if (max_packet_length != 0) {
1204 globals->quic_max_packet_length.set(max_packet_length);
1207 std::string quic_user_agent_id =
1208 chrome::VersionInfo::GetVersionStringModifier();
1209 if (!quic_user_agent_id.empty())
1210 quic_user_agent_id.push_back(' ');
1211 chrome::VersionInfo version_info;
1212 quic_user_agent_id.append(version_info.ProductNameAndVersionForUserAgent());
1213 globals->quic_user_agent_id.set(quic_user_agent_id);
1215 net::QuicVersion version = GetQuicVersion(command_line, quic_trial_params);
1216 if (version != net::QUIC_VERSION_UNSUPPORTED) {
1217 net::QuicVersionVector supported_versions;
1218 supported_versions.push_back(version);
1219 globals->quic_supported_versions.set(supported_versions);
1222 double threshold =
1223 GetAlternateProtocolProbabilityThreshold(command_line, quic_trial_params);
1224 if (threshold >=0 && threshold <= 1) {
1225 globals->alternate_protocol_probability_threshold.set(threshold);
1226 globals->http_server_properties->SetAlternateProtocolProbabilityThreshold(
1227 threshold);
1230 if (command_line.HasSwitch(switches::kOriginToForceQuicOn)) {
1231 net::HostPortPair quic_origin =
1232 net::HostPortPair::FromString(
1233 command_line.GetSwitchValueASCII(switches::kOriginToForceQuicOn));
1234 if (!quic_origin.IsEmpty()) {
1235 globals->origin_to_force_quic_on.set(quic_origin);
1240 bool IOThread::ShouldEnableQuic(const base::CommandLine& command_line,
1241 base::StringPiece quic_trial_group) {
1242 if (command_line.HasSwitch(switches::kDisableQuic))
1243 return false;
1245 if (command_line.HasSwitch(switches::kEnableQuic))
1246 return true;
1248 return quic_trial_group.starts_with(kQuicFieldTrialEnabledGroupName) ||
1249 quic_trial_group.starts_with(kQuicFieldTrialHttpsEnabledGroupName);
1252 bool IOThread::ShouldEnableQuicPortSelection(
1253 const base::CommandLine& command_line) {
1254 if (command_line.HasSwitch(switches::kDisableQuicPortSelection))
1255 return false;
1257 if (command_line.HasSwitch(switches::kEnableQuicPortSelection))
1258 return true;
1260 return false; // Default to disabling port selection on all channels.
1263 bool IOThread::ShouldEnableQuicPacing(
1264 const base::CommandLine& command_line,
1265 const VariationParameters& quic_trial_params) {
1266 if (command_line.HasSwitch(switches::kEnableQuicPacing))
1267 return true;
1269 if (command_line.HasSwitch(switches::kDisableQuicPacing))
1270 return false;
1272 return LowerCaseEqualsASCII(
1273 GetVariationParam(quic_trial_params, "enable_pacing"),
1274 "true");
1277 net::QuicTagVector IOThread::GetQuicConnectionOptions(
1278 const base::CommandLine& command_line,
1279 const VariationParameters& quic_trial_params) {
1280 if (command_line.HasSwitch(switches::kQuicConnectionOptions)) {
1281 return net::QuicUtils::ParseQuicConnectionOptions(
1282 command_line.GetSwitchValueASCII(switches::kQuicConnectionOptions));
1285 VariationParameters::const_iterator it =
1286 quic_trial_params.find("connection_options");
1287 if (it == quic_trial_params.end()) {
1288 return net::QuicTagVector();
1291 return net::QuicUtils::ParseQuicConnectionOptions(it->second);
1294 // static
1295 double IOThread::GetAlternateProtocolProbabilityThreshold(
1296 const base::CommandLine& command_line,
1297 const VariationParameters& quic_trial_params) {
1298 double value;
1299 if (command_line.HasSwitch(
1300 switches::kAlternateProtocolProbabilityThreshold)) {
1301 if (base::StringToDouble(
1302 command_line.GetSwitchValueASCII(
1303 switches::kAlternateProtocolProbabilityThreshold),
1304 &value)) {
1305 return value;
1308 if (command_line.HasSwitch(switches::kEnableQuic)) {
1309 return 0;
1311 if (base::StringToDouble(
1312 GetVariationParam(quic_trial_params,
1313 "alternate_protocol_probability_threshold"),
1314 &value)) {
1315 return value;
1317 return -1;
1320 // static
1321 bool IOThread::ShouldQuicAlwaysRequireHandshakeConfirmation(
1322 const VariationParameters& quic_trial_params) {
1323 return LowerCaseEqualsASCII(
1324 GetVariationParam(quic_trial_params,
1325 "always_require_handshake_confirmation"),
1326 "true");
1329 // static
1330 bool IOThread::ShouldQuicDisableConnectionPooling(
1331 const VariationParameters& quic_trial_params) {
1332 return LowerCaseEqualsASCII(
1333 GetVariationParam(quic_trial_params, "disable_connection_pooling"),
1334 "true");
1337 // static
1338 int IOThread::GetQuicLoadServerInfoTimeout(
1339 const VariationParameters& quic_trial_params) {
1340 int value;
1341 if (base::StringToInt(GetVariationParam(quic_trial_params,
1342 "load_server_info_timeout"),
1343 &value)) {
1344 return value;
1346 return 0;
1349 // static
1350 float IOThread::GetQuicLoadServerInfoTimeoutSrttMultiplier(
1351 const VariationParameters& quic_trial_params) {
1352 double value;
1353 if (base::StringToDouble(GetVariationParam(quic_trial_params,
1354 "load_server_info_time_to_srtt"),
1355 &value)) {
1356 return (float)value;
1358 return 0.0f;
1361 // static
1362 bool IOThread::ShouldQuicEnableTruncatedConnectionIds(
1363 const VariationParameters& quic_trial_params) {
1364 return LowerCaseEqualsASCII(
1365 GetVariationParam(quic_trial_params, "enable_truncated_connection_ids"),
1366 "true");
1369 // static
1370 bool IOThread::ShouldQuicEnableConnectionRacing(
1371 const VariationParameters& quic_trial_params) {
1372 return LowerCaseEqualsASCII(
1373 GetVariationParam(quic_trial_params, "enable_connection_racing"),
1374 "true");
1377 // static
1378 size_t IOThread::GetQuicMaxPacketLength(
1379 const base::CommandLine& command_line,
1380 const VariationParameters& quic_trial_params) {
1381 if (command_line.HasSwitch(switches::kQuicMaxPacketLength)) {
1382 unsigned value;
1383 if (!base::StringToUint(
1384 command_line.GetSwitchValueASCII(switches::kQuicMaxPacketLength),
1385 &value)) {
1386 return 0;
1388 return value;
1391 unsigned value;
1392 if (base::StringToUint(GetVariationParam(quic_trial_params,
1393 "max_packet_length"),
1394 &value)) {
1395 return value;
1397 return 0;
1400 // static
1401 net::QuicVersion IOThread::GetQuicVersion(
1402 const base::CommandLine& command_line,
1403 const VariationParameters& quic_trial_params) {
1404 if (command_line.HasSwitch(switches::kQuicVersion)) {
1405 return ParseQuicVersion(
1406 command_line.GetSwitchValueASCII(switches::kQuicVersion));
1409 return ParseQuicVersion(GetVariationParam(quic_trial_params, "quic_version"));
1412 // static
1413 net::QuicVersion IOThread::ParseQuicVersion(const std::string& quic_version) {
1414 net::QuicVersionVector supported_versions = net::QuicSupportedVersions();
1415 for (size_t i = 0; i < supported_versions.size(); ++i) {
1416 net::QuicVersion version = supported_versions[i];
1417 if (net::QuicVersionToString(version) == quic_version) {
1418 return version;
1422 return net::QUIC_VERSION_UNSUPPORTED;