[MediaRouter] Update MR-2-Extension's PostMessage to return boolean.
[chromium-blink-merge.git] / chromecast / browser / cast_content_browser_client.cc
blob85938256156d1af6154d7844ae7d5f852a07bef4
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"
7 #include <string>
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/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_message_filter_host.h"
25 #include "chromecast/browser/url_request_context_factory.h"
26 #include "chromecast/common/global_descriptors.h"
27 #include "chromecast/media/cma/backend/media_pipeline_device.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 "media/audio/audio_manager_factory.h"
43 #include "net/ssl/ssl_cert_request_info.h"
44 #include "net/url_request/url_request_context_getter.h"
45 #include "ui/gl/gl_switches.h"
47 #if defined(OS_ANDROID)
48 #include "components/crash/browser/crash_dump_manager_android.h"
49 #include "components/external_video_surface/browser/android/external_video_surface_container_impl.h"
50 #endif // defined(OS_ANDROID)
52 namespace chromecast {
53 namespace shell {
55 CastContentBrowserClient::CastContentBrowserClient()
56 : v8_natives_fd_(-1),
57 v8_snapshot_fd_(-1),
58 url_request_context_factory_(new URLRequestContextFactory()) {
61 CastContentBrowserClient::~CastContentBrowserClient() {
62 content::BrowserThread::DeleteSoon(
63 content::BrowserThread::IO,
64 FROM_HERE,
65 url_request_context_factory_.release());
68 void CastContentBrowserClient::AppendExtraCommandLineSwitches(
69 base::CommandLine* command_line) {
72 std::vector<scoped_refptr<content::BrowserMessageFilter>>
73 CastContentBrowserClient::GetBrowserMessageFilters() {
74 return std::vector<scoped_refptr<content::BrowserMessageFilter>>();
77 scoped_ptr<::media::AudioManagerFactory>
78 CastContentBrowserClient::CreateAudioManagerFactory() {
79 // Return nullptr. The factory will not be set, and the statically linked
80 // implementation of AudioManager will be used.
81 return scoped_ptr<::media::AudioManagerFactory>();
84 #if !defined(OS_ANDROID)
85 scoped_ptr<media::MediaPipelineDevice>
86 CastContentBrowserClient::CreateMediaPipelineDevice(
87 const media::MediaPipelineDeviceParams& params) {
88 return media::CreateMediaPipelineDevice(params);
90 #endif
92 content::BrowserMainParts* CastContentBrowserClient::CreateBrowserMainParts(
93 const content::MainFunctionParams& parameters) {
94 return new CastBrowserMainParts(parameters,
95 url_request_context_factory_.get(),
96 CreateAudioManagerFactory());
99 void CastContentBrowserClient::RenderProcessWillLaunch(
100 content::RenderProcessHost* host) {
101 #if !defined(OS_ANDROID)
102 scoped_refptr<media::CmaMessageFilterHost> cma_message_filter(
103 new media::CmaMessageFilterHost(
104 host->GetID(),
105 base::Bind(
106 &CastContentBrowserClient::CreateMediaPipelineDevice,
107 base::Unretained(this))));
108 host->AddFilter(cma_message_filter.get());
109 #endif // !defined(OS_ANDROID)
111 // Forcibly trigger I/O-thread URLRequestContext initialization before
112 // getting HostResolver.
113 content::BrowserThread::PostTaskAndReplyWithResult(
114 content::BrowserThread::IO, FROM_HERE,
115 base::Bind(&net::URLRequestContextGetter::GetURLRequestContext,
116 base::Unretained(
117 url_request_context_factory_->GetSystemGetter())),
118 base::Bind(&CastContentBrowserClient::AddNetworkHintsMessageFilter,
119 base::Unretained(this), host->GetID()));
121 auto extra_filters = GetBrowserMessageFilters();
122 for (auto const& filter : extra_filters) {
123 host->AddFilter(filter.get());
127 void CastContentBrowserClient::AddNetworkHintsMessageFilter(
128 int render_process_id, net::URLRequestContext* context) {
129 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
131 content::RenderProcessHost* host =
132 content::RenderProcessHost::FromID(render_process_id);
133 if (!host)
134 return;
136 scoped_refptr<content::BrowserMessageFilter> network_hints_message_filter(
137 new network_hints::NetworkHintsMessageFilter(
138 url_request_context_factory_->host_resolver()));
139 host->AddFilter(network_hints_message_filter.get());
142 net::URLRequestContextGetter* CastContentBrowserClient::CreateRequestContext(
143 content::BrowserContext* browser_context,
144 content::ProtocolHandlerMap* protocol_handlers,
145 content::URLRequestInterceptorScopedVector request_interceptors) {
146 return url_request_context_factory_->CreateMainGetter(
147 browser_context,
148 protocol_handlers,
149 request_interceptors.Pass());
152 bool CastContentBrowserClient::IsHandledURL(const GURL& url) {
153 if (!url.is_valid())
154 return false;
156 static const char* const kProtocolList[] = {
157 url::kBlobScheme,
158 url::kFileSystemScheme,
159 content::kChromeUIScheme,
160 content::kChromeDevToolsScheme,
161 url::kDataScheme,
164 const std::string& scheme = url.scheme();
165 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
166 if (scheme == kProtocolList[i])
167 return true;
170 if (scheme == url::kFileScheme) {
171 return base::CommandLine::ForCurrentProcess()->HasSwitch(
172 switches::kEnableLocalFileAccesses);
175 return false;
178 void CastContentBrowserClient::AppendMappedFileCommandLineSwitches(
179 base::CommandLine* command_line) {
180 std::string process_type =
181 command_line->GetSwitchValueNative(switches::kProcessType);
183 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
184 if (process_type != switches::kZygoteProcess) {
185 DCHECK(natives_fd_exists());
186 command_line->AppendSwitch(::switches::kV8NativesPassedByFD);
187 if (snapshot_fd_exists())
188 command_line->AppendSwitch(::switches::kV8SnapshotPassedByFD);
192 #endif // V8_USE_EXTERNAL_STARTUP_DATA
193 void CastContentBrowserClient::AppendExtraCommandLineSwitches(
194 base::CommandLine* command_line,
195 int child_process_id) {
196 std::string process_type =
197 command_line->GetSwitchValueNative(switches::kProcessType);
198 base::CommandLine* browser_command_line =
199 base::CommandLine::ForCurrentProcess();
201 // IsCrashReporterEnabled() is set when InitCrashReporter() is called, and
202 // controlled by GetBreakpadClient()->EnableBreakpadForProcess(), therefore
203 // it's ok to add switch to every process here.
204 if (breakpad::IsCrashReporterEnabled()) {
205 command_line->AppendSwitch(switches::kEnableCrashReporter);
208 // Renderer process command-line
209 if (process_type == switches::kRendererProcess) {
210 // Any browser command-line switches that should be propagated to
211 // the renderer go here.
213 if (browser_command_line->HasSwitch(switches::kEnableCmaMediaPipeline))
214 command_line->AppendSwitch(switches::kEnableCmaMediaPipeline);
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
220 // apps.
221 if (process_type == switches::kGpuProcess) {
222 command_line->AppendSwitch(switches::kGpuNoContextLost);
224 #endif
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,
264 int render_view_id,
265 int cert_error,
266 const net::SSLInfo& ssl_info,
267 const GURL& request_url,
268 content::ResourceType resource_type,
269 bool overridable,
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;
277 return;
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);
290 return;
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
299 // on the UI thread.
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(
314 GURL requesting_url,
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();
322 } else {
323 LOG(ERROR) << "Invalid host for client certificate request: "
324 << requesting_url.host()
325 << " with render_process_id: "
326 << render_process_id;
327 return NULL;
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,
340 bool user_gesture,
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;
348 return false;
351 void CastContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
352 const base::CommandLine& command_line,
353 int child_process_id,
354 content::FileDescriptorInfo* mappings) {
355 #if defined(V8_USE_EXTERNAL_STARTUP_DATA)
356 if (!natives_fd_exists()) {
357 int v8_natives_fd = -1;
358 int v8_snapshot_fd = -1;
359 if (gin::V8Initializer::OpenV8FilesForChildProcesses(&v8_natives_fd,
360 &v8_snapshot_fd)) {
361 v8_natives_fd_.reset(v8_natives_fd);
362 v8_snapshot_fd_.reset(v8_snapshot_fd);
365 // V8 can't start up without the source of the natives, but it can
366 // start up (slower) without the snapshot.
367 DCHECK(natives_fd_exists());
368 mappings->Share(kV8NativesDataDescriptor, v8_natives_fd_.get());
369 mappings->Share(kV8SnapshotDataDescriptor, v8_snapshot_fd_.get());
370 #endif // V8_USE_EXTERNAL_STARTUP_DATA
371 #if defined(OS_ANDROID)
372 const int flags_open_read = base::File::FLAG_OPEN | base::File::FLAG_READ;
373 base::FilePath pak_file_path;
374 CHECK(PathService::Get(FILE_CAST_PAK, &pak_file_path));
375 base::File pak_file(pak_file_path, flags_open_read);
376 if (!pak_file.IsValid()) {
377 NOTREACHED() << "Failed to open file when creating renderer process: "
378 << "cast_shell.pak";
380 mappings->Transfer(kAndroidPakDescriptor,
381 base::ScopedFD(pak_file.TakePlatformFile()));
383 if (breakpad::IsCrashReporterEnabled()) {
384 base::File minidump_file(
385 breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
386 child_process_id));
387 if (!minidump_file.IsValid()) {
388 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
389 << "be disabled for this process.";
390 } else {
391 mappings->Transfer(kAndroidMinidumpDescriptor,
392 base::ScopedFD(minidump_file.TakePlatformFile()));
396 base::FilePath app_data_path;
397 CHECK(PathService::Get(base::DIR_ANDROID_APP_DATA, &app_data_path));
398 base::FilePath icudata_path =
399 app_data_path.AppendASCII(base::i18n::kIcuDataFileName);
400 base::File icudata_file(icudata_path, flags_open_read);
401 if (!icudata_file.IsValid())
402 NOTREACHED() << "Failed to open ICU file when creating renderer process";
403 mappings->Transfer(kAndroidICUDataDescriptor,
404 base::ScopedFD(icudata_file.TakePlatformFile()));
405 #else
406 int crash_signal_fd = GetCrashSignalFD(command_line);
407 if (crash_signal_fd >= 0) {
408 mappings->Share(kCrashDumpSignal, crash_signal_fd);
410 #endif // defined(OS_ANDROID)
413 #if defined(OS_ANDROID) && defined(VIDEO_HOLE)
414 content::ExternalVideoSurfaceContainer*
415 CastContentBrowserClient::OverrideCreateExternalVideoSurfaceContainer(
416 content::WebContents* web_contents) {
417 return external_video_surface::ExternalVideoSurfaceContainerImpl::Create(
418 web_contents);
420 #endif // defined(OS_ANDROID) && defined(VIDEO_HOLE)
422 #if !defined(OS_ANDROID)
423 int CastContentBrowserClient::GetCrashSignalFD(
424 const base::CommandLine& command_line) {
425 std::string process_type =
426 command_line.GetSwitchValueASCII(switches::kProcessType);
428 if (process_type == switches::kRendererProcess ||
429 process_type == switches::kGpuProcess) {
430 breakpad::CrashHandlerHostLinux* crash_handler =
431 crash_handlers_[process_type];
432 if (!crash_handler) {
433 crash_handler = CreateCrashHandlerHost(process_type);
434 crash_handlers_[process_type] = crash_handler;
436 return crash_handler->GetDeathSignalSocket();
439 return -1;
442 breakpad::CrashHandlerHostLinux*
443 CastContentBrowserClient::CreateCrashHandlerHost(
444 const std::string& process_type) {
445 // Let cast shell dump to /tmp. Internal minidump generator code can move it
446 // to /data/minidumps later, since /data/minidumps is file lock-controlled.
447 base::FilePath dumps_path;
448 PathService::Get(base::DIR_TEMP, &dumps_path);
450 // Alway set "upload" to false to use our own uploader.
451 breakpad::CrashHandlerHostLinux* crash_handler =
452 new breakpad::CrashHandlerHostLinux(
453 process_type, dumps_path, false /* upload */);
454 // StartUploaderThread() even though upload is diferred.
455 // Breakpad-related memory is freed in the uploader thread.
456 crash_handler->StartUploaderThread();
457 return crash_handler;
459 #endif // !defined(OS_ANDROID)
461 } // namespace shell
462 } // namespace chromecast