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/rtl.h"
13 #include "base/path_service.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "chromecast/base/cast_paths.h"
16 #include "chromecast/base/chromecast_switches.h"
17 #include "chromecast/browser/cast_browser_context.h"
18 #include "chromecast/browser/cast_browser_main_parts.h"
19 #include "chromecast/browser/cast_browser_process.h"
20 #include "chromecast/browser/cast_network_delegate.h"
21 #include "chromecast/browser/cast_quota_permission_context.h"
22 #include "chromecast/browser/cast_resource_dispatcher_host_delegate.h"
23 #include "chromecast/browser/geolocation/cast_access_token_store.h"
24 #include "chromecast/browser/media/cma_media_pipeline_client.h"
25 #include "chromecast/browser/media/cma_message_filter_host.h"
26 #include "chromecast/browser/service/cast_service_simple.h"
27 #include "chromecast/browser/url_request_context_factory.h"
28 #include "chromecast/common/global_descriptors.h"
29 #include "chromecast/media/base/media_message_loop.h"
30 #include "chromecast/public/cast_media_shlib.h"
31 #include "chromecast/public/media/media_pipeline_backend.h"
32 #include "components/crash/app/breakpad_linux.h"
33 #include "components/crash/browser/crash_handler_host_linux.h"
34 #include "components/network_hints/browser/network_hints_message_filter.h"
35 #include "content/public/browser/browser_thread.h"
36 #include "content/public/browser/certificate_request_result_type.h"
37 #include "content/public/browser/client_certificate_delegate.h"
38 #include "content/public/browser/render_process_host.h"
39 #include "content/public/browser/resource_dispatcher_host.h"
40 #include "content/public/browser/web_contents.h"
41 #include "content/public/common/content_descriptors.h"
42 #include "content/public/common/content_switches.h"
43 #include "content/public/common/url_constants.h"
44 #include "content/public/common/web_preferences.h"
45 #include "media/audio/audio_manager_factory.h"
46 #include "net/ssl/ssl_cert_request_info.h"
47 #include "net/url_request/url_request_context_getter.h"
48 #include "ui/gl/gl_switches.h"
50 #if defined(OS_ANDROID)
51 #include "components/crash/browser/crash_dump_manager_android.h"
52 #include "components/external_video_surface/browser/android/external_video_surface_container_impl.h"
53 #endif // defined(OS_ANDROID)
55 namespace chromecast
{
58 CastContentBrowserClient::CastContentBrowserClient()
59 : url_request_context_factory_(new URLRequestContextFactory()) {
62 CastContentBrowserClient::~CastContentBrowserClient() {
63 content::BrowserThread::DeleteSoon(
64 content::BrowserThread::IO
,
66 url_request_context_factory_
.release());
69 void CastContentBrowserClient::AppendExtraCommandLineSwitches(
70 base::CommandLine
* command_line
) {
73 scoped_ptr
<CastService
> CastContentBrowserClient::CreateCastService(
74 content::BrowserContext
* browser_context
,
75 PrefService
* pref_service
,
76 net::URLRequestContextGetter
* request_context_getter
) {
77 return make_scoped_ptr(new CastServiceSimple(browser_context
, pref_service
));
80 scoped_ptr
<::media::AudioManagerFactory
>
81 CastContentBrowserClient::CreateAudioManagerFactory() {
82 // Return nullptr. The factory will not be set, and the statically linked
83 // implementation of AudioManager will be used.
84 return scoped_ptr
<::media::AudioManagerFactory
>();
87 #if !defined(OS_ANDROID)
88 scoped_refptr
<media::CmaMediaPipelineClient
>
89 CastContentBrowserClient::CreateCmaMediaPipelineClient() {
90 return make_scoped_refptr(new media::CmaMediaPipelineClient());
94 void CastContentBrowserClient::ProcessExiting() {
95 // Finalize CastMediaShlib on media thread to ensure it's not accessed
97 media::MediaMessageLoop::GetTaskRunner()->PostTask(
98 FROM_HERE
, base::Bind(&media::CastMediaShlib::Finalize
));
101 void CastContentBrowserClient::SetMetricsClientId(
102 const std::string
& client_id
) {
105 void CastContentBrowserClient::RegisterMetricsProviders(
106 ::metrics::MetricsService
* metrics_service
) {
109 content::BrowserMainParts
* CastContentBrowserClient::CreateBrowserMainParts(
110 const content::MainFunctionParams
& parameters
) {
111 content::BrowserMainParts
* parts
= new CastBrowserMainParts(
112 parameters
, url_request_context_factory_
.get(),
113 CreateAudioManagerFactory());
114 CastBrowserProcess::GetInstance()->SetCastContentBrowserClient(this);
118 void CastContentBrowserClient::RenderProcessWillLaunch(
119 content::RenderProcessHost
* host
) {
120 #if !defined(OS_ANDROID)
121 scoped_refptr
<media::CmaMessageFilterHost
> cma_message_filter(
122 new media::CmaMessageFilterHost(host
->GetID(),
123 CreateCmaMediaPipelineClient()));
124 host
->AddFilter(cma_message_filter
.get());
125 #endif // !defined(OS_ANDROID)
127 // Forcibly trigger I/O-thread URLRequestContext initialization before
128 // getting HostResolver.
129 content::BrowserThread::PostTaskAndReplyWithResult(
130 content::BrowserThread::IO
, FROM_HERE
,
131 base::Bind(&net::URLRequestContextGetter::GetURLRequestContext
,
133 url_request_context_factory_
->GetSystemGetter())),
134 base::Bind(&CastContentBrowserClient::AddNetworkHintsMessageFilter
,
135 base::Unretained(this), host
->GetID()));
138 void CastContentBrowserClient::AddNetworkHintsMessageFilter(
139 int render_process_id
, net::URLRequestContext
* context
) {
140 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
142 content::RenderProcessHost
* host
=
143 content::RenderProcessHost::FromID(render_process_id
);
147 scoped_refptr
<content::BrowserMessageFilter
> network_hints_message_filter(
148 new network_hints::NetworkHintsMessageFilter(
149 url_request_context_factory_
->host_resolver()));
150 host
->AddFilter(network_hints_message_filter
.get());
153 net::URLRequestContextGetter
* CastContentBrowserClient::CreateRequestContext(
154 content::BrowserContext
* browser_context
,
155 content::ProtocolHandlerMap
* protocol_handlers
,
156 content::URLRequestInterceptorScopedVector request_interceptors
) {
157 return url_request_context_factory_
->CreateMainGetter(
160 request_interceptors
.Pass());
163 bool CastContentBrowserClient::IsHandledURL(const GURL
& url
) {
167 static const char* const kProtocolList
[] = {
169 url::kFileSystemScheme
,
170 content::kChromeUIScheme
,
171 content::kChromeDevToolsScheme
,
175 const std::string
& scheme
= url
.scheme();
176 for (size_t i
= 0; i
< arraysize(kProtocolList
); ++i
) {
177 if (scheme
== kProtocolList
[i
])
181 if (scheme
== url::kFileScheme
) {
182 return base::CommandLine::ForCurrentProcess()->HasSwitch(
183 switches::kEnableLocalFileAccesses
);
189 void CastContentBrowserClient::AppendExtraCommandLineSwitches(
190 base::CommandLine
* command_line
,
191 int child_process_id
) {
192 std::string process_type
=
193 command_line
->GetSwitchValueNative(switches::kProcessType
);
194 base::CommandLine
* browser_command_line
=
195 base::CommandLine::ForCurrentProcess();
197 // IsCrashReporterEnabled() is set when InitCrashReporter() is called, and
198 // controlled by GetBreakpadClient()->EnableBreakpadForProcess(), therefore
199 // it's ok to add switch to every process here.
200 if (breakpad::IsCrashReporterEnabled()) {
201 command_line
->AppendSwitch(switches::kEnableCrashReporter
);
204 // Renderer process command-line
205 if (process_type
== switches::kRendererProcess
) {
206 // Any browser command-line switches that should be propagated to
207 // the renderer go here.
209 if (browser_command_line
->HasSwitch(switches::kEnableCmaMediaPipeline
))
210 command_line
->AppendSwitch(switches::kEnableCmaMediaPipeline
);
211 if (browser_command_line
->HasSwitch(switches::kEnableLegacyHolePunching
))
212 command_line
->AppendSwitch(switches::kEnableLegacyHolePunching
);
213 if (browser_command_line
->HasSwitch(switches::kAllowHiddenMediaPlayback
))
214 command_line
->AppendSwitch(switches::kAllowHiddenMediaPlayback
);
217 #if defined(OS_LINUX)
218 // Necessary for accelerated 2d canvas. By default on Linux, Chromium assumes
219 // GLES2 contexts can be lost to a power-save mode, which breaks GPU canvas
221 if (process_type
== switches::kGpuProcess
) {
222 command_line
->AppendSwitch(switches::kGpuNoContextLost
);
226 AppendExtraCommandLineSwitches(command_line
);
229 content::AccessTokenStore
* CastContentBrowserClient::CreateAccessTokenStore() {
230 return new CastAccessTokenStore(
231 CastBrowserProcess::GetInstance()->browser_context());
234 void CastContentBrowserClient::OverrideWebkitPrefs(
235 content::RenderViewHost
* render_view_host
,
236 content::WebPreferences
* prefs
) {
237 prefs
->allow_scripts_to_close_windows
= true;
238 // TODO(lcwu): http://crbug.com/391089. This pref is set to true by default
239 // because some content providers such as YouTube use plain http requests
240 // to retrieve media data chunks while running in a https page. This pref
241 // should be disabled once all the content providers are no longer doing that.
242 prefs
->allow_running_insecure_content
= true;
245 void CastContentBrowserClient::ResourceDispatcherHostCreated() {
246 CastBrowserProcess::GetInstance()->SetResourceDispatcherHostDelegate(
247 make_scoped_ptr(new CastResourceDispatcherHostDelegate
));
248 content::ResourceDispatcherHost::Get()->SetDelegate(
249 CastBrowserProcess::GetInstance()->resource_dispatcher_host_delegate());
252 std::string
CastContentBrowserClient::GetApplicationLocale() {
253 const std::string
locale(base::i18n::GetConfiguredLocale());
254 return locale
.empty() ? "en-US" : locale
;
257 content::QuotaPermissionContext
*
258 CastContentBrowserClient::CreateQuotaPermissionContext() {
259 return new CastQuotaPermissionContext();
262 void CastContentBrowserClient::AllowCertificateError(
263 int render_process_id
,
266 const net::SSLInfo
& ssl_info
,
267 const GURL
& request_url
,
268 content::ResourceType resource_type
,
270 bool strict_enforcement
,
271 bool expired_previous_decision
,
272 const base::Callback
<void(bool)>& callback
,
273 content::CertificateRequestResultType
* result
) {
274 // Allow developers to override certificate errors.
275 // Otherwise, any fatal certificate errors will cause an abort.
276 *result
= content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL
;
280 void CastContentBrowserClient::SelectClientCertificate(
281 content::WebContents
* web_contents
,
282 net::SSLCertRequestInfo
* cert_request_info
,
283 scoped_ptr
<content::ClientCertificateDelegate
> delegate
) {
284 GURL
requesting_url("https://" + cert_request_info
->host_and_port
.ToString());
286 if (!requesting_url
.is_valid()) {
287 LOG(ERROR
) << "Invalid URL string: "
288 << requesting_url
.possibly_invalid_spec();
289 delegate
->ContinueWithCertificate(nullptr);
293 // In our case there are no relevant certs in the cert_request_info. The cert
294 // we need to return (if permitted) is the Cast device cert, which we can
295 // access directly through the ClientAuthSigner instance. However, we need to
296 // be on the IO thread to determine whether the app is whitelisted to return
297 // it, because CastNetworkDelegate is bound to the IO thread.
298 // Subsequently, the callback must then itself be performed back here
301 // TODO(davidben): Stop using child ID to identify an app.
302 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
303 content::BrowserThread::PostTaskAndReplyWithResult(
304 content::BrowserThread::IO
, FROM_HERE
,
305 base::Bind(&CastContentBrowserClient::SelectClientCertificateOnIOThread
,
306 base::Unretained(this), requesting_url
,
307 web_contents
->GetRenderProcessHost()->GetID()),
308 base::Bind(&content::ClientCertificateDelegate::ContinueWithCertificate
,
309 base::Owned(delegate
.release())));
312 net::X509Certificate
*
313 CastContentBrowserClient::SelectClientCertificateOnIOThread(
315 int render_process_id
) {
316 DCHECK_CURRENTLY_ON(content::BrowserThread::IO
);
317 CastNetworkDelegate
* network_delegate
=
318 url_request_context_factory_
->app_network_delegate();
319 if (network_delegate
->IsWhitelisted(requesting_url
,
320 render_process_id
, false)) {
321 return CastNetworkDelegate::DeviceCert();
323 LOG(ERROR
) << "Invalid host for client certificate request: "
324 << requesting_url
.host()
325 << " with render_process_id: "
326 << render_process_id
;
331 bool CastContentBrowserClient::CanCreateWindow(
332 const GURL
& opener_url
,
333 const GURL
& opener_top_level_frame_url
,
334 const GURL
& source_origin
,
335 WindowContainerType container_type
,
336 const GURL
& target_url
,
337 const content::Referrer
& referrer
,
338 WindowOpenDisposition disposition
,
339 const blink::WebWindowFeatures
& features
,
341 bool opener_suppressed
,
342 content::ResourceContext
* context
,
343 int render_process_id
,
344 int opener_render_view_id
,
345 int opener_render_frame_id
,
346 bool* no_javascript_access
) {
347 *no_javascript_access
= true;
351 void CastContentBrowserClient::RegisterUnsandboxedOutOfProcessMojoApplications(
352 std::map
<GURL
, base::string16
>* apps
) {
353 #if defined(ENABLE_MOJO_MEDIA_IN_UTILITY_PROCESS)
354 apps
->insert(std::make_pair(GURL("mojo:media"),
355 base::UTF8ToUTF16("Media Renderer")));
359 #if defined(OS_ANDROID)
360 void CastContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
361 const base::CommandLine
& command_line
,
362 int child_process_id
,
363 content::FileDescriptorInfo
* mappings
,
364 std::map
<int, base::MemoryMappedFile::Region
>* regions
) {
366 kAndroidPakDescriptor
,
367 base::GlobalDescriptors::GetInstance()->Get(kAndroidPakDescriptor
));
368 regions
->insert(std::make_pair(
369 kAndroidPakDescriptor
, base::GlobalDescriptors::GetInstance()->GetRegion(
370 kAndroidPakDescriptor
)));
372 if (breakpad::IsCrashReporterEnabled()) {
373 base::File
minidump_file(
374 breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
376 if (!minidump_file
.IsValid()) {
377 LOG(ERROR
) << "Failed to create file for minidump, crash reporting will "
378 << "be disabled for this process.";
380 mappings
->Transfer(kAndroidMinidumpDescriptor
,
381 base::ScopedFD(minidump_file
.TakePlatformFile()));
386 void CastContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
387 const base::CommandLine
& command_line
,
388 int child_process_id
,
389 content::FileDescriptorInfo
* mappings
) {
390 int crash_signal_fd
= GetCrashSignalFD(command_line
);
391 if (crash_signal_fd
>= 0) {
392 mappings
->Share(kCrashDumpSignal
, crash_signal_fd
);
395 #endif // defined(OS_ANDROID)
397 #if defined(OS_ANDROID) && defined(VIDEO_HOLE)
398 content::ExternalVideoSurfaceContainer
*
399 CastContentBrowserClient::OverrideCreateExternalVideoSurfaceContainer(
400 content::WebContents
* web_contents
) {
401 return external_video_surface::ExternalVideoSurfaceContainerImpl::Create(
404 #endif // defined(OS_ANDROID) && defined(VIDEO_HOLE)
406 #if !defined(OS_ANDROID)
407 int CastContentBrowserClient::GetCrashSignalFD(
408 const base::CommandLine
& command_line
) {
409 std::string process_type
=
410 command_line
.GetSwitchValueASCII(switches::kProcessType
);
412 if (process_type
== switches::kRendererProcess
||
413 process_type
== switches::kGpuProcess
) {
414 breakpad::CrashHandlerHostLinux
* crash_handler
=
415 crash_handlers_
[process_type
];
416 if (!crash_handler
) {
417 crash_handler
= CreateCrashHandlerHost(process_type
);
418 crash_handlers_
[process_type
] = crash_handler
;
420 return crash_handler
->GetDeathSignalSocket();
426 breakpad::CrashHandlerHostLinux
*
427 CastContentBrowserClient::CreateCrashHandlerHost(
428 const std::string
& process_type
) {
429 // Let cast shell dump to /tmp. Internal minidump generator code can move it
430 // to /data/minidumps later, since /data/minidumps is file lock-controlled.
431 base::FilePath dumps_path
;
432 PathService::Get(base::DIR_TEMP
, &dumps_path
);
434 // Alway set "upload" to false to use our own uploader.
435 breakpad::CrashHandlerHostLinux
* crash_handler
=
436 new breakpad::CrashHandlerHostLinux(
437 process_type
, dumps_path
, false /* upload */);
438 // StartUploaderThread() even though upload is diferred.
439 // Breakpad-related memory is freed in the uploader thread.
440 crash_handler
->StartUploaderThread();
441 return crash_handler
;
443 #endif // !defined(OS_ANDROID)
446 } // namespace chromecast