blob: c7e9d29b99aa24f97a897281fa674f1dcb77701c [file] [log] [blame]
// Copyright (c) 2012 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 "chrome/browser/chrome_content_browser_client.h"
#include <iterator>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/i18n/base_i18n_switches.h"
#include "base/i18n/character_encoding.h"
#include "base/macros.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/sequenced_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/accessibility/accessibility_labels_service.h"
#include "chrome/browser/accessibility/accessibility_labels_service_factory.h"
#include "chrome/browser/accessibility/caption_util.h"
#include "chrome/browser/after_startup_task_utils.h"
#include "chrome/browser/bluetooth/chrome_bluetooth_delegate.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
#include "chrome/browser/captive_portal/captive_portal_service_factory.h"
#include "chrome/browser/chrome_content_browser_client_parts.h"
#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry.h"
#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h"
#include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h"
#include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h"
#include "chrome/browser/data_use_measurement/chrome_data_use_measurement.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/engagement/site_engagement_service.h"
#include "chrome/browser/extensions/chrome_extension_cookies.h"
#include "chrome/browser/external_protocol/external_protocol_handler.h"
#include "chrome/browser/federated_learning/floc_id_provider.h"
#include "chrome/browser/federated_learning/floc_id_provider_factory.h"
#include "chrome/browser/font_family_cache.h"
#include "chrome/browser/gpu/chrome_browser_main_extra_parts_gpu.h"
#include "chrome/browser/hid/chrome_hid_delegate.h"
#include "chrome/browser/interstitials/enterprise_util.h"
#include "chrome/browser/lifetime/browser_shutdown.h"
#include "chrome/browser/lookalikes/lookalike_url_navigation_throttle.h"
#include "chrome/browser/media/audio_service_util.h"
#include "chrome/browser/media/router/media_router_feature.h"
#include "chrome/browser/media/webrtc/audio_debug_recordings_handler.h"
#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
#include "chrome/browser/media/webrtc/webrtc_logging_controller.h"
#include "chrome/browser/memory/chrome_browser_main_extra_parts_memory.h"
#include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
#include "chrome/browser/metrics/chrome_feature_list_creator.h"
#include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
#include "chrome/browser/net/chrome_network_delegate.h"
#include "chrome/browser/net/profile_network_context_service.h"
#include "chrome/browser/net/profile_network_context_service_factory.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/notifications/platform_notification_service_factory.h"
#include "chrome/browser/notifications/platform_notification_service_impl.h"
#include "chrome/browser/password_manager/chrome_password_manager_client.h"
#include "chrome/browser/payments/payment_request_display_manager_factory.h"
#include "chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.h"
#include "chrome/browser/performance_manager/chrome_content_browser_client_performance_manager_part.h"
#include "chrome/browser/permissions/attestation_permission_request.h"
#include "chrome/browser/platform_util.h"
#include "chrome/browser/plugins/pdf_iframe_navigation_throttle.h"
#include "chrome/browser/plugins/plugin_utils.h"
#include "chrome/browser/prefetch/no_state_prefetch/chrome_prerender_contents_delegate.h"
#include "chrome/browser/prefetch/no_state_prefetch/prerender_manager_factory.h"
#include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_features.h"
#include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_service.h"
#include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_service_factory.h"
#include "chrome/browser/prefetch/prefetch_proxy/prefetch_proxy_url_loader_interceptor.h"
#include "chrome/browser/prefetch/search_prefetch/field_trial_settings.h"
#include "chrome/browser/prefetch/search_prefetch/search_prefetch_service.h"
#include "chrome/browser/prefetch/search_prefetch/search_prefetch_service_factory.h"
#include "chrome/browser/prefetch/search_prefetch/search_prefetch_url_loader_interceptor.h"
#include "chrome/browser/previews/previews_content_util.h"
#include "chrome/browser/previews/previews_service.h"
#include "chrome/browser/previews/previews_service_factory.h"
#include "chrome/browser/previews/previews_ui_tab_helper.h"
#include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_io_data.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/renderer_updater.h"
#include "chrome/browser/profiles/renderer_updater_factory.h"
#include "chrome/browser/profiling_host/chrome_browser_main_extra_parts_profiling.h"
#include "chrome/browser/profiling_host/profiling_process_host.h"
#include "chrome/browser/renderer_host/chrome_navigation_ui_data.h"
#include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
#include "chrome/browser/renderer_preferences_util.h"
#include "chrome/browser/resource_coordinator/background_tab_navigation_throttle.h"
#include "chrome/browser/safe_browsing/certificate_reporting_service.h"
#include "chrome/browser/safe_browsing/certificate_reporting_service_factory.h"
#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_utils.h"
#include "chrome/browser/safe_browsing/delayed_warning_navigation_throttle.h"
#include "chrome/browser/safe_browsing/safe_browsing_navigation_throttle.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/safe_browsing/ui_manager.h"
#include "chrome/browser/safe_browsing/url_checker_delegate_impl.h"
#include "chrome/browser/safe_browsing/url_lookup_service_factory.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/sharing/sms/sms_remote_fetcher.h"
#include "chrome/browser/signin/chrome_signin_proxying_url_loader_factory.h"
#include "chrome/browser/signin/chrome_signin_url_loader_throttle.h"
#include "chrome/browser/signin/header_modification_delegate_impl.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
#include "chrome/browser/ssl/chrome_security_blocking_page_factory.h"
#include "chrome/browser/ssl/sct_reporting_service.h"
#include "chrome/browser/ssl/sct_reporting_service_factory.h"
#include "chrome/browser/ssl/ssl_client_auth_metrics.h"
#include "chrome/browser/ssl/ssl_client_certificate_selector.h"
#include "chrome/browser/sync_file_system/local/sync_file_system_backend.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/tracing/chrome_tracing_delegate.h"
#include "chrome/browser/translate/translate_service.h"
#include "chrome/browser/ui/blocked_content/blocked_window_params.h"
#include "chrome/browser/ui/blocked_content/chrome_popup_navigation_delegate.h"
#include "chrome/browser/ui/blocked_content/tab_under_navigation_throttle.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
#include "chrome/browser/ui/login/login_handler.h"
#include "chrome/browser/ui/login/login_navigation_throttle.h"
#include "chrome/browser/ui/login/login_tab_helper.h"
#include "chrome/browser/ui/passwords/well_known_change_password_navigation_throttle.h"
#include "chrome/browser/ui/prefs/pref_watcher.h"
#include "chrome/browser/ui/sync/sync_promo_ui.h"
#include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
#include "chrome/browser/ui/webui/log_web_ui_url.h"
#include "chrome/browser/usb/frame_usb_services.h"
#include "chrome/browser/vr/vr_tab_helper.h"
#include "chrome/browser/web_applications/components/app_registrar.h"
#include "chrome/browser/web_applications/components/web_app_provider_base.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_content_client.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/google_url_loader_throttle.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/pepper_permission_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/profiler/thread_profiler_configuration.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/renderer_configuration.mojom.h"
#include "chrome/common/secure_origin_allowlist.h"
#include "chrome/common/url_constants.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/installer/util/google_update_settings.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "components/blocked_content/popup_blocker.h"
#include "components/browsing_data/content/browsing_data_helper.h"
#include "components/browsing_data/core/browsing_data_utils.h"
#include "components/captive_portal/content/captive_portal_service.h"
#include "components/captive_portal/core/buildflags.h"
#include "components/cdm/browser/cdm_message_filter_android.h"
#include "components/certificate_matching/certificate_principal_pattern.h"
#include "components/cloud_devices/common/cloud_devices_switches.h"
#include "components/content_settings/browser/page_specific_content_settings.h"
#include "components/content_settings/core/browser/content_settings_utils.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/browser/private_network_settings.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_data.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_features.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
#include "components/dom_distiller/core/dom_distiller_switches.h"
#include "components/dom_distiller/core/url_constants.h"
#include "components/embedder_support/switches.h"
#include "components/error_page/common/error.h"
#include "components/error_page/common/error_page_switches.h"
#include "components/error_page/common/localized_error.h"
#include "components/error_page/content/browser/net_error_auto_reloader.h"
#include "components/feature_engagement/public/feature_constants.h"
#include "components/feature_engagement/public/feature_list.h"
#include "components/google/core/common/google_switches.h"
#include "components/language/core/browser/pref_names.h"
#include "components/media_router/browser/presentation/presentation_service_delegate_impl.h"
#include "components/media_router/browser/presentation/receiver_presentation_service_delegate_impl.h"
#include "components/metrics/client_info.h"
#include "components/metrics_services_manager/metrics_services_manager.h"
#include "components/net_log/chrome_net_log.h"
#include "components/no_state_prefetch/browser/prerender_manager.h"
#include "components/no_state_prefetch/common/prerender_final_status.h"
#include "components/no_state_prefetch/common/prerender_types.mojom.h"
#include "components/no_state_prefetch/common/prerender_url_loader_throttle.h"
#include "components/no_state_prefetch/common/prerender_util.h"
#include "components/page_load_metrics/browser/metrics_navigation_throttle.h"
#include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
#include "components/payments/content/payment_request_display_manager.h"
#include "components/performance_manager/embedder/performance_manager_registry.h"
#include "components/permissions/permission_context_base.h"
#include "components/permissions/quota_permission_context_impl.h"
#include "components/policy/content/policy_blocklist_navigation_throttle.h"
#include "components/policy/content/policy_blocklist_service.h"
#include "components/policy/core/common/policy_pref_names.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/policy_constants.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/previews/content/previews_decider.h"
#include "components/previews/content/previews_decider_impl.h"
#include "components/previews/content/previews_ui_service.h"
#include "components/previews/content/previews_user_data.h"
#include "components/previews/core/previews_experiments.h"
#include "components/previews/core/previews_features.h"
#include "components/previews/core/previews_switches.h"
#include "components/safe_browsing/buildflags.h"
#include "components/safe_browsing/content/browser/browser_url_loader_throttle.h"
#include "components/safe_browsing/content/password_protection/password_protection_navigation_throttle.h"
#include "components/safe_browsing/core/browser/url_checker_delegate.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/safe_browsing/core/db/database_manager.h"
#include "components/safe_browsing/core/features.h"
#include "components/safe_browsing/core/realtime/policy_engine.h"
#include "components/safe_browsing/core/realtime/url_lookup_service.h"
#include "components/security_interstitials/content/insecure_form_navigation_throttle.h"
#include "components/security_interstitials/content/origin_policy_ui.h"
#include "components/security_interstitials/content/ssl_cert_reporter.h"
#include "components/security_interstitials/content/ssl_error_handler.h"
#include "components/security_interstitials/content/ssl_error_navigation_throttle.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/site_isolation/pref_names.h"
#include "components/site_isolation/preloaded_isolated_origins.h"
#include "components/site_isolation/site_isolation_policy.h"
#include "components/subresource_filter/content/browser/content_subresource_filter_throttle_manager.h"
#include "components/translate/core/common/translate_switches.h"
#include "components/ukm/content/source_url_recorder.h"
#include "components/url_formatter/url_fixer.h"
#include "components/variations/variations_associated_data.h"
#include "components/variations/variations_ids_provider.h"
#include "components/variations/variations_switches.h"
#include "components/version_info/version_info.h"
#include "components/viz/common/features.h"
#include "components/viz/common/viz_utils.h"
#include "content/public/browser/browser_child_process_host.h"
#include "content/public/browser/browser_main_parts.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/browsing_data_remover.h"
#include "content/public/browser/certificate_request_result_type.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/client_certificate_delegate.h"
#include "content/public/browser/file_url_loader.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/navigation_throttle.h"
#include "content/public/browser/non_network_url_loader_factory_base.h"
#include "content/public/browser/overlay_window.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/resource_context.h"
#include "content/public/browser/site_isolation_policy.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/tts_controller.h"
#include "content/public/browser/tts_platform.h"
#include "content/public/browser/url_loader_request_interceptor.h"
#include "content/public/browser/vpn_service_proxy.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_ui_url_loader_factory.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/content_descriptors.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/navigation_policy.h"
#include "content/public/common/network_service_util.h"
#include "content/public/common/service_names.mojom.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
#include "content/public/common/user_agent.h"
#include "content/public/common/window_container_type.mojom-shared.h"
#include "device/vr/buildflags/buildflags.h"
#include "extensions/browser/process_map.h"
#include "extensions/buildflags/buildflags.h"
#include "google_apis/gaia/gaia_urls.h"
#include "google_apis/google_api_keys.h"
#include "gpu/config/gpu_switches.h"
#include "ipc/ipc_message.h"
#include "media/audio/audio_manager.h"
#include "media/base/media_switches.h"
#include "media/media_buildflags.h"
#include "media/mojo/buildflags.h"
#include "media/webrtc/webrtc_switches.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h"
#include "net/base/load_flags.h"
#include "net/base/mime_util.h"
#include "net/http/http_util.h"
#include "net/ssl/client_cert_store.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "pdf/buildflags.h"
#include "ppapi/buildflags/buildflags.h"
#include "ppapi/host/ppapi_host.h"
#include "printing/buildflags/buildflags.h"
#include "sandbox/policy/features.h"
#include "sandbox/policy/sandbox_type.h"
#include "sandbox/policy/switches.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/is_potentially_trustworthy.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/strings/grit/services_strings.h"
#include "storage/browser/file_system/external_mount_points.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/loader/referrer_utils.h"
#include "third_party/blink/public/common/loader/url_loader_throttle.h"
#include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
#include "third_party/blink/public/common/switches.h"
#include "third_party/blink/public/mojom/site_engagement/site_engagement.mojom.h"
#include "third_party/blink/public/mojom/user_agent/user_agent_metadata.mojom.h"
#include "third_party/blink/public/mojom/webpreferences/web_preferences.mojom.h"
#include "third_party/blink/public/public_buildflags.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/widevine/cdm/buildflags.h"
#include "ui/base/clipboard/clipboard_format_type.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_features.h"
#include "ui/display/display.h"
#include "ui/gfx/color_utils.h"
#include "ui/native_theme/native_theme.h"
#include "ui/resources/grit/ui_resources.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/third_party/mozilla/url_parse.h"
#include "url/url_constants.h"
#if defined(OS_WIN)
#include "base/strings/string_tokenizer.h"
#include "base/win/win_util.h"
#include "base/win/windows_version.h"
#include "chrome/browser/chrome_browser_main_win.h"
#include "chrome/install_static/install_util.h"
#include "sandbox/win/src/sandbox_policy.h"
#elif defined(OS_MAC)
#include "chrome/browser/apps/intent_helper/mac_apps_navigation_throttle.h"
#include "chrome/browser/chrome_browser_main_mac.h"
#include "components/soda/constants.h"
#include "sandbox/mac/seatbelt_exec.h"
#include "sandbox/policy/mac/sandbox_mac.h"
#elif defined(OS_CHROMEOS)
#include "ash/public/cpp/ash_pref_names.h"
#include "ash/public/cpp/tablet_mode.h"
#include "chrome/app/chrome_crash_reporter_client.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/arc/fileapi/arc_content_file_system_backend_delegate.h"
#include "chrome/browser/chromeos/arc/fileapi/arc_documents_provider_backend_delegate.h"
#include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
#include "chrome/browser/chromeos/chrome_content_browser_client_chromeos_part.h"
#include "chrome/browser/chromeos/drive/fileapi/drivefs_file_system_backend_delegate.h"
#include "chrome/browser/chromeos/file_manager/app_id.h"
#include "chrome/browser/chromeos/file_system_provider/fileapi/backend_delegate.h"
#include "chrome/browser/chromeos/fileapi/external_file_url_loader_factory.h"
#include "chrome/browser/chromeos/fileapi/file_system_backend.h"
#include "chrome/browser/chromeos/fileapi/mtp_file_system_backend_delegate.h"
#include "chrome/browser/chromeos/login/signin/merge_session_navigation_throttle.h"
#include "chrome/browser/chromeos/login/signin/merge_session_throttling_utils.h"
#include "chrome/browser/chromeos/login/signin_partition_manager.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/policy_cert_service_factory.h"
#include "chrome/browser/chromeos/policy/system_features_disable_list_policy_handler.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/smb_client/fileapi/smbfs_file_system_backend_delegate.h"
#include "chrome/browser/chromeos/system/input_device_settings.h"
#include "chrome/browser/speech/tts_chromeos.h"
#include "chrome/browser/ui/ash/chrome_browser_main_extra_parts_ash.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chromeos/components/scanning/url_constants.h"
#include "chromeos/constants/chromeos_constants.h"
#include "chromeos/constants/chromeos_features.h"
#include "chromeos/constants/chromeos_switches.h"
#include "components/crash/core/app/breakpad_linux.h"
#include "components/policy/core/common/policy_pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "services/service_manager/public/mojom/interface_provider_spec.mojom.h"
#elif defined(OS_LINUX)
#include "chrome/browser/chrome_browser_main_linux.h"
#elif defined(OS_ANDROID)
#include "base/android/application_status_listener.h"
#include "base/feature_list.h"
#include "chrome/android/features/dev_ui/buildflags.h"
#include "chrome/android/modules/extra_icu/provider/module_provider.h"
#include "chrome/browser/android/customtabs/client_data_header_web_contents_observer.h"
#include "chrome/browser/android/devtools_manager_delegate_android.h"
#include "chrome/browser/android/ntp/new_tab_page_url_handler.h"
#include "chrome/browser/android/service_tab_launcher.h"
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/android/tab_web_contents_delegate_android.h"
#include "chrome/browser/chrome_browser_main_android.h"
#include "chrome/browser/download/android/available_offline_content_provider.h"
#include "chrome/browser/download/android/intercept_oma_download_navigation_throttle.h"
#include "chrome/browser/flags/android/chrome_feature_list.h"
#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
#include "chrome/common/chrome_descriptors.h"
#include "components/crash/content/browser/child_exit_observer_android.h"
#include "components/crash/content/browser/crash_memory_metrics_collector_android.h"
#include "components/navigation_interception/intercept_navigation_delegate.h"
#include "content/public/browser/android/java_interfaces.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "ui/base/resource/resource_bundle_android.h"
#include "ui/base/ui_base_paths.h"
#if BUILDFLAG(DFMIFY_DEV_UI)
#include "chrome/browser/dev_ui/android/dev_ui_loader_throttle.h"
#endif // BUILDFLAG(DFMIFY_DEV_UI)
#elif defined(OS_POSIX)
#include "chrome/browser/chrome_browser_main_posix.h"
#endif
#if !defined(OS_CHROMEOS)
#include "ui/accessibility/accessibility_features.h"
#endif // !defined(OS_CHROMEOS)
#if !defined(OS_ANDROID)
#include "chrome/browser/badging/badge_manager.h"
#include "chrome/browser/devtools/chrome_devtools_manager_delegate.h"
#include "chrome/browser/devtools/devtools_window.h"
#include "chrome/browser/media/unified_autoplay_config.h"
#include "chrome/browser/policy/dm_token_utils.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/browser/search/instant_service_factory.h"
#include "chrome/browser/serial/chrome_serial_delegate.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/search/new_tab_page_navigation_throttle.h"
#include "chrome/browser/webauthn/authenticator_request_scheduler.h"
#include "chrome/browser/webauthn/chrome_authenticator_request_delegate.h"
#include "chrome/common/importer/profile_import.mojom.h"
#include "chrome/grit/chrome_unscaled_resources.h" // nogncheck crbug.com/1125897
#endif // !defined(OS_ANDROID)
#if defined(OS_WIN) || defined(OS_MAC) || \
(defined(OS_LINUX) && !defined(OS_CHROMEOS))
#include "chrome/browser/browser_switcher/browser_switcher_navigation_throttle.h"
#endif
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
#include "components/crash/core/app/crash_switches.h"
#include "components/crash/core/app/crashpad.h"
#endif
#if defined(OS_POSIX) && !defined(OS_MAC)
#if !defined(OS_ANDROID)
#include "base/debug/leak_annotations.h"
#include "components/crash/core/app/breakpad_linux.h"
#endif // !defined(OS_ANDROID)
#include "components/crash/content/browser/crash_handler_host_linux.h"
#endif
// TODO(crbug.com/939205): Once the upcoming App Service is available, use a
// single navigation throttle to display the intent picker on all platforms.
#if !defined(OS_ANDROID)
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/apps/intent_helper/chromeos_apps_navigation_throttle.h"
#include "chrome/browser/chromeos/apps/intent_helper/common_apps_navigation_throttle.h"
#else
#include "chrome/browser/apps/intent_helper/apps_navigation_throttle.h"
#endif
#endif
#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
#endif
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
#include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views_linux.h"
#endif
#if defined(USE_OZONE)
#include "ui/ozone/public/ozone_platform.h"
#endif
#if defined(USE_X11) || defined(USE_OZONE)
#include "chrome/browser/chrome_browser_main_extra_parts_ozone.h"
#endif
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
#include "components/captive_portal/content/captive_portal_tab_helper.h"
#include "components/captive_portal/content/captive_portal_url_loader_throttle.h"
#endif
#if BUILDFLAG(ENABLE_NACL)
#include "components/nacl/browser/nacl_browser.h"
#include "components/nacl/browser/nacl_host_message_filter.h"
#include "components/nacl/browser/nacl_process_host.h"
#include "components/nacl/common/nacl_process_type.h"
#include "components/nacl/common/nacl_switches.h"
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/accessibility/animation_policy_prefs.h"
#include "chrome/browser/apps/platform_apps/platform_app_navigation_redirector.h"
#include "chrome/browser/extensions/chrome_content_browser_client_extensions_part.h"
#include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/user_script_listener.h"
#include "chrome/browser/speech/extension_api/tts_engine_extension_api.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/web_applications/app_browser_controller.h"
#include "components/guest_view/browser/guest_view_base.h"
#include "components/guest_view/browser/guest_view_manager.h"
#include "extensions/browser/api/web_request/web_request_api.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_navigation_throttle.h"
#include "extensions/browser/extension_protocols.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#include "extensions/browser/guest_view/web_view/web_view_permission_helper.h"
#include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
#include "extensions/browser/process_manager.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/manifest_handlers/background_info.h"
#include "extensions/common/manifest_handlers/shared_module_info.h"
#include "extensions/common/manifest_handlers/web_accessible_resources_info.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/permissions/socket_permission.h"
#include "extensions/common/switches.h"
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
#if BUILDFLAG(ENABLE_PLUGINS)
#include "chrome/browser/plugins/chrome_content_browser_client_plugins_part.h"
#include "chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h"
#endif
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
#include "chrome/browser/supervised_user/supervised_user_google_auth_navigation_throttle.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/app_mode/kiosk_settings_navigation_throttle.h"
#include "chrome/browser/chromeos/child_accounts/time_limits/web_time_limit_navigation_throttle.h"
#include "chrome/browser/speech/tts_controller_delegate_impl.h"
#endif // defined(OS_CHROMEOS)
#if BUILDFLAG(ENABLE_MEDIA_REMOTING)
#include "chrome/browser/media/cast_remoting_connector.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "chrome/browser/printing/printing_message_filter.h"
#endif
#if BUILDFLAG(ENABLE_LIBRARY_CDMS)
#include "chrome/browser/media/output_protection_impl.h"
#if defined(OS_WIN) && BUILDFLAG(ENABLE_WIDEVINE)
#include "chrome/browser/media/widevine_hardware_caps_win.h"
#include "third_party/widevine/cdm/widevine_cdm_common.h"
#endif
#endif
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
#include "chrome/browser/supervised_user/supervised_user_navigation_throttle.h"
#endif
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
#include "chrome/browser/safe_browsing/chrome_password_protection_service.h"
#include "chrome/browser/safe_browsing/client_side_detection_service_factory.h"
#endif
#if BUILDFLAG(SAFE_BROWSING_DB_LOCAL)
#include "chrome/browser/safe_browsing/chrome_enterprise_url_lookup_service.h" // nogncheck crbug.com/1125897
#include "chrome/browser/safe_browsing/chrome_enterprise_url_lookup_service_factory.h" // nogncheck crbug.com/1125897
#endif
#if BUILDFLAG(ENABLE_OFFLINE_PAGES)
#include "chrome/browser/offline_pages/offline_page_tab_helper.h"
#include "chrome/browser/offline_pages/offline_page_url_loader_request_interceptor.h"
#endif
#if BUILDFLAG(ENABLE_VR) && !defined(OS_ANDROID)
#include "device/vr/public/mojom/isolated_xr_service.mojom.h" // nogncheck crbug.com/1125897
#endif
#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP)
#include "chrome/browser/ui/webui/tab_strip/chrome_content_browser_client_tab_strip_part.h"
#endif
#if BUILDFLAG(FULL_SAFE_BROWSING)
#include "chrome/browser/enterprise/connectors/content_analysis_delegate.h"
#endif
#if BUILDFLAG(ENABLE_VR)
#include "chrome/browser/vr/chrome_xr_integration_client.h"
#endif
#if BUILDFLAG(IS_LACROS)
#include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views_lacros.h"
#include "chromeos/lacros/lacros_chrome_service_impl.h"
#endif
#if BUILDFLAG(USE_MINIKIN_HYPHENATION) && !defined(OS_ANDROID)
#include "chrome/browser/component_updater/hyphenation_component_installer.h"
#endif
using base::FileDescriptor;
using blink::web_pref::WebPreferences;
using content::BrowserThread;
using content::BrowserURLHandler;
using content::BrowsingDataFilterBuilder;
using content::ChildProcessSecurityPolicy;
using content::QuotaPermissionContext;
using content::RenderFrameHost;
using content::RenderViewHost;
using content::SiteInstance;
using content::WebContents;
using message_center::NotifierId;
#if defined(OS_POSIX)
using content::PosixFileDescriptorInfo;
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
using extensions::APIPermission;
using extensions::ChromeContentBrowserClientExtensionsPart;
using extensions::Extension;
using extensions::Manifest;
#endif
#if BUILDFLAG(ENABLE_PLUGINS)
using plugins::ChromeContentBrowserClientPluginsPart;
#endif
namespace {
#if defined(OS_WIN) && !defined(COMPONENT_BUILD) && !defined(ADDRESS_SANITIZER)
// Enables pre-launch Code Integrity Guard (CIG) for Chrome renderers, when
// running on Windows 10 1511 and above. See
// https://blogs.windows.com/blog/tag/code-integrity-guard/.
const base::Feature kRendererCodeIntegrity{"RendererCodeIntegrity",
base::FEATURE_ENABLED_BY_DEFAULT};
#endif // defined(OS_WIN) && !defined(COMPONENT_BUILD) &&
// !defined(ADDRESS_SANITIZER)
// Wrapper for SSLErrorHandler::HandleSSLError() that supplies //chrome-level
// parameters.
void HandleSSLErrorWrapper(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
std::unique_ptr<SSLCertReporter> ssl_cert_reporter,
SSLErrorHandler::BlockingPageReadyCallback blocking_page_ready_callback) {
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
// Profile should always outlive a WebContents
DCHECK(profile);
captive_portal::CaptivePortalService* captive_portal_service = nullptr;
#if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
captive_portal_service = CaptivePortalServiceFactory::GetForProfile(profile);
#endif
SSLErrorHandler::HandleSSLError(
web_contents, cert_error, ssl_info, request_url,
std::move(ssl_cert_reporter), std::move(blocking_page_ready_callback),
g_browser_process->network_time_tracker(), captive_portal_service,
std::make_unique<ChromeSecurityBlockingPageFactory>(),
profile->GetPrefs()->GetBoolean(prefs::kSSLErrorOverrideAllowed));
}
enum AppLoadedInTabSource {
// A platform app page tried to load one of its own URLs in a tab.
APP_LOADED_IN_TAB_SOURCE_APP = 0,
// A platform app background page tried to load one of its own URLs in a tab.
APP_LOADED_IN_TAB_SOURCE_BACKGROUND_PAGE,
// An extension or app tried to load a resource of a different platform app in
// a tab.
APP_LOADED_IN_TAB_SOURCE_OTHER_EXTENSION,
// A non-app and non-extension page tried to load a platform app in a tab.
APP_LOADED_IN_TAB_SOURCE_OTHER,
APP_LOADED_IN_TAB_SOURCE_MAX
};
// Cached version of the locale so we can return the locale on the I/O
// thread.
std::string& GetIOThreadApplicationLocale() {
static base::NoDestructor<std::string> s;
return *s;
}
// Returns a copy of the given url with its host set to given host and path set
// to given path. Other parts of the url will be the same.
GURL ReplaceURLHostAndPath(const GURL& url,
const std::string& host,
const std::string& path) {
url::Replacements<char> replacements;
replacements.SetHost(host.c_str(), url::Component(0, host.length()));
replacements.SetPath(path.c_str(), url::Component(0, path.length()));
return url.ReplaceComponents(replacements);
}
// Handles the rewriting of the new tab page URL based on group policy.
bool HandleNewTabPageLocationOverride(
GURL* url,
content::BrowserContext* browser_context) {
if (!url->SchemeIs(content::kChromeUIScheme) ||
url->host() != chrome::kChromeUINewTabHost)
return false;
Profile* profile = Profile::FromBrowserContext(browser_context);
std::string ntp_location =
profile->GetPrefs()->GetString(prefs::kNewTabPageLocationOverride);
if (ntp_location.empty())
return false;
url::Component scheme;
if (!url::ExtractScheme(ntp_location.data(),
static_cast<int>(ntp_location.length()), &scheme)) {
ntp_location = base::StrCat(
{url::kHttpsScheme, url::kStandardSchemeSeparator, ntp_location});
}
*url = GURL(ntp_location);
return true;
}
#if !defined(OS_ANDROID)
// Check if the current url is whitelisted based on a list of whitelisted urls.
bool IsURLWhitelisted(const GURL& current_url,
base::Value::ConstListView whitelisted_urls) {
// Only check on HTTP and HTTPS pages.
if (!current_url.SchemeIsHTTPOrHTTPS())
return false;
for (auto const& value : whitelisted_urls) {
ContentSettingsPattern pattern =
ContentSettingsPattern::FromString(value.GetString());
if (pattern == ContentSettingsPattern::Wildcard() || !pattern.IsValid())
continue;
if (pattern.Matches(current_url))
return true;
}
return false;
}
// Check if autoplay is allowed by policy configuration.
bool IsAutoplayAllowedByPolicy(content::WebContents* contents,
PrefService* prefs) {
DCHECK(prefs);
// Check if we have globally allowed autoplay by policy.
if (prefs->GetBoolean(prefs::kAutoplayAllowed) &&
prefs->IsManagedPreference(prefs::kAutoplayAllowed)) {
return true;
}
if (!contents)
return false;
// Check if the current URL matches a URL pattern on the whitelist.
const base::ListValue* autoplay_whitelist =
prefs->GetList(prefs::kAutoplayWhitelist);
return autoplay_whitelist &&
prefs->IsManagedPreference(prefs::kAutoplayWhitelist) &&
IsURLWhitelisted(contents->GetURL(), autoplay_whitelist->GetList());
}
#endif
#if defined(OS_ANDROID)
int GetCrashSignalFD(const base::CommandLine& command_line) {
return crashpad::CrashHandlerHost::Get()->GetDeathSignalSocket();
}
#elif defined(OS_POSIX) && !defined(OS_MAC)
breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
const std::string& process_type) {
base::FilePath dumps_path;
base::PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path);
{
ANNOTATE_SCOPED_MEMORY_LEAK;
bool upload = !getenv(env_vars::kHeadless);
breakpad::CrashHandlerHostLinux* crash_handler =
new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
crash_handler->StartUploaderThread();
return crash_handler;
}
}
int GetCrashSignalFD(const base::CommandLine& command_line) {
if (crash_reporter::IsCrashpadEnabled()) {
int fd;
pid_t pid;
return crash_reporter::GetHandlerSocket(&fd, &pid) ? fd : -1;
}
// Extensions have the same process type as renderers.
if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
if (!crash_handler)
crash_handler = CreateCrashHandlerHost("extension");
return crash_handler->GetDeathSignalSocket();
}
std::string process_type =
command_line.GetSwitchValueASCII(switches::kProcessType);
if (process_type == switches::kRendererProcess) {
static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
if (!crash_handler)
crash_handler = CreateCrashHandlerHost(process_type);
return crash_handler->GetDeathSignalSocket();
}
if (process_type == switches::kPpapiPluginProcess) {
static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
if (!crash_handler)
crash_handler = CreateCrashHandlerHost(process_type);
return crash_handler->GetDeathSignalSocket();
}
if (process_type == switches::kGpuProcess) {
static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
if (!crash_handler)
crash_handler = CreateCrashHandlerHost(process_type);
return crash_handler->GetDeathSignalSocket();
}
if (process_type == switches::kUtilityProcess) {
static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
if (!crash_handler)
crash_handler = CreateCrashHandlerHost(process_type);
return crash_handler->GetDeathSignalSocket();
}
return -1;
}
#endif // defined(OS_ANDROID)
void SetApplicationLocaleOnIOThread(const std::string& locale) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
GetIOThreadApplicationLocale() = locale;
}
// An implementation of the SSLCertReporter interface used by
// SSLErrorHandler. Uses CertificateReportingService to send reports. The
// service handles queueing and re-sending of failed reports. Each certificate
// error creates a new instance of this class.
class CertificateReportingServiceCertReporter : public SSLCertReporter {
public:
explicit CertificateReportingServiceCertReporter(
content::WebContents* web_contents)
: service_(CertificateReportingServiceFactory::GetForBrowserContext(
web_contents->GetBrowserContext())) {}
~CertificateReportingServiceCertReporter() override {}
// SSLCertReporter implementation
void ReportInvalidCertificateChain(
const std::string& serialized_report) override {
service_->Send(serialized_report);
}
private:
CertificateReportingService* service_;
DISALLOW_COPY_AND_ASSIGN(CertificateReportingServiceCertReporter);
};
#if BUILDFLAG(ENABLE_EXTENSIONS)
AppLoadedInTabSource ClassifyAppLoadedInTabSource(
const GURL& opener_url,
const extensions::Extension* target_platform_app) {
if (!opener_url.SchemeIs(extensions::kExtensionScheme)) {
// The forbidden app URL was being opened by a non-extension page (e.g.
// http).
return APP_LOADED_IN_TAB_SOURCE_OTHER;
}
if (opener_url.host_piece() != target_platform_app->id()) {
// The forbidden app URL was being opened by a different app or extension.
return APP_LOADED_IN_TAB_SOURCE_OTHER_EXTENSION;
}
// This platform app was trying to window.open() one of its own URLs.
if (opener_url ==
extensions::BackgroundInfo::GetBackgroundURL(target_platform_app)) {
// Source was the background page.
return APP_LOADED_IN_TAB_SOURCE_BACKGROUND_PAGE;
}
// Source was a different page inside the app.
return APP_LOADED_IN_TAB_SOURCE_APP;
}
// Returns true if there is is an extension matching |url| in
// |opener_render_process_id| with APIPermission::kBackground.
//
// Note that GetExtensionOrAppByURL requires a full URL in order to match with a
// hosted app, even though normal extensions just use the host.
bool URLHasExtensionBackgroundPermission(
extensions::ProcessMap* process_map,
extensions::ExtensionRegistry* registry,
const GURL& url,
int opener_render_process_id) {
// Note: includes web URLs that are part of an extension's web extent.
const Extension* extension =
registry->enabled_extensions().GetExtensionOrAppByURL(url);
return extension &&
extension->permissions_data()->HasAPIPermission(
APIPermission::kBackground) &&
process_map->Contains(extension->id(), opener_render_process_id);
}
#endif
mojo::PendingRemote<prerender::mojom::PrerenderCanceler> GetPrerenderCanceler(
base::OnceCallback<content::WebContents*()> wc_getter) {
mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler;
prerender::ChromePrerenderContentsDelegate::FromWebContents(
std::move(wc_getter).Run())
->AddPrerenderCancelerReceiver(canceler.InitWithNewPipeAndPassReceiver());
return canceler;
}
// Encapculates logic to determine if enterprise policies should be honored.
// This is a copy of the code in policy_loader_win.cc but it's ok to duplicate
// as a new central class to replace those checks is in the making.
bool ShouldHonorPolicies() {
#if defined(OS_WIN)
bool is_enterprise_version =
base::win::OSInfo::GetInstance()->version_type() != base::win::SUITE_HOME;
return base::win::IsEnrolledToDomain() ||
(base::win::IsDeviceRegisteredWithManagement() &&
is_enterprise_version);
#else // defined(OS_WIN)
// TODO(pastarmovj): Replace this with check for MacOS and the new management
// service once it is ready.
return true;
#endif // defined(OS_WIN)
}
void LaunchURL(const GURL& url,
content::WebContents::OnceGetter web_contents_getter,
ui::PageTransition page_transition,
bool has_user_gesture,
const base::Optional<url::Origin>& initiating_origin) {
// If there is no longer a WebContents, the request may have raced with tab
// closing. Don't fire the external request. (It may have been a prerender.)
content::WebContents* web_contents = std::move(web_contents_getter).Run();
if (!web_contents)
return;
// Do not launch external requests attached to unswapped prerenders.
prerender::PrerenderContents* prerender_contents =
prerender::ChromePrerenderContentsDelegate::FromWebContents(web_contents);
if (prerender_contents) {
prerender_contents->Destroy(prerender::FINAL_STATUS_UNSUPPORTED_SCHEME);
return;
}
// Do not launch external requests for schemes that have a handler registered.
ProtocolHandlerRegistry* protocol_handler_registry =
ProtocolHandlerRegistryFactory::GetForBrowserContext(
web_contents->GetBrowserContext());
if (protocol_handler_registry &&
protocol_handler_registry->IsHandledProtocol(url.scheme()))
return;
bool is_whitelisted = false;
PolicyBlocklistService* service =
PolicyBlocklistFactory::GetForBrowserContext(
web_contents->GetBrowserContext());
if (ShouldHonorPolicies() && service) {
const policy::URLBlocklist::URLBlocklistState url_state =
service->GetURLBlocklistState(url);
is_whitelisted =
url_state == policy::URLBlocklist::URLBlocklistState::URL_IN_ALLOWLIST;
}
// If the URL is in whitelist, we launch it without asking the user and
// without any additional security checks. Since the URL is whitelisted,
// we assume it can be executed.
if (is_whitelisted) {
ExternalProtocolHandler::LaunchUrlWithoutSecurityCheck(url, web_contents);
} else {
ExternalProtocolHandler::LaunchUrl(
url, web_contents->GetRenderViewHost()->GetProcess()->GetID(),
web_contents->GetRenderViewHost()->GetRoutingID(), page_transition,
has_user_gesture, initiating_origin);
}
}
std::string GetProduct() {
return version_info::GetProductNameAndVersionForUserAgent();
}
void MaybeAppendSecureOriginsAllowlistSwitch(base::CommandLine* cmdline) {
// |allowlist| combines pref/policy + cmdline switch in the browser process.
// For renderer and utility (e.g. NetworkService) processes the switch is the
// only available source, so below the combined (pref/policy + cmdline)
// allowlist of secure origins is injected into |cmdline| for these other
// processes.
std::vector<std::string> allowlist =
network::SecureOriginAllowlist::GetInstance().GetCurrentAllowlist();
if (!allowlist.empty()) {
cmdline->AppendSwitchASCII(
network::switches::kUnsafelyTreatInsecureOriginAsSecure,
base::JoinString(allowlist, ","));
}
}
#if defined(OS_WIN) && !defined(COMPONENT_BUILD) && !defined(ADDRESS_SANITIZER)
// Returns the full path to |module_name|. Both dev builds (where |module_name|
// is in the current executable's directory) and proper installs (where
// |module_name| is in a versioned sub-directory of the current executable's
// directory) are supported. The identified file is not guaranteed to exist.
base::FilePath GetModulePath(base::StringPiece16 module_name) {
base::FilePath exe_dir;
const bool has_path = base::PathService::Get(base::DIR_EXE, &exe_dir);
DCHECK(has_path);
// Look for the module in a versioned sub-directory of the current
// executable's directory and return the path if it can be read. This is the
// expected location of modules for proper installs.
const base::FilePath module_path =
exe_dir.AppendASCII(chrome::kChromeVersion).Append(module_name);
if (base::PathExists(module_path))
return module_path;
// Otherwise, return the path to the module in the current executable's
// directory. This is the expected location of modules for dev builds.
return exe_dir.Append(module_name);
}
#endif // defined(OS_WIN) && !defined(COMPONENT_BUILD) &&
// !defined(ADDRESS_SANITIZER)
void MaybeAddThrottle(
std::unique_ptr<content::NavigationThrottle> maybe_throttle,
std::vector<std::unique_ptr<content::NavigationThrottle>>* throttles) {
if (maybe_throttle)
throttles->push_back(std::move(maybe_throttle));
}
void MaybeAddThrottles(
std::vector<std::unique_ptr<content::NavigationThrottle>> additional,
std::vector<std::unique_ptr<content::NavigationThrottle>>* combined) {
combined->insert(combined->end(), std::make_move_iterator(additional.begin()),
std::make_move_iterator(additional.end()));
}
// Returns whether |web_contents| is within a hosted app.
bool IsInHostedApp(WebContents* web_contents) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
return (browser &&
web_app::AppBrowserController::IsForWebAppBrowser(browser));
#else
return false;
#endif
}
void MaybeRecordSameSiteCookieEngagementHistogram(
content::RenderFrameHost* render_frame_host,
blink::mojom::WebFeature feature) {
if (feature != blink::mojom::WebFeature::kCookieNoSameSite &&
feature != blink::mojom::WebFeature::kCookieInsecureAndSameSiteNone) {
return;
}
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(render_frame_host);
content::BrowserContext* browser_context =
WebContents::FromRenderFrameHost(render_frame_host)->GetBrowserContext();
Profile* profile = Profile::FromBrowserContext(browser_context);
SiteEngagementService* site_engagement_service =
SiteEngagementService::Get(profile);
if (!site_engagement_service)
return;
blink::mojom::EngagementLevel engagement_level =
site_engagement_service->GetEngagementLevel(
render_frame_host->GetLastCommittedURL());
if (feature == blink::mojom::WebFeature::kCookieNoSameSite) {
UMA_HISTOGRAM_ENUMERATION(
"Net.SameSiteBlockedCookieSiteEngagement.CookieNoSameSite",
engagement_level);
} else {
UMA_HISTOGRAM_ENUMERATION(
"Net.SameSiteBlockedCookieSiteEngagement."
"CookieInsecureAndSameSiteNone",
engagement_level);
}
}
bool IsErrorPageAutoReloadEnabled() {
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableAutomation))
return false;
if (command_line.HasSwitch(switches::kEnableAutoReload))
return true;
if (command_line.HasSwitch(switches::kDisableAutoReload))
return false;
return true;
}
} // namespace
// Generate a pseudo-random permutation of the following brand/version pairs:
// 1. The base project (i.e. Chromium)
// 2. The browser brand, if available
// 3. A randomized string containing escaped characters to ensure proper
// header parsing, along with an arbitrarily low version to ensure proper
// version checking.
blink::UserAgentBrandList GenerateBrandVersionList(
int seed,
base::Optional<std::string> brand,
std::string major_version) {
DCHECK_GE(seed, 0);
const int npermutations = 6; // 3!
int permutation = seed % npermutations;
// Pick a stable permutation seeded by major version number. any values here
// and in order should be under three.
const std::vector<std::vector<int>> orders{{0, 1, 2}, {0, 2, 1}, {1, 0, 2},
{1, 2, 0}, {2, 0, 1}, {2, 1, 0}};
const std::vector<int> order = orders[permutation];
DCHECK_EQ(6u, orders.size());
DCHECK_EQ(3u, order.size());
const std::vector<std::string> escaped_chars = {"\\", "\"", ";"};
std::string greasey_brand =
base::StrCat({escaped_chars[order[0]], "Not", escaped_chars[order[1]],
"A", escaped_chars[order[2]], "Brand"});
blink::UserAgentBrandVersion greasey_bv = {greasey_brand, "99"};
blink::UserAgentBrandVersion chromium_bv = {"Chromium", major_version};
blink::UserAgentBrandList greased_brand_version_list(3);
if (brand) {
blink::UserAgentBrandVersion brand_bv = {brand.value(), major_version};
greased_brand_version_list[order[0]] = greasey_bv;
greased_brand_version_list[order[1]] = chromium_bv;
greased_brand_version_list[order[2]] = brand_bv;
} else {
greased_brand_version_list[seed % 2] = greasey_bv;
greased_brand_version_list[(seed + 1) % 2] = chromium_bv;
// If left, the last element would make a blank "" at the end of the header.
greased_brand_version_list.pop_back();
}
return greased_brand_version_list;
}
const blink::UserAgentBrandList& GetBrandVersionList() {
static const base::NoDestructor<blink::UserAgentBrandList>
greased_brand_version_list([] {
int major_version_number;
std::string major_version = version_info::GetMajorVersionNumber();
base::StringToInt(major_version, &major_version_number);
base::Optional<std::string> brand;
#if !BUILDFLAG(CHROMIUM_BRANDING)
brand = version_info::GetProductName();
#endif
return GenerateBrandVersionList(major_version_number, brand,
major_version);
}());
return *greased_brand_version_list;
}
std::string GetUserAgent() {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kUserAgent)) {
std::string ua = command_line->GetSwitchValueASCII(switches::kUserAgent);
if (net::HttpUtil::IsValidHeaderValue(ua))
return ua;
LOG(WARNING) << "Ignored invalid value for flag --" << switches::kUserAgent;
}
if (base::FeatureList::IsEnabled(blink::features::kFreezeUserAgent)) {
return content::GetFrozenUserAgent(
command_line->HasSwitch(switches::kUseMobileUserAgent),
version_info::GetMajorVersionNumber());
}
std::string product = GetProduct();
#if defined(OS_ANDROID)
if (command_line->HasSwitch(switches::kUseMobileUserAgent))
product += " Mobile";
#endif
return content::BuildUserAgentFromProduct(product);
}
blink::UserAgentMetadata GetUserAgentMetadata() {
blink::UserAgentMetadata metadata;
metadata.brand_version_list = GetBrandVersionList();
metadata.full_version = version_info::GetVersionNumber();
metadata.platform = version_info::GetOSType();
metadata.platform_version =
content::GetOSVersion(content::IncludeAndroidBuildNumber::Exclude,
content::IncludeAndroidModel::Exclude);
metadata.architecture = content::GetLowEntropyCpuArchitecture();
metadata.model = content::BuildModelInfo();
metadata.mobile = false;
#if defined(OS_ANDROID)
metadata.mobile = base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kUseMobileUserAgent);
#endif
return metadata;
}
ChromeContentBrowserClient::ChromeContentBrowserClient() {
#if BUILDFLAG(ENABLE_PLUGINS)
extra_parts_.push_back(new ChromeContentBrowserClientPluginsPart);
#endif
#if defined(OS_CHROMEOS)
extra_parts_.push_back(new ChromeContentBrowserClientChromeOsPart);
#endif // defined(OS_CHROMEOS)
#if BUILDFLAG(ENABLE_WEBUI_TAB_STRIP)
extra_parts_.push_back(new ChromeContentBrowserClientTabStripPart);
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
extra_parts_.push_back(new ChromeContentBrowserClientExtensionsPart);
#endif
extra_parts_.push_back(new ChromeContentBrowserClientPerformanceManagerPart);
}
ChromeContentBrowserClient::~ChromeContentBrowserClient() {
for (int i = static_cast<int>(extra_parts_.size()) - 1; i >= 0; --i)
delete extra_parts_[i];
extra_parts_.clear();
}
// static
void ChromeContentBrowserClient::RegisterLocalStatePrefs(
PrefRegistrySimple* registry) {
registry->RegisterFilePathPref(prefs::kDiskCacheDir, base::FilePath());
registry->RegisterIntegerPref(prefs::kDiskCacheSize, 0);
registry->RegisterStringPref(prefs::kIsolateOrigins, std::string());
registry->RegisterBooleanPref(prefs::kSitePerProcess, false);
registry->RegisterBooleanPref(prefs::kTabFreezingEnabled, true);
}
// static
void ChromeContentBrowserClient::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterBooleanPref(prefs::kDisable3DAPIs, false);
registry->RegisterBooleanPref(prefs::kEnableHyperlinkAuditing, true);
// Register user prefs for mapping SitePerProcess and IsolateOrigins in
// user policy in addition to the same named ones in Local State (which are
// used for mapping the command-line flags).
registry->RegisterStringPref(prefs::kIsolateOrigins, std::string());
registry->RegisterBooleanPref(prefs::kSitePerProcess, false);
registry->RegisterListPref(
site_isolation::prefs::kUserTriggeredIsolatedOrigins);
registry->RegisterDictionaryPref(
prefs::kDevToolsBackgroundServicesExpirationDict);
registry->RegisterBooleanPref(prefs::kSignedHTTPExchangeEnabled, true);
#if !defined(OS_ANDROID)
registry->RegisterBooleanPref(prefs::kAutoplayAllowed, false);
registry->RegisterListPref(prefs::kAutoplayWhitelist);
#endif
}
// static
void ChromeContentBrowserClient::SetApplicationLocale(
const std::string& locale) {
// The common case is that this function is called early in Chrome startup
// before any threads are created or registered. When there are no threads,
// we can just set the string without worrying about threadsafety.
if (!BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
GetIOThreadApplicationLocale() = locale;
return;
}
// Otherwise we're being called to change the locale. In this case set it on
// the IO thread.
DCHECK_CURRENTLY_ON(BrowserThread::UI);
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&SetApplicationLocaleOnIOThread, locale));
}
std::unique_ptr<content::BrowserMainParts>
ChromeContentBrowserClient::CreateBrowserMainParts(
const content::MainFunctionParams& parameters) {
std::unique_ptr<ChromeBrowserMainParts> main_parts;
// Construct the Main browser parts based on the OS type.
#if defined(OS_WIN)
main_parts =
std::make_unique<ChromeBrowserMainPartsWin>(parameters, &startup_data_);
#elif defined(OS_MAC)
main_parts =
std::make_unique<ChromeBrowserMainPartsMac>(parameters, &startup_data_);
#elif defined(OS_CHROMEOS)
main_parts = std::make_unique<chromeos::ChromeBrowserMainPartsChromeos>(
parameters, &startup_data_);
#elif defined(OS_LINUX)
main_parts =
std::make_unique<ChromeBrowserMainPartsLinux>(parameters, &startup_data_);
#elif defined(OS_ANDROID)
main_parts = std::make_unique<ChromeBrowserMainPartsAndroid>(parameters,
&startup_data_);
#elif defined(OS_POSIX)
main_parts =
std::make_unique<ChromeBrowserMainPartsPosix>(parameters, &startup_data_);
#else
NOTREACHED();
main_parts =
std::make_unique<ChromeBrowserMainParts>(parameters, &startup_data_);
#endif
bool add_profiles_extra_parts = true;
#if defined(OS_ANDROID)
if (startup_data_.HasBuiltProfilePrefService())
add_profiles_extra_parts = false;
#endif
if (add_profiles_extra_parts)
chrome::AddProfilesExtraParts(main_parts.get());
// Construct additional browser parts. Stages are called in the order in
// which they are added.
#if defined(TOOLKIT_VIEWS)
#if BUILDFLAG(IS_LACROS)
main_parts->AddParts(
std::make_unique<ChromeBrowserMainExtraPartsViewsLacros>());
#elif defined(OS_LINUX) && !defined(OS_CHROMEOS)
main_parts->AddParts(
std::make_unique<ChromeBrowserMainExtraPartsViewsLinux>());
#else
main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsViews>());
#endif
#endif
#if defined(OS_CHROMEOS)
// TODO(jamescook): Combine with ChromeBrowserMainPartsChromeos.
main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsAsh>());
#endif
#if defined(USE_X11) || defined(USE_OZONE)
main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsOzone>());
#endif
main_parts->AddParts(
std::make_unique<ChromeBrowserMainExtraPartsPerformanceManager>());
main_parts->AddParts(
std::make_unique<ChromeBrowserMainExtraPartsProfiling>());
main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsMemory>());
chrome::AddMetricsExtraParts(main_parts.get());
// Always add ChromeBrowserMainExtraPartsGpu last to make sure
// GpuDataManager initialization could pick up about:flags settings.
main_parts->AddParts(std::make_unique<ChromeBrowserMainExtraPartsGpu>());
return main_parts;
}
void ChromeContentBrowserClient::PostAfterStartupTask(
const base::Location& from_here,
const scoped_refptr<base::SequencedTaskRunner>& task_runner,
base::OnceClosure task) {
AfterStartupTaskUtils::PostTask(from_here, task_runner, std::move(task));
InitNetworkContextsParentDirectory();
DCHECK_CURRENTLY_ON(BrowserThread::UI);
safe_browsing_service_ = g_browser_process->safe_browsing_service();
}
bool ChromeContentBrowserClient::IsBrowserStartupComplete() {
return AfterStartupTaskUtils::IsBrowserStartupComplete();
}
void ChromeContentBrowserClient::SetBrowserStartupIsCompleteForTesting() {
AfterStartupTaskUtils::SetBrowserStartupIsCompleteForTesting();
}
bool ChromeContentBrowserClient::IsShuttingDown() {
return browser_shutdown::HasShutdownStarted();
}
std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
content::BrowserContext* browser_context,
const GURL& site) {
std::string partition_id;
// The partition ID for webview guest processes is the string value of its
// SiteInstance URL - "chrome-guest://app_id/persist?partition".
if (site.SchemeIs(content::kGuestScheme))
partition_id = site.spec();
#if BUILDFLAG(ENABLE_EXTENSIONS)
// The partition ID for extensions with isolated storage is treated similarly
// to the above.
else if (extensions::util::IsExtensionSiteWithIsolatedStorage(
site, browser_context))
partition_id = site.spec();
#endif
DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
return partition_id;
}
bool ChromeContentBrowserClient::IsValidStoragePartitionId(
content::BrowserContext* browser_context,
const std::string& partition_id) {
// The default ID is empty and is always valid.
if (partition_id.empty())
return true;
return GURL(partition_id).is_valid();
}
content::StoragePartitionConfig
ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
content::BrowserContext* browser_context,
const GURL& site) {
// Default to the browser-wide storage partition and override based on |site|
// below.
content::StoragePartitionConfig storage_partition_config =
content::StoragePartitionConfig::CreateDefault();
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (extensions::WebViewGuest::GetGuestPartitionConfigForSite(
site, &storage_partition_config)) {
return storage_partition_config;
}
if (site.SchemeIs(extensions::kExtensionScheme)) {
// The host in an extension site URL is the extension_id.
CHECK(site.has_host());
return extensions::util::GetStoragePartitionConfigForExtensionId(
site.host(), browser_context);
}
#endif
return storage_partition_config;
}
content::WebContentsViewDelegate*
ChromeContentBrowserClient::GetWebContentsViewDelegate(
content::WebContents* web_contents) {
if (auto* registry =
performance_manager::PerformanceManagerRegistry::GetInstance()) {
registry->MaybeCreatePageNodeForWebContents(web_contents);
}
return CreateWebContentsViewDelegate(web_contents);
}
bool ChromeContentBrowserClient::AllowGpuLaunchRetryOnIOThread() {
#if defined(OS_ANDROID)
const base::android::ApplicationState app_state =
base::android::ApplicationStatusListener::GetState();
return base::android::APPLICATION_STATE_UNKNOWN == app_state ||
base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES == app_state ||
base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES == app_state;
#else
return true;
#endif
}
void ChromeContentBrowserClient::RenderProcessWillLaunch(
content::RenderProcessHost* host) {
int id = host->GetID();
Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
#if BUILDFLAG(ENABLE_PRINTING)
host->AddFilter(new printing::PrintingMessageFilter(id, profile));
#endif
WebRtcLoggingController::AttachToRenderProcessHost(
host, g_browser_process->webrtc_log_uploader());
// The audio manager outlives the host, so it's safe to hand a raw pointer to
// it to the AudioDebugRecordingsHandler, which is owned by the host.
AudioDebugRecordingsHandler* audio_debug_recordings_handler =
new AudioDebugRecordingsHandler(profile);
host->SetUserData(
AudioDebugRecordingsHandler::kAudioDebugRecordingsHandlerKey,
std::make_unique<base::UserDataAdapter<AudioDebugRecordingsHandler>>(
audio_debug_recordings_handler));
#if BUILDFLAG(ENABLE_NACL)
host->AddFilter(new nacl::NaClHostMessageFilter(id, profile->IsOffTheRecord(),
profile->GetPath()));
#endif
#if defined(OS_ANDROID)
// Data cannot be persisted if the profile is off the record.
host->AddFilter(
new cdm::CdmMessageFilterAndroid(!profile->IsOffTheRecord(), false));
// Register CrashMemoryMetricsCollector to report oom related metrics.
host->SetUserData(
CrashMemoryMetricsCollector::kCrashMemoryMetricsCollectorKey,
std::make_unique<CrashMemoryMetricsCollector>(host));
#endif
Profile* original_profile = profile->GetOriginalProfile();
RendererUpdaterFactory::GetForProfile(original_profile)
->InitializeRenderer(host);
for (size_t i = 0; i < extra_parts_.size(); ++i)
extra_parts_[i]->RenderProcessWillLaunch(host);
}
GURL ChromeContentBrowserClient::GetEffectiveURL(
content::BrowserContext* browser_context,
const GURL& url) {
Profile* profile = Profile::FromBrowserContext(browser_context);
if (!profile)
return url;
#if !defined(OS_ANDROID)
// If the input |url| should be assigned to the Instant renderer, make its
// effective URL distinct from other URLs on the search provider's domain.
// This needs to happen even if |url| corresponds to an isolated origin; see
// https://crbug.com/755595.
if (search::ShouldAssignURLToInstantRenderer(url, profile))
return search::GetEffectiveURLForInstant(url, profile);
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
return ChromeContentBrowserClientExtensionsPart::GetEffectiveURL(profile,
url);
#else
return url;
#endif
}
bool ChromeContentBrowserClient::
ShouldCompareEffectiveURLsForSiteInstanceSelection(
content::BrowserContext* browser_context,
content::SiteInstance* candidate_site_instance,
bool is_main_frame,
const GURL& candidate_url,
const GURL& destination_url) {
DCHECK(browser_context);
DCHECK(candidate_site_instance);
#if BUILDFLAG(ENABLE_EXTENSIONS)
return ChromeContentBrowserClientExtensionsPart::
ShouldCompareEffectiveURLsForSiteInstanceSelection(
browser_context, candidate_site_instance, is_main_frame,
candidate_url, destination_url);
#else
return true;
#endif
}
bool ChromeContentBrowserClient::ShouldUseMobileFlingCurve() {
#if defined(OS_ANDROID)
return true;
#elif defined(OS_CHROMEOS)
return ash::TabletMode::Get() && ash::TabletMode::Get()->InTabletMode();
#else
return false;
#endif // defined(OS_ANDROID)
}
bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
content::BrowserContext* browser_context,
const GURL& site_url) {
Profile* profile = Profile::FromBrowserContext(browser_context);
if (!profile)
return false;
// NTP should use process-per-site. This is a performance optimization to
// reduce process count associated with NTP tabs.
if (site_url == GURL(chrome::kChromeUINewTabURL) ||
site_url == GURL(chrome::kChromeUINewTabPageURL)) {
return true;
}
// The web footer experiment should share its renderer to not effectively
// instantiate one per window. See https://crbug.com/993502.
if (site_url == GURL(chrome::kChromeUIWebFooterExperimentURL))
return true;
#if !defined(OS_ANDROID)
if (search::ShouldUseProcessPerSiteForInstantSiteURL(site_url, profile))
return true;
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (ChromeContentBrowserClientExtensionsPart::ShouldUseProcessPerSite(
profile, site_url))
return true;
#endif
// Non-extension, non-NTP URLs should generally use process-per-site-instance
// (rather than process-per-site).
return false;
}
bool ChromeContentBrowserClient::ShouldUseSpareRenderProcessHost(
content::BrowserContext* browser_context,
const GURL& site_url) {
Profile* profile = Profile::FromBrowserContext(browser_context);
if (!profile)
return false;
#if !defined(OS_ANDROID)
// Instant renderers should not use a spare process, because they require
// passing switches::kInstantProcess to the renderer process when it
// launches. A spare process is launched earlier, before it is known which
// navigation will use it, so it lacks this flag.
if (search::ShouldAssignURLToInstantRenderer(site_url, profile))
return false;
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
return ChromeContentBrowserClientExtensionsPart::
ShouldUseSpareRenderProcessHost(profile, site_url);
#else
return true;
#endif
}
bool ChromeContentBrowserClient::DoesSiteRequireDedicatedProcess(
content::BrowserContext* browser_context,
const GURL& effective_site_url) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (ChromeContentBrowserClientExtensionsPart::DoesSiteRequireDedicatedProcess(
browser_context, effective_site_url)) {
return true;
}
#endif
return false;
}
bool ChromeContentBrowserClient::ShouldLockProcessToSite(
content::BrowserContext* browser_context,
const GURL& effective_site_url) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (!ChromeContentBrowserClientExtensionsPart::ShouldLockProcessToSite(
browser_context, effective_site_url)) {
return false;
}
#endif
return true;
}
bool ChromeContentBrowserClient::DoesWebUISchemeRequireProcessLock(
base::StringPiece scheme) {
// Note: This method can be called from multiple threads. It is not safe to
// assume it runs only on the UI thread.
// chrome-search: documents commit only in the NTP instant process and are not
// locked to chrome-search: origin. Locking to chrome-search would kill
// processes upon legitimate requests for cookies from the search engine's
// domain.
if (scheme == chrome::kChromeSearchScheme)
return false;
// All other WebUIs must be locked to origin.
return true;
}
bool ChromeContentBrowserClient::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel(
base::StringPiece scheme,
bool is_embedded_origin_secure) {
// This is needed to bypass the normal SameSite rules for any chrome:// page
// embedding a secure origin, regardless of the registrable domains of any
// intervening frames. For example, this is needed for browser UI to interact
// with SameSite cookies on accounts.google.com, which are used for logging
// into Cloud Print from chrome://print, for displaying a list of available
// accounts on the NTP (chrome://new-tab-page), etc.
if (is_embedded_origin_secure && scheme == content::kChromeUIScheme)
return true;
#if BUILDFLAG(ENABLE_EXTENSIONS)
return scheme == extensions::kExtensionScheme;
#else
return false;
#endif
}
bool ChromeContentBrowserClient::
ShouldIgnoreSameSiteCookieRestrictionsWhenTopLevel(
base::StringPiece scheme,
bool is_embedded_origin_secure) {
return is_embedded_origin_secure && scheme == content::kChromeUIScheme;
}
// TODO(crbug.com/1087559): This is based on SubframeTask::GetTitle()
// implementation. Find a general solution to avoid code duplication.
std::string ChromeContentBrowserClient::GetSiteDisplayNameForCdmProcess(
content::BrowserContext* browser_context,
const GURL& site_url) {
// By default, use the |site_url| spec as the display name.
std::string name = site_url.spec();
#if BUILDFLAG(ENABLE_EXTENSIONS)
// If |site_url| wraps a chrome extension ID, we can display the extension
// name instead, which is more human-readable.
if (site_url.SchemeIs(extensions::kExtensionScheme)) {
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(browser_context)
->enabled_extensions()
.GetExtensionOrAppByURL(site_url);
if (extension)
name = extension->name();
}
#endif // BUILDFLAG(ENABLE_EXTENSIONS)
return name;
}
void ChromeContentBrowserClient::OverrideURLLoaderFactoryParams(
content::BrowserContext* browser_context,
const url::Origin& origin,
bool is_for_isolated_world,
network::mojom::URLLoaderFactoryParams* factory_params) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
ChromeContentBrowserClientExtensionsPart::OverrideURLLoaderFactoryParams(
browser_context, origin, is_for_isolated_world, factory_params);
#endif
}
// These are treated as WebUI schemes but do not get WebUI bindings. Also,
// view-source is allowed for these schemes.
void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
std::vector<std::string>* additional_schemes) {
additional_schemes->push_back(chrome::kChromeSearchScheme);
additional_schemes->push_back(dom_distiller::kDomDistillerScheme);
additional_schemes->push_back(content::kChromeDevToolsScheme);
}
void ChromeContentBrowserClient::GetAdditionalViewSourceSchemes(
std::vector<std::string>* additional_schemes) {
GetAdditionalWebUISchemes(additional_schemes);
#if BUILDFLAG(ENABLE_EXTENSIONS)
additional_schemes->push_back(extensions::kExtensionScheme);
#endif
}
bool ChromeContentBrowserClient::LogWebUIUrl(const GURL& web_ui_url) {
return webui::LogWebUIUrl(web_ui_url);
}
bool ChromeContentBrowserClient::IsWebUIAllowedToMakeNetworkRequests(
const url::Origin& origin) {
return ChromeWebUIControllerFactory::IsWebUIAllowedToMakeNetworkRequests(
origin);
}
bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
return ProfileIOData::IsHandledURL(url);
}
bool ChromeContentBrowserClient::HasCustomSchemeHandler(
content::BrowserContext* browser_context,
const std::string& scheme) {
if (ProtocolHandlerRegistry* protocol_handler_registry =
ProtocolHandlerRegistryFactory::GetForBrowserContext(
browser_context)) {
return protocol_handler_registry->IsHandledProtocol(scheme);
}
return false;
}
bool ChromeContentBrowserClient::CanCommitURL(
content::RenderProcessHost* process_host,
const GURL& url) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
return ChromeContentBrowserClientExtensionsPart::CanCommitURL(process_host,
url);
#else
return true;
#endif
}
void ChromeContentBrowserClient::OverrideNavigationParams(
content::WebContents* web_contents,
SiteInstance* site_instance,
ui::PageTransition* transition,
bool* is_renderer_initiated,
content::Referrer* referrer,
base::Optional<url::Origin>* initiator_origin) {
DCHECK(transition);
DCHECK(is_renderer_initiated);
DCHECK(referrer);
// While using SiteInstance::GetSiteURL() is unreliable and the wrong thing to
// use for making security decisions 99.44% of the time, for detecting the NTP
// it is reliable and the correct way. See http://crbug.com/624410.
if (site_instance && search::IsNTPURL(site_instance->GetSiteURL()) &&
ui::PageTransitionCoreTypeIs(*transition, ui::PAGE_TRANSITION_LINK)) {
// Clicks on tiles of the new tab page should be treated as if a user
// clicked on a bookmark. This is consistent with native implementations
// like Android's. This also helps ensure that security features (like
// Sec-Fetch-Site and SameSite-cookies) will treat the navigation as
// browser-initiated.
*transition = ui::PAGE_TRANSITION_AUTO_BOOKMARK;
*is_renderer_initiated = false;
*referrer = content::Referrer();
*initiator_origin = base::nullopt;
}
#if defined(OS_ANDROID)
if (web_contents) {
TabAndroid* tab = TabAndroid::FromWebContents(web_contents);
if (tab && tab->should_add_api2_transition_to_future_navigations()) {
*transition = ui::PageTransitionFromInt(*transition |
ui::PAGE_TRANSITION_FROM_API_2);
}
}
#endif
}
bool ChromeContentBrowserClient::ShouldStayInParentProcessForNTP(
const GURL& url,
SiteInstance* parent_site_instance) {
// While using SiteInstance::GetSiteURL() is unreliable and the wrong thing to
// use for making security decisions 99.44% of the time, for detecting the NTP
// it is reliable and the correct way. See http://crbug.com/624410.
return url.SchemeIs(chrome::kChromeSearchScheme) && parent_site_instance &&
search::IsNTPURL(parent_site_instance->GetSiteURL());
}
bool ChromeContentBrowserClient::IsSuitableHost(
content::RenderProcessHost* process_host,
const GURL& site_url) {
Profile* profile =
Profile::FromBrowserContext(process_host->GetBrowserContext());
// This may be nullptr during tests. In that case, just assume any site can
// share any host.
if (!profile)
return true;
#if !defined(OS_ANDROID)
// Instant URLs should only be in the instant process and instant process
// should only have Instant URLs.
InstantService* instant_service =
InstantServiceFactory::GetForProfile(profile);
if (instant_service) {
bool is_instant_process =
instant_service->IsInstantProcess(process_host->GetID());
bool should_be_in_instant_process =
search::ShouldAssignURLToInstantRenderer(site_url, profile);
if (is_instant_process || should_be_in_instant_process)
return is_instant_process && should_be_in_instant_process;
}
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
profile, process_host, site_url);
#else
return true;
#endif
}
bool ChromeContentBrowserClient::MayReuseHost(
content::RenderProcessHost* process_host) {
// If there is currently a prerender in progress for the host provided,
// it may not be shared. We require prerenders to be by themselves in a
// separate process so that we can monitor their resource usage.
prerender::PrerenderManager* prerender_manager =
prerender::PrerenderManagerFactory::GetForBrowserContext(
process_host->GetBrowserContext());
if (prerender_manager &&
!prerender_manager->MayReuseProcessHost(process_host)) {
return false;
}
return true;
}
bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
content::BrowserContext* browser_context,
const GURL& url) {
// It has to be a valid URL for us to check for an extension.
if (!url.is_valid())
return false;
#if BUILDFLAG(ENABLE_EXTENSIONS)
Profile* profile = Profile::FromBrowserContext(browser_context);
return ChromeContentBrowserClientExtensionsPart::
ShouldTryToUseExistingProcessHost(profile, url);
#else
return false;
#endif
}
bool ChromeContentBrowserClient::ShouldSubframesTryToReuseExistingProcess(
content::RenderFrameHost* main_frame) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
return ChromeContentBrowserClientExtensionsPart::
ShouldSubframesTryToReuseExistingProcess(main_frame);
#else
return true;
#endif
}
void ChromeContentBrowserClient::SiteInstanceGotProcess(
SiteInstance* site_instance) {
CHECK(site_instance->HasProcess());
Profile* profile =
Profile::FromBrowserContext(site_instance->GetBrowserContext());
if (!profile)
return;
#if !defined(OS_ANDROID)
// Remember the ID of the Instant process to signal the renderer process
// on startup in |AppendExtraCommandLineSwitches| below.
if (search::ShouldAssignURLToInstantRenderer(site_instance->GetSiteURL(),
profile)) {
InstantService* instant_service =
InstantServiceFactory::GetForProfile(profile);
if (instant_service)
instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
}
#endif
for (size_t i = 0; i < extra_parts_.size(); ++i)
extra_parts_[i]->SiteInstanceGotProcess(site_instance);
}
void ChromeContentBrowserClient::SiteInstanceDeleting(
SiteInstance* site_instance) {
if (!site_instance->HasProcess())
return;
for (size_t i = 0; i < extra_parts_.size(); ++i)
extra_parts_[i]->SiteInstanceDeleting(site_instance);
}
bool ChromeContentBrowserClient::ShouldSwapBrowsingInstancesForNavigation(
SiteInstance* site_instance,
const GURL& current_effective_url,
const GURL& destination_effective_url) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
return ChromeContentBrowserClientExtensionsPart::
ShouldSwapBrowsingInstancesForNavigation(
site_instance, current_effective_url, destination_effective_url);
#else
return false;
#endif
}
bool ChromeContentBrowserClient::ShouldIsolateErrorPage(bool in_main_frame) {
// TODO(nasko): Consider supporting error page isolation in subframes if
// Site Isolation is enabled.
return in_main_frame;
}
bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
return !url.SchemeIs(chrome::kChromeNativeScheme);
}
std::vector<url::Origin>
ChromeContentBrowserClient::GetOriginsRequiringDedicatedProcess() {
std::vector<url::Origin> isolated_origin_list;
// Sign-in process isolation is not needed on Android, see
// https://crbug.com/739418.
#if !defined(OS_ANDROID)
isolated_origin_list.push_back(
url::Origin::Create(GaiaUrls::GetInstance()->gaia_url()));
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
auto origins_from_extensions = ChromeContentBrowserClientExtensionsPart::
GetOriginsRequiringDedicatedProcess();
std::move(std::begin(origins_from_extensions),
std::end(origins_from_extensions),
std::back_inserter(isolated_origin_list));
#endif
// Include additional origins preloaded with specific browser configurations,
// if any. For example, this is used on Google Chrome for Android to preload
// a list of important sites to isolate.
auto built_in_origins =
site_isolation::GetBrowserSpecificBuiltInIsolatedOrigins();
std::move(std::begin(built_in_origins), std::end(built_in_origins),
std::back_inserter(isolated_origin_list));
return isolated_origin_list;
}
bool ChromeContentBrowserClient::ShouldEnableStrictSiteIsolation() {
return base::FeatureList::IsEnabled(features::kSitePerProcess);
}
bool ChromeContentBrowserClient::ShouldDisableSiteIsolation() {
return site_isolation::SiteIsolationPolicy::
ShouldDisableSiteIsolationDueToMemoryThreshold();
}
std::vector<std::string>
ChromeContentBrowserClient::GetAdditionalSiteIsolationModes() {
if (site_isolation::SiteIsolationPolicy::IsIsolationForPasswordSitesEnabled())
return {"Isolate Password Sites"};
else
return {};
}
void ChromeContentBrowserClient::PersistIsolatedOrigin(
content::BrowserContext* context,
const url::Origin& origin) {
DCHECK(!context->IsOffTheRecord());
Profile* profile = Profile::FromBrowserContext(context);
ListPrefUpdate update(profile->GetPrefs(),
site_isolation::prefs::kUserTriggeredIsolatedOrigins);
base::ListValue* list = update.Get();
base::Value value(origin.Serialize());
if (!base::Contains(list->GetList(), value))
list->Append(std::move(value));
}
bool ChromeContentBrowserClient::IsFileAccessAllowed(
const base::FilePath& path,
const base::FilePath& absolute_path,
const base::FilePath& profile_path) {
return ChromeNetworkDelegate::IsAccessAllowed(path, absolute_path,
profile_path);
}
namespace {
void MaybeAppendBlinkSettingsSwitchForFieldTrial(
const base::CommandLine& browser_command_line,
base::CommandLine* command_line) {
// List of field trials that modify the blink-settings command line flag. No
// two field trials in the list should specify the same keys, otherwise one
// field trial may overwrite another. See Source/core/frame/Settings.in in
// Blink for the list of valid keys.
static const char* const kBlinkSettingsFieldTrials[] = {
// Keys: disallowFetchForDocWrittenScriptsInMainFrame
// disallowFetchForDocWrittenScriptsInMainFrameOnSlowConnections
// disallowFetchForDocWrittenScriptsInMainFrameIfEffectively2G
"DisallowFetchForDocWrittenScriptsInMainFrame",
};
std::vector<std::string> blink_settings;
for (const char* field_trial_name : kBlinkSettingsFieldTrials) {
// Each blink-settings field trial should include a forcing_flag group,
// to make sure that clients that specify the blink-settings flag on the
// command line are excluded from the experiment groups. To make
// sure we assign clients that specify this flag to the forcing_flag
// group, we must call GetVariationParams for each field trial first
// (for example, before checking HasSwitch() and returning), since
// GetVariationParams has the side-effect of assigning the client to
// a field trial group.
std::map<std::string, std::string> params;
if (variations::GetVariationParams(field_trial_name, &params)) {
for (const auto& param : params) {
blink_settings.push_back(base::StringPrintf(
"%s=%s", param.first.c_str(), param.second.c_str()));
}
}
}
if (blink_settings.empty()) {
return;
}
if (browser_command_line.HasSwitch(blink::switches::kBlinkSettings) ||
command_line->HasSwitch(blink::switches::kBlinkSettings)) {
// The field trials should be configured to force users that specify the
// blink-settings flag into a group with no params, and we return
// above if no params were specified, so it's an error if we reach
// this point.
LOG(WARNING) << "Received field trial params, "
"but blink-settings switch already specified.";
return;
}
command_line->AppendSwitchASCII(blink::switches::kBlinkSettings,
base::JoinString(blink_settings, ","));
}
} // namespace
void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
base::CommandLine* command_line,
int child_process_id) {
#if defined(OS_MAC)
std::unique_ptr<metrics::ClientInfo> client_info =
GoogleUpdateSettings::LoadMetricsClientInfo();
if (client_info) {
command_line->AppendSwitchASCII(switches::kMetricsClientID,
client_info->client_id);
}
#elif defined(OS_POSIX)
#if defined(OS_ANDROID)
bool enable_crash_reporter = true;
#else
bool enable_crash_reporter = false;
if (crash_reporter::IsCrashpadEnabled()) {
command_line->AppendSwitch(crash_reporter::kEnableCrashpad);
enable_crash_reporter = true;
int fd;
pid_t pid;
if (crash_reporter::GetHandlerSocket(&fd, &pid)) {
command_line->AppendSwitchASCII(
crash_reporter::switches::kCrashpadHandlerPid,
base::NumberToString(pid));
}
} else {
enable_crash_reporter = breakpad::IsCrashReporterEnabled();
}
#endif
if (enable_crash_reporter) {
std::string switch_value;
std::unique_ptr<metrics::ClientInfo> client_info =
GoogleUpdateSettings::LoadMetricsClientInfo();
if (client_info)
switch_value = client_info->client_id;
switch_value.push_back(',');
switch_value.append(chrome::GetChannelName());
command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
switch_value);
}
#endif
if (logging::DialogsAreSuppressed())
command_line->AppendSwitch(switches::kNoErrorDialogs);
std::string process_type =
command_line->GetSwitchValueASCII(switches::kProcessType);
const base::CommandLine& browser_command_line =
*base::CommandLine::ForCurrentProcess();
static const char* const kCommonSwitchNames[] = {
switches::kUserAgent,
switches::kUserDataDir, // Make logs go to the right file.
};
command_line->CopySwitchesFrom(browser_command_line, kCommonSwitchNames,
base::size(kCommonSwitchNames));
static const char* const kDinosaurEasterEggSwitches[] = {
error_page::switches::kDisableDinosaurEasterEgg,
};
command_line->CopySwitchesFrom(browser_command_line,
kDinosaurEasterEggSwitches,
base::size(kDinosaurEasterEggSwitches));
if (blink::ReferrerUtils::ShouldForceLegacyDefaultReferrerPolicy())
command_line->AppendSwitch(
blink::switches::kForceLegacyDefaultReferrerPolicy);
#if defined(OS_CHROMEOS)
// On Chrome OS need to pass primary user homedir (in multi-profiles session).
base::FilePath homedir;
base::PathService::Get(base::DIR_HOME, &homedir);
command_line->AppendSwitchASCII(chromeos::switches::kHomedir,
homedir.value().c_str());
#endif
if (process_type == switches::kRendererProcess) {
content::RenderProcessHost* process =
content::RenderProcessHost::FromID(child_process_id);
Profile* profile =
process ? Profile::FromBrowserContext(process->GetBrowserContext())
: nullptr;
for (size_t i = 0; i < extra_parts_.size(); ++i) {
extra_parts_[i]->AppendExtraRendererCommandLineSwitches(command_line,
process, profile);
}
#if defined(OS_CHROMEOS)
const std::string& login_profile = browser_command_line.GetSwitchValueASCII(
chromeos::switches::kLoginProfile);
if (!login_profile.empty())
command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile,
login_profile);
#endif
MaybeCopyDisableWebRtcEncryptionSwitch(command_line, browser_command_line,
chrome::GetChannel());
if (process) {
PrefService* prefs = profile->GetPrefs();
// Currently this pref is only registered if applied via a policy.
if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
prefs->GetBoolean(prefs::kDisable3DAPIs)) {
// Turn this policy into a command line switch.
command_line->AppendSwitch(switches::kDisable3DAPIs);
}
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
bool client_side_detection_enabled =
safe_browsing::IsSafeBrowsingEnabled(*prefs) &&
!base::CommandLine::ForCurrentProcess()->HasSwitch(
::switches::kDisableClientSidePhishingDetection);
#if BUILDFLAG(SAFE_BROWSING_DB_REMOTE)
client_side_detection_enabled &= base::FeatureList::IsEnabled(
safe_browsing::kClientSideDetectionForAndroid);
#endif // BUILDFLAG(SAFE_BROWSING_DB_REMOTE)
// Disable client-side phishing detection in the renderer if it is
// disabled in the Profile preferences, or by command line flag, or by not
// being enabled on Android.
if (!client_side_detection_enabled) {
command_line->AppendSwitch(
switches::kDisableClientSidePhishingDetection);
}
#endif // BUILDFLAG(SAFE_BROWSING_AVAILABLE)
if (prefs->GetBoolean(prefs::kPrintPreviewDisabled))
command_line->AppendSwitch(switches::kDisablePrintPreview);
#if !defined(OS_ANDROID)
InstantService* instant_service =
InstantServiceFactory::GetForProfile(profile);
if (instant_service &&
instant_service->IsInstantProcess(process->GetID())) {
command_line->AppendSwitch(switches::kInstantProcess);
}
#endif
if (prefs->HasPrefPath(prefs::kAllowDinosaurEasterEgg) &&
!prefs->GetBoolean(prefs::kAllowDinosaurEasterEgg)) {
command_line->AppendSwitch(
error_page::switches::kDisableDinosaurEasterEgg);
}
MaybeAppendSecureOriginsAllowlistSwitch(command_line);
if (prefs->HasPrefPath(prefs::kAllowSyncXHRInPageDismissal) &&
prefs->GetBoolean(prefs::kAllowSyncXHRInPageDismissal)) {
command_line->AppendSwitch(switches::kAllowSyncXHRInPageDismissal);
}
if (prefs->HasPrefPath(prefs::kScrollToTextFragmentEnabled) &&
!prefs->GetBoolean(prefs::kScrollToTextFragmentEnabled)) {
command_line->AppendSwitch(switches::kDisableScrollToTextFragment);
}
if (prefs->HasPrefPath(prefs::kAppCacheForceEnabled) &&
prefs->GetBoolean(prefs::kAppCacheForceEnabled)) {
command_line->AppendSwitch(switches::kAppCacheForceEnabled);
}
// The IntensiveWakeUpThrottling feature is typically managed via a
// base::Feature, but it has a managed policy override. The override is
// communicated to blink via a custom command-line flag. See
// PageSchedulerImpl for the other half of related logic.
PrefService* local_state = g_browser_process->local_state();
const PrefService::Preference* pref = local_state->FindPreference(
policy::policy_prefs::kIntensiveWakeUpThrottlingEnabled);
if (pref && pref->IsManaged()) {
command_line->AppendSwitchASCII(
blink::switches::kIntensiveWakeUpThrottlingPolicy,
pref->GetValue()->GetBool()
? blink::switches::kIntensiveWakeUpThrottlingPolicy_ForceEnable
: blink::switches::
kIntensiveWakeUpThrottlingPolicy_ForceDisable);
}
// Same as above, but for the blink side of UserAgentClientHints
if (!local_state->GetBoolean(
policy::policy_prefs::kUserAgentClientHintsEnabled)) {
command_line->AppendSwitch(
blink::switches::kUserAgentClientHintDisable);
}
if (!local_state->GetBoolean(
policy::policy_prefs::kTargetBlankImpliesNoOpener)) {
command_line->AppendSwitch(
switches::kDisableTargetBlankImpliesNoOpener);
}
#if defined(OS_ANDROID)
// Communicating to content/ for BackForwardCache.
if (prefs->HasPrefPath(policy::policy_prefs::kBackForwardCacheEnabled) &&
!prefs->GetBoolean(policy::policy_prefs::kBackForwardCacheEnabled)) {
command_line->AppendSwitch(switches::kDisableBackForwardCache);
}
#endif // defined(OS_ANDROID)
}
MaybeAppendBlinkSettingsSwitchForFieldTrial(browser_command_line,
command_line);
#if defined(OS_ANDROID)
// If the platform is Android, force the distillability service on.
command_line->AppendSwitch(switches::kEnableDistillabilityService);
#endif
// Please keep this in alphabetical order.
static const char* const kSwitchNames[] = {
autofill::switches::kIgnoreAutocompleteOffForAutofill,
autofill::switches::kShowAutofillSignatures,
#if defined(OS_CHROMEOS)
switches::kShortMergeSessionTimeoutForTest, // For tests only.
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
extensions::switches::kAllowHTTPBackgroundPage,
extensions::switches::kAllowLegacyExtensionManifests,
extensions::switches::kDisableExtensionsHttpThrottling,
extensions::switches::kEnableExperimentalExtensionApis,
extensions::switches::kExtensionsOnChromeURLs,
extensions::switches::kSetExtensionThrottleTestParams, // For tests only.
extensions::switches::kAllowlistedExtensionID,
#endif
switches::kAllowInsecureLocalhost,
switches::kAppsGalleryURL,
switches::kCloudPrintURL,
switches::kCloudPrintXmppEndpoint,
switches::kDisableJavaScriptHarmonyShipping,
variations::switches::kEnableBenchmarking,
switches::kEnableDistillabilityService,
switches::kEnableNaCl,
#if BUILDFLAG(ENABLE_NACL)
switches::kEnableNaClDebug,
switches::kEnableNaClNonSfiMode,
#endif
switches::kEnableNetBenchmarking,
#if defined(OS_CHROMEOS)
switches::kForceAppMode,
#endif
#if BUILDFLAG(ENABLE_NACL)
switches::kForcePNaClSubzero,
#endif
switches::kForceUIDirection,
switches::kIgnoreGooglePortNumbers,
switches::kJavaScriptHarmony,
switches::kEnableExperimentalWebAssemblyFeatures,
embedder_support::kOriginTrialDisabledFeatures,
embedder_support::kOriginTrialDisabledTokens,
embedder_support::kOriginTrialPublicKey,
switches::kReaderModeHeuristics,
translate::switches::kTranslateSecurityOrigin,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
base::size(kSwitchNames));
} else if (process_type == switches::kUtilityProcess) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
static const char* const kSwitchNames[] = {
extensions::switches::kAllowHTTPBackgroundPage,
extensions::switches::kEnableExperimentalExtensionApis,
extensions::switches::kExtensionsOnChromeURLs,
extensions::switches::kAllowlistedExtensionID,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
base::size(kSwitchNames));
#endif
MaybeAppendSecureOriginsAllowlistSwitch(command_line);
} else if (process_type == switches::kZygoteProcess) {
// Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
#if BUILDFLAG(ENABLE_NACL)
static const char* const kSwitchNames[] = {
switches::kEnableNaClDebug,
switches::kEnableNaClNonSfiMode,
switches::kForcePNaClSubzero,
switches::kNaClDangerousNoSandboxNonSfi,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
base::size(kSwitchNames));
#endif
} else if (process_type == switches::kGpuProcess) {
// If --ignore-gpu-blocklist is passed in, don't send in crash reports
// because GPU is expected to be unreliable.
if ((browser_command_line.HasSwitch(switches::kIgnoreGpuBlocklist) ||
browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist)) &&
!command_line->HasSwitch(switches::kDisableBreakpad))
command_line->AppendSwitch(switches::kDisableBreakpad);
}
#if defined(OS_CHROMEOS)
if (ChromeCrashReporterClient::ShouldPassCrashLoopBefore(process_type)) {
static const char* const kSwitchNames[] = {
crash_reporter::switches::kCrashLoopBefore,
};
command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
base::size(kSwitchNames));
}
#endif
ThreadProfilerConfiguration::Get()->AppendCommandLineSwitchForChildProcess(
command_line);
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
// Processes may only query perf_event_open with the BPF sandbox disabled.
if (browser_command_line.HasSwitch(switches::kEnableThreadInstructionCount) &&
command_line->HasSwitch(sandbox::policy::switches::kNoSandbox)) {
command_line->AppendSwitch(switches::kEnableThreadInstructionCount);
}
#endif
}
std::string
ChromeContentBrowserClient::GetApplicationClientGUIDForQuarantineCheck() {
return std::string(chrome::kApplicationClientIDStringForAVScanning);
}
download::QuarantineConnectionCallback
ChromeContentBrowserClient::GetQuarantineConnectionCallback() {
return base::BindRepeating(
&ChromeDownloadManagerDelegate::ConnectToQuarantineService);
}
std::string ChromeContentBrowserClient::GetApplicationLocale() {
if (BrowserThread::CurrentlyOn(BrowserThread::IO))
return GetIOThreadApplicationLocale();
return g_browser_process->GetApplicationLocale();
}
std::string ChromeContentBrowserClient::GetAcceptLangs(
content::BrowserContext* context) {
Profile* profile = Profile::FromBrowserContext(context);
return profile->GetPrefs()->GetString(language::prefs::kAcceptLanguages);
}
gfx::ImageSkia ChromeContentBrowserClient::GetDefaultFavicon() {
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
return rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).AsImageSkia();
}
bool ChromeContentBrowserClient::IsDataSaverEnabled(
content::BrowserContext* browser_context) {
if (!browser_context || browser_context->IsOffTheRecord())
return false;
Profile* profile = Profile::FromBrowserContext(browser_context);
return profile && data_reduction_proxy::DataReductionProxySettings::
IsDataSaverEnabledByUser(profile->IsOffTheRecord(),
profile->GetPrefs());
}
void ChromeContentBrowserClient::UpdateRendererPreferencesForWorker(
content::BrowserContext* browser_context,
blink::RendererPreferences* out_prefs) {
DCHECK(browser_context);
DCHECK(out_prefs);
renderer_preferences_util::UpdateFromSystemSettings(
out_prefs, Profile::FromBrowserContext(browser_context));
}
bool ChromeContentBrowserClient::AllowAppCache(
const GURL& manifest_url,
const GURL& site_for_cookies,
const base::Optional<url::Origin>& top_frame_origin,
content::BrowserContext* context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return CookieSettingsFactory::GetForProfile(
Profile::FromBrowserContext(context))
->IsCookieAccessAllowed(manifest_url, site_for_cookies, top_frame_origin);
}
content::AllowServiceWorkerResult
ChromeContentBrowserClient::AllowServiceWorker(
const GURL& scope,
const GURL& site_for_cookies,
const base::Optional<url::Origin>& top_frame_origin,
const GURL& script_url,
content::BrowserContext* context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
GURL first_party_url = top_frame_origin ? top_frame_origin->GetURL() : GURL();
#if BUILDFLAG(ENABLE_EXTENSIONS)
// Check if this is an extension-related service worker, and, if so, if it's
// allowed (this can return false if, e.g., the extension is disabled).
// If it's not allowed, return immediately. We deliberately do *not* report
// to the PageSpecificContentSettings, since the service worker is blocked
// because of the extension, rather than because of the user's content
// settings.
if (!ChromeContentBrowserClientExtensionsPart::AllowServiceWorker(
scope, first_party_url, script_url, context)) {
return content::AllowServiceWorkerResult::No();
}
#endif
Profile* profile = Profile::FromBrowserContext(context);
// Check if JavaScript is allowed.
content_settings::SettingInfo info;
std::unique_ptr<base::Value> value =
HostContentSettingsMapFactory::GetForProfile(profile)->GetWebsiteSetting(
first_party_url, first_party_url, ContentSettingsType::JAVASCRIPT,
&info);
ContentSetting setting = content_settings::ValueToContentSetting(value.get());
bool allow_javascript = (setting == CONTENT_SETTING_ALLOW);
// Check if cookies are allowed.
bool allow_cookies =
CookieSettingsFactory::GetForProfile(profile)->IsCookieAccessAllowed(
scope, site_for_cookies, top_frame_origin);
return content::AllowServiceWorkerResult::FromPolicy(!allow_javascript,
!allow_cookies);
}
bool ChromeContentBrowserClient::AllowSharedWorker(
const GURL& worker_url,
const GURL& site_for_cookies,
const base::Optional<url::Origin>& top_frame_origin,
const std::string& name,
const url::Origin& constructor_origin,
content::BrowserContext* context,
int render_process_id,
int render_frame_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Check if cookies are allowed.
bool allow =
CookieSettingsFactory::GetForProfile(Profile::FromBrowserContext(context))
->IsCookieAccessAllowed(worker_url, site_for_cookies,
top_frame_origin);
content_settings::PageSpecificContentSettings::SharedWorkerAccessed(
render_process_id, render_frame_id, worker_url, name, constructor_origin,
!allow);
return allow;
}
bool ChromeContentBrowserClient::DoesSchemeAllowCrossOriginSharedWorker(
const std::string& scheme) {
#if BUILDFLAG(ENABLE_EXTENSIONS)
// Extensions are allowed to start cross-origin shared workers.
if (scheme == extensions::kExtensionScheme)
return true;
#endif
return false;
}
bool ChromeContentBrowserClient::AllowSignedExchange(
content::BrowserContext* browser_context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
Profile* profile = Profile::FromBrowserContext(browser_context);
return profile->GetPrefs()->GetBoolean(prefs::kSignedHTTPExchangeEnabled);
}
void ChromeContentBrowserClient::AllowWorkerFileSystem(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalFrameRoutingId>& render_frames,
base::OnceCallback<void(bool)> callback) {
Profile* profile = Profile::FromBrowserContext(browser_context);
auto cookie_settings = CookieSettingsFactory::GetForProfile(profile);
bool allow = cookie_settings->IsCookieAccessAllowed(url, url, base::nullopt);
#if BUILDFLAG(ENABLE_EXTENSIONS)
GuestPermissionRequestHelper(url, render_frames, std::move(callback), allow);
#else
FileSystemAccessed(url, render_frames, std::move(callback), allow);
#endif
}
#if BUILDFLAG(ENABLE_EXTENSIONS)
void ChromeContentBrowserClient::GuestPermissionRequestHelper(
const GURL& url,
const std::vector<content::GlobalFrameRoutingId>& render_frames,
base::OnceCallback<void(bool)> callback,
bool allow) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
std::map<int, int> process_map;
std::map<int, int>::const_iterator it;
bool has_web_view_guest = false;
// Record access to file system for potential display in UI.
for (const auto& it : render_frames) {
if (process_map.find(it.child_id) != process_map.end())
continue;
process_map.insert(std::pair<int, int>(it.child_id, it.frame_routing_id));
if (extensions::WebViewRendererState::GetInstance()->IsGuest(it.child_id))
has_web_view_guest = true;
}
if (!has_web_view_guest) {
FileSystemAccessed(url, render_frames, std::move(callback), allow);
return;
}
DCHECK_EQ(1U, process_map.size());
it = process_map.begin();
extensions::WebViewPermissionHelper* web_view_permission_helper =
extensions::WebViewPermissionHelper::FromFrameID(it->first, it->second);
web_view_permission_helper->RequestFileSystemPermission(
url, allow,
base::BindOnce(&ChromeContentBrowserClient::FileSystemAccessed,
weak_factory_.GetWeakPtr(), url, render_frames,
std::move(callback)));
}
#endif
void ChromeContentBrowserClient::FileSystemAccessed(
const GURL& url,
const std::vector<content::GlobalFrameRoutingId>& render_frames,
base::OnceCallback<void(bool)> callback,
bool allow) {
// Record access to file system for potential display in UI.
for (const auto& it : render_frames) {
content_settings::PageSpecificContentSettings::FileSystemAccessed(
it.child_id, it.frame_routing_id, url, !allow);
}
std::move(callback).Run(allow);
}
bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalFrameRoutingId>& render_frames) {
Profile* profile = Profile::FromBrowserContext(browser_context);
auto cookie_settings = CookieSettingsFactory::GetForProfile(profile);
bool allow = cookie_settings->IsCookieAccessAllowed(url, url, base::nullopt);
// Record access to IndexedDB for potential display in UI.
for (const auto& it : render_frames) {
content_settings::PageSpecificContentSettings::IndexedDBAccessed(
it.child_id, it.frame_routing_id, url, !allow);
}
return allow;
}
bool ChromeContentBrowserClient::AllowWorkerCacheStorage(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalFrameRoutingId>& render_frames) {
Profile* profile = Profile::FromBrowserContext(browser_context);
auto cookie_settings = CookieSettingsFactory::GetForProfile(profile);
bool allow = cookie_settings->IsCookieAccessAllowed(url, url, base::nullopt);
// Record access to CacheStorage for potential display in UI.
for (const auto& it : render_frames) {
content_settings::PageSpecificContentSettings::CacheStorageAccessed(
it.child_id, it.frame_routing_id, url, !allow);
}
return allow;
}
bool ChromeContentBrowserClient::AllowWorkerWebLocks(
const GURL& url,
content::BrowserContext* browser_context,
const std::vector<content::GlobalFrameRoutingId>& render_frames) {
Profile* profile = Profile::FromBrowserContext(browser_context);
auto cookie_settings = CookieSettingsFactory::GetForProfile(profile);
return cookie_settings->IsCookieAccessAllowed(url, url, base::nullopt);
}
ChromeContentBrowserClient::AllowWebBluetoothResult
ChromeContentBrowserClient::AllowWebBluetooth(
content::BrowserContext* browser_context,
const url::Origin& requesting_origin,
const url::Origin& embedding_origin) {
// TODO(crbug.com/598890): Don't disable if
// base::CommandLine::ForCurrentProcess()->
// HasSwitch(switches::kEnableWebBluetooth) is true.
if (variations::GetVariationParamValue(
permissions::PermissionContextBase::kPermissionsKillSwitchFieldStudy,
"Bluetooth") ==
permissions::PermissionContextBase::kPermissionsKillSwitchBlockedValue) {
// The kill switch is enabled for this permission. Block requests.
return AllowWebBluetoothResult::BLOCK_GLOBALLY_DISABLED;
}
const HostContentSettingsMap* const content_settings =
HostContentSettingsMapFactory::GetForProfile(
Profile::FromBrowserContext(browser_context));
if (content_settings->GetContentSetting(
requesting_origin.GetURL(), embedding_origin.GetURL(),
ContentSettingsType::BLUETOOTH_GUARD) == CONTENT_SETTING_BLOCK) {
return AllowWebBluetoothResult::BLOCK_POLICY;
}
return AllowWebBluetoothResult::ALLOW;
}
std::string ChromeContentBrowserClient::GetWebBluetoothBlocklist() {
return variations::GetVariationParamValue("WebBluetoothBlocklist",
"blocklist_additions");
}
bool ChromeContentBrowserClient::AllowConversionMeasurement(
content::BrowserContext* browser_context) {
// For now, disable conversion measurement if third party cookie blocking is
// enabled.
// TODO(crbug.com/1058018): Add dedicated UI to this feature.
Profile* profile = Profile::FromBrowserContext(browser_context);
auto cookie_settings = CookieSettingsFactory::GetForProfile(profile);
return !cookie_settings->ShouldBlockThirdPartyCookies();
}
#if defined(OS_CHROMEOS)
void ChromeContentBrowserClient::OnTrustAnchorUsed(
content::BrowserContext* browser_context) {
user_manager::UserManager* user_manager = user_manager::UserManager::Get();