blob: 0f1ea54ebc4424f0b36fbc100ad13b7263fb4a91 [file] [log] [blame]
// Copyright 2013 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.
#include "content/browser/frame_host/render_frame_host_impl.h"
#include <algorithm>
#include <unordered_map>
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/containers/queue.h"
#include "base/debug/alias.h"
#include "base/debug/dump_without_crashing.h"
#include "base/hash/hash.h"
#include "base/lazy_instance.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/metrics_hashes.h"
#include "base/metrics/user_metrics.h"
#include "base/no_destructor.h"
#include "base/numerics/safe_conversions.h"
#include "base/process/kill.h"
#include "base/stl_util.h"
#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/traced_value.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "content/browser/about_url_loader_factory.h"
#include "content/browser/accessibility/browser_accessibility_manager.h"
#include "content/browser/accessibility/browser_accessibility_state_impl.h"
#include "content/browser/appcache/appcache_navigation_handle.h"
#include "content/browser/background_fetch/background_fetch_service_impl.h"
#include "content/browser/bluetooth/web_bluetooth_service_impl.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/child_process_security_policy_impl.h"
#include "content/browser/contacts/contacts_manager_impl.h"
#include "content/browser/data_url_loader_factory.h"
#include "content/browser/devtools/devtools_instrumentation.h"
#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
#include "content/browser/download/mhtml_generation_manager.h"
#include "content/browser/file_url_loader_factory.h"
#include "content/browser/fileapi/file_system_manager_impl.h"
#include "content/browser/fileapi/file_system_url_loader_factory.h"
#include "content/browser/frame_host/cross_process_frame_connector.h"
#include "content/browser/frame_host/debug_urls.h"
#include "content/browser/frame_host/frame_tree.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/input/input_injector_impl.h"
#include "content/browser/frame_host/ipc_utils.h"
#include "content/browser/frame_host/keep_alive_handle_factory.h"
#include "content/browser/frame_host/navigation_entry_impl.h"
#include "content/browser/frame_host/navigation_handle_impl.h"
#include "content/browser/frame_host/navigation_request.h"
#include "content/browser/frame_host/navigator.h"
#include "content/browser/frame_host/navigator_impl.h"
#include "content/browser/frame_host/render_frame_host_delegate.h"
#include "content/browser/frame_host/render_frame_proxy_host.h"
#include "content/browser/generic_sensor/sensor_provider_proxy_impl.h"
#include "content/browser/geolocation/geolocation_service_impl.h"
#include "content/browser/image_capture/image_capture_impl.h"
#include "content/browser/installedapp/installed_app_provider_impl_default.h"
#include "content/browser/interface_provider_filtering.h"
#include "content/browser/keyboard_lock/keyboard_lock_service_impl.h"
#include "content/browser/loader/prefetch_url_loader_service.h"
#include "content/browser/loader/resource_dispatcher_host_impl.h"
#include "content/browser/log_console_message.h"
#include "content/browser/media/capture/audio_mirroring_manager.h"
#include "content/browser/media/media_interface_proxy.h"
#include "content/browser/media/session/media_session_service_impl.h"
#include "content/browser/media/webaudio/audio_context_manager_impl.h"
#include "content/browser/native_file_system/native_file_system_manager_impl.h"
#include "content/browser/navigation_subresource_loader_params.h"
#include "content/browser/payments/payment_app_context_impl.h"
#include "content/browser/permissions/permission_controller_impl.h"
#include "content/browser/permissions/permission_service_context.h"
#include "content/browser/permissions/permission_service_impl.h"
#include "content/browser/picture_in_picture/picture_in_picture_service_impl.h"
#include "content/browser/portal/portal.h"
#include "content/browser/presentation/presentation_service_impl.h"
#include "content/browser/push_messaging/push_messaging_manager.h"
#include "content/browser/quota_dispatcher_host.h"
#include "content/browser/renderer_host/dip_util.h"
#include "content/browser/renderer_host/input/input_router.h"
#include "content/browser/renderer_host/input/timeout_monitor.h"
#include "content/browser/renderer_host/media/audio_input_delegate_impl.h"
#include "content/browser/renderer_host/media/media_devices_dispatcher_host.h"
#include "content/browser/renderer_host/media/media_stream_dispatcher_host.h"
#include "content/browser/renderer_host/render_process_host_impl.h"
#include "content/browser/renderer_host/render_view_host_delegate.h"
#include "content/browser/renderer_host/render_view_host_delegate_view.h"
#include "content/browser/renderer_host/render_view_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_factory.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_base.h"
#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
#include "content/browser/renderer_interface_binders.h"
#include "content/browser/scoped_active_url.h"
#include "content/browser/speech/speech_recognition_dispatcher_host.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/wake_lock/wake_lock_service_impl.h"
#include "content/browser/web_package/prefetched_signed_exchange_cache.h"
#include "content/browser/webauth/authenticator_environment_impl.h"
#include "content/browser/webauth/authenticator_impl.h"
#include "content/browser/websockets/websocket_manager.h"
#include "content/browser/webui/url_data_manager_backend.h"
#include "content/browser/webui/web_ui_controller_factory_registry.h"
#include "content/browser/webui/web_ui_url_loader_factory_internal.h"
#include "content/browser/worker_host/dedicated_worker_host.h"
#include "content/browser/worker_host/shared_worker_connector_impl.h"
#include "content/browser/worker_host/shared_worker_service_impl.h"
#include "content/common/accessibility_messages.h"
#include "content/common/associated_interfaces.mojom.h"
#include "content/common/content_security_policy/content_security_policy.h"
#include "content/common/frame_messages.h"
#include "content/common/frame_owner_properties.h"
#include "content/common/input/input_handler.mojom.h"
#include "content/common/inter_process_time_ticks_converter.h"
#include "content/common/navigation_params.h"
#include "content/common/render_message_filter.mojom.h"
#include "content/common/renderer.mojom.h"
#include "content/common/swapped_out_messages.h"
#include "content/common/widget.mojom.h"
#include "content/public/browser/ax_event_notification_details.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_plugin_guest_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/file_select_listener.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/page_visibility_state.h"
#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/sms_service.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/webvr_service_provider.h"
#include "content/public/common/bindings_policy.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/isolated_world_ids.h"
#include "content/public/common/mime_handler_view_mode.h"
#include "content/public/common/navigation_policy.h"
#include "content/public/common/network_service_util.h"
#include "content/public/common/referrer_type_converters.h"
#include "content/public/common/service_manager_connection.h"
#include "content/public/common/service_names.mojom.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
#include "device/gamepad/gamepad_monitor.h"
#include "device/vr/public/mojom/vr_service.mojom.h"
#include "media/audio/audio_manager.h"
#include "media/base/media_switches.h"
#include "media/base/user_input_monitor.h"
#include "media/learning/common/value.h"
#include "media/media_buildflags.h"
#include "media/mojo/interfaces/remoting.mojom.h"
#include "media/mojo/services/media_interface_provider.h"
#include "media/mojo/services/media_metrics_provider.h"
#include "media/mojo/services/video_decode_perf_history.h"
#include "mojo/public/cpp/bindings/associated_interface_ptr.h"
#include "mojo/public/cpp/bindings/interface_request.h"
#include "mojo/public/cpp/bindings/message.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "net/url_request/url_request_context.h"
#include "services/device/public/cpp/device_features.h"
#include "services/device/public/mojom/sensor_provider.mojom.h"
#include "services/device/public/mojom/wake_lock.mojom.h"
#include "services/device/public/mojom/wake_lock_context.mojom.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/network_service.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/blob/blob_utils.h"
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/frame/frame_policy.h"
#include "third_party/blink/public/common/messaging/transferable_message.h"
#include "third_party/blink/public/mojom/appcache/appcache.mojom.h"
#include "third_party/blink/public/mojom/frame/frame_host_test_interface.mojom.h"
#include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h"
#include "third_party/blink/public/mojom/loader/url_loader_factory_bundle.mojom.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom.h"
#include "third_party/blink/public/mojom/sms/sms_receiver.mojom.h"
#include "third_party/blink/public/mojom/usb/web_usb_service.mojom.h"
#include "third_party/blink/public/mojom/webauthn/virtual_authenticator.mojom.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_id_registry.h"
#include "ui/accessibility/ax_tree_update.h"
#include "ui/gfx/geometry/quad_f.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/url_constants.h"
#if defined(OS_ANDROID)
#include "content/browser/android/content_url_loader_factory.h"
#include "content/browser/android/java_interfaces_impl.h"
#include "content/browser/frame_host/render_frame_host_android.h"
#include "content/public/browser/android/java_interfaces.h"
#else
#include "content/browser/hid/hid_service.h"
#include "content/browser/serial/serial_service.h"
#endif
#if defined(OS_MACOSX)
#include "content/browser/frame_host/popup_menu_helper_mac.h"
#endif
using base::TimeDelta;
namespace content {
namespace {
#if defined(OS_ANDROID)
const void* const kRenderFrameHostAndroidKey = &kRenderFrameHostAndroidKey;
#endif // OS_ANDROID
// The next value to use for the accessibility reset token.
int g_next_accessibility_reset_token = 1;
#if defined(OS_ANDROID) || defined(OS_FUCHSIA)
// Whether to allow injecting javascript into any kind of frame, for Android
// WebView and Fuchsia web.ContextProvider.
bool g_allow_injecting_javascript = false;
#endif
// The (process id, routing id) pair that identifies one RenderFrame.
typedef std::pair<int32_t, int32_t> RenderFrameHostID;
typedef std::unordered_map<RenderFrameHostID,
RenderFrameHostImpl*,
base::IntPairHash<RenderFrameHostID>>
RoutingIDFrameMap;
base::LazyInstance<RoutingIDFrameMap>::DestructorAtExit g_routing_id_frame_map =
LAZY_INSTANCE_INITIALIZER;
RenderFrameHostImpl::CreateNetworkFactoryCallback&
GetCreateNetworkFactoryCallbackForRenderFrame() {
static base::NoDestructor<RenderFrameHostImpl::CreateNetworkFactoryCallback>
s_callback;
return *s_callback;
}
using TokenFrameMap = std::unordered_map<base::UnguessableToken,
RenderFrameHostImpl*,
base::UnguessableTokenHash>;
base::LazyInstance<TokenFrameMap>::Leaky g_token_frame_map =
LAZY_INSTANCE_INITIALIZER;
// Translate a WebKit text direction into a base::i18n one.
base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
blink::WebTextDirection dir) {
switch (dir) {
case blink::kWebTextDirectionLeftToRight:
return base::i18n::LEFT_TO_RIGHT;
case blink::kWebTextDirectionRightToLeft:
return base::i18n::RIGHT_TO_LEFT;
default:
NOTREACHED();
return base::i18n::UNKNOWN_DIRECTION;
}
}
// Ensure that we reset nav_entry_id_ in DidCommitProvisionalLoad if any of
// the validations fail and lead to an early return. Call disable() once we
// know the commit will be successful. Resetting nav_entry_id_ avoids acting on
// any UpdateState or UpdateTitle messages after an ignored commit.
class ScopedCommitStateResetter {
public:
explicit ScopedCommitStateResetter(RenderFrameHostImpl* render_frame_host)
: render_frame_host_(render_frame_host), disabled_(false) {}
~ScopedCommitStateResetter() {
if (!disabled_) {
render_frame_host_->set_nav_entry_id(0);
}
}
void disable() { disabled_ = true; }
private:
RenderFrameHostImpl* render_frame_host_;
bool disabled_;
};
void GrantFileAccess(int child_id,
const std::vector<base::FilePath>& file_paths) {
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
for (const auto& file : file_paths) {
if (!policy->CanReadFile(child_id, file))
policy->GrantReadFile(child_id, file);
}
}
#if BUILDFLAG(ENABLE_MEDIA_REMOTING)
// RemoterFactory that delegates Create() calls to the ContentBrowserClient.
//
// Since Create() could be called at any time, perhaps by a stray task being run
// after a RenderFrameHost has been destroyed, the RemoterFactoryImpl uses the
// process/routing IDs as a weak reference to the RenderFrameHostImpl.
class RemoterFactoryImpl final : public media::mojom::RemoterFactory {
public:
RemoterFactoryImpl(int process_id, int routing_id)
: process_id_(process_id), routing_id_(routing_id) {}
static void Bind(int process_id,
int routing_id,
media::mojom::RemoterFactoryRequest request) {
mojo::MakeStrongBinding(
std::make_unique<RemoterFactoryImpl>(process_id, routing_id),
std::move(request));
}
private:
void Create(media::mojom::RemotingSourcePtr source,
media::mojom::RemoterRequest request) final {
if (auto* host = RenderFrameHostImpl::FromID(process_id_, routing_id_)) {
GetContentClient()->browser()->CreateMediaRemoter(
host, std::move(source), std::move(request));
}
}
const int process_id_;
const int routing_id_;
DISALLOW_COPY_AND_ASSIGN(RemoterFactoryImpl);
};
#endif // BUILDFLAG(ENABLE_MEDIA_REMOTING)
using FrameNotifyCallback =
base::RepeatingCallback<void(ResourceDispatcherHostImpl*,
const GlobalFrameRoutingId&)>;
// The following functions simplify code paths where the UI thread notifies the
// ResourceDispatcherHostImpl of information pertaining to loading behavior of
// frame hosts.
void NotifyRouteChangesOnIO(
const FrameNotifyCallback& frame_callback,
std::unique_ptr<std::set<GlobalFrameRoutingId>> routing_ids) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
ResourceDispatcherHostImpl* rdh = ResourceDispatcherHostImpl::Get();
if (!rdh)
return;
for (const auto& routing_id : *routing_ids)
frame_callback.Run(rdh, routing_id);
}
void NotifyForEachFrameFromUI(RenderFrameHostImpl* root_frame_host,
const FrameNotifyCallback& frame_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
FrameTree* frame_tree = root_frame_host->frame_tree_node()->frame_tree();
DCHECK_EQ(root_frame_host, frame_tree->GetMainFrame());
auto routing_ids = std::make_unique<std::set<GlobalFrameRoutingId>>();
for (FrameTreeNode* node : frame_tree->Nodes()) {
RenderFrameHostImpl* frame_host = node->current_frame_host();
RenderFrameHostImpl* pending_frame_host =
node->render_manager()->speculative_frame_host();
if (frame_host)
routing_ids->insert(frame_host->GetGlobalFrameRoutingId());
if (pending_frame_host)
routing_ids->insert(pending_frame_host->GetGlobalFrameRoutingId());
}
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::IO},
base::BindOnce(&NotifyRouteChangesOnIO, frame_callback,
std::move(routing_ids)));
}
using FrameCallback = base::RepeatingCallback<void(RenderFrameHostImpl*)>;
void ForEachFrame(RenderFrameHostImpl* root_frame_host,
const FrameCallback& frame_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
FrameTree* frame_tree = root_frame_host->frame_tree_node()->frame_tree();
DCHECK_EQ(root_frame_host, frame_tree->GetMainFrame());
for (FrameTreeNode* node : frame_tree->Nodes()) {
RenderFrameHostImpl* frame_host = node->current_frame_host();
RenderFrameHostImpl* pending_frame_host =
node->render_manager()->speculative_frame_host();
if (frame_host)
frame_callback.Run(frame_host);
if (pending_frame_host)
frame_callback.Run(pending_frame_host);
}
}
void LookupRenderFrameHostOrProxy(int process_id,
int routing_id,
RenderFrameHostImpl** rfh,
RenderFrameProxyHost** rfph) {
*rfh = RenderFrameHostImpl::FromID(process_id, routing_id);
if (*rfh == nullptr)
*rfph = RenderFrameProxyHost::FromID(process_id, routing_id);
}
// Takes the lower 31 bits of the metric-name-hash of a Mojo interface |name|.
base::Histogram::Sample HashInterfaceNameToHistogramSample(
base::StringPiece name) {
return base::strict_cast<base::Histogram::Sample>(
static_cast<int32_t>(base::HashMetricName(name) & 0x7fffffffull));
}
// Set crash keys that will help understand the circumstances of a renderer
// kill. Note that the commit URL is already reported in a crash key, and
// additional keys are logged in RenderProcessHostImpl::ShutdownForBadMessage.
void LogRendererKillCrashKeys(const GURL& site_url) {
static auto* site_url_key = base::debug::AllocateCrashKeyString(
"current_site_url", base::debug::CrashKeySize::Size64);
base::debug::SetCrashKeyString(site_url_key, site_url.spec());
}
base::Optional<url::Origin> GetOriginForURLLoaderFactoryUnchecked(
NavigationRequest* navigation_request) {
// Return a safe unique origin when there is no |navigation_request| (e.g.
// when RFHI::CommitNavigation is called via RFHI::NavigateToInterstitialURL).
if (!navigation_request)
return url::Origin();
// GetOriginForURLLoaderFactory should only be called at the ready-to-commit
// time, when the RFHI and process to commit the navigation are already known.
DCHECK_LE(NavigationRequest::RESPONSE_STARTED, navigation_request->state());
RenderFrameHostImpl* target_frame = navigation_request->render_frame_host();
// Check if this is loadDataWithBaseUrl (which needs special treatment).
const CommonNavigationParams& common_params =
navigation_request->common_params();
if (common_params.url.SchemeIs(url::kDataScheme) &&
!common_params.base_url_for_data_url.is_empty()) {
// A (potentially attacker-controlled) renderer process should not be able
// to use loadDataWithBaseUrl code path to initiate fetches on behalf of a
// victim origin (fetches controlled by attacker-provided
// |common_params.url| data: URL in a victim's origin from the
// attacker-provided |common_params.base_url_for_data_url|). Browser
// process should verify that |common_params.base_url_for_data_url| is empty
// for all renderer-initiated navigations (e.g. see
// VerifyBeginNavigationCommonParams), but as a defense-in-depth this is
// also asserted below.
CHECK(navigation_request->browser_initiated());
// loadDataWithBaseUrl submits a data: |common_params.url| (which has a
// unique origin), but commits that URL as if it came from
// |common_params.base_url_for_data_url|. See also
// https://crbug.com/976253.
return url::Origin::Create(common_params.base_url_for_data_url);
}
// MHTML frames should commit as unique origin (and should not be able to make
// network requests on behalf of the real origin).
//
// TODO(lukasza): Cover MHTML main frames here.
if (navigation_request->IsForMhtmlSubframe())
return url::Origin();
// TODO(lukasza, nasko): https://crbug.com/888079: Use exact origin, instead
// of falling back to site URL for about:blank and about:srcdoc.
if (common_params.url.SchemeIs(url::kAboutScheme)) {
// |site_instance|'s site URL cannot be used as
// |request_initiator_site_lock| unless the site requires a dedicated
// process. Otherwise b.com may share a process associated with a.com, in
// a SiteInstance with |site_url| set to "http://a.com" (and/or
// "http://nonisolated.invalid" in the future) and in that scenario
// |request_initiator| for requests from b.com should NOT be locked to
// a.com.
SiteInstanceImpl* site_instance = target_frame->GetSiteInstance();
if (!SiteInstanceImpl::ShouldLockToOrigin(
site_instance->GetIsolationContext(), site_instance->GetSiteURL()))
return base::nullopt;
return SiteInstanceImpl::GetRequestInitiatorSiteLock(
site_instance->GetSiteURL());
}
// In cases not covered above, URLLoaderFactory should be associated with the
// origin of |common_params.url|. This works fine for all URLs, including
// data: URLs (which should use an opaque origin for their subresource
// requests) and blob: URLs (which embed their origin inside the URL).
return url::Origin::Create(common_params.url);
}
base::Optional<url::Origin> GetOriginForURLLoaderFactory(
NavigationRequest* navigation_request) {
base::Optional<url::Origin> result =
GetOriginForURLLoaderFactoryUnchecked(navigation_request);
// Any non-opaque |result| must be an origin that is allowed to be accessed
// from the process that is the target of this navigation.
if (result.has_value() && !result->opaque()) {
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
CHECK(policy->CanAccessDataForOrigin(
navigation_request->render_frame_host()->GetProcess()->GetID(),
*result));
}
return result;
}
std::unique_ptr<blink::URLLoaderFactoryBundleInfo> CloneFactoryBundle(
scoped_refptr<blink::URLLoaderFactoryBundle> bundle) {
return base::WrapUnique(static_cast<blink::URLLoaderFactoryBundleInfo*>(
bundle->Clone().release()));
}
void GetRestrictedCookieManager(
RenderFrameHostImpl* frame_host,
int process_id,
int frame_id,
StoragePartition* storage_partition,
network::mojom::RestrictedCookieManagerRequest request) {
GetContentClient()->browser()->WillCreateRestrictedCookieManager(
frame_host->GetLastCommittedOrigin(),
/* is_service_worker = */ false, process_id, frame_id, &request);
storage_partition->GetNetworkContext()->GetRestrictedCookieManager(
std::move(request), frame_host->GetLastCommittedOrigin(),
/* is_service_worker = */ false, process_id, frame_id);
}
// TODO(crbug.com/977040): Remove when no longer needed.
const uint32_t kMaxCookieSameSiteDeprecationUrls = 20;
} // namespace
class RenderFrameHostImpl::DroppedInterfaceRequestLogger
: public service_manager::mojom::InterfaceProvider {
public:
DroppedInterfaceRequestLogger(
service_manager::mojom::InterfaceProviderRequest request)
: binding_(this) {
binding_.Bind(std::move(request));
}
~DroppedInterfaceRequestLogger() override {
UMA_HISTOGRAM_EXACT_LINEAR("RenderFrameHostImpl.DroppedInterfaceRequests",
num_dropped_requests_, 20);
}
protected:
// service_manager::mojom::InterfaceProvider:
void GetInterface(const std::string& interface_name,
mojo::ScopedMessagePipeHandle pipe) override {
++num_dropped_requests_;
base::UmaHistogramSparse(
"RenderFrameHostImpl.DroppedInterfaceRequestName",
HashInterfaceNameToHistogramSample(interface_name));
DLOG(WARNING)
<< "InterfaceRequest was dropped, the document is no longer active: "
<< interface_name;
}
private:
mojo::Binding<service_manager::mojom::InterfaceProvider> binding_;
int num_dropped_requests_ = 0;
DISALLOW_COPY_AND_ASSIGN(DroppedInterfaceRequestLogger);
};
struct PendingNavigation {
CommonNavigationParams common_params;
mojom::BeginNavigationParamsPtr begin_navigation_params;
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory;
mojom::NavigationClientAssociatedPtrInfo navigation_client;
blink::mojom::NavigationInitiatorPtr navigation_initiator;
PendingNavigation(
CommonNavigationParams common_params,
mojom::BeginNavigationParamsPtr begin_navigation_params,
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
mojom::NavigationClientAssociatedPtrInfo navigation_client,
blink::mojom::NavigationInitiatorPtr navigation_initiator);
};
PendingNavigation::PendingNavigation(
CommonNavigationParams common_params,
mojom::BeginNavigationParamsPtr begin_navigation_params,
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
mojom::NavigationClientAssociatedPtrInfo navigation_client,
blink::mojom::NavigationInitiatorPtr navigation_initiator)
: common_params(common_params),
begin_navigation_params(std::move(begin_navigation_params)),
blob_url_loader_factory(std::move(blob_url_loader_factory)),
navigation_client(std::move(navigation_client)),
navigation_initiator(std::move(navigation_initiator)) {}
// An implementation of blink::mojom::FileChooser and FileSelectListener
// associated to RenderFrameHost.
class FileChooserImpl : public blink::mojom::FileChooser,
public content::WebContentsObserver {
using FileChooserResult = blink::mojom::FileChooserResult;
public:
static void Create(RenderFrameHostImpl* render_frame_host,
blink::mojom::FileChooserRequest request) {
mojo::MakeStrongBinding(
std::make_unique<FileChooserImpl>(render_frame_host),
std::move(request));
}
FileChooserImpl(RenderFrameHostImpl* render_frame_host)
: render_frame_host_(render_frame_host) {
Observe(WebContents::FromRenderFrameHost(render_frame_host));
}
~FileChooserImpl() override {
if (proxy_)
proxy_->ResetOwner();
}
void OpenFileChooser(blink::mojom::FileChooserParamsPtr params,
OpenFileChooserCallback callback) override {
if (proxy_ || !render_frame_host_) {
std::move(callback).Run(nullptr);
return;
}
callback_ = std::move(callback);
auto listener = std::make_unique<ListenerProxy>(this);
proxy_ = listener.get();
// Do not allow messages with absolute paths in them as this can permit a
// renderer to coerce the browser to perform I/O on a renderer controlled
// path.
if (params->default_file_name != params->default_file_name.BaseName()) {
mojo::ReportBadMessage(
"FileChooser: The default file name should not be an absolute path.");
listener->FileSelectionCanceled();
return;
}
render_frame_host_->delegate()->RunFileChooser(
render_frame_host_, std::move(listener), *params);
}
void EnumerateChosenDirectory(
const base::FilePath& directory_path,
EnumerateChosenDirectoryCallback callback) override {
if (proxy_ || !render_frame_host_) {
std::move(callback).Run(nullptr);
return;
}
callback_ = std::move(callback);
auto listener = std::make_unique<ListenerProxy>(this);
proxy_ = listener.get();
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
if (policy->CanReadFile(render_frame_host_->GetProcess()->GetID(),
directory_path)) {
render_frame_host_->delegate()->EnumerateDirectory(
render_frame_host_, std::move(listener), directory_path);
} else {
listener->FileSelectionCanceled();
}
}
void FileSelected(std::vector<blink::mojom::FileChooserFileInfoPtr> files,
const base::FilePath& base_dir,
blink::mojom::FileChooserParams::Mode mode) {
proxy_ = nullptr;
if (!render_frame_host_)
return;
storage::FileSystemContext* file_system_context = nullptr;
const int pid = render_frame_host_->GetProcess()->GetID();
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
// Grant the security access requested to the given files.
for (const auto& file : files) {
if (mode == blink::mojom::FileChooserParams::Mode::kSave) {
policy->GrantCreateReadWriteFile(pid,
file->get_native_file()->file_path);
} else {
if (file->is_file_system()) {
if (!file_system_context) {
file_system_context =
BrowserContext::GetStoragePartition(
render_frame_host_->GetProcess()->GetBrowserContext(),
render_frame_host_->GetSiteInstance())
->GetFileSystemContext();
}
policy->GrantReadFileSystem(
pid, file_system_context->CrackURL(file->get_file_system()->url)
.mount_filesystem_id());
} else {
policy->GrantReadFile(pid, file->get_native_file()->file_path);
}
}
}
std::move(callback_).Run(
FileChooserResult::New(std::move(files), base_dir));
}
void FileSelectionCanceled() {
proxy_ = nullptr;
if (!render_frame_host_)
return;
std::move(callback_).Run(nullptr);
}
private:
class ListenerProxy : public content::FileSelectListener {
public:
explicit ListenerProxy(FileChooserImpl* owner) : owner_(owner) {}
~ListenerProxy() override {
#if DCHECK_IS_ON()
DCHECK(was_file_select_listener_function_called_)
<< "Should call either FileSelectListener::FileSelected() or "
"FileSelectListener::FileSelectionCanceled()";
#endif
}
void ResetOwner() { owner_ = nullptr; }
// FileSelectListener overrides:
void FileSelected(std::vector<blink::mojom::FileChooserFileInfoPtr> files,
const base::FilePath& base_dir,
blink::mojom::FileChooserParams::Mode mode) override {
#if DCHECK_IS_ON()
DCHECK(!was_file_select_listener_function_called_)
<< "Should not call both of FileSelectListener::FileSelected() and "
"FileSelectListener::FileSelectionCanceled()";
was_file_select_listener_function_called_ = true;
#endif
if (owner_)
owner_->FileSelected(std::move(files), base_dir, mode);
}
void FileSelectionCanceled() override {
#if DCHECK_IS_ON()
DCHECK(!was_file_select_listener_function_called_)
<< "Should not call both of FileSelectListener::FileSelected() and "
"FileSelectListener::FileSelectionCanceled()";
was_file_select_listener_function_called_ = true;
#endif
if (owner_)
owner_->FileSelectionCanceled();
}
private:
FileChooserImpl* owner_;
#if DCHECK_IS_ON()
bool was_file_select_listener_function_called_ = false;
#endif
};
// content::WebContentsObserver overrides:
void RenderFrameHostChanged(RenderFrameHost* old_host,
RenderFrameHost* new_host) override {
if (old_host == render_frame_host_)
render_frame_host_ = nullptr;
}
void RenderFrameDeleted(RenderFrameHost* render_frame_host) override {
if (render_frame_host == render_frame_host_)
render_frame_host_ = nullptr;
}
void WebContentsDestroyed() override { render_frame_host_ = nullptr; }
RenderFrameHostImpl* render_frame_host_;
ListenerProxy* proxy_ = nullptr;
base::OnceCallback<void(blink::mojom::FileChooserResultPtr)> callback_;
};
// static
RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
int render_frame_id) {
return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
}
#if defined(OS_ANDROID) || defined(OS_FUCHSIA)
// static
void RenderFrameHost::AllowInjectingJavaScript() {
g_allow_injecting_javascript = true;
}
#endif // defined(OS_ANDROID) || defined(OS_FUCHSIA)
// static
RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
int routing_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
auto it = frames->find(RenderFrameHostID(process_id, routing_id));
return it == frames->end() ? NULL : it->second;
}
// static
RenderFrameHost* RenderFrameHost::FromAXTreeID(ui::AXTreeID ax_tree_id) {
return RenderFrameHostImpl::FromAXTreeID(ax_tree_id);
}
// static
RenderFrameHostImpl* RenderFrameHostImpl::FromAXTreeID(
ui::AXTreeID ax_tree_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
ui::AXTreeIDRegistry::FrameID frame_id =
ui::AXTreeIDRegistry::GetInstance()->GetFrameID(ax_tree_id);
return RenderFrameHostImpl::FromID(frame_id.first, frame_id.second);
}
// static
RenderFrameHostImpl* RenderFrameHostImpl::FromOverlayRoutingToken(
const base::UnguessableToken& token) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auto it = g_token_frame_map.Get().find(token);
return it == g_token_frame_map.Get().end() ? nullptr : it->second;
}
// static
void RenderFrameHostImpl::SetNetworkFactoryForTesting(
const CreateNetworkFactoryCallback& create_network_factory_callback) {
DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(create_network_factory_callback.is_null() ||
GetCreateNetworkFactoryCallbackForRenderFrame().is_null())
<< "It is not expected that this is called with non-null callback when "
<< "another overriding callback is already set.";
GetCreateNetworkFactoryCallbackForRenderFrame() =
create_network_factory_callback;
}
RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance,
RenderViewHostImpl* render_view_host,
RenderFrameHostDelegate* delegate,
FrameTree* frame_tree,
FrameTreeNode* frame_tree_node,
int32_t routing_id,
int32_t widget_routing_id,
bool hidden,
bool renderer_initiated_creation)
: render_view_host_(render_view_host),
delegate_(delegate),
site_instance_(static_cast<SiteInstanceImpl*>(site_instance)),
process_(site_instance->GetProcess()),
frame_tree_(frame_tree),
frame_tree_node_(frame_tree_node),
parent_(nullptr),
routing_id_(routing_id),
is_waiting_for_swapout_ack_(false),
render_frame_created_(false),
is_waiting_for_beforeunload_ack_(false),
beforeunload_dialog_request_cancels_unload_(false),
unload_ack_is_for_navigation_(false),
beforeunload_timeout_delay_(base::TimeDelta::FromMilliseconds(
RenderViewHostImpl::kUnloadTimeoutMS)),
was_discarded_(false),
is_loading_(false),
nav_entry_id_(0),
accessibility_reset_token_(0),
accessibility_reset_count_(0),
browser_plugin_embedder_ax_tree_id_(ui::AXTreeIDUnknown()),
no_create_browser_accessibility_manager_for_testing_(false),
web_ui_type_(WebUI::kNoWebUI),
pending_web_ui_type_(WebUI::kNoWebUI),
should_reuse_web_ui_(false),
has_selection_(false),
is_audible_(false),
last_navigation_previews_state_(PREVIEWS_UNSPECIFIED),
frame_host_associated_binding_(this),
waiting_for_init_(renderer_initiated_creation),
has_focused_editable_element_(false),
active_sandbox_flags_(blink::WebSandboxFlags::kNone),
document_scoped_interface_provider_binding_(this),
document_interface_broker_content_binding_(this),
document_interface_broker_blink_binding_(this),
keep_alive_timeout_(base::TimeDelta::FromSeconds(30)),
subframe_unload_timeout_(base::TimeDelta::FromMilliseconds(
RenderViewHostImpl::kUnloadTimeoutMS)),
commit_callback_interceptor_(nullptr),
weak_ptr_factory_(this) {
frame_tree_->AddRenderViewHostRef(render_view_host_);
GetProcess()->AddRoute(routing_id_, this);
g_routing_id_frame_map.Get().emplace(
RenderFrameHostID(GetProcess()->GetID(), routing_id_), this);
site_instance_->AddObserver(this);
process_->AddObserver(this);
GetSiteInstance()->IncrementActiveFrameCount();
if (frame_tree_node_->parent()) {
// Keep track of the parent RenderFrameHost, which shouldn't change even if
// this RenderFrameHost is on the pending deletion list and the parent
// FrameTreeNode has changed its current RenderFrameHost.
parent_ = frame_tree_node_->parent()->current_frame_host();
// All frames in a page are expected to have the same bindings.
if (parent_->GetEnabledBindings())
enabled_bindings_ = parent_->GetEnabledBindings();
// New child frames should inherit the nav_entry_id of their parent.
set_nav_entry_id(
frame_tree_node_->parent()->current_frame_host()->nav_entry_id());
}
SetUpMojoIfNeeded();
swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
&RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
beforeunload_timeout_.reset(
new TimeoutMonitor(base::Bind(&RenderFrameHostImpl::BeforeUnloadTimeout,
weak_ptr_factory_.GetWeakPtr())));
if (widget_routing_id != MSG_ROUTING_NONE) {
mojom::WidgetPtr widget;
GetRemoteInterfaces()->GetInterface(&widget);
if (!parent_) {
// For main frames, the RenderWidgetHost is owned by the RenderViewHost.
// TODO(https://crbug.com/545684): Once RenderViewHostImpl has-a
// RenderWidgetHostImpl, the main render frame should probably start
// owning the RenderWidgetHostImpl itself.
DCHECK(GetLocalRenderWidgetHost());
DCHECK_EQ(GetLocalRenderWidgetHost()->GetRoutingID(), widget_routing_id);
DCHECK(!GetLocalRenderWidgetHost()->owned_by_render_frame_host());
// Make the RenderWidgetHostImpl able to call the mojo Widget interface
// (implemented by the RenderWidgetImpl).
GetLocalRenderWidgetHost()->SetWidget(std::move(widget));
} else {
// For subframes, the RenderFrameHost directly creates and owns its
// RenderWidgetHost.
DCHECK_EQ(nullptr, GetLocalRenderWidgetHost());
DCHECK_EQ(nullptr, RenderWidgetHostImpl::FromID(GetProcess()->GetID(),
widget_routing_id));
owned_render_widget_host_ = RenderWidgetHostFactory::Create(
frame_tree_->render_widget_delegate(), GetProcess(),
widget_routing_id, std::move(widget), hidden);
owned_render_widget_host_->set_owned_by_render_frame_host(true);
}
mojom::WidgetInputHandlerAssociatedPtr widget_handler;
mojom::WidgetInputHandlerHostRequest host_request;
if (frame_input_handler_) {
mojom::WidgetInputHandlerHostPtr host;
host_request = mojo::MakeRequest(&host);
frame_input_handler_->GetWidgetInputHandler(
mojo::MakeRequest(&widget_handler), std::move(host));
}
if (!frame_tree_node_->parent())
GetLocalRenderWidgetHost()->SetIntersectsViewport(true);
GetLocalRenderWidgetHost()->SetFrameDepth(frame_tree_node_->depth());
GetLocalRenderWidgetHost()->SetWidgetInputHandler(std::move(widget_handler),
std::move(host_request));
GetLocalRenderWidgetHost()->input_router()->SetFrameTreeNodeId(
frame_tree_node_->frame_tree_node_id());
}
ResetFeaturePolicy();
ui::AXTreeIDRegistry::GetInstance()->SetFrameIDForAXTreeID(
ui::AXTreeIDRegistry::FrameID(GetProcess()->GetID(), routing_id_),
GetAXTreeID());
// Content-Security-Policy: The CSP source 'self' is usually the origin of the
// current document, set by SetLastCommittedOrigin(). However, before a new
// frame commits its first navigation, 'self' should correspond to the origin
// of the parent (in case of a new iframe) or the opener (in case of a new
// window). This is necessary to correctly enforce CSP during the initial
// navigation.
FrameTreeNode* frame_owner = frame_tree_node_->parent()
? frame_tree_node_->parent()
: frame_tree_node_->opener();
if (frame_owner)
CSPContext::SetSelf(frame_owner->current_origin());
}
RenderFrameHostImpl::~RenderFrameHostImpl() {
// When a RenderFrameHostImpl is deleted, it may still contain children. This
// can happen with the swap out timer. It causes a RenderFrameHost to delete
// itself even if it is still waiting for its children to complete their
// unload handlers.
//
// Observers expect children to be deleted first. Do it now before notifying
// them.
ResetChildren();
// Destroying |navigation_request_| may call into delegates/observers,
// so we do it early while |this| object is still in a sane state.
ResetNavigationRequests();
// Release the WebUI instances before all else as the WebUI may accesses the
// RenderFrameHost during cleanup.
ClearAllWebUI();
SetLastCommittedSiteUrl(GURL());
if (overlay_routing_token_)
g_token_frame_map.Get().erase(*overlay_routing_token_);
site_instance_->RemoveObserver(this);
process_->RemoveObserver(this);
const bool was_created = render_frame_created_;
render_frame_created_ = false;
if (delegate_ && was_created)
delegate_->RenderFrameDeleted(this);
// Ensure that the render process host has been notified that all audio
// streams from this frame have terminated. This is required to ensure the
// process host has the correct media stream count, which affects its
// background priority.
OnAudibleStateChanged(false);
// If this was the last active frame in the SiteInstance, the
// DecrementActiveFrameCount call will trigger the deletion of the
// SiteInstance's proxies.
GetSiteInstance()->DecrementActiveFrameCount();
// Once a RenderFrame is created in the renderer, there are three possible
// clean-up paths:
// 1. The RenderFrame can be the main frame. In this case, closing the
// associated RenderView will clean up the resources associated with the
// main RenderFrame.
// 2. The RenderFrame can be swapped out. In this case, the browser sends a
// FrameMsg_SwapOut for the RenderFrame to replace itself with a
// RenderFrameProxy and release its associated resources. |unload_state_|
// is advanced to UnloadState::InProgress to track that this IPC is in
// flight.
// 3. The RenderFrame can be detached, as part of removing a subtree (due to
// navigation, swap out, or DOM mutation). In this case, the browser sends
// a FrameMsg_Delete for the RenderFrame to detach itself and release its
// associated resources. If the subframe contains an unload handler,
// |unload_state_| is advanced to UnloadState::InProgress to track that the
// detach is in progress; otherwise, it is advanced directly to
// UnloadState::Completed.
//
// The browser side gives the renderer a small timeout to finish processing
// swap out / detach messages. When the timeout expires, the RFH will be
// removed regardless of whether or not the renderer acknowledged that it
// completed the work, to avoid indefinitely leaking browser-side state. To
// avoid leaks, ~RenderFrameHostImpl still validates that the appropriate
// cleanup IPC was sent to the renderer, by checking that |unload_state_| !=
// UnloadState::NotRun.
//
// TODO(dcheng): Due to how frame detach is signalled today, there are some
// bugs in this area. In particular, subtree detach is reported from the
// bottom up, so the replicated FrameMsg_Delete messages actually operate on a
// node-by-node basis rather than detaching an entire subtree at once...
//
// Note that this logic is fairly subtle. It needs to include all subframes
// and all speculative frames, but it should exclude case #1 (a main
// RenderFrame owned by the RenderView). It can't simply:
// - check |frame_tree_node_->render_manager()->speculative_frame_host()| for
// equality against |this|. The speculative frame host is unset before the
// speculative frame host is destroyed, so this condition would never be
// matched for a speculative RFH that needs to be destroyed.
// - check |IsCurrent()|, because the RenderFrames in an InterstitialPageImpl
// are never considered current.
//
// Directly comparing against |RenderViewHostImpl::GetMainFrame()| still has
// one additional subtlety though: |GetMainFrame()| can sometimes return a
// speculative RFH! For subframes, this obviously does not matter: a subframe
// will always pass the condition |render_view_host_->GetMainFrame() != this|.
// However, it turns out that a speculative main frame being deleted will
// *always* pass this condition as well: a speculative RFH being deleted will
// *always* first be unassociated from its corresponding RFHM. Thus, it
// follows that |GetMainFrame()| will never return the speculative main frame
// being deleted, since it must have already been unset.
if (was_created && render_view_host_->GetMainFrame() != this)
CHECK(!is_active());
GetProcess()->RemoveRoute(routing_id_);
g_routing_id_frame_map.Get().erase(
RenderFrameHostID(GetProcess()->GetID(), routing_id_));
// Null out the swapout timer; in crash dumps this member will be null only if
// the dtor has run. (It may also be null in tests.)
swapout_event_monitor_timeout_.reset();
for (auto& iter : visual_state_callbacks_)
std::move(iter.second).Run(false);
// Note: The RenderWidgetHost of the main frame is owned by the RenderViewHost
// instead. In this case the RenderViewHost is responsible for shutting down
// its RenderViewHost.
if (owned_render_widget_host_)
owned_render_widget_host_->ShutdownAndDestroyWidget(false);
// Notify the FrameTree that this RFH is going away, allowing it to shut down
// the corresponding RenderViewHost if it is no longer needed.
frame_tree_->ReleaseRenderViewHostRef(render_view_host_);
// If another frame is waiting for a beforeunload ACK from this frame,
// simulate it now.
RenderFrameHostImpl* beforeunload_initiator = GetBeforeUnloadInitiator();
if (beforeunload_initiator && beforeunload_initiator != this) {
base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
beforeunload_initiator->ProcessBeforeUnloadACKFromFrame(
true /* proceed */, false /* treat_as_final_ack */, this,
true /* is_frame_being_destroyed */, approx_renderer_start_time,
base::TimeTicks::Now());
}
if (prefetched_signed_exchange_cache_)
prefetched_signed_exchange_cache_->RecordHistograms();
}
int RenderFrameHostImpl::GetRoutingID() {
return routing_id_;
}
ui::AXTreeID RenderFrameHostImpl::GetAXTreeID() {
return ax_tree_id();
}
const base::UnguessableToken& RenderFrameHostImpl::GetOverlayRoutingToken() {
if (!overlay_routing_token_) {
overlay_routing_token_ = base::UnguessableToken::Create();
g_token_frame_map.Get().emplace(*overlay_routing_token_, this);
}
return *overlay_routing_token_;
}
void RenderFrameHostImpl::AudioContextPlaybackStarted(int audio_context_id) {
delegate_->AudioContextPlaybackStarted(this, audio_context_id);
}
void RenderFrameHostImpl::AudioContextPlaybackStopped(int audio_context_id) {
delegate_->AudioContextPlaybackStopped(this, audio_context_id);
}
// The current frame went into the BackForwardCache.
void RenderFrameHostImpl::EnterBackForwardCache() {
DCHECK(IsBackForwardCacheEnabled());
DCHECK(!is_in_back_forward_cache_);
is_in_back_forward_cache_ = true;
for (auto& child : children_)
child->current_frame_host()->EnterBackForwardCache();
}
// The frame as been restored from the BackForwardCache.
void RenderFrameHostImpl::LeaveBackForwardCache() {
DCHECK(IsBackForwardCacheEnabled());
DCHECK(is_in_back_forward_cache_);
is_in_back_forward_cache_ = false;
for (auto& child : children_)
child->current_frame_host()->LeaveBackForwardCache();
}
void RenderFrameHostImpl::OnPortalActivated(
const base::UnguessableToken& portal_token,
mojo::PendingAssociatedRemote<blink::mojom::Portal> portal,
mojo::PendingAssociatedReceiver<blink::mojom::PortalClient> portal_client,
blink::TransferableMessage data,
base::OnceCallback<void(bool)> callback) {
GetNavigationControl()->OnPortalActivated(
portal_token, std::move(portal), std::move(portal_client),
std::move(data), std::move(callback));
}
void RenderFrameHostImpl::ForwardMessageFromHost(
blink::TransferableMessage message,
const url::Origin& source_origin,
const base::Optional<url::Origin>& target_origin) {
// The target origin check needs to be done here in case the frame has
// navigated after the postMessage call, or if the renderer is compromised and
// the check done in PortalHost::ReceiveMessage is bypassed.
if (target_origin) {
if (target_origin != GetLastCommittedOrigin())
return;
}
GetNavigationControl()->ForwardMessageFromHost(std::move(message),
source_origin, target_origin);
}
SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
return site_instance_.get();
}
RenderProcessHost* RenderFrameHostImpl::GetProcess() {
return process_;
}
RenderFrameHostImpl* RenderFrameHostImpl::GetParent() {
return parent_;
}
bool RenderFrameHostImpl::IsDescendantOf(RenderFrameHost* ancestor) {
if (!ancestor || !static_cast<RenderFrameHostImpl*>(ancestor)->child_count())
return false;
for (RenderFrameHostImpl* current = GetParent(); current;
current = current->GetParent()) {
if (current == ancestor)
return true;
}
return false;
}
int RenderFrameHostImpl::GetFrameTreeNodeId() {
return frame_tree_node_->frame_tree_node_id();
}
base::UnguessableToken RenderFrameHostImpl::GetDevToolsFrameToken() {
return frame_tree_node_->devtools_frame_token();
}
const std::string& RenderFrameHostImpl::GetFrameName() {
return frame_tree_node_->frame_name();
}
bool RenderFrameHostImpl::IsFrameDisplayNone() {
return frame_tree_node()->frame_owner_properties().is_display_none;
}
const base::Optional<gfx::Size>& RenderFrameHostImpl::GetFrameSize() {
return frame_size_;
}
size_t RenderFrameHostImpl::GetFrameDepth() {
return frame_tree_node()->depth();
}
bool RenderFrameHostImpl::IsCrossProcessSubframe() {
if (!parent_)
return false;
return GetSiteInstance() != parent_->GetSiteInstance();
}
const GURL& RenderFrameHostImpl::GetLastCommittedURL() {
return last_committed_url_;
}
const url::Origin& RenderFrameHostImpl::GetLastCommittedOrigin() {
return last_committed_origin_;
}
void RenderFrameHostImpl::GetCanonicalUrlForSharing(
mojom::Frame::GetCanonicalUrlForSharingCallback callback) {
// TODO(https://crbug.com/859110): Remove this once frame_ can no longer be
// null.
if (IsRenderFrameLive()) {
frame_->GetCanonicalUrlForSharing(std::move(callback));
} else {
std::move(callback).Run(base::nullopt);
}
}
blink::mojom::PauseSubresourceLoadingHandlePtr
RenderFrameHostImpl::PauseSubresourceLoading() {
DCHECK(frame_);
blink::mojom::PauseSubresourceLoadingHandlePtr
pause_subresource_loading_handle;
GetRemoteInterfaces()->GetInterface(&pause_subresource_loading_handle);
return pause_subresource_loading_handle;
}
void RenderFrameHostImpl::ExecuteMediaPlayerActionAtLocation(
const gfx::Point& location,
const blink::WebMediaPlayerAction& action) {
gfx::PointF point_in_view = GetView()->TransformRootPointToViewCoordSpace(
gfx::PointF(location.x(), location.y()));
Send(new FrameMsg_MediaPlayerActionAt(routing_id_, point_in_view, action));
}
bool RenderFrameHostImpl::CreateNetworkServiceDefaultFactory(
network::mojom::URLLoaderFactoryRequest default_factory_request) {
return CreateNetworkServiceDefaultFactoryInternal(
last_committed_origin_, std::move(default_factory_request));
}
void RenderFrameHostImpl::MarkInitiatorsAsRequiringSeparateURLLoaderFactory(
base::flat_set<url::Origin> request_initiators,
bool push_to_renderer_now) {
size_t old_size = initiators_requiring_separate_url_loader_factory_.size();
initiators_requiring_separate_url_loader_factory_.insert(
request_initiators.begin(), request_initiators.end());
size_t new_size = initiators_requiring_separate_url_loader_factory_.size();
bool insertion_took_place = (old_size != new_size);
// Push the updated set of factories to the renderer, but only if
// 1) the caller requested an immediate push (e.g. for content scripts
// injected programmatically chrome.tabs.executeCode, but not for content
// scripts declared in the manifest - the difference is that the latter
// happen at a commit and the factories can just be send in the commit
// IPC).
// 2) an insertion actually took place / the factories have been modified
// 3) a commit has taken place before (i.e. the frame has received a factory
// bundle before).
if (push_to_renderer_now && insertion_took_place &&
has_committed_any_navigation_) {
std::unique_ptr<blink::URLLoaderFactoryBundleInfo>
subresource_loader_factories =
std::make_unique<blink::URLLoaderFactoryBundleInfo>();
subresource_loader_factories->initiator_specific_factory_infos() =
CreateInitiatorSpecificURLLoaderFactories(request_initiators);
GetNavigationControl()->UpdateSubresourceLoaderFactories(
std::move(subresource_loader_factories));
}
}
bool RenderFrameHostImpl::IsSandboxed(blink::WebSandboxFlags flags) {
return static_cast<int>(active_sandbox_flags_) & static_cast<int>(flags);
}
blink::URLLoaderFactoryBundleInfo::OriginMap
RenderFrameHostImpl::CreateInitiatorSpecificURLLoaderFactories(
const base::flat_set<url::Origin>& initiator_origins) {
blink::URLLoaderFactoryBundleInfo::OriginMap result;
for (const url::Origin& initiator : initiator_origins) {
network::mojom::URLLoaderFactoryPtrInfo factory_info;
CreateNetworkServiceDefaultFactoryAndObserve(
initiator, mojo::MakeRequest(&factory_info));
result[initiator] = std::move(factory_info);
}
return result;
}
gfx::NativeView RenderFrameHostImpl::GetNativeView() {
RenderWidgetHostView* view = render_view_host_->GetWidget()->GetView();
if (!view)
return nullptr;
return view->GetNativeView();
}
void RenderFrameHostImpl::AddMessageToConsole(
blink::mojom::ConsoleMessageLevel level,
const std::string& message) {
AddMessageToConsoleImpl(level, message, false /* discard_duplicates */);
}
void RenderFrameHostImpl::ExecuteJavaScript(const base::string16& javascript,
JavaScriptResultCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
CHECK(CanExecuteJavaScript());
const bool wants_result = !callback.is_null();
GetNavigationControl()->JavaScriptExecuteRequest(javascript, wants_result,
std::move(callback));
}
void RenderFrameHostImpl::ExecuteJavaScriptInIsolatedWorld(
const base::string16& javascript,
JavaScriptResultCallback callback,
int world_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_GT(world_id, ISOLATED_WORLD_ID_GLOBAL);
DCHECK_LE(world_id, ISOLATED_WORLD_ID_MAX);
const bool wants_result = !callback.is_null();
GetNavigationControl()->JavaScriptExecuteRequestInIsolatedWorld(
javascript, wants_result, world_id, std::move(callback));
}
void RenderFrameHostImpl::ExecuteJavaScriptForTests(
const base::string16& javascript,
JavaScriptResultCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
const bool has_user_gesture = false;
const bool wants_result = !callback.is_null();
GetNavigationControl()->JavaScriptExecuteRequestForTests(
javascript, wants_result, has_user_gesture, std::move(callback));
}
void RenderFrameHostImpl::ExecuteJavaScriptWithUserGestureForTests(
const base::string16& javascript) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
const bool has_user_gesture = true;
GetNavigationControl()->JavaScriptExecuteRequestForTests(
javascript, false, has_user_gesture, base::NullCallback());
}
void RenderFrameHostImpl::CopyImageAt(int x, int y) {
gfx::PointF point_in_view =
GetView()->TransformRootPointToViewCoordSpace(gfx::PointF(x, y));
Send(new FrameMsg_CopyImageAt(routing_id_, point_in_view.x(),
point_in_view.y()));
}
void RenderFrameHostImpl::SaveImageAt(int x, int y) {
gfx::PointF point_in_view =
GetView()->TransformRootPointToViewCoordSpace(gfx::PointF(x, y));
Send(new FrameMsg_SaveImageAt(routing_id_, point_in_view.x(),
point_in_view.y()));
}
RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
return render_view_host_;
}
service_manager::InterfaceProvider* RenderFrameHostImpl::GetRemoteInterfaces() {
return remote_interfaces_.get();
}
blink::AssociatedInterfaceProvider*
RenderFrameHostImpl::GetRemoteAssociatedInterfaces() {
if (!remote_associated_interfaces_) {
blink::mojom::AssociatedInterfaceProviderAssociatedPtr remote_interfaces;
IPC::ChannelProxy* channel = GetProcess()->GetChannel();
if (channel) {
RenderProcessHostImpl* process =
static_cast<RenderProcessHostImpl*>(GetProcess());
process->GetRemoteRouteProvider()->GetRoute(
GetRoutingID(), mojo::MakeRequest(&remote_interfaces));
} else {
// The channel may not be initialized in some tests environments. In this
// case we set up a dummy interface provider.
mojo::MakeRequestAssociatedWithDedicatedPipe(&remote_interfaces);
}
remote_associated_interfaces_ =
std::make_unique<blink::AssociatedInterfaceProvider>(
std::move(remote_interfaces));
}
return remote_associated_interfaces_.get();
}
PageVisibilityState RenderFrameHostImpl::GetVisibilityState() {
// Works around the crashes seen in https://crbug.com/501863, where the
// active WebContents from a browser iterator may contain a render frame
// detached from the frame tree. This tries to find a RenderWidgetHost
// attached to an ancestor frame, and defaults to visibility hidden if
// it fails.
// TODO(yfriedman, peter): Ideally this would never be called on an
// unattached frame and we could omit this check. See
// https://crbug.com/615867.
RenderFrameHostImpl* frame = this;
while (frame) {
if (frame->GetLocalRenderWidgetHost())
break;
frame = frame->GetParent();
}
if (!frame)
return PageVisibilityState::kHidden;
PageVisibilityState visibility_state = GetRenderWidgetHost()->is_hidden()
? PageVisibilityState::kHidden
: PageVisibilityState::kVisible;
GetContentClient()->browser()->OverridePageVisibilityState(this,
&visibility_state);
return visibility_state;
}
bool RenderFrameHostImpl::Send(IPC::Message* message) {
DCHECK(IPC_MESSAGE_ID_CLASS(message->type()) != InputMsgStart);
return GetProcess()->Send(message);
}
bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
// Only process messages if the RenderFrame is alive.
if (!render_frame_created_)
return false;
// Crash reports triggered by IPC messages for this frame should be associated
// with its URL.
// TODO(lukasza): Also call SetActiveURL for mojo messages dispatched to
// either the FrameHost interface or to interfaces bound by this frame.
ScopedActiveURL scoped_active_url(this);
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockNavigation, OnDidBlockNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState,
OnUpdateUserActivationState)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking,
OnSetNeedsOcclusionTracking);
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame,
OnBubbleLogicalScrollInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess,
OnRenderFallbackContentInParentProcess)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_END_MESSAGE_MAP()
// No further actions here, since we may have been deleted.
return handled;
}
void RenderFrameHostImpl::OnAssociatedInterfaceRequest(
const std::string& interface_name,
mojo::ScopedInterfaceEndpointHandle handle) {
ContentBrowserClient* browser_client = GetContentClient()->browser();
if (!associated_registry_->TryBindInterface(interface_name, &handle) &&
!browser_client->BindAssociatedInterfaceRequestFromFrame(
this, interface_name, &handle)) {
delegate_->OnAssociatedInterfaceRequest(this, interface_name,
std::move(handle));
}
}
void RenderFrameHostImpl::AccessibilityPerformAction(
const ui::AXActionData& action_data) {
Send(new AccessibilityMsg_PerformAction(routing_id_, action_data));
}
bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
RenderWidgetHostView* view = render_view_host_->GetWidget()->GetView();
if (view)
return view->HasFocus();
return false;
}
gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
RenderWidgetHostView* view = render_view_host_->GetWidget()->GetView();
if (view)
return view->GetViewBounds();
return gfx::Rect();
}
float RenderFrameHostImpl::AccessibilityGetDeviceScaleFactor() const {
RenderWidgetHostView* view = render_view_host_->GetWidget()->GetView();
if (view)
return GetScaleFactorForView(view);
return 1.0f;
}
void RenderFrameHostImpl::AccessibilityReset() {
accessibility_reset_token_ = g_next_accessibility_reset_token++;
Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
}
void RenderFrameHostImpl::AccessibilityFatalError() {
browser_accessibility_manager_.reset(nullptr);
if (accessibility_reset_token_)
return;
accessibility_reset_count_++;
if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
Send(new AccessibilityMsg_FatalError(routing_id_));
} else {
accessibility_reset_token_ = g_next_accessibility_reset_token++;
Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
}
}
gfx::AcceleratedWidget
RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
// Only the main frame's current frame host is connected to the native
// widget tree for accessibility, so return null if this is queried on
// any other frame.
if (frame_tree_node()->parent() || !IsCurrent())
return gfx::kNullAcceleratedWidget;
RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
render_view_host_->GetWidget()->GetView());
if (view)
return view->AccessibilityGetAcceleratedWidget();
return gfx::kNullAcceleratedWidget;
}
gfx::NativeViewAccessible
RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
render_view_host_->GetWidget()->GetView());
if (view)
return view->AccessibilityGetNativeViewAccessible();
return nullptr;
}
gfx::NativeViewAccessible
RenderFrameHostImpl::AccessibilityGetNativeViewAccessibleForWindow() {
RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
render_view_host_->GetWidget()->GetView());
if (view)
return view->AccessibilityGetNativeViewAccessibleForWindow();
return nullptr;
}
bool RenderFrameHostImpl::AccessibilityIsMainFrame() {
return frame_tree_node()->IsMainFrame();
}
void RenderFrameHostImpl::RenderProcessExited(
RenderProcessHost* host,
const ChildProcessTerminationInfo& info) {
if (base::FeatureList::IsEnabled(features::kCrashReporting))
MaybeGenerateCrashReport(info.status, info.exit_code);
// When a frame's process dies, its RenderFrame no longer exists, which means
// that its child frames must be cleaned up as well.
ResetChildren();
// Reset state for the current RenderFrameHost once the FrameTreeNode has been
// reset.
SetRenderFrameCreated(false);
InvalidateMojoConnection();
document_scoped_interface_provider_binding_.Close();
document_interface_broker_content_binding_.Close();
document_interface_broker_blink_binding_.Close();
SetLastCommittedUrl(GURL());
// Execute any pending AX tree snapshot callbacks with an empty response,
// since we're never going to get a response from this renderer.
for (auto& iter : ax_tree_snapshot_callbacks_)
std::move(iter.second).Run(ui::AXTreeUpdate());
#if defined(OS_ANDROID)
// Execute any pending Samsung smart clip callbacks.
for (base::IDMap<std::unique_ptr<ExtractSmartClipDataCallback>>::iterator
iter(&smart_clip_callbacks_);
!iter.IsAtEnd(); iter.Advance()) {
std::move(*iter.GetCurrentValue())
.Run(base::string16(), base::string16(), gfx::Rect());
}
smart_clip_callbacks_.Clear();
#endif // defined(OS_ANDROID)
ax_tree_snapshot_callbacks_.clear();
visual_state_callbacks_.clear();
// Ensure that future remote interface requests are associated with the new
// process's channel.
remote_associated_interfaces_.reset();
// Any termination disablers in content loaded by the new process will
// be sent again.
sudden_termination_disabler_types_enabled_ = 0;
if (unload_state_ != UnloadState::NotRun) {
// If the process has died, we don't need to wait for the ACK. Complete the
// deletion immediately.
unload_state_ = UnloadState::Completed;
DCHECK(children_.empty());
PendingDeletionCheckCompleted();
// |this| is deleted. Don't add any more code at this point in the function.
return;
}
// If this was the current pending or speculative RFH dying, cancel and
// destroy it.
frame_tree_node_->render_manager()->CancelPendingIfNecessary(this);
// Note: don't add any more code at this point in the function because
// |this| may be deleted. Any additional cleanup should happen before
// the last block of code here.
}
void RenderFrameHostImpl::RenderProcessGone(SiteInstanceImpl* site_instance) {
DCHECK_EQ(site_instance_.get(), site_instance);
if (owned_render_widget_host_)
owned_render_widget_host_->RendererExited();
// The renderer process is gone, so this frame can no longer be loading.
if (navigation_request())
navigation_request()->set_net_error(net::ERR_ABORTED);
ResetNavigationRequests();
ResetLoadingState();
// Any future UpdateState or UpdateTitle messages from this or a recreated
// process should be ignored until the next commit.
set_nav_entry_id(0);
OnAudibleStateChanged(false);
}
void RenderFrameHostImpl::ReportContentSecurityPolicyViolation(
const CSPViolationParams& violation_params) {
Send(new FrameMsg_ReportContentSecurityPolicyViolation(routing_id_,
violation_params));
}
void RenderFrameHostImpl::SanitizeDataForUseInCspViolation(
bool is_redirect,
CSPDirective::Name directive,
GURL* blocked_url,
SourceLocation* source_location) const {
DCHECK(blocked_url);
DCHECK(source_location);
GURL source_location_url(source_location->url);
// The main goal of this is to avoid leaking information between potentially
// separate renderers, in the event of one of them being compromised.
// See https://crbug.com/633306.
bool sanitize_blocked_url = true;
bool sanitize_source_location = true;
// There is no need to sanitize data when it is same-origin with the current
// url of the renderer.
if (url::Origin::Create(*blocked_url)
.IsSameOriginWith(last_committed_origin_))
sanitize_blocked_url = false;
if (url::Origin::Create(source_location_url)
.IsSameOriginWith(last_committed_origin_))
sanitize_source_location = false;
// When a renderer tries to do a form submission, it already knows the url of
// the blocked url, except when it is redirected.
if (!is_redirect && directive == CSPDirective::FormAction)
sanitize_blocked_url = false;
if (sanitize_blocked_url)
*blocked_url = blocked_url->GetOrigin();
if (sanitize_source_location) {
*source_location =
SourceLocation(source_location_url.GetOrigin().spec(), 0u, 0u);
}
}
void RenderFrameHostImpl::PerformAction(const ui::AXActionData& data) {
AccessibilityPerformAction(data);
}
bool RenderFrameHostImpl::RequiresPerformActionPointInPixels() const {
return true;
}
bool RenderFrameHostImpl::SchemeShouldBypassCSP(
const base::StringPiece& scheme) {
// Blink uses its SchemeRegistry to check if a scheme should be bypassed.
// It can't be used on the browser process. It is used for two things:
// 1) Bypassing the "chrome-extension" scheme when chrome is built with the
// extensions support.
// 2) Bypassing arbitrary scheme for testing purpose only in blink and in V8.
// TODO(arthursonzogni): url::GetBypassingCSPScheme() is used instead of the
// blink::SchemeRegistry. It contains 1) but not 2).
const auto& bypassing_schemes = url::GetCSPBypassingSchemes();
return base::Contains(bypassing_schemes, scheme);
}
mojom::FrameInputHandler* RenderFrameHostImpl::GetFrameInputHandler() {
return frame_input_handler_.get();
}
bool RenderFrameHostImpl::CreateRenderFrame(int previous_routing_id,
int opener_routing_id,
int parent_routing_id,
int previous_sibling_routing_id) {
TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
// The process may (if we're sharing a process with another host that already
// initialized it) or may not (we have our own process or the old process
// crashed) have been initialized. Calling Init multiple times will be
// ignored, so this is safe.
if (!GetProcess()->Init())
return false;
DCHECK(GetProcess()->IsInitializedAndNotDead());
service_manager::mojom::InterfaceProviderPtr interface_provider;
BindInterfaceProviderRequest(mojo::MakeRequest(&interface_provider));
blink::mojom::DocumentInterfaceBrokerPtrInfo
document_interface_broker_content_info;
blink::mojom::DocumentInterfaceBrokerPtrInfo
document_interface_broker_blink_info;
BindDocumentInterfaceBrokerRequest(
mojo::MakeRequest(&document_interface_broker_content_info),
mojo::MakeRequest(&document_interface_broker_blink_info));
mojom::CreateFrameParamsPtr params = mojom::CreateFrameParams::New();
params->interface_bundle = mojom::DocumentScopedInterfaceBundle::New(
interface_provider.PassInterface(),
std::move(document_interface_broker_content_info),
std::move(document_interface_broker_blink_info));
params->routing_id = routing_id_;
params->previous_routing_id = previous_routing_id;
params->opener_routing_id = opener_routing_id;
params->parent_routing_id = parent_routing_id;
params->previous_sibling_routing_id = previous_sibling_routing_id;
params->replication_state = frame_tree_node()->current_replication_state();
params->devtools_frame_token = frame_tree_node()->devtools_frame_token();
// Normally, the replication state contains effective frame policy, excluding
// sandbox flags and feature policy attributes that were updated but have not
// taken effect. However, a new RenderFrame should use the pending frame
// policy, since it is being created as part of the navigation that will
// commit it. (I.e., the RenderFrame needs to know the policy to use when
// initializing the new document once it commits).
params->replication_state.frame_policy =
frame_tree_node()->pending_frame_policy();
params->frame_owner_properties =
FrameOwnerProperties(frame_tree_node()->frame_owner_properties());
params->has_committed_real_load =
frame_tree_node()->has_committed_real_load();
params->widget_params = mojom::CreateFrameWidgetParams::New();
if (GetLocalRenderWidgetHost()) {
params->widget_params->routing_id =
GetLocalRenderWidgetHost()->GetRoutingID();
params->widget_params->hidden = GetLocalRenderWidgetHost()->is_hidden();
} else {
// MSG_ROUTING_NONE will prevent a new RenderWidget from being created in
// the renderer process.
params->widget_params->routing_id = MSG_ROUTING_NONE;
params->widget_params->hidden = true;
}
GetProcess()->GetRendererInterface()->CreateFrame(std::move(params));
// The RenderWidgetHost takes ownership of its view. It is tied to the
// lifetime of the current RenderProcessHost for this RenderFrameHost.
// TODO(avi): This will need to change to initialize a
// RenderWidgetHostViewAura for the main frame once RenderViewHostImpl has-a
// RenderWidgetHostImpl. https://crbug.com/545684
if (owned_render_widget_host_) {
DCHECK(parent_);
DCHECK_NE(parent_routing_id, MSG_ROUTING_NONE);
RenderWidgetHostView* rwhv =
RenderWidgetHostViewChildFrame::Create(owned_render_widget_host_.get());
rwhv->Hide();
}
if (previous_routing_id != MSG_ROUTING_NONE) {
RenderFrameProxyHost* proxy = RenderFrameProxyHost::FromID(
GetProcess()->GetID(), previous_routing_id);
// We have also created a RenderFrameProxy in CreateFrame above, so
// remember that.
proxy->set_render_frame_proxy_created(true);
}
// The renderer now has a RenderFrame for this RenderFrameHost. Note that
// this path is only used for out-of-process iframes. Main frame RenderFrames
// are created with their RenderView, and same-site iframes are created at the
// time of OnCreateChildFrame.
SetRenderFrameCreated(true);
return true;
}
void RenderFrameHostImpl::DeleteRenderFrame(FrameDeleteIntention intent) {
if (!is_active())
return;
if (render_frame_created_) {
Send(new FrameMsg_Delete(routing_id_, intent));
if (!frame_tree_node_->IsMainFrame() && IsCurrent()) {
// If this subframe has an unload handler (and isn't speculative), ensure
// that it has a chance to execute by delaying process cleanup. This will
// prevent the process from shutting down immediately in the case where
// this is the last active frame in the process. See
// https://crbug.com/852204.
if (GetSuddenTerminationDisablerState(blink::kUnloadHandler)) {
RenderProcessHostImpl* process =
static_cast<RenderProcessHostImpl*>(GetProcess());
process->DelayProcessShutdownForUnload(subframe_unload_timeout_);
}
// If the subframe takes too long to unload, force its removal from the
// tree. See https://crbug.com/950625.
subframe_unload_timer_.Start(FROM_HERE, subframe_unload_timeout_, this,
&RenderFrameHostImpl::OnUnloadTimeout);
}
}
unload_state_ = GetSuddenTerminationDisablerState(blink::kUnloadHandler)
? UnloadState::InProgress
: UnloadState::Completed;
}
void RenderFrameHostImpl::SetRenderFrameCreated(bool created) {
// We should not create new RenderFrames while our delegate is being destroyed
// (e.g., via a WebContentsObserver during WebContents shutdown). This seems
// to have caused crashes in https://crbug.com/717650.
if (created && delegate_)
CHECK(!delegate_->IsBeingDestroyed());
bool was_created = render_frame_created_;
render_frame_created_ = created;
// If the current status is different than the new status, the delegate
// needs to be notified.
if (delegate_ && (created != was_created)) {
if (created) {
SetUpMojoIfNeeded();
delegate_->RenderFrameCreated(this);
} else {
delegate_->RenderFrameDeleted(this);
}
}
if (created && GetLocalRenderWidgetHost()) {
mojom::WidgetPtr widget;
GetRemoteInterfaces()->GetInterface(&widget);
GetLocalRenderWidgetHost()->SetWidget(std::move(widget));
if (frame_input_handler_) {
mojom::WidgetInputHandlerAssociatedPtr widget_handler;
mojom::WidgetInputHandlerHostPtr host;
mojom::WidgetInputHandlerHostRequest host_request =
mojo::MakeRequest(&host);
frame_input_handler_->GetWidgetInputHandler(
mojo::MakeRequest(&widget_handler), std::move(host));
GetLocalRenderWidgetHost()->SetWidgetInputHandler(
std::move(widget_handler), std::move(host_request));
}
GetLocalRenderWidgetHost()->input_router()->SetFrameTreeNodeId(
frame_tree_node_->frame_tree_node_id());
viz::mojom::InputTargetClientPtr input_target_client;
remote_interfaces_->GetInterface(&input_target_client);
input_target_client_ = input_target_client.get();
GetLocalRenderWidgetHost()->SetInputTargetClient(
std::move(input_target_client));
GetLocalRenderWidgetHost()->InitForFrame();
}
if (enabled_bindings_ && created) {
if (!frame_bindings_control_)
GetRemoteAssociatedInterfaces()->GetInterface(&frame_bindings_control_);
frame_bindings_control_->AllowBindings(enabled_bindings_);
}
}
void RenderFrameHostImpl::Init() {
ResumeBlockedRequestsForFrame();
if (!waiting_for_init_)
return;
waiting_for_init_ = false;
if (pending_navigate_) {
frame_tree_node()->navigator()->OnBeginNavigation(
frame_tree_node(), pending_navigate_->common_params,
std::move(pending_navigate_->begin_navigation_params),
std::move(pending_navigate_->blob_url_loader_factory),
std::move(pending_navigate_->navigation_client),
std::move(pending_navigate_->navigation_initiator),
EnsurePrefetchedSignedExchangeCache());
pending_navigate_.reset();
}
}
void RenderFrameHostImpl::OnAudibleStateChanged(bool is_audible) {
if (is_audible_ == is_audible)
return;
if (is_audible)
GetProcess()->OnMediaStreamAdded();
else
GetProcess()->OnMediaStreamRemoved();
is_audible_ = is_audible;
}
void RenderFrameHostImpl::DidAddMessageToConsole(
blink::mojom::ConsoleMessageLevel log_level,
const base::string16& message,
int32_t line_no,
const base::string16& source_id) {
if (delegate_->DidAddMessageToConsole(log_level, message, line_no,
source_id)) {
return;
}
// Pass through log severity only on builtin components pages to limit console
// spew.
const bool is_builtin_component =
HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) ||
GetContentClient()->browser()->IsBuiltinComponent(
GetProcess()->GetBrowserContext(), GetLastCommittedOrigin());
const bool is_off_the_record =
GetSiteInstance()->GetBrowserContext()->IsOffTheRecord();
LogConsoleMessage(log_level, message, line_no, is_builtin_component,
is_off_the_record, source_id);
}
void RenderFrameHostImpl::OnCreateChildFrame(
int new_routing_id,
service_manager::mojom::InterfaceProviderRequest
new_interface_provider_provider_request,
blink::mojom::DocumentInterfaceBrokerRequest
document_interface_broker_content_request,
blink::mojom::DocumentInterfaceBrokerRequest
document_interface_broker_blink_request,
blink::WebTreeScopeType scope,
const std::string& frame_name,
const std::string& frame_unique_name,
bool is_created_by_script,
const base::UnguessableToken& devtools_frame_token,
const blink::FramePolicy& frame_policy,
const FrameOwnerProperties& frame_owner_properties,
const blink::FrameOwnerElementType owner_type) {
// TODO(lukasza): Call ReceivedBadMessage when |frame_unique_name| is empty.
DCHECK(!frame_unique_name.empty());
DCHECK(new_interface_provider_provider_request.is_pending());
DCHECK(document_interface_broker_content_request.is_pending());
DCHECK(document_interface_broker_blink_request.is_pending());
if (owner_type == blink::FrameOwnerElementType::kNone) {
// Any child frame must have a HTMLFrameOwnerElement in its parent document
// and therefore the corresponding type of kNone (specific to main frames)
// is invalid.
bad_message::ReceivedBadMessage(
GetProcess(), bad_message::RFH_CHILD_FRAME_NEEDS_OWNER_ELEMENT_TYPE);
}
// The RenderFrame corresponding to this host sent an IPC message to create a
// child, but by the time we get here, it's possible for the host to have been
// swapped out, or for its process to have disconnected (maybe due to browser
// shutdown). Ignore such messages.
if (!is_active() || !IsCurrent() || !render_frame_created_)
return;
// |new_routing_id|, |new_interface_provider_provider_request|,
// |document_interface_broker_content_handle|,
// |document_interface_broker_blink_handle| and |devtools_frame_token| were
// generated on the browser's IO thread and not taken from the renderer
// process.
frame_tree_->AddFrame(
frame_tree_node_, GetProcess()->GetID(), new_routing_id,
std::move(new_interface_provider_provider_request),
std::move(document_interface_broker_content_request),
std::move(document_interface_broker_blink_request), scope, frame_name,
frame_unique_name, is_created_by_script, devtools_frame_token,
frame_policy, frame_owner_properties, was_discarded_, owner_type);
}
void RenderFrameHostImpl::DidNavigate(
const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
bool is_same_document_navigation) {
// Keep track of the last committed URL and origin in the RenderFrameHost
// itself. These allow GetLastCommittedURL and GetLastCommittedOrigin to
// stay correct even if the render_frame_host later becomes pending deletion.
// The URL is set regardless of whether it's for a net error or not.
frame_tree_node_->SetCurrentURL(params.url);
SetLastCommittedOrigin(params.origin);
// Separately, update the frame's last successful URL except for net error
// pages, since those do not end up in the correct process after transfers
// (see https://crbug.com/560511). Instead, the next cross-process navigation
// or transfer should decide whether to swap as if the net error had not
// occurred.
// TODO(creis): Remove this block and always set the URL once transfers handle
// network errors or PlzNavigate is enabled. See https://crbug.com/588314.
if (!params.url_is_unreachable)
last_successful_url_ = params.url;
// After setting the last committed origin, reset the feature policy and
// sandbox flags in the RenderFrameHost to a blank policy based on the parent
// frame.
if (!is_same_document_navigation) {
ResetFeaturePolicy();
active_sandbox_flags_ = frame_tree_node()->active_sandbox_flags();
}
}
void RenderFrameHostImpl::SetLastCommittedOrigin(const url::Origin& origin) {
last_committed_origin_ = origin;
CSPContext::SetSelf(origin);
}
void RenderFrameHostImpl::SetLastCommittedOriginForTesting(
const url::Origin& origin) {
SetLastCommittedOrigin(origin);
}
void RenderFrameHostImpl::SetOriginOfNewFrame(
const url::Origin& new_frame_creator) {
// This method should only be called for *new* frames, that haven't committed
// a navigation yet.
DCHECK(!has_committed_any_navigation_);
DCHECK(GetLastCommittedOrigin().opaque());
// Calculate and set |new_frame_origin|.
bool new_frame_should_be_sandboxed =
blink::WebSandboxFlags::kOrigin ==
(frame_tree_node()->active_sandbox_flags() &
blink::WebSandboxFlags::kOrigin);
url::Origin new_frame_origin = new_frame_should_be_sandboxed
? new_frame_creator.DeriveNewOpaqueOrigin()
: new_frame_creator;
SetLastCommittedOrigin(new_frame_origin);
}
FrameTreeNode* RenderFrameHostImpl::AddChild(
std::unique_ptr<FrameTreeNode> child,
int process_id,
int frame_routing_id) {
// Child frame must always be created in the same process as the parent.
CHECK_EQ(process_id, GetProcess()->GetID());
// Initialize the RenderFrameHost for the new node. We always create child
// frames in the same SiteInstance as the current frame, and they can swap to
// a different one if they navigate away.
child->render_manager()->Init(GetSiteInstance(),
render_view_host()->GetRoutingID(),
frame_routing_id, MSG_ROUTING_NONE, false);
// Other renderer processes in this BrowsingInstance may need to find out
// about the new frame. Create a proxy for the child frame in all
// SiteInstances that have a proxy for the frame's parent, since all frames
// in a frame tree should have the same set of proxies.
frame_tree_node_->render_manager()->CreateProxiesForChildFrame(child.get());
// When the child is added, it hasn't committed any navigation yet - its
// initial empty document should inherit the origin of its parent (the origin
// may change after the first commit). See also https://crbug.com/932067.
child->current_frame_host()->SetOriginOfNewFrame(GetLastCommittedOrigin());
children_.push_back(std::move(child));
return children_.back().get();
}
void RenderFrameHostImpl::RemoveChild(FrameTreeNode* child) {
for (auto iter = children_.begin(); iter != children_.end(); ++iter) {
if (iter->get() == child) {
// Subtle: we need to make sure the node is gone from the tree before
// observers are notified of its deletion.
std::unique_ptr<FrameTreeNode> node_to_delete(std::move(*iter));
children_.erase(iter);
node_to_delete->current_frame_host()->DeleteRenderFrame(
FrameDeleteIntention::kNotMainFrame);
// Speculative RenderFrameHosts are deleted by the FrameTreeNode's
// RenderFrameHostManager's destructor. RenderFrameProxyHosts send
// FrameMsg_Delete automatically in the destructor.
// TODO(dcheng): This is horribly confusing. Refactor this logic so it's
// more understandable.
node_to_delete.reset();
PendingDeletionCheckCompleted();
return;
}
}
}
void RenderFrameHostImpl::ResetChildren() {
// Remove child nodes from the tree, then delete them. This destruction
// operation will notify observers. See https://crbug.com/612450 for
// explanation why we don't just call the std::vector::clear method.
std::vector<std::unique_ptr<FrameTreeNode>> children;
children.swap(children_);
// TODO(dcheng): Ideally, this would be done by messaging all the proxies of
// this RenderFrameHostImpl to detach the current frame's children, rather
// than messaging each child's current frame host...
for (auto& child : children)
child->current_frame_host()->DeleteRenderFrame(
FrameDeleteIntention::kNotMainFrame);
}
void RenderFrameHostImpl::SetLastCommittedUrl(const GURL& url) {
last_committed_url_ = url;
}
void RenderFrameHostImpl::OnDetach() {
if (!parent_) {
bad_message::ReceivedBadMessage(GetProcess(),
bad_message::RFH_DETACH_MAIN_FRAME);
return;
}
// A frame is removed while replacing this document with the new one. When it
// happens, delete the frame and both the new and old documents. Unload
// handlers aren't guaranteed to run here.
if (is_waiting_for_swapout_ack_) {
parent_->RemoveChild(frame_tree_node_);
return;
}
if (unload_state_ != UnloadState::NotRun) {
// The frame is pending deletion. FrameHostMsg_Detach is used to confirm
// its unload handlers ran.
unload_state_ = UnloadState::Completed;
PendingDeletionCheckCompleted(); // Can delete |this|.
return;
}
// This frame is being removed by the renderer, and it has already executed
// its unload handler.
unload_state_ = UnloadState::Completed;
// Before completing the removal, we still need to wait for all of its
// descendant frames to execute unload handlers. Start executing those
// handlers now.
StartPendingDeletionOnSubtree();
frame_tree_node_->frame_tree()->FrameUnloading(frame_tree_node_);
// Some children with no unload handler may be eligible for immediate
// deletion. Cut the dead branches now. This is a performance optimization.
PendingDeletionCheckCompletedOnSubtree(); // Can delete |this|.
}
void RenderFrameHostImpl::OnFrameFocused() {
if (!is_active())
return;
delegate_->SetFocusedFrame(frame_tree_node_, GetSiteInstance());
}
void RenderFrameHostImpl::OnOpenURL(const FrameHostMsg_OpenURL_Params& params) {
// Verify and unpack IPC payload.
GURL validated_url;
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory;
if (!VerifyOpenURLParams(GetSiteInstance(), params, &validated_url,
&blob_url_loader_factory)) {
return;
}
TRACE_EVENT1("navigation", "RenderFrameHostImpl::OpenURL", "url",
validated_url.possibly_invalid_spec());
frame_tree_node_->navigator()->RequestOpenURL(
this, validated_url, params.initiator_origin, params.uses_post,
params.resource_request_body, params.extra_headers, params.referrer,
params.disposition, params.should_replace_current_entry,
params.user_gesture, params.triggering_event_info, params.href_translate,
std::move(blob_url_loader_factory));
}
void RenderFrameHostImpl::CancelInitialHistoryLoad() {
// A Javascript navigation interrupted the initial history load. Check if an
// initial subframe cross-process navigation needs to be canceled as a result.
// TODO(creis, clamy): Cancel any cross-process navigation.
NOTIMPLEMENTED();
}
void RenderFrameHostImpl::DocumentOnLoadCompleted() {
// This message is only sent for top-level frames. TODO(avi): when frame tree
// mirroring works correctly, add a check here to enforce it.
delegate_->DocumentOnLoadCompleted(this);
}
void RenderFrameHostImpl::UpdateActiveSchedulerTrackedFeatures(
uint64_t features_mask) {
TRACE_EVENT0("toplevel", "UpdateActiveSchedulerTrackedFeatures");
renderer_reported_scheduler_tracked_features_ = features_mask;
}
void RenderFrameHostImpl::OnSchedulerTrackedFeatureUsed(
blink::scheduler::WebSchedulerTrackedFeature feature) {
TRACE_EVENT0("toplevel", "OnSchedulerTrackedFeatureUsed");
browser_reported_scheduler_tracked_features_ |=
1 << static_cast<uint64_t>(feature);
}
void RenderFrameHostImpl::DidFailProvisionalLoadWithError(
const GURL& url,
int error_code,
const base::string16& error_description,
bool showing_repost_interstitial) {
TRACE_EVENT2("navigation",
"RenderFrameHostImpl::DidFailProvisionalLoadWithError",
"frame_tree_node", frame_tree_node_->frame_tree_node_id(),
"error", error_code);
// TODO(clamy): Kill the renderer with RFH_FAIL_PROVISIONAL_LOAD_NO_HANDLE and
// return early if navigation_handle_ is null, once we prevent that case from
// happening in practice. See https://crbug.com/605289.
// Update the error code in the NavigationRequest.
if (navigation_request()) {
navigation_request()->set_net_error(static_cast<net::Error>(error_code));
}
frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(
this, url, error_code, error_description, showing_repost_interstitial);
}
void RenderFrameHostImpl::DidFailLoadWithError(
const GURL& url,
int error_code,
const base::string16& error_description) {
TRACE_EVENT2("navigation",
"RenderFrameHostImpl::DidFailProvisionalLoadWithError",
"frame_tree_node", frame_tree_node_->frame_tree_node_id(),
"error", error_code);
GURL validated_url(url);
GetProcess()->FilterURL(false, &validated_url);
frame_tree_node_->navigator()->DidFailLoadWithError(
this, validated_url, error_code, error_description);
}
void RenderFrameHostImpl::DidCommitProvisionalLoad(
std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params>
validated_params,
mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) {
if (MaybeInterceptCommitCallback(nullptr, validated_params.get(),
&interface_params)) {
DidCommitNavigation(std::move(navigation_request_),
std::move(validated_params),
std::move(interface_params));
}
}
void RenderFrameHostImpl::DidCommitPerNavigationMojoInterfaceNavigation(
NavigationRequest* committing_navigation_request,
std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params>
validated_params,
mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) {
DCHECK(committing_navigation_request);
committing_navigation_request->IgnoreCommitInterfaceDisconnection();
if (!MaybeInterceptCommitCallback(committing_navigation_request,
validated_params.get(),
&interface_params)) {
return;
}
auto request = navigation_requests_.find(committing_navigation_request);
// The committing request should be in the map of NavigationRequests for
// this RenderFrameHost.
CHECK(request != navigation_requests_.end());
std::unique_ptr<NavigationRequest> owned_request = std::move(request->second);
navigation_requests_.erase(committing_navigation_request);
DidCommitNavigation(std::move(owned_request), std::move(validated_params),
std::move(interface_params));
}
void RenderFrameHostImpl::DidCommitSameDocumentNavigation(
std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params>
validated_params) {
ScopedActiveURL scoped_active_url(
validated_params->url,
frame_tree_node()->frame_tree()->root()->current_origin());
ScopedCommitStateResetter commit_state_resetter(this);
// When the frame is pending deletion, the browser is waiting for it to unload
// properly. In the meantime, because of race conditions, it might tries to
// commit a same-document navigation before unloading. Similarly to what is
// done with cross-document navigations, such navigation are ignored. The
// browser already committed to destroying this RenderFrameHost.
// See https://crbug.com/805705 and https://crbug.com/930132.
// TODO(ahemery): Investigate to see if this can be removed when the
// NavigationClient interface is implemented.
if (!is_active())
return;
TRACE_EVENT2("navigation",
"RenderFrameHostImpl::DidCommitSameDocumentNavigation",
"frame_tree_node", frame_tree_node_->frame_tree_node_id(), "url",
validated_params->url.possibly_invalid_spec());
// Check if the navigation matches a stored same-document NavigationRequest.
// In that case it is browser-initiated.
bool is_browser_initiated =
same_document_navigation_request_ &&
(same_document_navigation_request_->commit_params().navigation_token ==
validated_params->navigation_token);
if (!DidCommitNavigationInternal(
is_browser_initiated ? std::move(same_document_navigation_request_)
: nullptr,
validated_params.get(), true /* is_same_document_navigation*/)) {
return;
}
// Since we didn't early return, it's safe to keep the commit state.
commit_state_resetter.disable();
}
void RenderFrameHostImpl::OnUpdateState(const PageState& state) {
// TODO(creis): Verify the state's ISN matches the last committed FNE.
// Without this check, the renderer can trick the browser into using
// filenames it can't access in a future session restore.
if (!CanAccessFilesOfPageState(state)) {
bad_message::ReceivedBadMessage(
GetProcess(), bad_message::RFH_CAN_ACCESS_FILES_OF_PAGE_STATE);
return;
}
delegate_->UpdateStateForFrame(this, state);
}
RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
RenderFrameHostImpl* frame = this;
while (frame) {
if (frame->GetLocalRenderWidgetHost())
return frame->GetLocalRenderWidgetHost();
frame = frame->GetParent();
}
NOTREACHED();
return nullptr;
}
RenderWidgetHostView* RenderFrameHostImpl::GetView() {
return GetRenderWidgetHost()->GetView();
}
GlobalFrameRoutingId RenderFrameHostImpl::GetGlobalFrameRoutingId() {
return GlobalFrameRoutingId(GetProcess()->GetID(), GetRoutingID());
}
NavigationHandleImpl* RenderFrameHostImpl::GetNavigationHandle() {
return navigation_request() ? navigation_request()->navigation_handle()
: nullptr;
}
void RenderFrameHostImpl::ResetNavigationRequests() {
navigation_request_.reset();
same_document_navigation_request_.reset();
navigation_requests_.clear();
}
void RenderFrameHostImpl::SetNavigationRequest(
std::unique_ptr<NavigationRequest> navigation_request) {
DCHECK(navigation_request);
if (FrameMsg_Navigate_Type::IsSameDocument(
navigation_request->common_params().navigation_type)) {
same_document_navigation_request_ = std::move(navigation_request);
return;
}
navigation_requests_[navigation_request.get()] =
std::move(navigation_request);
}
void RenderFrameHostImpl::SwapOut(
RenderFrameProxyHost* proxy,
bool is_loading) {
// The end of this event is in OnSwapOutACK when the RenderFrame has completed
// the operation and sends back an IPC message.
// The trace event may not end properly if the ACK times out. We expect this
// to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
TRACE_EVENT_ASYNC_BEGIN1("navigation", "RenderFrameHostImpl::SwapOut", this,
"frame_tree_node",
frame_tree_node_->frame_tree_node_id());
// If this RenderFrameHost is already pending deletion, it must have already
// gone through this, therefore just return.
if (unload_state_ != UnloadState::NotRun) {
NOTREACHED() << "RFH should be in default state when calling SwapOut.";
return;
}
if (swapout_event_monitor_timeout_) {
swapout_event_monitor_timeout_->Start(base::TimeDelta::FromMilliseconds(
RenderViewHostImpl::kUnloadTimeoutMS));
}
// There should always be a proxy to replace the old RenderFrameHost. If
// there are no remaining active views in the process, the proxy will be
// short-lived and will be deleted when the SwapOut ACK is received.
CHECK(proxy);
// TODO(nasko): If the frame is not live, the RFH should just be deleted by
// simulating the receipt of swap out ack.
is_waiting_for_swapout_ack_ = true;
unload_state_ = UnloadState::InProgress;
if (IsRenderFrameLive()) {
FrameReplicationState replication_state =
proxy->frame_tree_node()->current_replication_state();
Send(new FrameMsg_SwapOut(routing_id_, proxy->GetRoutingID(), is_loading,
replication_state));
// Remember that a RenderFrameProxy was created as part of processing the
// SwapOut message above.
proxy->set_render_frame_proxy_created(true);
StartPendingDeletionOnSubtree();
}
// Some children with no unload handler may be eligible for deletion. Cut the
// dead branches now. This is a performance optimization.
PendingDeletionCheckCompletedOnSubtree();
if (web_ui())
web_ui()->RenderFrameHostSwappingOut();
web_bluetooth_services_.clear();
#if !defined(OS_ANDROID)
serial_service_.reset();
#endif
}
void RenderFrameHostImpl::DetachFromProxy() {
if (unload_state_ != UnloadState::NotRun)
return;
// Start pending deletion on this frame and its children.
DeleteRenderFrame(FrameDeleteIntention::kNotMainFrame);
StartPendingDeletionOnSubtree();
frame_tree_node_->frame_tree()->FrameUnloading(frame_tree_node_);
// Some children with no unload handler may be eligible for immediate
// deletion. Cut the dead branches now. This is a performance optimization.
PendingDeletionCheckCompletedOnSubtree(); // May delete |this|.
}
void RenderFrameHostImpl::OnBeforeUnloadACK(
bool proceed,
const base::TimeTicks& renderer_before_unload_start_time,
const base::TimeTicks& renderer_before_unload_end_time) {
ProcessBeforeUnloadACK(proceed, false /* treat_as_final_ack */,
renderer_before_unload_start_time,
renderer_before_unload_end_time);
}
void RenderFrameHostImpl::ProcessBeforeUnloadACK(
bool proceed,
bool treat_as_final_ack,
const base::TimeTicks& renderer_before_unload_start_time,
const base::TimeTicks& renderer_before_unload_end_time) {
TRACE_EVENT_ASYNC_END1("navigation", "RenderFrameHostImpl BeforeUnload", this,
"FrameTreeNode id",
frame_tree_node_->frame_tree_node_id());
// If this renderer navigated while the beforeunload request was in flight, we
// may have cleared this state in DidCommitProvisionalLoad, in which case we
// can ignore this message.
// However renderer might also be swapped out but we still want to proceed
// with navigation, otherwise it would block future navigations. This can
// happen when pending cross-site navigation is canceled by a second one just
// before DidCommitProvisionalLoad while current RVH is waiting for commit
// but second navigation is started from the beginning.
RenderFrameHostImpl* initiator = GetBeforeUnloadInitiator();
if (!initiator)
return;
// Continue processing the ACK in the frame that triggered beforeunload in
// this frame. This could be either this frame itself or an ancestor frame.
initiator->ProcessBeforeUnloadACKFromFrame(
proceed, treat_as_final_ack, this, false /* is_frame_being_destroyed */,
renderer_before_unload_start_time, renderer_before_unload_end_time);
}
RenderFrameHostImpl* RenderFrameHostImpl::GetBeforeUnloadInitiator() {
for (RenderFrameHostImpl* frame = this; frame; frame = frame->GetParent()) {
if (frame->is_waiting_for_beforeunload_ack_)
return frame;
}
return nullptr;
}
void RenderFrameHostImpl::ProcessBeforeUnloadACKFromFrame(
bool proceed,
bool treat_as_final_ack,
RenderFrameHostImpl* frame,
bool is_frame_being_destroyed,
const base::TimeTicks& renderer_before_unload_start_time,
const base::TimeTicks& renderer_before_unload_end_time) {
// Check if we need to wait for more beforeunload ACKs. If |proceed| is
// false, we know the navigation or window close will be aborted, so we don't
// need to wait for beforeunload ACKs from any other frames.
// |treat_as_final_ack| also indicates that we shouldn't wait for any other
// ACKs (e.g., when a beforeunload timeout fires).
if (!proceed || treat_as_final_ack) {
beforeunload_pending_replies_.clear();
} else {
beforeunload_pending_replies_.erase(frame);
if (!beforeunload_pending_replies_.empty())
return;
}
DCHECK(!send_before_unload_start_time_.is_null());
// Sets a default value for before_unload_end_time so that the browser
// survives a hacked renderer.
base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
if (!renderer_before_unload_start_time.is_null() &&
!renderer_before_unload_end_time.is_null()) {
base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
if (!base::TimeTicks::IsConsistentAcrossProcesses()) {
// TimeTicks is not consistent across processes and we are passing
// TimeTicks across process boundaries so we need to compensate for any
// skew between the processes. Here we are converting the renderer's
// notion of before_unload_end_time to TimeTicks in the browser process.
// See comments in inter_process_time_ticks_converter.h for more.
InterProcessTimeTicksConverter converter(
LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
LocalTimeTicks browser_before_unload_end_time =
converter.ToLocalTimeTicks(
RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
}
base::TimeDelta on_before_unload_overhead_time =
(receive_before_unload_ack_time - send_before_unload_start_time_) -
(renderer_before_unload_end_time - renderer_before_unload_start_time);
UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
on_before_unload_overhead_time);
frame_tree_node_->navigator()->LogBeforeUnloadTime(
renderer_before_unload_start_time, renderer_before_unload_end_time);
}
// Resets beforeunload waiting state.
is_waiting_for_beforeunload_ack_ = false;
has_shown_beforeunload_dialog_ = false;
if (beforeunload_timeout_)
beforeunload_timeout_->Stop();
send_before_unload_start_time_ = base::TimeTicks();
// If the ACK is for a navigation, send it to the Navigator to have the
// current navigation stop/proceed. Otherwise, send it to the
// RenderFrameHostManager which handles closing.
if (unload_ack_is_for_navigation_) {
frame_tree_node_->navigator()->OnBeforeUnloadACK(frame_tree_node_, proceed,
before_unload_end_time);
} else {
// We could reach this from a subframe destructor for |frame| while we're
// in the middle of closing the current tab. In that case, dispatch the
// ACK to prevent re-entrancy and a potential nested attempt to free the
// current frame. See https://crbug.com/866382.
base::OnceClosure task = base::BindOnce(
[](base::WeakPtr<RenderFrameHostImpl> self,
const base::TimeTicks& before_unload_end_time, bool proceed) {
if (!self)
return;
self->frame_tree_node()->render_manager()->OnBeforeUnloadACK(
proceed, before_unload_end_time);
},
weak_ptr_factory_.GetWeakPtr(), before_unload_end_time, proceed);
if (is_frame_being_destroyed) {
DCHECK(proceed);
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(task));
} else {
std::move(task).Run();
}
}
// If canceled, notify the delegate to cancel its pending navigation entry.
// This is usually redundant with the dialog closure code in WebContentsImpl's
// OnDialogClosed, but there may be some cases that Blink returns !proceed
// without showing the dialog. We also update the address bar here to be safe.
if (!proceed)
delegate_->DidCancelLoading();
}
bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
return render_view_host_->is_waiting_for_close_ack_ ||
is_waiting_for_swapout_ack_;
}
void RenderFrameHostImpl::OnSwapOutACK() {
if (frame_tree_node_->render_manager()->is_attaching_inner_delegate()) {
// This RFH was swapped out while attaching an inner delegate. The RFH
// will stay around but it will no longer be associated with a RenderFrame.
SetRenderFrameCreated(false);
return;
}
// Ignore spurious swap out ack.
if (!is_waiting_for_swapout_ack_)
return;
DCHECK_EQ(UnloadState::InProgress, unload_state_);
unload_state_ = UnloadState::Completed;
PendingDeletionCheckCompleted(); // Can delete |this|.
}
void RenderFrameHostImpl::OnSwappedOut() {
DCHECK(is_waiting_for_swapout_ack_);
TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
if (swapout_event_monitor_timeout_)
swapout_event_monitor_timeout_->Stop();
ClearAllWebUI();
// If this is a main frame RFH that's about to be deleted, update its RVH's
// swapped-out state here. https://crbug.com/505887. This should only be
// done if the RVH hasn't been already reused and marked as active by another
// navigation. See https://crbug.com/823567.
if (frame_tree_node_->IsMainFrame() && !render_view_host_->is_active())
render_view_host_->set_is_swapped_out(true);
bool deleted =
frame_tree_node_->render_manager()->DeleteFromPendingList(this);
CHECK(deleted);
}
void RenderFrameHostImpl::DisableSwapOutTimerForTesting() {
swapout_event_monitor_timeout_.reset();
}
void RenderFrameHostImpl::SetSubframeUnloadTimeoutForTesting(
const base::TimeDelta& timeout) {
subframe_unload_timeout_ = timeout;
}
void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
if (!is_active())
return;
// Validate the URLs in |params|. If the renderer can't request the URLs
// directly, don't show them in the context menu.
ContextMenuParams validated_params(params);
RenderProcessHost* process = GetProcess();