cef/libcef/browser/browser_context.h

244 lines
9.7 KiB
C
Raw Normal View History

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_IMPL_H_
#define CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_IMPL_H_
#pragma once
#include <set>
#include <vector>
Add support for complete isolation of storage and permissions (cache, cookies, localStorage, access grants, etc) on a per-request-context basis (issue #1044). - CefRequestContext instances can be configured using a new CefRequestContextSettings structure passed to CefRequestContext::CreateContext. - Scheme registration is now per-request-context using new CefRequestContext::RegisterSchemeHandlerFactory and ClearSchemeHandlerFactories methods. - Cookie managers are now per-request-context by default and can be retrieved using a new CefRequestContext::GetDefaultCookieManager method. - CefURLRequest::Create now accepts an optional CefRequestContext argument for associating a URL request with a context (browser process only). - The CefRequestContextHandler associated with a CefRequestContext will not be released until all objects related to that context have been destroyed. - When the cache path is empty an in-memory cache ("incognito mode") will be used for storage and no data will be persisted to disk. - Add CefSettings.user_data_path which specifies the location where user data such as spell checking dictionary files will be stored on disk. - Add asynchronous callbacks for all CefCookieManager methods. - Add PK_LOCAL_APP_DATA and PK_USER_DATA path keys for retrieving user directories via CefGetPath. - cefclient: Add "New Window" test that creates a new window unrelated to existing windows. When used in combination with `--request-context-per-browser` the new window will be given a new and isolated request context. git-svn-id: https://chromiumembedded.googlecode.com/svn/trunk@2040 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
2015-03-02 21:25:14 +01:00
#include "include/cef_request_context_handler.h"
#include "libcef/browser/iothread_state.h"
#include "libcef/browser/request_context_handler_map.h"
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/task/sequenced_task_runner_helpers.h"
#include "chrome/common/plugin.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/origin.h"
/*
// Classes used in request processing (network, storage, service, etc.):
//
// WC = WebContents
// Content API representation of a browser. Created by BHI or the system (for
// popups) and owned by BHI. Keeps a pointer to the content::BrowserContext.
//
// BHI = AlloyBrowserHostImpl
// Implements the CefBrowser and CefBrowserHost interfaces which are exposed
// to clients. References an RCI instance. Owns a WC. Lifespan is controlled
// by client references and CefBrowserInfoManager (until the browser has
// closed).
//
// RCI = CefRequestContextImpl
// Implements the CefRequestContext interface which is exposed to clients.
// Creates or references a BC. Lifespan is controlled by client references and
// BrowserMainParts (for the global RCI).
//
// BC = CefBrowserContext
// Is/owns the content::BrowserContext which is the entry point from WC.
// Owns the IOTS and creates the SPI indirectly. Potentially shared by
// multiple RCI. Deletes itself when no longer needed by RCI.
//
// SPI = content::StoragePartitionImpl
// Owns storage-related objects like Quota, IndexedDB, Cache, etc. Created by
// StoragePartitionImplMap::Get(). Life span is controlled indirectly by BC.
//
// IOTS = CefIOThreadState
// Stores state for access on the IO thread. Life span is controlled by BC.
//
//
// Relationship diagram:
// ref = reference (CefRefPtr/scoped_refptr)
// own = ownership (std::unique_ptr)
// ptr = raw pointer
//
// BHI -ref-> RCI -ptr-> BC -own-> SPI, IOTS
// ^
// BHI -own-> WC -ptr--/
//
//
// How shutdown works:
// 1. AlloyBrowserHostImpl::DestroyBrowser is called on the UI thread after the
// browser is closed and deletes the WebContents.
// 1. AlloyBrowserHostImpl is destroyed on any thread when the last reference
// is released.
// 2. CefRequestContextImpl is destroyed (possibly asynchronously) on the UI
// thread when the last reference is released.
// 3. CefBrowserContext is destroyed on the UI thread when no longer needed
// by any CefRequestContextImpl (via RemoveCefRequestContext).
// 4. CefIOThreadState is destroyed asynchronously on the IO thread after
// the owning CefBrowserContext is destroyed.
*/
namespace content {
class BrowserContext;
struct GlobalRenderFrameHostId;
} // namespace content
class CefMediaRouterManager;
class CefRequestContextImpl;
class Profile;
// Main entry point for configuring behavior on a per-RequestContext basis. The
// content::BrowserContext represented by this class is passed to
// WebContents::Create in AlloyBrowserHostImpl::CreateInternal. Only accessed on
// the UI thread unless otherwise indicated.
class CefBrowserContext {
public:
CefBrowserContext(const CefBrowserContext&) = delete;
CefBrowserContext& operator=(const CefBrowserContext&) = delete;
// Returns the existing instance, if any, associated with the specified
// |cache_path|.
static CefBrowserContext* FromCachePath(const base::FilePath& cache_path);
// Returns the existing instance, if any, associated with the specified IDs.
// See comments on IsAssociatedContext() for usage.
static CefBrowserContext* FromGlobalId(
const content::GlobalRenderFrameHostId& global_id,
bool require_frame_match);
// Returns the underlying CefBrowserContext if any.
static CefBrowserContext* FromBrowserContext(
const content::BrowserContext* context);
static CefBrowserContext* FromProfile(const Profile* profile);
// Returns all existing CefBrowserContext.
static std::vector<CefBrowserContext*> GetAll();
// Returns the content and chrome layer representations of the context.
virtual content::BrowserContext* AsBrowserContext() = 0;
virtual Profile* AsProfile() = 0;
// Returns true if the context is fully initialized.
virtual bool IsInitialized() const = 0;
// If the context is fully initialized execute |callback|, otherwise
// store it until the context is fully initialized.
virtual void StoreOrTriggerInitCallback(base::OnceClosure callback) = 0;
// Called from CefRequestContextImpl to track associated objects. This
// object will delete itself when the count reaches zero.
void AddCefRequestContext(CefRequestContextImpl* context);
virtual void RemoveCefRequestContext(CefRequestContextImpl* context);
// Called from CefRequestContextImpl::OnRenderFrameCreated.
void OnRenderFrameCreated(CefRequestContextImpl* request_context,
const content::GlobalRenderFrameHostId& global_id,
bool is_main_frame,
bool is_guest_view);
// Called from CefRequestContextImpl::OnRenderFrameDeleted.
void OnRenderFrameDeleted(CefRequestContextImpl* request_context,
const content::GlobalRenderFrameHostId& global_id,
bool is_main_frame,
bool is_guest_view);
// Returns the handler that matches the specified IDs. Pass -1 for unknown
// values. If |require_frame_match| is true only exact matches will be
// returned. If |require_frame_match| is false, and there is not an exact
// match, then the first handler for the same |render_process_id| will be
// returned.
CefRefPtr<CefRequestContextHandler> GetHandler(
const content::GlobalRenderFrameHostId& global_id,
bool require_frame_match) const;
// Returns true if this context is associated with the specified IDs. Pass -1
// for unknown values. If |require_frame_match| is true only exact matches
// will qualify. If |require_frame_match| is false, and there is not an exact
// match, then any match for |render_process_id| will qualify.
bool IsAssociatedContext(const content::GlobalRenderFrameHostId& global_id,
bool require_frame_match) const;
Implement NetworkService request interception/handling (see issue #2622). Implementation notes: - Chromium change: CookieMonster::SetCookieableSchemes needs to be called immediately after the CookieMonster is created in NetworkContext:: ApplyContextParamsToBuilder. Add a Profile::GetCookieableSchemes method and NetworkContextParams.cookieable_schemes member (set from ProfileNetworkContextService::CreateNetworkContextParams) to support that. - Chromium change: Add a ContentBrowserClient::HandleExternalProtocol variant that exposes additional NetworkService request information. - GetResourceResponseFilter is not yet implemented. API changes: - Resource-related callbacks have been moved from CefRequestHandler to a new CefResourceRequestHandler interface which is returned via the GetResourceRequestHandler method. If the CefRequestHandler declines to handle a resource it can optionally be handled by the CefRequestContextHandler, if any, associated with the loading context. - The OnProtocolExecution callback has been moved from CefRequestHandler to CefResourceRequestHandler and will be called if a custom scheme request is unhandled. - Cookie send/save permission callbacks have been moved from CefRequestHandler and CefResourceHandler to CefResourceRequestHandler. - New methods added to CefResourceHandler that better match NetworkService execution sequence expectations. The old methods are now deprecated. - New methods added to CefRequest and CefResponse. Known behavior changes with the NetworkService implementation: - Modifying the |new_url| parameter in OnResourceRedirect will no longer result in the method being called an additional time (likely a bug in the old implementation). - Modifying the request URL in OnResourceResponse would previously cause a redirect. This behavior is now deprecated because the NetworkService does not support this functionality when using default network loaders. Temporary support has been added in combination with CefResourceHandler usage only. - Other changes to the request object in OnResourceResponse will now cause the request to be restarted. This means that OnBeforeResourceLoad, etc, will be called an additional time with the new request information. - CefResponse::GetMimeType will now be empty for non-200 responses. - Requests using custom schemes can now be handled via CefResourceRequestHandler with the same callback behavior as builtin schemes. - Redirects of custom scheme requests will now be followed as expected. - Default handling of builtin schemes can now be disabled by setting |disable_default_handling| to true in GetResourceRequestHandler. - Unhandled requests (custom scheme or builtin scheme with default handling disabled) will fail with an CefResponse::GetError value of ERR_UNKNOWN_URL_SCHEME. - The CefSchemeHandlerFactory::Create callback will now include cookie headers. To test: - Run `cefclient --enable-network-service`. All resources should load successfully (this tests the transparent proxy capability). - All tests pass with NetworkService disabled. - The following tests pass with NetworkService enabled: - CookieTest.* - FrameTest.* (excluding .*Nav) - NavigationTest.* (excluding .Redirect*) - RequestHandlerTest.* - RequestContextTest.Basic* - RequestContextTest.Popup* - RequestTest.* - ResourceManagerTest.* - ResourceRequestHandlerTest.* (excluding .Filter*) - SchemeHandlerTest.* - StreamResourceHandlerTest.*
2019-04-24 04:50:25 +02:00
// Called from CefRequestContextImpl methods of the same name.
void RegisterSchemeHandlerFactory(const CefString& scheme_name,
const CefString& domain_name,
Implement NetworkService request interception/handling (see issue #2622). Implementation notes: - Chromium change: CookieMonster::SetCookieableSchemes needs to be called immediately after the CookieMonster is created in NetworkContext:: ApplyContextParamsToBuilder. Add a Profile::GetCookieableSchemes method and NetworkContextParams.cookieable_schemes member (set from ProfileNetworkContextService::CreateNetworkContextParams) to support that. - Chromium change: Add a ContentBrowserClient::HandleExternalProtocol variant that exposes additional NetworkService request information. - GetResourceResponseFilter is not yet implemented. API changes: - Resource-related callbacks have been moved from CefRequestHandler to a new CefResourceRequestHandler interface which is returned via the GetResourceRequestHandler method. If the CefRequestHandler declines to handle a resource it can optionally be handled by the CefRequestContextHandler, if any, associated with the loading context. - The OnProtocolExecution callback has been moved from CefRequestHandler to CefResourceRequestHandler and will be called if a custom scheme request is unhandled. - Cookie send/save permission callbacks have been moved from CefRequestHandler and CefResourceHandler to CefResourceRequestHandler. - New methods added to CefResourceHandler that better match NetworkService execution sequence expectations. The old methods are now deprecated. - New methods added to CefRequest and CefResponse. Known behavior changes with the NetworkService implementation: - Modifying the |new_url| parameter in OnResourceRedirect will no longer result in the method being called an additional time (likely a bug in the old implementation). - Modifying the request URL in OnResourceResponse would previously cause a redirect. This behavior is now deprecated because the NetworkService does not support this functionality when using default network loaders. Temporary support has been added in combination with CefResourceHandler usage only. - Other changes to the request object in OnResourceResponse will now cause the request to be restarted. This means that OnBeforeResourceLoad, etc, will be called an additional time with the new request information. - CefResponse::GetMimeType will now be empty for non-200 responses. - Requests using custom schemes can now be handled via CefResourceRequestHandler with the same callback behavior as builtin schemes. - Redirects of custom scheme requests will now be followed as expected. - Default handling of builtin schemes can now be disabled by setting |disable_default_handling| to true in GetResourceRequestHandler. - Unhandled requests (custom scheme or builtin scheme with default handling disabled) will fail with an CefResponse::GetError value of ERR_UNKNOWN_URL_SCHEME. - The CefSchemeHandlerFactory::Create callback will now include cookie headers. To test: - Run `cefclient --enable-network-service`. All resources should load successfully (this tests the transparent proxy capability). - All tests pass with NetworkService disabled. - The following tests pass with NetworkService enabled: - CookieTest.* - FrameTest.* (excluding .*Nav) - NavigationTest.* (excluding .Redirect*) - RequestHandlerTest.* - RequestContextTest.Basic* - RequestContextTest.Popup* - RequestTest.* - ResourceManagerTest.* - ResourceRequestHandlerTest.* (excluding .Filter*) - SchemeHandlerTest.* - StreamResourceHandlerTest.*
2019-04-24 04:50:25 +02:00
CefRefPtr<CefSchemeHandlerFactory> factory);
void ClearSchemeHandlerFactories();
// TODO(chrome-runtime): Make these extension methods pure virtual.
virtual void LoadExtension(const CefString& root_directory,
CefRefPtr<CefDictionaryValue> manifest,
CefRefPtr<CefExtensionHandler> handler,
CefRefPtr<CefRequestContext> loader_context);
virtual bool GetExtensions(std::vector<CefString>& extension_ids);
virtual CefRefPtr<CefExtension> GetExtension(const CefString& extension_id);
// Called from CefExtensionImpl::Unload().
virtual bool UnloadExtension(const CefString& extension_id);
// Returns true if this context supports print preview.
virtual bool IsPrintPreviewSupported() const;
network::mojom::NetworkContext* GetNetworkContext();
CefMediaRouterManager* GetMediaRouterManager();
using CookieableSchemes = absl::optional<std::vector<std::string>>;
Add chrome runtime support for more callbacks and ceftests (see issue #2969) This change adds support for: - Protocol and request handling. - Loading and navigation events. - Display and focus events. - Mouse/keyboard events. - Popup browsers. - Callbacks in the renderer process. - Misc. functionality required for ceftests. This change also adds a new CefBrowserProcessHandler::GetCookieableSchemes callback for configuring global state that will be applied to all CefCookieManagers by default. This global callback is currently required by the chrome runtime because the primary ProfileImpl is created via ChromeBrowserMainParts::PreMainMessageLoopRun (CreatePrimaryProfile) before OnContextCreated can be called. ProfileImpl will use the "C:\Users\[user]\AppData\Local\CEF\User Data\Default" directory by default (on Windows). Cookies may persist in this directory when running ceftests and may need to be manually deleted if those tests fail. Remaining work includes: - Support for client-created request contexts. - Embedding the browser in a Views hierarchy (cefclient support). - TryCloseBrowser and DoClose support. - Most of the CefSettings configuration. - DevTools protocol and window control (ShowDevTools, ExecuteDevToolsMethod). - CEF-specific WebUI pages (about, license, webui-hosts). - Context menu customization (CefContextMenuHandler). - Auto resize (SetAutoResizeEnabled). - Zoom settings (SetZoomLevel). - File dialog runner (RunFileDialog). - File and JS dialog handlers (CefDialogHandler, CefJSDialogHandler). - Extension loading (LoadExtension, etc). - Plugin loading (OnBeforePluginLoad). - Widevine loading (CefRegisterWidevineCdm). - PDF and print preview does not display. - Crash reporting is untested. - Mac: Web content loads but does not display. The following ceftests are now passing when run with the "--enable-chrome-runtime" command-line flag: CorsTest.* DisplayTest.*:-DisplayTest.AutoResize DOMTest.* DraggableRegionsTest.* ImageTest.* MessageRouterTest.* NavigationTest.* ParserTest.* RequestContextTest.*Global* RequestTest.* ResourceManagerTest.* ResourceRequestHandlerTest.* ResponseTest.* SchemeHandlerTest.* ServerTest.* StreamResourceHandlerTest.* StreamTest.* StringTest.* TaskTest.* TestServerTest.* ThreadTest.* URLRequestTest.*Global* V8Test.*:-V8Test.OnUncaughtExceptionDevTools ValuesTest.* WaitableEventTest.* XmlReaderTest.* ZipReaderTest.*
2020-09-25 03:40:47 +02:00
// Returns the schemes associated with this context specifically, or the
// global configuration if unset.
CookieableSchemes GetCookieableSchemes() const;
static CookieableSchemes GetGlobalCookieableSchemes();
Implement NetworkService request interception/handling (see issue #2622). Implementation notes: - Chromium change: CookieMonster::SetCookieableSchemes needs to be called immediately after the CookieMonster is created in NetworkContext:: ApplyContextParamsToBuilder. Add a Profile::GetCookieableSchemes method and NetworkContextParams.cookieable_schemes member (set from ProfileNetworkContextService::CreateNetworkContextParams) to support that. - Chromium change: Add a ContentBrowserClient::HandleExternalProtocol variant that exposes additional NetworkService request information. - GetResourceResponseFilter is not yet implemented. API changes: - Resource-related callbacks have been moved from CefRequestHandler to a new CefResourceRequestHandler interface which is returned via the GetResourceRequestHandler method. If the CefRequestHandler declines to handle a resource it can optionally be handled by the CefRequestContextHandler, if any, associated with the loading context. - The OnProtocolExecution callback has been moved from CefRequestHandler to CefResourceRequestHandler and will be called if a custom scheme request is unhandled. - Cookie send/save permission callbacks have been moved from CefRequestHandler and CefResourceHandler to CefResourceRequestHandler. - New methods added to CefResourceHandler that better match NetworkService execution sequence expectations. The old methods are now deprecated. - New methods added to CefRequest and CefResponse. Known behavior changes with the NetworkService implementation: - Modifying the |new_url| parameter in OnResourceRedirect will no longer result in the method being called an additional time (likely a bug in the old implementation). - Modifying the request URL in OnResourceResponse would previously cause a redirect. This behavior is now deprecated because the NetworkService does not support this functionality when using default network loaders. Temporary support has been added in combination with CefResourceHandler usage only. - Other changes to the request object in OnResourceResponse will now cause the request to be restarted. This means that OnBeforeResourceLoad, etc, will be called an additional time with the new request information. - CefResponse::GetMimeType will now be empty for non-200 responses. - Requests using custom schemes can now be handled via CefResourceRequestHandler with the same callback behavior as builtin schemes. - Redirects of custom scheme requests will now be followed as expected. - Default handling of builtin schemes can now be disabled by setting |disable_default_handling| to true in GetResourceRequestHandler. - Unhandled requests (custom scheme or builtin scheme with default handling disabled) will fail with an CefResponse::GetError value of ERR_UNKNOWN_URL_SCHEME. - The CefSchemeHandlerFactory::Create callback will now include cookie headers. To test: - Run `cefclient --enable-network-service`. All resources should load successfully (this tests the transparent proxy capability). - All tests pass with NetworkService disabled. - The following tests pass with NetworkService enabled: - CookieTest.* - FrameTest.* (excluding .*Nav) - NavigationTest.* (excluding .Redirect*) - RequestHandlerTest.* - RequestContextTest.Basic* - RequestContextTest.Popup* - RequestTest.* - ResourceManagerTest.* - ResourceRequestHandlerTest.* (excluding .Filter*) - SchemeHandlerTest.* - StreamResourceHandlerTest.*
2019-04-24 04:50:25 +02:00
// These accessors are safe to call from any thread because the values don't
// change during this object's lifespan.
const CefRequestContextSettings& settings() const { return settings_; }
base::FilePath cache_path() const { return cache_path_; }
scoped_refptr<CefIOThreadState> iothread_state() const {
return iothread_state_;
}
// Used to hold a WeakPtr reference to this this object. The Getter returns
// nullptr if this object has already been destroyed.
using Getter = base::RepeatingCallback<CefBrowserContext*()>;
Getter getter() const { return getter_; }
protected:
explicit CefBrowserContext(const CefRequestContextSettings& settings);
virtual ~CefBrowserContext();
// Will be called immediately after this object is created.
virtual void Initialize();
// Will be called immediately before this object is deleted.
virtual void Shutdown();
// Members initialized during construction or Initialize() are safe to access
// from any thread.
const CefRequestContextSettings settings_;
base::FilePath cache_path_;
private:
// For DeleteSoon().
friend class base::DeleteHelper<CefBrowserContext>;
scoped_refptr<CefIOThreadState> iothread_state_;
CookieableSchemes cookieable_schemes_;
std::unique_ptr<CefMediaRouterManager> media_router_manager_;
// CefRequestContextImpl objects referencing this object.
std::set<CefRequestContextImpl*> request_context_set_;
// Map IDs to CefRequestContextHandler objects.
CefRequestContextHandlerMap handler_map_;
// Set of global IDs associated with this context.
using RenderIdSet = std::set<content::GlobalRenderFrameHostId>;
RenderIdSet render_id_set_;
#if DCHECK_IS_ON()
bool is_shutdown_ = false;
#endif
Getter getter_;
base::WeakPtrFactory<CefBrowserContext> weak_ptr_factory_;
};
#endif // CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_IMPL_H_