Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(202)

Side by Side Diff: ios/components/io_thread/io_thread.mm

Issue 2894483003: Initialize ios/web_view translate with a system-wide URLRequestContext. (Closed)
Patch Set: Remove unneeded deps. Created 3 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ios/components/io_thread/io_thread.h"
6
7 #include <stddef.h>
8
9 #include <utility>
10 #include <vector>
11
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/compiler_specific.h"
15 #include "base/debug/leak_tracker.h"
16 #include "base/environment.h"
17 #include "base/logging.h"
18 #include "base/macros.h"
19 #include "base/memory/ptr_util.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/stl_util.h"
22 #include "base/strings/string_number_conversions.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/time/time.h"
28 #include "base/trace_event/trace_event.h"
29 #include "components/net_log/chrome_net_log.h"
30 #include "components/network_session_configurator/network_session_configurator.h "
31 #include "components/prefs/pref_service.h"
32 #include "components/proxy_config/ios/proxy_service_factory.h"
33 #include "components/proxy_config/pref_proxy_config_tracker.h"
34 #include "components/variations/variations_associated_data.h"
35 #include "components/version_info/version_info.h"
36 #include "ios/web/public/user_agent.h"
37 #include "ios/web/public/web_client.h"
38 #include "ios/web/public/web_thread.h"
39 #include "net/base/sdch_manager.h"
40 #include "net/cert/cert_verifier.h"
41 #include "net/cert/ct_known_logs.h"
42 #include "net/cert/ct_log_verifier.h"
43 #include "net/cert/ct_policy_enforcer.h"
44 #include "net/cert/ct_verifier.h"
45 #include "net/cert/multi_log_ct_verifier.h"
46 #include "net/cert/multi_threaded_cert_verifier.h"
47 #include "net/cookies/cookie_monster.h"
48 #include "net/cookies/cookie_store.h"
49 #include "net/dns/host_cache.h"
50 #include "net/dns/host_resolver.h"
51 #include "net/http/http_auth_filter.h"
52 #include "net/http/http_auth_handler_factory.h"
53 #include "net/http/http_auth_preferences.h"
54 #include "net/http/http_network_layer.h"
55 #include "net/http/http_server_properties_impl.h"
56 #include "net/log/net_log_event_type.h"
57 #include "net/nqe/external_estimate_provider.h"
58 #include "net/nqe/network_quality_estimator.h"
59 #include "net/proxy/proxy_config_service.h"
60 #include "net/proxy/proxy_script_fetcher_impl.h"
61 #include "net/proxy/proxy_service.h"
62 #include "net/socket/tcp_client_socket.h"
63 #include "net/spdy/chromium/spdy_session.h"
64 #include "net/ssl/channel_id_service.h"
65 #include "net/ssl/default_channel_id_store.h"
66 #include "net/url_request/data_protocol_handler.h"
67 #include "net/url_request/file_protocol_handler.h"
68 #include "net/url_request/static_http_user_agent_settings.h"
69 #include "net/url_request/url_request_context.h"
70 #include "net/url_request/url_request_context_builder.h"
71 #include "net/url_request/url_request_context_getter.h"
72 #include "net/url_request/url_request_job_factory_impl.h"
73 #include "url/url_constants.h"
74
75 #if !defined(__has_feature) || !__has_feature(objc_arc)
76 #error "This file requires ARC support."
77 #endif
78
79 // The IOThread object must outlive any tasks posted to the IO thread
80 // before the Quit task, so base::Bind() calls are not refcounted.
81
82 namespace {
83
84 const char kSupportedAuthSchemes[] = "basic,digest,ntlm";
85
86 // Field trial for network quality estimator. Seeds RTT and downstream
87 // throughput observations with values that correspond to the connection type
88 // determined by the operating system.
89 const char kNetworkQualityEstimatorFieldTrialName[] = "NetworkQualityEstimator";
90
91 } // namespace
92
93 namespace io_thread {
94
95 // Used for the "system" URLRequestContext.
96 class SystemURLRequestContext : public net::URLRequestContext {
97 public:
98 SystemURLRequestContext() = default;
99
100 private:
101 ~SystemURLRequestContext() override { AssertNoURLRequests(); }
102 };
103
104 std::unique_ptr<net::HostResolver> CreateGlobalHostResolver(
105 net::NetLog* net_log) {
106 TRACE_EVENT0("startup", "IOThread::CreateGlobalHostResolver");
107
108 std::unique_ptr<net::HostResolver> global_host_resolver =
109 net::HostResolver::CreateSystemResolver(net::HostResolver::Options(),
110 net_log);
111
112 return global_host_resolver;
113 }
114
115 class IOThread::LoggingNetworkChangeObserver
116 : public net::NetworkChangeNotifier::IPAddressObserver,
117 public net::NetworkChangeNotifier::ConnectionTypeObserver,
118 public net::NetworkChangeNotifier::NetworkChangeObserver {
119 public:
120 // |net_log| must remain valid throughout our lifetime.
121 explicit LoggingNetworkChangeObserver(net::NetLog* net_log)
122 : net_log_(net_log) {
123 net::NetworkChangeNotifier::AddIPAddressObserver(this);
124 net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
125 net::NetworkChangeNotifier::AddNetworkChangeObserver(this);
126 }
127
128 ~LoggingNetworkChangeObserver() override {
129 net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
130 net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
131 net::NetworkChangeNotifier::RemoveNetworkChangeObserver(this);
132 }
133
134 // NetworkChangeNotifier::IPAddressObserver implementation.
135 void OnIPAddressChanged() override {
136 VLOG(1) << "Observed a change to the network IP addresses";
137
138 net_log_->AddGlobalEntry(
139 net::NetLogEventType::NETWORK_IP_ADDRESSES_CHANGED);
140 }
141
142 // NetworkChangeNotifier::ConnectionTypeObserver implementation.
143 void OnConnectionTypeChanged(
144 net::NetworkChangeNotifier::ConnectionType type) override {
145 std::string type_as_string =
146 net::NetworkChangeNotifier::ConnectionTypeToString(type);
147
148 VLOG(1) << "Observed a change to network connectivity state "
149 << type_as_string;
150
151 net_log_->AddGlobalEntry(
152 net::NetLogEventType::NETWORK_CONNECTIVITY_CHANGED,
153 net::NetLog::StringCallback("new_connection_type", &type_as_string));
154 }
155
156 // NetworkChangeNotifier::NetworkChangeObserver implementation.
157 void OnNetworkChanged(
158 net::NetworkChangeNotifier::ConnectionType type) override {
159 std::string type_as_string =
160 net::NetworkChangeNotifier::ConnectionTypeToString(type);
161
162 VLOG(1) << "Observed a network change to state " << type_as_string;
163
164 net_log_->AddGlobalEntry(
165 net::NetLogEventType::NETWORK_CHANGED,
166 net::NetLog::StringCallback("new_connection_type", &type_as_string));
167 }
168
169 private:
170 net::NetLog* net_log_;
171 DISALLOW_COPY_AND_ASSIGN(LoggingNetworkChangeObserver);
172 };
173
174 class SystemURLRequestContextGetter : public net::URLRequestContextGetter {
175 public:
176 explicit SystemURLRequestContextGetter(IOThread* io_thread);
177
178 // Implementation for net::UrlRequestContextGetter.
179 net::URLRequestContext* GetURLRequestContext() override;
180 scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
181 const override;
182
183 // Tells the getter that the URLRequestContext is about to be shut down.
184 void Shutdown();
185
186 protected:
187 ~SystemURLRequestContextGetter() override;
188
189 private:
190 IOThread* io_thread_; // Weak pointer, owned by ApplicationContext.
191 scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
192
193 base::debug::LeakTracker<SystemURLRequestContextGetter> leak_tracker_;
194 };
195
196 SystemURLRequestContextGetter::SystemURLRequestContextGetter(
197 IOThread* io_thread)
198 : io_thread_(io_thread),
199 network_task_runner_(
200 web::WebThread::GetTaskRunnerForThread(web::WebThread::IO)) {}
201
202 SystemURLRequestContextGetter::~SystemURLRequestContextGetter() {}
203
204 net::URLRequestContext* SystemURLRequestContextGetter::GetURLRequestContext() {
205 DCHECK_CURRENTLY_ON(web::WebThread::IO);
206 if (!io_thread_)
207 return nullptr;
208 DCHECK(io_thread_->globals()->system_request_context.get());
209
210 return io_thread_->globals()->system_request_context.get();
211 }
212
213 scoped_refptr<base::SingleThreadTaskRunner>
214 SystemURLRequestContextGetter::GetNetworkTaskRunner() const {
215 return network_task_runner_;
216 }
217
218 void SystemURLRequestContextGetter::Shutdown() {
219 DCHECK_CURRENTLY_ON(web::WebThread::IO);
220 io_thread_ = nullptr;
221 NotifyContextShuttingDown();
222 }
223
224 IOThread::Globals::SystemRequestContextLeakChecker::
225 SystemRequestContextLeakChecker(Globals* globals)
226 : globals_(globals) {
227 DCHECK(globals_);
228 }
229
230 IOThread::Globals::SystemRequestContextLeakChecker::
231 ~SystemRequestContextLeakChecker() {
232 if (globals_->system_request_context.get())
233 globals_->system_request_context->AssertNoURLRequests();
234 }
235
236 IOThread::Globals::Globals() : system_request_context_leak_checker(this) {}
237
238 IOThread::Globals::~Globals() {}
239
240 // |local_state| is passed in explicitly in order to (1) reduce implicit
241 // dependencies and (2) make IOThread more flexible for testing.
242 IOThread::IOThread(PrefService* local_state, net_log::ChromeNetLog* net_log)
243 : net_log_(net_log),
244 globals_(nullptr),
245 creation_time_(base::TimeTicks::Now()),
246 weak_factory_(this) {
247 pref_proxy_config_tracker_ =
248 ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
249 local_state);
250 ssl_config_service_manager_.reset(
251 ssl_config::SSLConfigServiceManager::CreateDefaultManager(
252 local_state,
253 web::WebThread::GetTaskRunnerForThread(web::WebThread::IO)));
254
255 web::WebThread::SetDelegate(web::WebThread::IO, this);
256 }
257
258 IOThread::~IOThread() {
259 // This isn't needed for production code, but in tests, IOThread may
260 // be multiply constructed.
261 web::WebThread::SetDelegate(web::WebThread::IO, nullptr);
262
263 pref_proxy_config_tracker_->DetachFromPrefService();
264 DCHECK(!globals_);
265 }
266
267 IOThread::Globals* IOThread::globals() {
268 DCHECK_CURRENTLY_ON(web::WebThread::IO);
269 return globals_;
270 }
271
272 void IOThread::SetGlobalsForTesting(Globals* globals) {
273 DCHECK_CURRENTLY_ON(web::WebThread::IO);
274 DCHECK(!globals || !globals_);
275 globals_ = globals;
276 }
277
278 net_log::ChromeNetLog* IOThread::net_log() {
279 return net_log_;
280 }
281
282 void IOThread::ChangedToOnTheRecord() {
283 DCHECK_CURRENTLY_ON(web::WebThread::UI);
284 web::WebThread::PostTask(web::WebThread::IO, FROM_HERE,
285 base::Bind(&IOThread::ChangedToOnTheRecordOnIOThread,
286 base::Unretained(this)));
287 }
288
289 net::URLRequestContextGetter* IOThread::system_url_request_context_getter() {
290 DCHECK_CURRENTLY_ON(web::WebThread::UI);
291 if (!system_url_request_context_getter_.get()) {
292 InitSystemRequestContext();
293 }
294 return system_url_request_context_getter_.get();
295 }
296
297 void IOThread::Init() {
298 TRACE_EVENT0("startup", "IOThread::Init");
299 DCHECK_CURRENTLY_ON(web::WebThread::IO);
300
301 DCHECK(!globals_);
302 globals_ = new Globals;
303
304 // Add an observer that will emit network change events to the ChromeNetLog.
305 // Assuming NetworkChangeNotifier dispatches in FIFO order, we should be
306 // logging the network change before other IO thread consumers respond to it.
307 network_change_observer_.reset(new LoggingNetworkChangeObserver(net_log_));
308
309 // Setup the HistogramWatcher to run on the IO thread.
310 net::NetworkChangeNotifier::InitHistogramWatcher();
311
312 globals_->system_network_delegate = GetSystemNetworkDelegate();
313 globals_->host_resolver = CreateGlobalHostResolver(net_log_);
314
315 std::map<std::string, std::string> network_quality_estimator_params;
316 variations::GetVariationParams(kNetworkQualityEstimatorFieldTrialName,
317 &network_quality_estimator_params);
318
319 std::unique_ptr<net::ExternalEstimateProvider> external_estimate_provider;
320 // Pass ownership.
321 globals_->network_quality_estimator.reset(new net::NetworkQualityEstimator(
322 std::move(external_estimate_provider), network_quality_estimator_params,
323 net_log_));
324
325 globals_->cert_verifier = net::CertVerifier::CreateDefault();
326
327 globals_->transport_security_state.reset(new net::TransportSecurityState());
328
329 std::vector<scoped_refptr<const net::CTLogVerifier>> ct_logs(
330 net::ct::CreateLogVerifiersForKnownLogs());
331
332 net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier();
333 globals_->cert_transparency_verifier.reset(ct_verifier);
334 // Add built-in logs
335 ct_verifier->AddLogs(ct_logs);
336
337 globals_->ct_policy_enforcer.reset(new net::CTPolicyEnforcer());
338
339 globals_->ssl_config_service = GetSSLConfigService();
340
341 CreateDefaultAuthHandlerFactory();
342 globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl());
343 // In-memory cookie store.
344 globals_->system_cookie_store.reset(new net::CookieMonster(nullptr, nullptr));
345 // In-memory channel ID store.
346 globals_->system_channel_id_service.reset(
347 new net::ChannelIDService(new net::DefaultChannelIDStore(nullptr)));
348 globals_->system_cookie_store->SetChannelIDServiceID(
349 globals_->system_channel_id_service->GetUniqueID());
350 globals_->http_user_agent_settings.reset(new net::StaticHttpUserAgentSettings(
351 std::string(),
352 web::GetWebClient()->GetUserAgent(web::UserAgentType::MOBILE)));
353
354 params_.ignore_certificate_errors = false;
355 params_.enable_user_alternate_protocol_ports = false;
356
357 std::string quic_user_agent_id = std::string();
358 quic_user_agent_id.append(
359 version_info::GetProductNameAndVersionForUserAgent());
360 quic_user_agent_id.push_back(' ');
361 quic_user_agent_id.append(web::BuildOSCpuInfo());
362
363 network_session_configurator::ParseFieldTrials(
364 /*is_quic_force_disabled=*/false,
365 /*is_quic_force_enabled=*/false, quic_user_agent_id, &params_);
366
367 // InitSystemRequestContext turns right around and posts a task back
368 // to the IO thread, so we can't let it run until we know the IO
369 // thread has started.
370 //
371 // Note that since we are at WebThread::Init time, the UI thread
372 // is blocked waiting for the thread to start. Therefore, posting
373 // this task to the main thread's message loop here is guaranteed to
374 // get it onto the message loop while the IOThread object still
375 // exists. However, the message might not be processed on the UI
376 // thread until after IOThread is gone, so use a weak pointer.
377 web::WebThread::PostTask(web::WebThread::UI, FROM_HERE,
378 base::Bind(&IOThread::InitSystemRequestContext,
379 weak_factory_.GetWeakPtr()));
380 }
381
382 void IOThread::CleanUp() {
383 system_url_request_context_getter_->Shutdown();
384 system_url_request_context_getter_ = nullptr;
385
386 // Release objects that the net::URLRequestContext could have been pointing
387 // to.
388
389 // Shutdown the HistogramWatcher on the IO thread.
390 net::NetworkChangeNotifier::ShutdownHistogramWatcher();
391
392 // This must be reset before the ChromeNetLog is destroyed.
393 network_change_observer_.reset();
394
395 system_proxy_config_service_.reset();
396
397 delete globals_;
398 globals_ = nullptr;
399
400 base::debug::LeakTracker<SystemURLRequestContextGetter>::CheckForLeaks();
401 }
402
403 void IOThread::CreateDefaultAuthHandlerFactory() {
404 std::vector<std::string> supported_schemes =
405 base::SplitString(kSupportedAuthSchemes, ",", base::TRIM_WHITESPACE,
406 base::SPLIT_WANT_NONEMPTY);
407 globals_->http_auth_preferences.reset(
408 new net::HttpAuthPreferences(supported_schemes, std::string()));
409 globals_->http_auth_handler_factory =
410 net::HttpAuthHandlerRegistryFactory::Create(
411 globals_->http_auth_preferences.get(), globals_->host_resolver.get());
412 }
413
414 void IOThread::ClearHostCache() {
415 DCHECK_CURRENTLY_ON(web::WebThread::IO);
416
417 net::HostCache* host_cache = globals_->host_resolver->GetHostCache();
418 if (host_cache)
419 host_cache->clear();
420 }
421
422 const net::HttpNetworkSession::Params& IOThread::NetworkSessionParams() const {
423 return params_;
424 }
425
426 base::TimeTicks IOThread::creation_time() const {
427 return creation_time_;
428 }
429
430 net::SSLConfigService* IOThread::GetSSLConfigService() {
431 return ssl_config_service_manager_->Get();
432 }
433
434 void IOThread::ChangedToOnTheRecordOnIOThread() {
435 DCHECK_CURRENTLY_ON(web::WebThread::IO);
436
437 // Clear the host cache to avoid showing entries from the OTR session
438 // in about:net-internals.
439 ClearHostCache();
440 }
441
442 void IOThread::InitSystemRequestContext() {
443 if (system_url_request_context_getter_.get())
444 return;
445 // If we're in unit_tests, IOThread may not be run.
446 if (!web::WebThread::IsMessageLoopValid(web::WebThread::IO))
447 return;
448 system_proxy_config_service_ = ProxyServiceFactory::CreateProxyConfigService(
449 pref_proxy_config_tracker_.get());
450
451 system_url_request_context_getter_ = new SystemURLRequestContextGetter(this);
452 // Safe to post an unretained this pointer, since IOThread is
453 // guaranteed to outlive the IO WebThread.
454 web::WebThread::PostTask(
455 web::WebThread::IO, FROM_HERE,
456 base::Bind(&IOThread::InitSystemRequestContextOnIOThread,
457 base::Unretained(this)));
458 }
459
460 void IOThread::InitSystemRequestContextOnIOThread() {
461 DCHECK_CURRENTLY_ON(web::WebThread::IO);
462 DCHECK(!globals_->system_proxy_service.get());
463 DCHECK(system_proxy_config_service_.get());
464
465 globals_->system_proxy_service = ProxyServiceFactory::CreateProxyService(
466 net_log_, nullptr, globals_->system_network_delegate.get(),
467 std::move(system_proxy_config_service_), true /* quick_check_enabled */);
468
469 globals_->system_request_context.reset(
470 ConstructSystemRequestContext(globals_, params_, net_log_));
471 }
472
473 net::URLRequestContext* IOThread::ConstructSystemRequestContext(
474 IOThread::Globals* globals,
475 const net::HttpNetworkSession::Params& params,
476 net::NetLog* net_log) {
477 net::URLRequestContext* context = new SystemURLRequestContext;
478 context->set_net_log(net_log);
479 context->set_host_resolver(globals->host_resolver.get());
480 context->set_cert_verifier(globals->cert_verifier.get());
481 context->set_transport_security_state(
482 globals->transport_security_state.get());
483 context->set_cert_transparency_verifier(
484 globals->cert_transparency_verifier.get());
485 context->set_ssl_config_service(globals->ssl_config_service.get());
486 context->set_http_auth_handler_factory(
487 globals->http_auth_handler_factory.get());
488 context->set_proxy_service(globals->system_proxy_service.get());
489 context->set_ct_policy_enforcer(globals->ct_policy_enforcer.get());
490
491 net::URLRequestJobFactoryImpl* system_job_factory =
492 new net::URLRequestJobFactoryImpl();
493 // Data URLs are always loaded through the system request context on iOS
494 // (due to UIWebView limitations).
495 bool set_protocol = system_job_factory->SetProtocolHandler(
496 url::kDataScheme, base::MakeUnique<net::DataProtocolHandler>());
497 DCHECK(set_protocol);
498 globals->system_url_request_job_factory.reset(system_job_factory);
499 context->set_job_factory(globals->system_url_request_job_factory.get());
500
501 context->set_cookie_store(globals->system_cookie_store.get());
502 context->set_channel_id_service(globals->system_channel_id_service.get());
503 context->set_network_delegate(globals->system_network_delegate.get());
504 context->set_http_user_agent_settings(
505 globals->http_user_agent_settings.get());
506 context->set_network_quality_estimator(
507 globals->network_quality_estimator.get());
508
509 context->set_http_server_properties(globals->http_server_properties.get());
510
511 net::HttpNetworkSession::Params system_params(params);
512 net::URLRequestContextBuilder::SetHttpNetworkSessionComponents(
513 context, &system_params);
514
515 globals->system_http_network_session.reset(
516 new net::HttpNetworkSession(system_params));
517 globals->system_http_transaction_factory.reset(
518 new net::HttpNetworkLayer(globals->system_http_network_session.get()));
519 context->set_http_transaction_factory(
520 globals->system_http_transaction_factory.get());
521
522 return context;
523 }
524
525 } // namespace io_thread
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698