Move OSVersion out of platform_backend.
[chromium-blink-merge.git] / chromecast / browser / cast_content_browser_client.cc
blob5b2c0540649cb762506410f2d9b803a23d125a9a
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/rtl.h"
13 #include "base/path_service.h"
14 #include "chromecast/base/cast_paths.h"
15 #include "chromecast/base/chromecast_switches.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/geolocation/cast_access_token_store.h"
23 #include "chromecast/browser/media/cma_message_filter_host.h"
24 #include "chromecast/browser/url_request_context_factory.h"
25 #include "chromecast/common/global_descriptors.h"
26 #include "chromecast/media/cma/backend/media_pipeline_device.h"
27 #include "chromecast/media/cma/backend/media_pipeline_device_factory.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 "media/audio/audio_manager_factory.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 "components/crash/browser/crash_dump_manager_android.h"
48 #include "components/external_video_surface/browser/android/external_video_surface_container_impl.h"
49 #endif // defined(OS_ANDROID)
51 namespace chromecast {
52 namespace shell {
54 CastContentBrowserClient::CastContentBrowserClient()
55 : url_request_context_factory_(new URLRequestContextFactory()) {
58 CastContentBrowserClient::~CastContentBrowserClient() {
59 content::BrowserThread::DeleteSoon(
60 content::BrowserThread::IO,
61 FROM_HERE,
62 url_request_context_factory_.release());
65 void CastContentBrowserClient::AppendExtraCommandLineSwitches(
66 base::CommandLine* command_line) {
69 std::vector<scoped_refptr<content::BrowserMessageFilter>>
70 CastContentBrowserClient::GetBrowserMessageFilters() {
71 return std::vector<scoped_refptr<content::BrowserMessageFilter>>();
74 scoped_ptr<::media::AudioManagerFactory>
75 CastContentBrowserClient::CreateAudioManagerFactory() {
76 // Return nullptr. The factory will not be set, and the statically linked
77 // implementation of AudioManager will be used.
78 return scoped_ptr<::media::AudioManagerFactory>();
81 #if !defined(OS_ANDROID)
82 scoped_ptr<media::MediaPipelineDevice>
83 CastContentBrowserClient::CreateMediaPipelineDevice(
84 const media::MediaPipelineDeviceParams& params) {
85 scoped_ptr<media::MediaPipelineDeviceFactory> factory =
86 GetMediaPipelineDeviceFactory(params);
87 return make_scoped_ptr(new media::MediaPipelineDevice(factory.Pass()));
89 #endif
91 content::BrowserMainParts* CastContentBrowserClient::CreateBrowserMainParts(
92 const content::MainFunctionParams& parameters) {
93 return new CastBrowserMainParts(parameters,
94 url_request_context_factory_.get(),
95 CreateAudioManagerFactory());
98 void CastContentBrowserClient::RenderProcessWillLaunch(
99 content::RenderProcessHost* host) {
100 #if !defined(OS_ANDROID)
101 scoped_refptr<media::CmaMessageFilterHost> cma_message_filter(
102 new media::CmaMessageFilterHost(
103 host->GetID(),
104 base::Bind(
105 &CastContentBrowserClient::CreateMediaPipelineDevice,
106 base::Unretained(this))));
107 host->AddFilter(cma_message_filter.get());
108 #endif // !defined(OS_ANDROID)
110 // Forcibly trigger I/O-thread URLRequestContext initialization before
111 // getting HostResolver.
112 content::BrowserThread::PostTaskAndReplyWithResult(
113 content::BrowserThread::IO, FROM_HERE,
114 base::Bind(&net::URLRequestContextGetter::GetURLRequestContext,
115 base::Unretained(
116 url_request_context_factory_->GetSystemGetter())),
117 base::Bind(&CastContentBrowserClient::AddNetworkHintsMessageFilter,
118 base::Unretained(this), host->GetID()));
120 auto extra_filters = GetBrowserMessageFilters();
121 for (auto const& filter : extra_filters) {
122 host->AddFilter(filter.get());
126 void CastContentBrowserClient::AddNetworkHintsMessageFilter(
127 int render_process_id, net::URLRequestContext* context) {
128 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
130 content::RenderProcessHost* host =
131 content::RenderProcessHost::FromID(render_process_id);
132 if (!host)
133 return;
135 scoped_refptr<content::BrowserMessageFilter> network_hints_message_filter(
136 new network_hints::NetworkHintsMessageFilter(
137 url_request_context_factory_->host_resolver()));
138 host->AddFilter(network_hints_message_filter.get());
141 net::URLRequestContextGetter* CastContentBrowserClient::CreateRequestContext(
142 content::BrowserContext* browser_context,
143 content::ProtocolHandlerMap* protocol_handlers,
144 content::URLRequestInterceptorScopedVector request_interceptors) {
145 return url_request_context_factory_->CreateMainGetter(
146 browser_context,
147 protocol_handlers,
148 request_interceptors.Pass());
151 bool CastContentBrowserClient::IsHandledURL(const GURL& url) {
152 if (!url.is_valid())
153 return false;
155 static const char* const kProtocolList[] = {
156 url::kBlobScheme,
157 url::kFileSystemScheme,
158 content::kChromeUIScheme,
159 content::kChromeDevToolsScheme,
160 url::kDataScheme,
163 const std::string& scheme = url.scheme();
164 for (size_t i = 0; i < arraysize(kProtocolList); ++i) {
165 if (scheme == kProtocolList[i])
166 return true;
169 if (scheme == url::kFileScheme) {
170 return base::CommandLine::ForCurrentProcess()->HasSwitch(
171 switches::kEnableLocalFileAccesses);
174 return false;
177 void CastContentBrowserClient::AppendExtraCommandLineSwitches(
178 base::CommandLine* command_line,
179 int child_process_id) {
180 std::string process_type =
181 command_line->GetSwitchValueNative(switches::kProcessType);
182 base::CommandLine* browser_command_line =
183 base::CommandLine::ForCurrentProcess();
185 // IsCrashReporterEnabled() is set when InitCrashReporter() is called, and
186 // controlled by GetBreakpadClient()->EnableBreakpadForProcess(), therefore
187 // it's ok to add switch to every process here.
188 if (breakpad::IsCrashReporterEnabled()) {
189 command_line->AppendSwitch(switches::kEnableCrashReporter);
192 // Renderer process command-line
193 if (process_type == switches::kRendererProcess) {
194 // Any browser command-line switches that should be propagated to
195 // the renderer go here.
197 if (browser_command_line->HasSwitch(switches::kEnableCmaMediaPipeline))
198 command_line->AppendSwitch(switches::kEnableCmaMediaPipeline);
199 if (browser_command_line->HasSwitch(switches::kEnableLegacyHolePunching))
200 command_line->AppendSwitch(switches::kEnableLegacyHolePunching);
203 #if defined(OS_LINUX)
204 // Necessary for accelerated 2d canvas. By default on Linux, Chromium assumes
205 // GLES2 contexts can be lost to a power-save mode, which breaks GPU canvas
206 // apps.
207 if (process_type == switches::kGpuProcess) {
208 command_line->AppendSwitch(switches::kGpuNoContextLost);
210 #endif
212 AppendExtraCommandLineSwitches(command_line);
215 content::AccessTokenStore* CastContentBrowserClient::CreateAccessTokenStore() {
216 return new CastAccessTokenStore(
217 CastBrowserProcess::GetInstance()->browser_context());
220 void CastContentBrowserClient::OverrideWebkitPrefs(
221 content::RenderViewHost* render_view_host,
222 content::WebPreferences* prefs) {
223 prefs->allow_scripts_to_close_windows = true;
224 // TODO(lcwu): http://crbug.com/391089. This pref is set to true by default
225 // because some content providers such as YouTube use plain http requests
226 // to retrieve media data chunks while running in a https page. This pref
227 // should be disabled once all the content providers are no longer doing that.
228 prefs->allow_running_insecure_content = true;
231 void CastContentBrowserClient::ResourceDispatcherHostCreated() {
232 CastBrowserProcess::GetInstance()->SetResourceDispatcherHostDelegate(
233 make_scoped_ptr(new CastResourceDispatcherHostDelegate));
234 content::ResourceDispatcherHost::Get()->SetDelegate(
235 CastBrowserProcess::GetInstance()->resource_dispatcher_host_delegate());
238 std::string CastContentBrowserClient::GetApplicationLocale() {
239 const std::string locale(base::i18n::GetConfiguredLocale());
240 return locale.empty() ? "en-US" : locale;
243 content::QuotaPermissionContext*
244 CastContentBrowserClient::CreateQuotaPermissionContext() {
245 return new CastQuotaPermissionContext();
248 void CastContentBrowserClient::AllowCertificateError(
249 int render_process_id,
250 int render_view_id,
251 int cert_error,
252 const net::SSLInfo& ssl_info,
253 const GURL& request_url,
254 content::ResourceType resource_type,
255 bool overridable,
256 bool strict_enforcement,
257 bool expired_previous_decision,
258 const base::Callback<void(bool)>& callback,
259 content::CertificateRequestResultType* result) {
260 // Allow developers to override certificate errors.
261 // Otherwise, any fatal certificate errors will cause an abort.
262 *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
263 return;
266 void CastContentBrowserClient::SelectClientCertificate(
267 content::WebContents* web_contents,
268 net::SSLCertRequestInfo* cert_request_info,
269 scoped_ptr<content::ClientCertificateDelegate> delegate) {
270 GURL requesting_url("https://" + cert_request_info->host_and_port.ToString());
272 if (!requesting_url.is_valid()) {
273 LOG(ERROR) << "Invalid URL string: "
274 << requesting_url.possibly_invalid_spec();
275 delegate->ContinueWithCertificate(nullptr);
276 return;
279 // In our case there are no relevant certs in the cert_request_info. The cert
280 // we need to return (if permitted) is the Cast device cert, which we can
281 // access directly through the ClientAuthSigner instance. However, we need to
282 // be on the IO thread to determine whether the app is whitelisted to return
283 // it, because CastNetworkDelegate is bound to the IO thread.
284 // Subsequently, the callback must then itself be performed back here
285 // on the UI thread.
287 // TODO(davidben): Stop using child ID to identify an app.
288 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
289 content::BrowserThread::PostTaskAndReplyWithResult(
290 content::BrowserThread::IO, FROM_HERE,
291 base::Bind(&CastContentBrowserClient::SelectClientCertificateOnIOThread,
292 base::Unretained(this), requesting_url,
293 web_contents->GetRenderProcessHost()->GetID()),
294 base::Bind(&content::ClientCertificateDelegate::ContinueWithCertificate,
295 base::Owned(delegate.release())));
298 net::X509Certificate*
299 CastContentBrowserClient::SelectClientCertificateOnIOThread(
300 GURL requesting_url,
301 int render_process_id) {
302 DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
303 CastNetworkDelegate* network_delegate =
304 url_request_context_factory_->app_network_delegate();
305 if (network_delegate->IsWhitelisted(requesting_url,
306 render_process_id, false)) {
307 return CastNetworkDelegate::DeviceCert();
308 } else {
309 LOG(ERROR) << "Invalid host for client certificate request: "
310 << requesting_url.host()
311 << " with render_process_id: "
312 << render_process_id;
313 return NULL;
317 bool CastContentBrowserClient::CanCreateWindow(
318 const GURL& opener_url,
319 const GURL& opener_top_level_frame_url,
320 const GURL& source_origin,
321 WindowContainerType container_type,
322 const GURL& target_url,
323 const content::Referrer& referrer,
324 WindowOpenDisposition disposition,
325 const blink::WebWindowFeatures& features,
326 bool user_gesture,
327 bool opener_suppressed,
328 content::ResourceContext* context,
329 int render_process_id,
330 int opener_render_view_id,
331 int opener_render_frame_id,
332 bool* no_javascript_access) {
333 *no_javascript_access = true;
334 return false;
337 #if defined(OS_ANDROID)
338 void CastContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
339 const base::CommandLine& command_line,
340 int child_process_id,
341 content::FileDescriptorInfo* mappings,
342 std::map<int, base::MemoryMappedFile::Region>* regions) {
343 mappings->Share(
344 kAndroidPakDescriptor,
345 base::GlobalDescriptors::GetInstance()->Get(kAndroidPakDescriptor));
346 regions->insert(std::make_pair(
347 kAndroidPakDescriptor, base::GlobalDescriptors::GetInstance()->GetRegion(
348 kAndroidPakDescriptor)));
350 if (breakpad::IsCrashReporterEnabled()) {
351 base::File minidump_file(
352 breakpad::CrashDumpManager::GetInstance()->CreateMinidumpFile(
353 child_process_id));
354 if (!minidump_file.IsValid()) {
355 LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
356 << "be disabled for this process.";
357 } else {
358 mappings->Transfer(kAndroidMinidumpDescriptor,
359 base::ScopedFD(minidump_file.TakePlatformFile()));
363 #else
364 void CastContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
365 const base::CommandLine& command_line,
366 int child_process_id,
367 content::FileDescriptorInfo* mappings) {
368 int crash_signal_fd = GetCrashSignalFD(command_line);
369 if (crash_signal_fd >= 0) {
370 mappings->Share(kCrashDumpSignal, crash_signal_fd);
373 #endif // defined(OS_ANDROID)
375 #if defined(OS_ANDROID) && defined(VIDEO_HOLE)
376 content::ExternalVideoSurfaceContainer*
377 CastContentBrowserClient::OverrideCreateExternalVideoSurfaceContainer(
378 content::WebContents* web_contents) {
379 return external_video_surface::ExternalVideoSurfaceContainerImpl::Create(
380 web_contents);
382 #endif // defined(OS_ANDROID) && defined(VIDEO_HOLE)
384 #if !defined(OS_ANDROID)
385 int CastContentBrowserClient::GetCrashSignalFD(
386 const base::CommandLine& command_line) {
387 std::string process_type =
388 command_line.GetSwitchValueASCII(switches::kProcessType);
390 if (process_type == switches::kRendererProcess ||
391 process_type == switches::kGpuProcess) {
392 breakpad::CrashHandlerHostLinux* crash_handler =
393 crash_handlers_[process_type];
394 if (!crash_handler) {
395 crash_handler = CreateCrashHandlerHost(process_type);
396 crash_handlers_[process_type] = crash_handler;
398 return crash_handler->GetDeathSignalSocket();
401 return -1;
404 breakpad::CrashHandlerHostLinux*
405 CastContentBrowserClient::CreateCrashHandlerHost(
406 const std::string& process_type) {
407 // Let cast shell dump to /tmp. Internal minidump generator code can move it
408 // to /data/minidumps later, since /data/minidumps is file lock-controlled.
409 base::FilePath dumps_path;
410 PathService::Get(base::DIR_TEMP, &dumps_path);
412 // Alway set "upload" to false to use our own uploader.
413 breakpad::CrashHandlerHostLinux* crash_handler =
414 new breakpad::CrashHandlerHostLinux(
415 process_type, dumps_path, false /* upload */);
416 // StartUploaderThread() even though upload is diferred.
417 // Breakpad-related memory is freed in the uploader thread.
418 crash_handler->StartUploaderThread();
419 return crash_handler;
421 #endif // !defined(OS_ANDROID)
423 } // namespace shell
424 } // namespace chromecast