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.
4 
5 #ifndef CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_
6 #define CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_
7 
8 #include <map>
9 #include <memory>
10 #include <string>
11 #include <vector>
12 
13 #include "base/macros.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/threading/thread.h"
16 #include "build/build_config.h"
17 #include "build/buildflag.h"
18 #include "chromecast/chromecast_buildflags.h"
19 #include "chromecast/metrics/cast_metrics_service_client.h"
20 #include "content/public/browser/certificate_request_result_type.h"
21 #include "content/public/browser/content_browser_client.h"
22 #include "media/mojo/buildflags.h"
23 #include "media/mojo/mojom/media_service.mojom.h"
24 #include "media/mojo/mojom/renderer.mojom.h"
25 #include "mojo/public/cpp/bindings/pending_receiver.h"
26 #include "services/metrics/public/cpp/ukm_source_id.h"
27 #include "services/service_manager/public/cpp/binder_registry.h"
28 #include "services/service_manager/public/mojom/interface_provider.mojom-forward.h"
29 #include "services/service_manager/public/mojom/service.mojom-forward.h"
30 #include "storage/browser/quota/quota_settings.h"
31 
32 class PrefService;
33 
34 namespace base {
35 struct OnTaskRunnerDeleter;
36 }
37 
38 namespace breakpad {
39 class CrashHandlerHostLinux;
40 }
41 
42 namespace device {
43 class BluetoothAdapterCast;
44 }
45 
46 namespace media {
47 class CdmFactory;
48 }
49 
50 namespace metrics {
51 class MetricsService;
52 }
53 
54 namespace net {
55 class SSLPrivateKey;
56 class X509Certificate;
57 }
58 
59 namespace chromecast {
60 class CastService;
61 class CastSystemMemoryPressureEvaluatorAdjuster;
62 class CastWindowManager;
63 class CastFeatureListCreator;
64 class GeneralAudienceBrowsingService;
65 class MemoryPressureControllerImpl;
66 class ServiceConnector;
67 
68 namespace media {
69 class MediaCapsImpl;
70 class CmaBackendFactory;
71 class MediaPipelineBackendManager;
72 class MediaResourceTracker;
73 class VideoGeometrySetterService;
74 class VideoPlaneController;
75 class VideoModeSwitcher;
76 class VideoResolutionPolicy;
77 }
78 
79 namespace shell {
80 class CastBrowserMainParts;
81 class CastNetworkContexts;
82 
83 class CastContentBrowserClient
84     : public content::ContentBrowserClient,
85       public chromecast::metrics::CastMetricsServiceDelegate {
86  public:
87   // Creates an implementation of CastContentBrowserClient. Platform should
88   // link in an implementation as needed.
89   static std::unique_ptr<CastContentBrowserClient> Create(
90       CastFeatureListCreator* cast_feature_list_creator);
91 
92   // Returns a list of headers that will be exempt from CORS preflight checks.
93   // This is needed since currently servers don't have the correct response to
94   // preflight checks.
95   static std::vector<std::string> GetCorsExemptHeadersList();
96 
97   ~CastContentBrowserClient() override;
98 
99   // Creates a ServiceConnector for routing Cast-related service interface
100   // binding requests.
101   virtual std::unique_ptr<chromecast::ServiceConnector>
102   CreateServiceConnector();
103 
104   // Creates and returns the CastService instance for the current process.
105   virtual std::unique_ptr<CastService> CreateCastService(
106       content::BrowserContext* browser_context,
107       CastSystemMemoryPressureEvaluatorAdjuster*
108           cast_system_memory_pressure_evaluator_adjuster,
109       PrefService* pref_service,
110       media::VideoPlaneController* video_plane_controller,
111       CastWindowManager* window_manager);
112 
113   virtual media::VideoModeSwitcher* GetVideoModeSwitcher();
114 
115   virtual void InitializeURLLoaderThrottleDelegate();
116 
117   // Returns the task runner that must be used for media IO.
118   scoped_refptr<base::SingleThreadTaskRunner> GetMediaTaskRunner();
119 
120   // Gets object for enforcing video resolution policy restrictions.
121   virtual media::VideoResolutionPolicy* GetVideoResolutionPolicy();
122 
123   // Creates a CmaBackendFactory.
124   virtual media::CmaBackendFactory* GetCmaBackendFactory();
125 
126   media::MediaResourceTracker* media_resource_tracker();
127 
128   void ResetMediaResourceTracker();
129 
130   media::MediaPipelineBackendManager* media_pipeline_backend_manager();
131 
132   std::unique_ptr<::media::AudioManager> CreateAudioManager(
133       ::media::AudioLogFactory* audio_log_factory) override;
134   bool OverridesAudioManager() override;
135   media::MediaCapsImpl* media_caps();
136 
137 #if !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
138   // Create a BluetoothAdapter for WebBluetooth support.
139   // TODO(slan): This further couples the browser to the Cast service. Remove
140   // this once the dedicated Bluetooth service has been implemented.
141   // (b/76155468)
142   virtual scoped_refptr<device::BluetoothAdapterCast> CreateBluetoothAdapter();
143 #endif  // !defined(OS_ANDROID) && !defined(OS_FUCHSIA)
144 
145   // chromecast::metrics::CastMetricsServiceDelegate implementation:
146   void SetMetricsClientId(const std::string& client_id) override;
147   void RegisterMetricsProviders(
148       ::metrics::MetricsService* metrics_service) override;
149 
150   // Returns whether or not the remote debugging service should be started
151   // on browser startup.
152   virtual bool EnableRemoteDebuggingImmediately();
153 
154   // content::ContentBrowserClient implementation:
155   std::vector<std::string> GetStartupServices() override;
156   std::unique_ptr<content::BrowserMainParts> CreateBrowserMainParts(
157       const content::MainFunctionParams& parameters) override;
158   void RenderProcessWillLaunch(content::RenderProcessHost* host) override;
159   bool IsHandledURL(const GURL& url) override;
160   void SiteInstanceGotProcess(content::SiteInstance* site_instance) override;
161   void AppendExtraCommandLineSwitches(base::CommandLine* command_line,
162                                       int child_process_id) override;
163   std::string GetAcceptLangs(content::BrowserContext* context) override;
164   network::mojom::NetworkContext* GetSystemNetworkContext() override;
165   void OverrideWebkitPrefs(content::RenderViewHost* render_view_host,
166                            blink::web_pref::WebPreferences* prefs) override;
167   std::string GetApplicationLocale() override;
168   scoped_refptr<content::QuotaPermissionContext> CreateQuotaPermissionContext()
169       override;
170   void AllowCertificateError(
171       content::WebContents* web_contents,
172       int cert_error,
173       const net::SSLInfo& ssl_info,
174       const GURL& request_url,
175       bool is_main_frame_request,
176       bool strict_enforcement,
177       base::OnceCallback<void(content::CertificateRequestResultType)> callback)
178       override;
179   base::OnceClosure SelectClientCertificate(
180       content::WebContents* web_contents,
181       net::SSLCertRequestInfo* cert_request_info,
182       net::ClientCertIdentityList client_certs,
183       std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
184   bool CanCreateWindow(content::RenderFrameHost* opener,
185                        const GURL& opener_url,
186                        const GURL& opener_top_level_frame_url,
187                        const url::Origin& source_origin,
188                        content::mojom::WindowContainerType container_type,
189                        const GURL& target_url,
190                        const content::Referrer& referrer,
191                        const std::string& frame_name,
192                        WindowOpenDisposition disposition,
193                        const blink::mojom::WindowFeatures& features,
194                        bool user_gesture,
195                        bool opener_suppressed,
196                        bool* no_javascript_access) override;
197   // New Mojo bindings should be added to
198   // cast_content_browser_client_receiver_bindings.cc, so that they go through
199   // security review.
200   void ExposeInterfacesToRenderer(
201       service_manager::BinderRegistry* registry,
202       blink::AssociatedInterfaceRegistry* associated_registry,
203       content::RenderProcessHost* render_process_host) override;
204   void BindMediaServiceReceiver(content::RenderFrameHost* render_frame_host,
205                                 mojo::GenericPendingReceiver receiver) override;
206   void RegisterBrowserInterfaceBindersForFrame(
207       content::RenderFrameHost* render_frame_host,
208       mojo::BinderMapWithContext<content::RenderFrameHost*>* map) override;
209   mojo::Remote<::media::mojom::MediaService> RunSecondaryMediaService()
210       override;
211   void RunServiceInstance(
212       const service_manager::Identity& identity,
213       mojo::PendingReceiver<service_manager::mojom::Service>* receiver)
214       override;
215   base::Optional<service_manager::Manifest> GetServiceManifestOverlay(
216       base::StringPiece service_name) override;
217   std::vector<service_manager::Manifest> GetExtraServiceManifests() override;
218   void GetAdditionalMappedFilesForChildProcess(
219       const base::CommandLine& command_line,
220       int child_process_id,
221       content::PosixFileDescriptorInfo* mappings) override;
222   void GetAdditionalWebUISchemes(
223       std::vector<std::string>* additional_schemes) override;
224   content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() override;
225   std::unique_ptr<content::NavigationUIData> GetNavigationUIData(
226       content::NavigationHandle* navigation_handle) override;
227   bool ShouldEnableStrictSiteIsolation() override;
228   std::vector<std::unique_ptr<content::NavigationThrottle>>
229   CreateThrottlesForNavigation(content::NavigationHandle* handle) override;
230   void RegisterNonNetworkNavigationURLLoaderFactories(
231       int frame_tree_node_id,
232       ukm::SourceIdObj ukm_source_id,
233       NonNetworkURLLoaderFactoryMap* factories) override;
234   void RegisterNonNetworkSubresourceURLLoaderFactories(
235       int render_process_id,
236       int render_frame_id,
237       NonNetworkURLLoaderFactoryMap* factories) override;
238   void OnNetworkServiceCreated(
239       network::mojom::NetworkService* network_service) override;
240   void ConfigureNetworkContextParams(
241       content::BrowserContext* context,
242       bool in_memory,
243       const base::FilePath& relative_partition_path,
244       network::mojom::NetworkContextParams* network_context_params,
245       network::mojom::CertVerifierCreationParams* cert_verifier_creation_params)
246       override;
247   std::string GetUserAgent() override;
248   bool DoesSiteRequireDedicatedProcess(content::BrowserContext* browser_context,
249                                        const GURL& effective_site_url) override;
250   // New Mojo bindings should be added to
251   // cast_content_browser_client_receiver_bindings.cc, so that they go through
252   // security review.
253   void BindHostReceiverForRenderer(
254       content::RenderProcessHost* render_process_host,
255       mojo::GenericPendingReceiver receiver) override;
GetCastFeatureListCreator()256   CastFeatureListCreator* GetCastFeatureListCreator() {
257     return cast_feature_list_creator_;
258   }
259 
260   void CreateGeneralAudienceBrowsingService();
261 
262   virtual std::unique_ptr<::media::CdmFactory> CreateCdmFactory(
263       ::media::mojom::FrameInterfaceFactory* frame_interfaces);
264 
265 #if BUILDFLAG(ENABLE_CAST_RENDERER)
266   void BindGpuHostReceiver(mojo::GenericPendingReceiver receiver) override;
267 #endif  // BUILDFLAG(ENABLE_CAST_RENDERER)
268 
cast_network_contexts()269   CastNetworkContexts* cast_network_contexts() {
270     return cast_network_contexts_.get();
271   }
272 
273  protected:
274   explicit CastContentBrowserClient(
275       CastFeatureListCreator* cast_feature_list_creator);
276 
277   void BindMediaRenderer(
278       mojo::PendingReceiver<::media::mojom::Renderer> receiver);
279 
280   void GetApplicationMediaInfo(std::string* application_session_id,
281                                bool* mixer_audio_enabled,
282                                content::RenderFrameHost* render_frame_host);
283 
284  private:
285   // Create device cert/key
286   virtual scoped_refptr<net::X509Certificate> DeviceCert();
287   virtual scoped_refptr<net::SSLPrivateKey> DeviceKey();
288 
289   virtual bool IsWhitelisted(const GURL& gurl,
290                              const std::string& session_id,
291                              int render_process_id,
292                              int render_frame_id,
293                              bool for_device_auth);
294 
295   void SelectClientCertificateOnIOThread(
296       GURL requesting_url,
297       const std::string& session_id,
298       int render_process_id,
299       int render_frame_id,
300       scoped_refptr<base::SequencedTaskRunner> original_runner,
301       base::OnceCallback<void(scoped_refptr<net::X509Certificate>,
302                               scoped_refptr<net::SSLPrivateKey>)>
303           continue_callback);
304 
305 #if !defined(OS_FUCHSIA)
306   // Returns the crash signal FD corresponding to the current process type.
307   int GetCrashSignalFD(const base::CommandLine& command_line);
308 
309 #if !defined(OS_ANDROID)
310   // Creates a CrashHandlerHost instance for the given process type.
311   breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
312       const std::string& process_type);
313 
314   // A static cache to hold crash_handlers for each process_type
315   std::map<std::string, breakpad::CrashHandlerHostLinux*> crash_handlers_;
316 
317   // Notify renderers of memory pressure (Android renderers register directly
318   // with OS for this).
319   std::unique_ptr<MemoryPressureControllerImpl> memory_pressure_controller_;
320 #endif  // !defined(OS_ANDROID)
321 #endif  // !defined(OS_FUCHSIA)
322 
323   // CMA thread used by AudioManager, MojoRenderer, and MediaPipelineBackend.
324   std::unique_ptr<base::Thread> media_thread_;
325 
326   // Tracks usage of media resource by e.g. CMA pipeline, CDM.
327   media::MediaResourceTracker* media_resource_tracker_ = nullptr;
328 
329 #if BUILDFLAG(ENABLE_CAST_RENDERER)
330   void CreateMediaService(
331       mojo::PendingReceiver<::media::mojom::MediaService> receiver);
332 
333   // VideoGeometrySetterService must be constructed On a sequence, and later
334   // runs and destructs on this sequence.
335   void CreateVideoGeometrySetterServiceOnMediaThread();
336   void BindVideoGeometrySetterServiceOnMediaThread(
337       mojo::GenericPendingReceiver receiver);
338   // video_geometry_setter_service_ lives on media thread.
339   std::unique_ptr<media::VideoGeometrySetterService, base::OnTaskRunnerDeleter>
340       video_geometry_setter_service_;
341 #endif
342 
343   // Created by CastContentBrowserClient but owned by BrowserMainLoop.
344   CastBrowserMainParts* cast_browser_main_parts_;
345   std::unique_ptr<CastNetworkContexts> cast_network_contexts_;
346   std::unique_ptr<media::CmaBackendFactory> cma_backend_factory_;
347   std::unique_ptr<GeneralAudienceBrowsingService>
348       general_audience_browsing_service_;
349 
350   CastFeatureListCreator* cast_feature_list_creator_;
351 
352   DISALLOW_COPY_AND_ASSIGN(CastContentBrowserClient);
353 };
354 
355 }  // namespace shell
356 }  // namespace chromecast
357 
358 #endif  // CHROMECAST_BROWSER_CAST_CONTENT_BROWSER_CLIENT_H_
359