1 // Copyright 2014 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 "chromecast/browser/cast_content_browser_client.h"
9 #include "base/base_switches.h"
10 #include "base/command_line.h"
11 #include "base/files/scoped_file.h"
12 #include "base/i18n/icu_util.h"
13 #include "base/i18n/rtl.h"
14 #include "base/path_service.h"
15 #include "chromecast/base/cast_paths.h"
16 #include "chromecast/browser/cast_browser_context.h"
17 #include "chromecast/browser/cast_browser_main_parts.h"
18 #include "chromecast/browser/cast_browser_process.h"
19 #include "chromecast/browser/cast_network_delegate.h"
20 #include "chromecast/browser/cast_quota_permission_context.h"
21 #include "chromecast/browser/cast_resource_dispatcher_host_delegate.h"
22 #include "chromecast/browser/devtools/cast_dev_tools_delegate.h"
23 #include "chromecast/browser/geolocation/cast_access_token_store.h"
24 #include "chromecast/browser/media/cma_message_filter_host.h"
25 #include "chromecast/browser/url_request_context_factory.h"
26 #include "chromecast/common/chromecast_switches.h"
27 #include "chromecast/common/global_descriptors.h"
28 #include "components/crash/app/breakpad_linux.h"
29 #include "components/crash/browser/crash_handler_host_linux.h"
30 #include "components/network_hints/browser/network_hints_message_filter.h"
31 #include "content/public/browser/browser_thread.h"
32 #include "content/public/browser/certificate_request_result_type.h"
33 #include "content/public/browser/client_certificate_delegate.h"
34 #include "content/public/browser/render_process_host.h"
35 #include "content/public/browser/resource_dispatcher_host.h"
36 #include "content/public/browser/web_contents.h"
37 #include "content/public/common/content_descriptors.h"
38 #include "content/public/common/content_switches.h"
39 #include "content/public/common/url_constants.h"
40 #include "content/public/common/web_preferences.h"
41 #include "gin/v8_initializer.h"
42 #include "net/ssl/ssl_cert_request_info.h"
43 #include "net/url_request/url_request_context_getter.h"
44 #include "ui/gl/gl_switches.h"
46 #if defined(OS_ANDROID)
47 #include "chromecast/browser/android/external_video_surface_container_impl.h"
48 #endif // defined(OS_ANDROID)
50 #if defined(OS_ANDROID)
51 #include "components/crash/browser/crash_dump_manager_android.h"
52 #endif // defined(OS_ANDROID)
54 namespace chromecast
{
57 CastContentBrowserClient::CastContentBrowserClient()
60 url_request_context_factory_(new URLRequestContextFactory()) {
63 CastContentBrowserClient::~CastContentBrowserClient() {
64 content::BrowserThread::DeleteSoon(
65 content::BrowserThread::IO
,
67 url_request_context_factory_
.release());
70 content::BrowserMainParts
* CastContentBrowserClient::CreateBrowserMainParts(
71 const content::MainFunctionParams
& parameters
) {
72 return new CastBrowserMainParts(parameters
,
73 url_request_context_factory_
.get());
76 void CastContentBrowserClient::RenderProcessWillLaunch(
77 content::RenderProcessHost
* host
) {
78 #if !defined(OS_ANDROID)
79 scoped_refptr
<media::CmaMessageFilterHost
> cma_message_filter(
80 new media::CmaMessageFilterHost(host
->GetID()));
81 host
->AddFilter(cma_message_filter
.get());
82 #endif // !defined(OS_ANDROID)
84 // Forcibly trigger I/O-thread URLRequestContext initialization before
85 // getting HostResolver.
86 content::BrowserThread::PostTaskAndReplyWithResult(
87 content::BrowserThread::IO
, FROM_HERE
,
88 base::Bind(&net::URLRequestContextGetter::GetURLRequestContext
,
90 url_request_context_factory_
->GetSystemGetter())),
91 base::Bind(&CastContentBrowserClient::AddNetworkHintsMessageFilter
,
92 base::Unretained(this), host
->GetID()));
94 auto extra_filters
= PlatformGetBrowserMessageFilters();
95 for (auto const& filter
: extra_filters
) {
96 host
->AddFilter(filter
.get());
100 void CastContentBrowserClient::AddNetworkHintsMessageFilter(
101 int render_process_id
, net::URLRequestContext
* context
) {
102 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
104 content::RenderProcessHost
* host
=
105 content::RenderProcessHost::FromID(render_process_id
);
109 scoped_refptr
<content::BrowserMessageFilter
> network_hints_message_filter(
110 new network_hints::NetworkHintsMessageFilter(
111 url_request_context_factory_
->host_resolver()));
112 host
->AddFilter(network_hints_message_filter
.get());
115 net::URLRequestContextGetter
* CastContentBrowserClient::CreateRequestContext(
116 content::BrowserContext
* browser_context
,
117 content::ProtocolHandlerMap
* protocol_handlers
,
118 content::URLRequestInterceptorScopedVector request_interceptors
) {
119 return url_request_context_factory_
->CreateMainGetter(
122 request_interceptors
.Pass());
125 bool CastContentBrowserClient::IsHandledURL(const GURL
& url
) {
129 static const char* const kProtocolList
[] = {
131 url::kFileSystemScheme
,
132 content::kChromeUIScheme
,
133 content::kChromeDevToolsScheme
,
137 const std::string
& scheme
= url
.scheme();
138 for (size_t i
= 0; i
< arraysize(kProtocolList
); ++i
) {
139 if (scheme
== kProtocolList
[i
])
143 if (scheme
== url::kFileScheme
) {
144 return base::CommandLine::ForCurrentProcess()->HasSwitch(
145 switches::kEnableLocalFileAccesses
);
151 void CastContentBrowserClient::AppendExtraCommandLineSwitches(
152 base::CommandLine
* command_line
,
153 int child_process_id
) {
155 std::string process_type
=
156 command_line
->GetSwitchValueNative(switches::kProcessType
);
157 base::CommandLine
* browser_command_line
=
158 base::CommandLine::ForCurrentProcess();
160 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
161 if (process_type
!= switches::kZygoteProcess
) {
162 command_line
->AppendSwitch(::switches::kV8NativesPassedByFD
);
163 command_line
->AppendSwitch(::switches::kV8SnapshotPassedByFD
);
165 #endif // V8_USE_EXTERNAL_STARTUP_DATA
167 // IsCrashReporterEnabled() is set when InitCrashReporter() is called, and
168 // controlled by GetBreakpadClient()->EnableBreakpadForProcess(), therefore
169 // it's ok to add switch to every process here.
170 if (breakpad::IsCrashReporterEnabled()) {
171 command_line
->AppendSwitch(switches::kEnableCrashReporter
);
174 // Renderer process command-line
175 if (process_type
== switches::kRendererProcess
) {
176 // Any browser command-line switches that should be propagated to
177 // the renderer go here.
179 if (browser_command_line
->HasSwitch(switches::kEnableCmaMediaPipeline
))
180 command_line
->AppendSwitch(switches::kEnableCmaMediaPipeline
);
183 #if defined(OS_LINUX)
184 // Necessary for accelerated 2d canvas. By default on Linux, Chromium assumes
185 // GLES2 contexts can be lost to a power-save mode, which breaks GPU canvas
187 if (process_type
== switches::kGpuProcess
) {
188 command_line
->AppendSwitch(switches::kGpuNoContextLost
);
192 PlatformAppendExtraCommandLineSwitches(command_line
);
195 content::AccessTokenStore
* CastContentBrowserClient::CreateAccessTokenStore() {
196 return new CastAccessTokenStore(
197 CastBrowserProcess::GetInstance()->browser_context());
200 void CastContentBrowserClient::OverrideWebkitPrefs(
201 content::RenderViewHost
* render_view_host
,
202 content::WebPreferences
* prefs
) {
203 prefs
->allow_scripts_to_close_windows
= true;
204 // TODO(lcwu): http://crbug.com/391089. This pref is set to true by default
205 // because some content providers such as YouTube use plain http requests
206 // to retrieve media data chunks while running in a https page. This pref
207 // should be disabled once all the content providers are no longer doing that.
208 prefs
->allow_running_insecure_content
= true;
211 void CastContentBrowserClient::ResourceDispatcherHostCreated() {
212 CastBrowserProcess::GetInstance()->SetResourceDispatcherHostDelegate(
213 make_scoped_ptr(new CastResourceDispatcherHostDelegate
));
214 content::ResourceDispatcherHost::Get()->SetDelegate(
215 CastBrowserProcess::GetInstance()->resource_dispatcher_host_delegate());
218 std::string
CastContentBrowserClient::GetApplicationLocale() {
219 const std::string
locale(base::i18n::GetConfiguredLocale());
220 return locale
.empty() ? "en-US" : locale
;
223 content::QuotaPermissionContext
*
224 CastContentBrowserClient::CreateQuotaPermissionContext() {
225 return new CastQuotaPermissionContext();
228 void CastContentBrowserClient::AllowCertificateError(
229 int render_process_id
,
232 const net::SSLInfo
& ssl_info
,
233 const GURL
& request_url
,
234 content::ResourceType resource_type
,
236 bool strict_enforcement
,
237 bool expired_previous_decision
,
238 const base::Callback
<void(bool)>& callback
,
239 content::CertificateRequestResultType
* result
) {
240 // Allow developers to override certificate errors.
241 // Otherwise, any fatal certificate errors will cause an abort.
242 *result
= content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL
;
246 void CastContentBrowserClient::SelectClientCertificate(
247 content::WebContents
* web_contents
,
248 net::SSLCertRequestInfo
* cert_request_info
,
249 scoped_ptr
<content::ClientCertificateDelegate
> delegate
) {
250 GURL
requesting_url("https://" + cert_request_info
->host_and_port
.ToString());
252 if (!requesting_url
.is_valid()) {
253 LOG(ERROR
) << "Invalid URL string: "
254 << requesting_url
.possibly_invalid_spec();
255 delegate
->ContinueWithCertificate(nullptr);
259 // In our case there are no relevant certs in the cert_request_info. The cert
260 // we need to return (if permitted) is the Cast device cert, which we can
261 // access directly through the ClientAuthSigner instance. However, we need to
262 // be on the IO thread to determine whether the app is whitelisted to return
263 // it, because CastNetworkDelegate is bound to the IO thread.
264 // Subsequently, the callback must then itself be performed back here
267 // TODO(davidben): Stop using child ID to identify an app.
268 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
269 content::BrowserThread::PostTaskAndReplyWithResult(
270 content::BrowserThread::IO
, FROM_HERE
,
271 base::Bind(&CastContentBrowserClient::SelectClientCertificateOnIOThread
,
272 base::Unretained(this), requesting_url
,
273 web_contents
->GetRenderProcessHost()->GetID()),
274 base::Bind(&content::ClientCertificateDelegate::ContinueWithCertificate
,
275 base::Owned(delegate
.release())));
278 net::X509Certificate
*
279 CastContentBrowserClient::SelectClientCertificateOnIOThread(
281 int render_process_id
) {
282 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
283 CastNetworkDelegate
* network_delegate
=
284 url_request_context_factory_
->app_network_delegate();
285 if (network_delegate
->IsWhitelisted(requesting_url
,
286 render_process_id
, false)) {
287 return CastNetworkDelegate::DeviceCert();
289 LOG(ERROR
) << "Invalid host for client certificate request: "
290 << requesting_url
.host()
291 << " with render_process_id: "
292 << render_process_id
;
297 bool CastContentBrowserClient::CanCreateWindow(
298 const GURL
& opener_url
,
299 const GURL
& opener_top_level_frame_url
,
300 const GURL
& source_origin
,
301 WindowContainerType container_type
,
302 const GURL
& target_url
,
303 const content::Referrer
& referrer
,
304 WindowOpenDisposition disposition
,
305 const blink::WebWindowFeatures
& features
,
307 bool opener_suppressed
,
308 content::ResourceContext
* context
,
309 int render_process_id
,
311 bool* no_javascript_access
) {
312 *no_javascript_access
= true;
316 content::DevToolsManagerDelegate
*
317 CastContentBrowserClient::GetDevToolsManagerDelegate() {
318 return new CastDevToolsManagerDelegate();
321 void CastContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
322 const base::CommandLine
& command_line
,
323 int child_process_id
,
324 content::FileDescriptorInfo
* mappings
) {
325 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
326 if (v8_natives_fd_
.get() == -1 || v8_snapshot_fd_
.get() == -1) {
327 int v8_natives_fd
= -1;
328 int v8_snapshot_fd
= -1;
329 if (gin::V8Initializer::OpenV8FilesForChildProcesses(&v8_natives_fd
,
331 v8_natives_fd_
.reset(v8_natives_fd
);
332 v8_snapshot_fd_
.reset(v8_snapshot_fd
);
335 DCHECK(v8_natives_fd_
.get() != -1 && v8_snapshot_fd_
.get() != -1);
336 mappings
->Share(kV8NativesDataDescriptor
, v8_natives_fd_
.get());
337 mappings
->Share(kV8SnapshotDataDescriptor
, v8_snapshot_fd_
.get());
338 #endif // V8_USE_EXTERNAL_STARTUP_DATA
339 #if defined(OS_ANDROID)
340 const int flags_open_read
= base::File::FLAG_OPEN
| base::File::FLAG_READ
;
341 base::FilePath pak_file_path
;
342 CHECK(PathService::Get(FILE_CAST_PAK
, &pak_file_path
));
343 base::File
pak_file(pak_file_path
, flags_open_read
);
344 if (!pak_file
.IsValid()) {
345 NOTREACHED() << "Failed to open file when creating renderer process: "
348 mappings
->Transfer(kAndroidPakDescriptor
,
349 base::ScopedFD(pak_file
.TakePlatformFile()));
351 if (breakpad::IsCrashReporterEnabled()) {
352 base::File
minidump_file(
353 breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
355 if (!minidump_file
.IsValid()) {
356 LOG(ERROR
) << "Failed to create file for minidump, crash reporting will "
357 << "be disabled for this process.";
359 mappings
->Transfer(kAndroidMinidumpDescriptor
,
360 base::ScopedFD(minidump_file
.TakePlatformFile()));
364 base::FilePath app_data_path
;
365 CHECK(PathService::Get(base::DIR_ANDROID_APP_DATA
, &app_data_path
));
366 base::FilePath icudata_path
=
367 app_data_path
.AppendASCII(base::i18n::kIcuDataFileName
);
368 base::File
icudata_file(icudata_path
, flags_open_read
);
369 if (!icudata_file
.IsValid())
370 NOTREACHED() << "Failed to open ICU file when creating renderer process";
371 mappings
->Transfer(kAndroidICUDataDescriptor
,
372 base::ScopedFD(icudata_file
.TakePlatformFile()));
374 int crash_signal_fd
= GetCrashSignalFD(command_line
);
375 if (crash_signal_fd
>= 0) {
376 mappings
->Share(kCrashDumpSignal
, crash_signal_fd
);
378 #endif // defined(OS_ANDROID)
381 #if defined(OS_ANDROID) && defined(VIDEO_HOLE)
382 content::ExternalVideoSurfaceContainer
*
383 CastContentBrowserClient::OverrideCreateExternalVideoSurfaceContainer(
384 content::WebContents
* web_contents
) {
385 return ExternalVideoSurfaceContainerImpl::Create(web_contents
);
387 #endif // defined(OS_ANDROID) && defined(VIDEO_HOLE)
389 #if !defined(OS_ANDROID)
390 int CastContentBrowserClient::GetCrashSignalFD(
391 const base::CommandLine
& command_line
) {
392 std::string process_type
=
393 command_line
.GetSwitchValueASCII(switches::kProcessType
);
395 if (process_type
== switches::kRendererProcess
||
396 process_type
== switches::kGpuProcess
) {
397 breakpad::CrashHandlerHostLinux
* crash_handler
=
398 crash_handlers_
[process_type
];
399 if (!crash_handler
) {
400 crash_handler
= CreateCrashHandlerHost(process_type
);
401 crash_handlers_
[process_type
] = crash_handler
;
403 return crash_handler
->GetDeathSignalSocket();
409 breakpad::CrashHandlerHostLinux
*
410 CastContentBrowserClient::CreateCrashHandlerHost(
411 const std::string
& process_type
) {
412 // Let cast shell dump to /tmp. Internal minidump generator code can move it
413 // to /data/minidumps later, since /data/minidumps is file lock-controlled.
414 base::FilePath dumps_path
;
415 PathService::Get(base::DIR_TEMP
, &dumps_path
);
417 // Alway set "upload" to false to use our own uploader.
418 breakpad::CrashHandlerHostLinux
* crash_handler
=
419 new breakpad::CrashHandlerHostLinux(
420 process_type
, dumps_path
, false /* upload */);
421 // StartUploaderThread() even though upload is diferred.
422 // Breakpad-related memory is freed in the uploader thread.
423 crash_handler
->StartUploaderThread();
424 return crash_handler
;
426 #endif // !defined(OS_ANDROID)
429 } // namespace chromecast