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

Side by Side Diff: ios/web_view/internal/app/web_view_io_thread.mm

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

Powered by Google App Engine
This is Rietveld 408576698