content_browser_client.h revision 558790d6acca3451cf3a6b497803a5f07d0bec58
1// Copyright (c) 2012 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 CONTENT_PUBLIC_BROWSER_CONTENT_BROWSER_CLIENT_H_
6#define CONTENT_PUBLIC_BROWSER_CONTENT_BROWSER_CLIENT_H_
7
8#include <map>
9#include <string>
10#include <utility>
11#include <vector>
12
13#include "base/callback_forward.h"
14#include "base/memory/linked_ptr.h"
15#include "base/memory/scoped_ptr.h"
16#include "base/memory/scoped_vector.h"
17#include "base/values.h"
18#include "content/public/browser/certificate_request_result_type.h"
19#include "content/public/browser/file_descriptor_info.h"
20#include "content/public/common/content_client.h"
21#include "content/public/common/socket_permission_request.h"
22#include "content/public/common/window_container_type.h"
23#include "net/base/mime_util.h"
24#include "net/cookies/canonical_cookie.h"
25#include "net/url_request/url_request_job_factory.h"
26#include "third_party/WebKit/public/web/WebNotificationPresenter.h"
27#include "ui/base/window_open_disposition.h"
28#include "webkit/common/resource_type.h"
29
30#if defined(OS_POSIX) && !defined(OS_MACOSX)
31#include "base/posix/global_descriptors.h"
32#endif
33
34class CommandLine;
35class GURL;
36struct WebPreferences;
37
38namespace WebKit {
39struct WebWindowFeatures;
40}
41
42namespace base {
43class DictionaryValue;
44class FilePath;
45}
46namespace crypto {
47class CryptoModuleBlockingPasswordDelegate;
48}
49
50namespace gfx {
51class ImageSkia;
52}
53
54namespace net {
55class CookieOptions;
56class HttpNetworkSession;
57class NetLog;
58class SSLCertRequestInfo;
59class SSLInfo;
60class URLRequest;
61class URLRequestContext;
62class URLRequestContextGetter;
63class X509Certificate;
64}
65
66namespace sandbox {
67class TargetPolicy;
68}
69
70namespace ui {
71class SelectFilePolicy;
72}
73
74namespace fileapi {
75class ExternalMountPoints;
76class FileSystemBackend;
77}
78
79namespace content {
80
81class AccessTokenStore;
82class BrowserChildProcessHost;
83class BrowserContext;
84class BrowserMainParts;
85class BrowserPluginGuestDelegate;
86class BrowserPpapiHost;
87class BrowserURLHandler;
88class LocationProvider;
89class MediaObserver;
90class QuotaPermissionContext;
91class RenderProcessHost;
92class RenderViewHost;
93class RenderViewHostDelegateView;
94class ResourceContext;
95class SiteInstance;
96class SpeechRecognitionManagerDelegate;
97class WebContents;
98class WebContentsViewDelegate;
99class WebContentsViewPort;
100struct MainFunctionParams;
101struct Referrer;
102struct ShowDesktopNotificationHostMsgParams;
103
104// A mapping from the scheme name to the protocol handler that services its
105// content.
106typedef std::map<
107  std::string, linked_ptr<net::URLRequestJobFactory::ProtocolHandler> >
108    ProtocolHandlerMap;
109
110// Embedder API (or SPI) for participating in browser logic, to be implemented
111// by the client of the content browser. See ChromeContentBrowserClient for the
112// principal implementation. The methods are assumed to be called on the UI
113// thread unless otherwise specified. Use this "escape hatch" sparingly, to
114// avoid the embedder interface ballooning and becoming very specific to Chrome.
115// (Often, the call out to the client can happen in a different part of the code
116// that either already has a hook out to the embedder, or calls out to one of
117// the observer interfaces.)
118class CONTENT_EXPORT ContentBrowserClient {
119 public:
120  virtual ~ContentBrowserClient() {}
121
122  // Allows the embedder to set any number of custom BrowserMainParts
123  // implementations for the browser startup code. See comments in
124  // browser_main_parts.h.
125  virtual BrowserMainParts* CreateBrowserMainParts(
126      const MainFunctionParams& parameters);
127
128  // Allows an embedder to return their own WebContentsViewPort implementation.
129  // Return NULL to let the default one for the platform be created. Otherwise
130  // |render_view_host_delegate_view| also needs to be provided, and it is
131  // owned by the embedder.
132  virtual WebContentsViewPort* OverrideCreateWebContentsView(
133      WebContents* web_contents,
134      RenderViewHostDelegateView** render_view_host_delegate_view);
135
136  // If content creates the WebContentsView implementation, it will ask the
137  // embedder to return an (optional) delegate to customize it. The view will
138  // own the delegate.
139  virtual WebContentsViewDelegate* GetWebContentsViewDelegate(
140      WebContents* web_contents);
141
142  // Notifies that a guest WebContents has been created. A guest WebContents
143  // represents a renderer that's hosted within a BrowserPlugin. Creation can
144  // occur an arbitrary length of time before attachment. If the new guest has
145  // an |opener_web_contents|, then it's a new window created by that opener.
146  // If the guest was created via navigation, then |extra_params| will be
147  // non-NULL. |extra_params| are parameters passed to the BrowserPlugin object
148  // element by the content embedder. These parameters may include the API to
149  // enable for the given guest. |guest_delegate| is a return parameter of
150  // the delegate in the content embedder that will service the guest in the
151  // content layer. The content layer takes ownership of the |guest_delegate|.
152  virtual void GuestWebContentsCreated(
153      WebContents* guest_web_contents,
154      WebContents* opener_web_contents,
155      BrowserPluginGuestDelegate** guest_delegate,
156      scoped_ptr<base::DictionaryValue> extra_params) {}
157
158  // Notifies that a guest WebContents has been attached to a BrowserPlugin.
159  // A guest is attached to a BrowserPlugin when the guest has acquired an
160  // embedder WebContents. This happens on initial navigation or when a new
161  // window is attached to a BrowserPlugin. |extra_params| are params sent
162  // from javascript.
163  virtual void GuestWebContentsAttached(
164      WebContents* guest_web_contents,
165      WebContents* embedder_web_contents,
166      int browser_plugin_instance_id,
167      const base::DictionaryValue& extra_params) {}
168
169  // Notifies that a RenderProcessHost has been created. This is called before
170  // the content layer adds its own BrowserMessageFilters, so that the
171  // embedder's IPC filters have priority.
172  virtual void RenderProcessHostCreated(RenderProcessHost* host) {}
173
174  // Notifies that a BrowserChildProcessHost has been created.
175  virtual void BrowserChildProcessHostCreated(BrowserChildProcessHost* host) {}
176
177  // Determines whether a navigation from |current_instance| to |url| would be a
178  // valid entry point to a "privileged site," based on whether it
179  // |is_renderer_initiated|. A privileged site requires careful process
180  // isolation to ensure its privileges do not leak, and it can only be entered
181  // via known navigation paths.
182  //
183  // If this is a valid entry to a privileged site, this function should rewrite
184  // the origin of |url| with a non-http(s) origin that represents the
185  // privileged site. This will distinguish the resulting SiteInstance from
186  // other SiteInstances in the process model.
187  virtual GURL GetPossiblyPrivilegedURL(
188      content::BrowserContext* browser_context,
189      const GURL& url,
190      bool is_renderer_initiated,
191      SiteInstance* current_instance);
192
193  // Get the effective URL for the given actual URL, to allow an embedder to
194  // group different url schemes in the same SiteInstance.
195  virtual GURL GetEffectiveURL(BrowserContext* browser_context,
196                               const GURL& url);
197
198  // Returns whether all instances of the specified effective URL should be
199  // rendered by the same process, rather than using process-per-site-instance.
200  virtual bool ShouldUseProcessPerSite(BrowserContext* browser_context,
201                                       const GURL& effective_url);
202
203  // Returns a list additional WebUI schemes, if any.  These additional schemes
204  // act as aliases to the chrome: scheme.  The additional schemes may or may
205  // not serve specific WebUI pages depending on the particular URLDataSource
206  // and its override of URLDataSource::ShouldServiceRequest.
207  virtual void GetAdditionalWebUISchemes(
208      std::vector<std::string>* additional_schemes) {}
209
210  // Creates the main net::URLRequestContextGetter. Should only be called once
211  // per ContentBrowserClient object.
212  // TODO(ajwong): Remove once http://crbug.com/159193 is resolved.
213  virtual net::URLRequestContextGetter* CreateRequestContext(
214      BrowserContext* browser_context,
215      ProtocolHandlerMap* protocol_handlers);
216
217  // Creates the net::URLRequestContextGetter for a StoragePartition. Should
218  // only be called once per partition_path per ContentBrowserClient object.
219  // TODO(ajwong): Remove once http://crbug.com/159193 is resolved.
220  virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition(
221      BrowserContext* browser_context,
222      const base::FilePath& partition_path,
223      bool in_memory,
224      ProtocolHandlerMap* protocol_handlers);
225
226  // Returns whether a specified URL is handled by the embedder's internal
227  // protocol handlers.
228  virtual bool IsHandledURL(const GURL& url);
229
230  // Returns whether the given process is allowed to commit |url|.  This is a
231  // more conservative check than IsSuitableHost, since it is used after a
232  // navigation has committed to ensure that the process did not exceed its
233  // authority.
234  virtual bool CanCommitURL(RenderProcessHost* process_host, const GURL& url);
235
236  // Returns whether a new view for a given |site_url| can be launched in a
237  // given |process_host|.
238  virtual bool IsSuitableHost(RenderProcessHost* process_host,
239                              const GURL& site_url);
240
241  // Returns whether a new process should be created or an existing one should
242  // be reused based on the URL we want to load. This should return false,
243  // unless there is a good reason otherwise.
244  virtual bool ShouldTryToUseExistingProcessHost(
245      BrowserContext* browser_context, const GURL& url);
246
247  // Called when a site instance is first associated with a process.
248  virtual void SiteInstanceGotProcess(SiteInstance* site_instance) {}
249
250  // Called from a site instance's destructor.
251  virtual void SiteInstanceDeleting(SiteInstance* site_instance) {}
252
253  // Returns true if for the navigation from |current_url| to |new_url|
254  // in |site_instance|, the process should be swapped (even if we are in a
255  // process model that doesn't usually swap).
256  virtual bool ShouldSwapProcessesForNavigation(SiteInstance* site_instance,
257                                                const GURL& current_url,
258                                                const GURL& new_url);
259
260  // Returns true if the given navigation redirect should cause a renderer
261  // process swap.
262  // This is called on the IO thread.
263  virtual bool ShouldSwapProcessesForRedirect(ResourceContext* resource_context,
264                                              const GURL& current_url,
265                                              const GURL& new_url);
266
267  // Returns true if the passed in URL should be assigned as the site of the
268  // current SiteInstance, if it does not yet have a site.
269  virtual bool ShouldAssignSiteForURL(const GURL& url);
270
271  // See CharacterEncoding's comment.
272  virtual std::string GetCanonicalEncodingNameByAliasName(
273      const std::string& alias_name);
274
275  // Allows the embedder to pass extra command line flags.
276  // switches::kProcessType will already be set at this point.
277  virtual void AppendExtraCommandLineSwitches(CommandLine* command_line,
278                                              int child_process_id) {}
279
280  // Returns the locale used by the application.
281  // This is called on the UI and IO threads.
282  virtual std::string GetApplicationLocale();
283
284  // Returns the languages used in the Accept-Languages HTTP header.
285  // (Not called GetAcceptLanguages so it doesn't clash with win32).
286  virtual std::string GetAcceptLangs(BrowserContext* context);
287
288  // Returns the default favicon.  The callee doesn't own the given bitmap.
289  virtual gfx::ImageSkia* GetDefaultFavicon();
290
291  // Allow the embedder to control if an AppCache can be used for the given url.
292  // This is called on the IO thread.
293  virtual bool AllowAppCache(const GURL& manifest_url,
294                             const GURL& first_party,
295                             ResourceContext* context);
296
297  // Allow the embedder to control if the given cookie can be read.
298  // This is called on the IO thread.
299  virtual bool AllowGetCookie(const GURL& url,
300                              const GURL& first_party,
301                              const net::CookieList& cookie_list,
302                              ResourceContext* context,
303                              int render_process_id,
304                              int render_view_id);
305
306  // Allow the embedder to control if the given cookie can be set.
307  // This is called on the IO thread.
308  virtual bool AllowSetCookie(const GURL& url,
309                              const GURL& first_party,
310                              const std::string& cookie_line,
311                              ResourceContext* context,
312                              int render_process_id,
313                              int render_view_id,
314                              net::CookieOptions* options);
315
316  // This is called on the IO thread.
317  virtual bool AllowSaveLocalState(ResourceContext* context);
318
319  // Allow the embedder to control if access to web database by a shared worker
320  // is allowed. |render_views| is a vector of pairs of
321  // RenderProcessID/RenderViewID of RenderViews that are using this worker.
322  // This is called on the IO thread.
323  virtual bool AllowWorkerDatabase(
324      const GURL& url,
325      const string16& name,
326      const string16& display_name,
327      unsigned long estimated_size,
328      ResourceContext* context,
329      const std::vector<std::pair<int, int> >& render_views);
330
331  // Allow the embedder to control if access to file system by a shared worker
332  // is allowed.
333  // This is called on the IO thread.
334  virtual bool AllowWorkerFileSystem(
335      const GURL& url,
336      ResourceContext* context,
337      const std::vector<std::pair<int, int> >& render_views);
338
339  // Allow the embedder to control if access to IndexedDB by a shared worker
340  // is allowed.
341  // This is called on the IO thread.
342  virtual bool AllowWorkerIndexedDB(
343      const GURL& url,
344      const string16& name,
345      ResourceContext* context,
346      const std::vector<std::pair<int, int> >& render_views);
347
348  // Allow the embedder to override the request context based on the URL for
349  // certain operations, like cookie access. Returns NULL to indicate the
350  // regular request context should be used.
351  // This is called on the IO thread.
352  virtual net::URLRequestContext* OverrideRequestContextForURL(
353      const GURL& url, ResourceContext* context);
354
355  // Allow the embedder to specify a string version of the storage partition
356  // config with a site.
357  virtual std::string GetStoragePartitionIdForSite(
358      content::BrowserContext* browser_context,
359      const GURL& site);
360
361  // Allows the embedder to provide a validation check for |partition_id|s.
362  // This domain of valid entries should match the range of outputs for
363  // GetStoragePartitionIdForChildProcess().
364  virtual bool IsValidStoragePartitionId(BrowserContext* browser_context,
365                                         const std::string& partition_id);
366
367  // Allows the embedder to provide a storage parititon configuration for a
368  // site. A storage partition configuration includes a domain of the embedder's
369  // choice, an optional name within that domain, and whether the partition is
370  // in-memory only.
371  //
372  // If |can_be_default| is false, the caller is telling the embedder that the
373  // |site| is known to not be in the default partition. This is useful in
374  // some shutdown situations where the bookkeeping logic that maps sites to
375  // their partition configuration are no longer valid.
376  //
377  // The |partition_domain| is [a-z]* UTF-8 string, specifying the domain in
378  // which partitions live (similar to namespace). Within a domain, partitions
379  // can be uniquely identified by the combination of |partition_name| and
380  // |in_memory| values. When a partition is not to be persisted, the
381  // |in_memory| value must be set to true.
382  virtual void GetStoragePartitionConfigForSite(
383      content::BrowserContext* browser_context,
384      const GURL& site,
385      bool can_be_default,
386      std::string* partition_domain,
387      std::string* partition_name,
388      bool* in_memory);
389
390  // Create and return a new quota permission context.
391  virtual QuotaPermissionContext* CreateQuotaPermissionContext();
392
393  // Informs the embedder that a certificate error has occured.  If
394  // |overridable| is true and if |strict_enforcement| is false, the user
395  // can ignore the error and continue. The embedder can call the callback
396  // asynchronously. If |result| is not set to
397  // CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE, the request will be cancelled
398  // or denied immediately, and the callback won't be run.
399  virtual void AllowCertificateError(
400      int render_process_id,
401      int render_view_id,
402      int cert_error,
403      const net::SSLInfo& ssl_info,
404      const GURL& request_url,
405      ResourceType::Type resource_type,
406      bool overridable,
407      bool strict_enforcement,
408      const base::Callback<void(bool)>& callback,
409      CertificateRequestResultType* result) {}
410
411  // Selects a SSL client certificate and returns it to the |callback|. If no
412  // certificate was selected NULL is returned to the |callback|.
413  virtual void SelectClientCertificate(
414      int render_process_id,
415      int render_view_id,
416      const net::HttpNetworkSession* network_session,
417      net::SSLCertRequestInfo* cert_request_info,
418      const base::Callback<void(net::X509Certificate*)>& callback) {}
419
420  // Adds a new installable certificate or private key.
421  // Typically used to install an X.509 user certificate.
422  // Note that it's up to the embedder to verify that the data is
423  // well-formed. |cert_data| will be NULL if file_size is 0.
424  virtual void AddCertificate(
425      net::URLRequest* request,
426      net::CertificateMimeType cert_type,
427      const void* cert_data,
428      size_t cert_size,
429      int render_process_id,
430      int render_view_id) {}
431
432  // Returns a class to get notifications about media event. The embedder can
433  // return NULL if they're not interested.
434  virtual MediaObserver* GetMediaObserver();
435
436  // Asks permission to show desktop notifications.
437  virtual void RequestDesktopNotificationPermission(
438      const GURL& source_origin,
439      int callback_context,
440      int render_process_id,
441      int render_view_id) {}
442
443  // Checks if the given page has permission to show desktop notifications.
444  // This is called on the IO thread.
445  virtual WebKit::WebNotificationPresenter::Permission
446      CheckDesktopNotificationPermission(
447          const GURL& source_url,
448          ResourceContext* context,
449          int render_process_id);
450
451  // Show a desktop notification.  If |worker| is true, the request came from an
452  // HTML5 web worker, otherwise, it came from a renderer.
453  virtual void ShowDesktopNotification(
454      const ShowDesktopNotificationHostMsgParams& params,
455      int render_process_id,
456      int render_view_id,
457      bool worker) {}
458
459  // Cancels a displayed desktop notification.
460  virtual void CancelDesktopNotification(
461      int render_process_id,
462      int render_view_id,
463      int notification_id) {}
464
465  // Returns true if the given page is allowed to open a window of the given
466  // type. If true is returned, |no_javascript_access| will indicate whether
467  // the window that is created should be scriptable/in the same process.
468  // This is called on the IO thread.
469  virtual bool CanCreateWindow(const GURL& opener_url,
470                               const GURL& source_origin,
471                               WindowContainerType container_type,
472                               const GURL& target_url,
473                               const content::Referrer& referrer,
474                               WindowOpenDisposition disposition,
475                               const WebKit::WebWindowFeatures& features,
476                               bool user_gesture,
477                               bool opener_suppressed,
478                               content::ResourceContext* context,
479                               int render_process_id,
480                               bool is_guest,
481                               int opener_id,
482                               bool* no_javascript_access);
483
484  // Returns a title string to use in the task manager for a process host with
485  // the given URL, or the empty string to fall back to the default logic.
486  // This is called on the IO thread.
487  virtual std::string GetWorkerProcessTitle(const GURL& url,
488                                            ResourceContext* context);
489
490  // Notifies the embedder that the ResourceDispatcherHost has been created.
491  // This is when it can optionally add a delegate.
492  virtual void ResourceDispatcherHostCreated() {}
493
494  // Allows the embedder to return a delegate for the SpeechRecognitionManager.
495  // The delegate will be owned by the manager. It's valid to return NULL.
496  virtual SpeechRecognitionManagerDelegate*
497      GetSpeechRecognitionManagerDelegate();
498
499  // Getters for common objects.
500  virtual net::NetLog* GetNetLog();
501
502  // Creates a new AccessTokenStore for gelocation.
503  virtual AccessTokenStore* CreateAccessTokenStore();
504
505  // Returns true if fast shutdown is possible.
506  virtual bool IsFastShutdownPossible();
507
508  // Called by WebContents to override the WebKit preferences that are used by
509  // the renderer. The content layer will add its own settings, and then it's up
510  // to the embedder to update it if it wants.
511  virtual void OverrideWebkitPrefs(RenderViewHost* render_view_host,
512                                   const GURL& url,
513                                   WebPreferences* prefs) {}
514
515  // Inspector setting was changed and should be persisted.
516  virtual void UpdateInspectorSetting(RenderViewHost* rvh,
517                                      const std::string& key,
518                                      const std::string& value) {}
519
520  // Notifies that BrowserURLHandler has been created, so that the embedder can
521  // optionally add their own handlers.
522  virtual void BrowserURLHandlerCreated(BrowserURLHandler* handler) {}
523
524  // Clears browser cache.
525  virtual void ClearCache(RenderViewHost* rvh) {}
526
527  // Clears browser cookies.
528  virtual void ClearCookies(RenderViewHost* rvh) {}
529
530  // Returns the default download directory.
531  // This can be called on any thread.
532  virtual base::FilePath GetDefaultDownloadDirectory();
533
534  // Returns the default filename used in downloads when we have no idea what
535  // else we should do with the file.
536  virtual std::string GetDefaultDownloadName();
537
538  // Notification that a pepper plugin has just been spawned. This allows the
539  // embedder to add filters onto the host to implement interfaces.
540  // This is called on the IO thread.
541  virtual void DidCreatePpapiPlugin(BrowserPpapiHost* browser_host) {}
542
543  // Gets the host for an external out-of-process plugin.
544  virtual content::BrowserPpapiHost* GetExternalBrowserPpapiHost(
545      int plugin_child_id);
546
547  // Returns true if the given browser_context and site_url support hosting
548  // BrowserPlugins.
549  virtual bool SupportsBrowserPlugin(BrowserContext* browser_context,
550                                     const GURL& site_url);
551
552  // Returns true if the socket operation specified by |params| is allowed
553  // from the given |browser_context| and |url|. |private_api| indicates whether
554  // this permission check is for the private Pepper socket API or the public
555  // one.
556  virtual bool AllowPepperSocketAPI(BrowserContext* browser_context,
557                                    const GURL& url,
558                                    bool private_api,
559                                    const SocketPermissionRequest& params);
560
561  // Returns the directory containing hyphenation dictionaries.
562  virtual base::FilePath GetHyphenDictionaryDirectory();
563
564  // Returns an implementation of a file selecition policy. Can return NULL.
565  virtual ui::SelectFilePolicy* CreateSelectFilePolicy(
566      WebContents* web_contents);
567
568  // Returns additional allowed scheme set which can access files in
569  // FileSystem API.
570  virtual void GetAdditionalAllowedSchemesForFileSystem(
571      std::vector<std::string>* additional_schemes) {}
572
573  // Returns additional file system backends for FileSystem API.
574  // |browser_context| is needed in the additional FileSystemBackends.
575  // It has mount points to create objects returned by additional
576  // FileSystemBackends, and SpecialStoragePolicy for permission granting.
577  virtual void GetAdditionalFileSystemBackends(
578      BrowserContext* browser_context,
579      const base::FilePath& storage_partition_path,
580      ScopedVector<fileapi::FileSystemBackend>* additional_backends) {}
581
582  // Allows an embedder to return its own LocationProvider implementation.
583  // Return NULL to use the default one for the platform to be created.
584  virtual LocationProvider* OverrideSystemLocationProvider();
585
586#if defined(OS_POSIX) && !defined(OS_MACOSX)
587  // Populates |mappings| with all files that need to be mapped before launching
588  // a child process.
589  virtual void GetAdditionalMappedFilesForChildProcess(
590      const CommandLine& command_line,
591      int child_process_id,
592      std::vector<FileDescriptorInfo>* mappings) {}
593#endif
594
595#if defined(OS_WIN)
596  // Returns the name of the dll that contains cursors and other resources.
597  virtual const wchar_t* GetResourceDllName();
598
599  // This is called on the PROCESS_LAUNCHER thread before the renderer process
600  // is launched. It gives the embedder a chance to add loosen the sandbox
601  // policy.
602  virtual void PreSpawnRenderer(sandbox::TargetPolicy* policy,
603                                bool* success) {}
604#endif
605
606#if defined(USE_NSS)
607  // Return a delegate to authenticate and unlock |module|.
608  // This is called on a worker thread.
609  virtual
610      crypto::CryptoModuleBlockingPasswordDelegate* GetCryptoPasswordDelegate(
611          const GURL& url);
612#endif
613};
614
615}  // namespace content
616
617#endif  // CONTENT_PUBLIC_BROWSER_CONTENT_BROWSER_CLIENT_H_
618