1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
|
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_API_EXECUTE_CODE_FUNCTION_IMPL_H_
#define EXTENSIONS_BROWSER_API_EXECUTE_CODE_FUNCTION_IMPL_H_
#include "extensions/browser/api/execute_code_function.h"
#include <algorithm>
#include <optional>
#include <utility>
#include "base/functional/bind.h"
#include "base/strings/escape.h"
#include "base/strings/string_util.h"
#include "extensions/browser/extension_api_frame_id_map.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/browser/load_and_localize_file.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_resource.h"
#include "extensions/common/mojom/css_origin.mojom-shared.h"
#include "extensions/common/mojom/run_location.mojom-shared.h"
#include "extensions/common/utils/content_script_utils.h"
#include "extensions/common/utils/extension_types_utils.h"
namespace {
// Error messages
const char kNoCodeOrFileToExecuteError[] = "No source code or file specified.";
const char kMoreThanOneValuesError[] =
"Code and file should not be specified "
"at the same time in the second argument.";
const char kBadFileEncodingError[] =
"Could not load file '*' for content script. It isn't UTF-8 encoded.";
const char kCSSOriginForNonCSSError[] =
"CSS origin should be specified only for CSS code.";
}
namespace extensions {
using api::extension_types::InjectDetails;
ExecuteCodeFunction::ExecuteCodeFunction() {
}
ExecuteCodeFunction::~ExecuteCodeFunction() {
}
void ExecuteCodeFunction::DidLoadAndLocalizeFile(
const std::string& file,
std::vector<std::unique_ptr<std::string>> data,
std::optional<std::string> load_error) {
if (load_error) {
// TODO(viettrungluu): bug: there's no particular reason the path should be
// UTF-8, in which case this may fail.
Respond(Error(std::move(*load_error)));
return;
}
DCHECK_EQ(1u, data.size());
auto& file_data = data.front();
if (!base::IsStringUTF8(*file_data)) {
Respond(Error(ErrorUtils::FormatErrorMessage(kBadFileEncodingError, file)));
return;
}
std::string error;
if (!Execute(*file_data, &error))
Respond(Error(std::move(error)));
// If Execute() succeeds, the function will respond in
// OnExecuteCodeFinished().
}
bool ExecuteCodeFunction::Execute(const std::string& code_string,
std::string* error) {
ScriptExecutor* executor = GetScriptExecutor(error);
if (!executor)
return false;
// TODO(lazyboy): Set |error|?
if (!extension() && !IsWebView())
return false;
DCHECK(!(ShouldInsertCSS() && ShouldRemoveCSS()));
ScriptExecutor::FrameScope frame_scope =
details_->all_frames.value_or(false) ? ScriptExecutor::INCLUDE_SUB_FRAMES
: ScriptExecutor::SPECIFIED_FRAMES;
root_frame_id_ = details_->frame_id.value_or(GetRootFrameId());
mojom::MatchOriginAsFallbackBehavior match_about_blank =
details_->match_about_blank.value_or(false)
? mojom::MatchOriginAsFallbackBehavior::
kMatchForAboutSchemeAndClimbTree
: mojom::MatchOriginAsFallbackBehavior::kNever;
mojom::RunLocation run_at = ConvertRunLocation(details_->run_at);
mojom::CSSOrigin css_origin = mojom::CSSOrigin::kAuthor;
switch (details_->css_origin) {
case api::extension_types::CSSOrigin::kNone:
case api::extension_types::CSSOrigin::kAuthor:
css_origin = mojom::CSSOrigin::kAuthor;
break;
case api::extension_types::CSSOrigin::kUser:
css_origin = mojom::CSSOrigin::kUser;
break;
}
mojom::CodeInjectionPtr injection;
bool is_css_injection = ShouldInsertCSS() || ShouldRemoveCSS();
if (is_css_injection) {
std::optional<std::string> injection_key;
if (host_id_.type == mojom::HostID::HostType::kExtensions) {
injection_key = ScriptExecutor::GenerateInjectionKey(
host_id_, script_url_, code_string);
}
mojom::CSSInjection::Operation operation =
ShouldInsertCSS() ? mojom::CSSInjection::Operation::kAdd
: mojom::CSSInjection::Operation::kRemove;
std::vector<mojom::CSSSourcePtr> sources;
sources.push_back(
mojom::CSSSource::New(code_string, std::move(injection_key)));
injection = mojom::CodeInjection::NewCss(
mojom::CSSInjection::New(std::move(sources), css_origin, operation));
} else {
bool wants_result = has_callback();
std::vector<mojom::JSSourcePtr> sources;
sources.push_back(mojom::JSSource::New(code_string, script_url_));
// tabs.executeScript does not support waiting for promises (only
// scripting.executeScript does).
injection = mojom::CodeInjection::NewJs(mojom::JSInjection::New(
std::move(sources), mojom::ExecutionWorld::kIsolated,
/*world_id=*/std::nullopt,
wants_result ? blink::mojom::WantResultOption::kWantResult
: blink::mojom::WantResultOption::kNoResult,
user_gesture() ? blink::mojom::UserActivationOption::kActivate
: blink::mojom::UserActivationOption::kDoNotActivate,
blink::mojom::PromiseResultOption::kDoNotWait));
}
executor->ExecuteScript(
host_id_, std::move(injection), frame_scope, {root_frame_id_},
match_about_blank, run_at,
IsWebView() ? ScriptExecutor::WEB_VIEW_PROCESS
: ScriptExecutor::DEFAULT_PROCESS,
GetWebViewSrc(),
base::BindOnce(&ExecuteCodeFunction::OnExecuteCodeFinished, this));
return true;
}
ExtensionFunction::ResponseAction ExecuteCodeFunction::Run() {
InitResult init_result = Init();
EXTENSION_FUNCTION_VALIDATE(init_result != VALIDATION_FAILURE);
if (init_result == FAILURE)
return RespondNow(Error(init_error_.value_or(kUnknownErrorDoNotUse)));
if (!details_->code && !details_->file)
return RespondNow(Error(kNoCodeOrFileToExecuteError));
if (details_->code && details_->file)
return RespondNow(Error(kMoreThanOneValuesError));
if (details_->css_origin != api::extension_types::CSSOrigin::kNone &&
!ShouldInsertCSS() && !ShouldRemoveCSS()) {
return RespondNow(Error(kCSSOriginForNonCSSError));
}
std::string error;
if (!CanExecuteScriptOnPage(&error))
return RespondNow(Error(std::move(error)));
if (details_->code) {
if (!IsWebView() && extension()) {
ExtensionsBrowserClient::Get()->NotifyExtensionApiTabExecuteScript(
browser_context(), extension_id(), *details_->code);
}
if (!Execute(*details_->code, &error))
return RespondNow(Error(std::move(error)));
return did_respond() ? AlreadyResponded() : RespondLater();
}
DCHECK(details_->file);
if (!LoadFile(*details_->file, &error))
return RespondNow(Error(std::move(error)));
// LoadFile will respond asynchronously later.
return RespondLater();
}
bool ExecuteCodeFunction::LoadFile(const std::string& file,
std::string* error) {
ExtensionResource resource = extension()->GetResource(file);
if (resource.extension_root().empty() || resource.relative_path().empty()) {
*error = kNoCodeOrFileToExecuteError;
return false;
}
bool is_css_injection = ShouldInsertCSS() || ShouldRemoveCSS();
if (!script_parsing::ValidateMimeTypeFromFileExtension(
resource.relative_path(),
is_css_injection ? script_parsing::ContentScriptType::kCss
: script_parsing::ContentScriptType::kJs,
error)) {
return false;
}
script_url_ = extension()->ResolveExtensionURL(base::EscapePath(file));
bool might_require_localization = is_css_injection;
std::string relative_path = resource.relative_path().AsUTF8Unsafe();
LoadAndLocalizeResources(
*extension(), {std::move(resource)}, might_require_localization,
script_parsing::GetMaxScriptLength(),
base::BindOnce(&ExecuteCodeFunction::DidLoadAndLocalizeFile, this,
relative_path));
return true;
}
void ExecuteCodeFunction::OnExecuteCodeFinished(
std::vector<ScriptExecutor::FrameResult> results) {
DCHECK(!results.empty());
auto root_frame_result = std::ranges::find(
results, root_frame_id_, &ScriptExecutor::FrameResult::frame_id);
CHECK(root_frame_result != results.end());
// We just error out if we never injected in the root frame.
// TODO(devlin): That's a bit odd, because other injections may have
// succeeded. It seems like it might be worth passing back the values
// anyway.
if (!root_frame_result->error.empty()) {
// If the frame never responded (e.g. the frame was removed or didn't
// exist), we provide a different error message for backwards
// compatibility.
if (!root_frame_result->frame_responded) {
root_frame_result->error =
root_frame_id_ == ExtensionApiFrameIdMap::kTopFrameId
? "The tab was closed."
: "The frame was removed.";
}
Respond(Error(std::move(root_frame_result->error)));
return;
}
if (ShouldInsertCSS() || ShouldRemoveCSS()) {
// insertCSS and removeCSS don't have a result argument.
Respond(NoArguments());
return;
}
// Place the root frame result at the beginning.
std::iter_swap(root_frame_result, results.begin());
base::Value::List result_list;
for (auto& result : results) {
if (result.error.empty())
result_list.Append(std::move(result.value));
}
Respond(WithArguments(std::move(result_list)));
}
} // namespace extensions
#endif // EXTENSIONS_BROWSER_API_EXECUTE_CODE_FUNCTION_IMPL_H_
|