blob: 77b892715d4ad128cc561bd2ebe756c9db787018 [file] [log] [blame]
Devlin Cronin0b875672017-10-06 00:49:211// Copyright 2017 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "extensions/renderer/messaging_util.h"
6
7#include <string>
8
9#include "base/logging.h"
Devlin Croninfe7aae62017-11-16 03:49:5510#include "base/metrics/histogram_macros.h"
Devlin Croninc4b07fb2017-11-14 20:26:3411#include "base/strings/stringprintf.h"
Devlin Croninb15f7f02018-01-31 19:37:3212#include "components/crx_file/id_util.h"
Devlin Cronin0b875672017-10-06 00:49:2113#include "extensions/common/api/messaging/message.h"
Devlin Croninc4b07fb2017-11-14 20:26:3414#include "extensions/common/extension.h"
Devlin Croninb1344722017-11-29 02:04:1715#include "extensions/common/manifest.h"
16#include "extensions/common/manifest_handlers/background_info.h"
Mustaq Ahmed4cd69a22018-11-15 16:34:5317#include "extensions/renderer/get_script_context.h"
Devlin Croninc4b07fb2017-11-14 20:26:3418#include "extensions/renderer/script_context.h"
Devlin Cronin0b875672017-10-06 00:49:2119#include "gin/converter.h"
Devlin Cronin37198932017-11-07 20:15:2320#include "gin/dictionary.h"
Mustaq Ahmed4baa9a6e82019-12-20 23:43:4621#include "third_party/blink/public/web/web_local_frame.h"
Devlin Cronin0b875672017-10-06 00:49:2122
23namespace extensions {
24namespace messaging_util {
25
Devlin Croninc4b07fb2017-11-14 20:26:3426namespace {
27
28constexpr char kExtensionIdRequiredErrorTemplate[] =
29 "chrome.%s() called from a webpage must specify an "
30 "Extension ID (string) for its first argument.";
31
Devlin Croninfe7aae62017-11-16 03:49:5532constexpr char kErrorCouldNotSerialize[] = "Could not serialize message.";
33
Devlin Croninc4b07fb2017-11-14 20:26:3434} // namespace
35
Devlin Cronin37198932017-11-07 20:15:2336const char kSendMessageChannel[] = "chrome.runtime.sendMessage";
37const char kSendRequestChannel[] = "chrome.extension.sendRequest";
38
Devlin Cronin182b0892017-11-10 22:22:1639const char kOnMessageEvent[] = "runtime.onMessage";
40const char kOnMessageExternalEvent[] = "runtime.onMessageExternal";
41const char kOnRequestEvent[] = "extension.onRequest";
42const char kOnRequestExternalEvent[] = "extension.onRequestExternal";
43const char kOnConnectEvent[] = "runtime.onConnect";
44const char kOnConnectExternalEvent[] = "runtime.onConnectExternal";
Maksim Ivanov1dd8391e2019-02-26 01:08:1945const char kOnConnectNativeEvent[] = "runtime.onConnectNative";
Devlin Cronin182b0892017-11-10 22:22:1646
Devlin Cronin37198932017-11-07 20:15:2347const int kNoFrameId = -1;
48
Devlin Cronin0b875672017-10-06 00:49:2149std::unique_ptr<Message> MessageFromV8(v8::Local<v8::Context> context,
Devlin Croninfe7aae62017-11-16 03:49:5550 v8::Local<v8::Value> value,
51 std::string* error_out) {
Devlin Cronin0b875672017-10-06 00:49:2152 DCHECK(!value.IsEmpty());
53 v8::Isolate* isolate = context->GetIsolate();
54 v8::Context::Scope context_scope(context);
55
56 // TODO(devlin): For some reason, we don't use the signature for
57 // Port.postMessage when evaluating the parameters. We probably should, but
58 // we don't know how many extensions that may break. It would be good to
59 // investigate, and, ideally, use the signature.
60
61 if (value->IsUndefined()) {
62 // JSON.stringify won't serialized undefined (it returns undefined), but it
63 // will serialized null. We've always converted undefined to null in JS
64 // bindings, so preserve this behavior for now.
65 value = v8::Null(isolate);
66 }
67
68 bool success = false;
69 v8::Local<v8::String> stringified;
70 {
71 v8::TryCatch try_catch(isolate);
72 success = v8::JSON::Stringify(context, value).ToLocal(&stringified);
73 }
74
Devlin Croninfe7aae62017-11-16 03:49:5575 if (!success) {
76 *error_out = kErrorCouldNotSerialize;
77 return nullptr;
Devlin Cronin0b875672017-10-06 00:49:2178 }
79
Mustaq Ahmed4cd69a22018-11-15 16:34:5380 ScriptContext* script_context = GetScriptContextFromV8Context(context);
81 blink::WebLocalFrame* web_frame =
82 script_context ? script_context->web_frame() : nullptr;
83 return MessageFromJSONString(isolate, stringified, error_out, web_frame);
Devlin Croninfe7aae62017-11-16 03:49:5584}
85
Mustaq Ahmed7b61d032018-02-14 21:59:0886std::unique_ptr<Message> MessageFromJSONString(
Dan Elphick38a508052018-07-23 22:19:5387 v8::Isolate* isolate,
Mustaq Ahmed7b61d032018-02-14 21:59:0888 v8::Local<v8::String> json,
89 std::string* error_out,
90 blink::WebLocalFrame* web_frame) {
Devlin Croninfe7aae62017-11-16 03:49:5591 std::string message;
Dan Elphick38a508052018-07-23 22:19:5392 message = gin::V8ToString(isolate, json);
Devlin Croninfe7aae62017-11-16 03:49:5593 // JSON.stringify can fail to produce a string value in one of two ways: it
94 // can throw an exception (as with unserializable objects), or it can return
95 // `undefined` (as with e.g. passing a function). If JSON.stringify returns
96 // `undefined`, the v8 API then coerces it to the string value "undefined".
97 // Check for this, and consider it a failure (since we didn't properly
98 // serialize a value).
99 if (message == "undefined") {
100 *error_out = kErrorCouldNotSerialize;
Devlin Cronin0b875672017-10-06 00:49:21101 return nullptr;
Devlin Croninfe7aae62017-11-16 03:49:55102 }
103
104 size_t message_length = message.length();
105
106 // Max bucket at 512 MB - anything over that, and we don't care.
107 static constexpr int kMaxUmaLength = 1024 * 1024 * 512;
108 static constexpr int kMinUmaLength = 1;
109 static constexpr int kBucketCount = 50;
110 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.Messaging.MessageSize",
111 message_length, kMinUmaLength, kMaxUmaLength,
112 kBucketCount);
113
114 // IPC messages will fail at > 128 MB. Restrict extension messages to 64 MB.
115 // A 64 MB JSON-ifiable object is scary enough as is.
116 static constexpr size_t kMaxMessageLength = 1024 * 1024 * 64;
117 if (message_length > kMaxMessageLength) {
118 *error_out = "Message length exceeded maximum allowed length.";
119 return nullptr;
120 }
Devlin Cronin0b875672017-10-06 00:49:21121
Mustaq Ahmed4baa9a6e82019-12-20 23:43:46122 bool has_transient_user_activation =
123 web_frame ? web_frame->HasTransientUserActivation() : false;
124 return std::make_unique<Message>(message, has_transient_user_activation);
Devlin Cronin0b875672017-10-06 00:49:21125}
126
127v8::Local<v8::Value> MessageToV8(v8::Local<v8::Context> context,
128 const Message& message) {
129 v8::Isolate* isolate = context->GetIsolate();
130 v8::Context::Scope context_scope(context);
131
132 v8::Local<v8::String> v8_message_string =
133 gin::StringToV8(isolate, message.data);
134 v8::Local<v8::Value> parsed_message;
135 v8::TryCatch try_catch(isolate);
136 if (!v8::JSON::Parse(context, v8_message_string).ToLocal(&parsed_message)) {
137 NOTREACHED();
138 return v8::Local<v8::Value>();
139 }
140 return parsed_message;
141}
142
Devlin Cronin37198932017-11-07 20:15:23143int ExtractIntegerId(v8::Local<v8::Value> value) {
Dan Elphickd010a85a2018-08-03 11:32:26144 if (value->IsInt32())
145 return value.As<v8::Int32>()->Value();
146
Devlin Cronin37198932017-11-07 20:15:23147 // Account for -0, which is a valid integer, but is stored as a number in v8.
Dan Elphickd010a85a2018-08-03 11:32:26148 DCHECK(value->IsNumber() && value.As<v8::Number>()->Value() == 0.0);
149 return 0;
Devlin Cronin37198932017-11-07 20:15:23150}
151
Devlin Cronin85efd622017-12-05 19:31:57152MessageOptions ParseMessageOptions(v8::Local<v8::Context> context,
153 v8::Local<v8::Object> v8_options,
154 int flags) {
Devlin Cronin37198932017-11-07 20:15:23155 DCHECK(!v8_options.IsEmpty());
156 DCHECK(!v8_options->IsNull());
157
158 v8::Isolate* isolate = context->GetIsolate();
159
160 MessageOptions options;
161
Devlin Cronin37198932017-11-07 20:15:23162 gin::Dictionary options_dict(isolate, v8_options);
163 if ((flags & PARSE_CHANNEL_NAME) != 0) {
164 v8::Local<v8::Value> v8_channel_name;
Devlin Cronin85efd622017-12-05 19:31:57165 bool success = options_dict.Get("name", &v8_channel_name);
166 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23167
168 if (!v8_channel_name->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57169 DCHECK(v8_channel_name->IsString());
Dan Elphick38a508052018-07-23 22:19:53170 options.channel_name = gin::V8ToString(isolate, v8_channel_name);
Devlin Cronin37198932017-11-07 20:15:23171 }
172 }
173
Devlin Cronin37198932017-11-07 20:15:23174 if ((flags & PARSE_FRAME_ID) != 0) {
175 v8::Local<v8::Value> v8_frame_id;
Devlin Cronin85efd622017-12-05 19:31:57176 bool success = options_dict.Get("frameId", &v8_frame_id);
177 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23178
179 if (!v8_frame_id->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57180 DCHECK(v8_frame_id->IsInt32());
Devlin Croninf054d0e2018-04-21 00:25:33181 int frame_id = v8_frame_id.As<v8::Int32>()->Value();
182 // NOTE(devlin): JS bindings coerce any negative value to -1. For
183 // backwards compatibility, we do the same here.
184 options.frame_id = frame_id < 0 ? -1 : frame_id;
Devlin Cronin37198932017-11-07 20:15:23185 }
186 }
187
Nick Harper41374d52020-01-30 22:36:47188 // Note: the options object may also include an includeTlsChannelId property.
189 // That property has been a no-op since M72. See crbug.com/1045232.
Devlin Cronin85efd622017-12-05 19:31:57190 return options;
Devlin Cronin37198932017-11-07 20:15:23191}
192
Devlin Croninc4b07fb2017-11-14 20:26:34193bool GetTargetExtensionId(ScriptContext* script_context,
194 v8::Local<v8::Value> v8_target_id,
195 const char* method_name,
196 std::string* target_out,
197 std::string* error_out) {
198 DCHECK(!v8_target_id.IsEmpty());
Devlin Cronine4eb1d912018-03-23 14:55:30199 // Argument parsing should guarantee this is null or a string before we reach
200 // this point.
201 DCHECK(v8_target_id->IsNull() || v8_target_id->IsString());
Devlin Croninc4b07fb2017-11-14 20:26:34202
203 std::string target_id;
Devlin Cronine4eb1d912018-03-23 14:55:30204 // If omitted, we use the extension associated with the context.
205 // Note: we deliberately treat the empty string as omitting the id, even
206 // though it's not strictly correct. See https://crbug.com/823577.
207 if (v8_target_id->IsNull() ||
208 (v8_target_id->IsString() &&
209 v8_target_id.As<v8::String>()->Length() == 0)) {
Devlin Croninc4b07fb2017-11-14 20:26:34210 if (!script_context->extension()) {
211 *error_out =
212 base::StringPrintf(kExtensionIdRequiredErrorTemplate, method_name);
213 return false;
214 }
215
Devlin Croninb15f7f02018-01-31 19:37:32216 target_id = script_context->extension()->id();
217 // An extension should never have an invalid id.
218 DCHECK(crx_file::id_util::IdIsValid(target_id));
Devlin Croninc4b07fb2017-11-14 20:26:34219 } else {
220 DCHECK(v8_target_id->IsString());
Dan Elphick38a508052018-07-23 22:19:53221 target_id = gin::V8ToString(script_context->isolate(), v8_target_id);
Devlin Croninb15f7f02018-01-31 19:37:32222 // NOTE(devlin): JS bindings only validate that the extension id is present,
223 // rather than validating its content. This seems better. Let's see how this
224 // goes.
225 if (!crx_file::id_util::IdIsValid(target_id)) {
226 *error_out =
227 base::StringPrintf("Invalid extension id: '%s'", target_id.c_str());
228 return false;
229 }
Devlin Croninc4b07fb2017-11-14 20:26:34230 }
231
Devlin Croninb15f7f02018-01-31 19:37:32232 *target_out = std::move(target_id);
Devlin Croninc4b07fb2017-11-14 20:26:34233 return true;
234}
235
236void MassageSendMessageArguments(
237 v8::Isolate* isolate,
238 bool allow_options_argument,
239 std::vector<v8::Local<v8::Value>>* arguments_out) {
240 base::span<const v8::Local<v8::Value>> arguments = *arguments_out;
241 size_t max_size = allow_options_argument ? 4u : 3u;
242 if (arguments.empty() || arguments.size() > max_size)
243 return;
244
245 v8::Local<v8::Value> target_id = v8::Null(isolate);
246 v8::Local<v8::Value> message = v8::Null(isolate);
247 v8::Local<v8::Value> options;
248 if (allow_options_argument)
249 options = v8::Null(isolate);
250 v8::Local<v8::Value> response_callback = v8::Null(isolate);
251
252 // If the last argument is a function, it is the response callback.
253 // Ignore it for the purposes of further argument parsing.
254 if ((*arguments.rbegin())->IsFunction()) {
255 response_callback = *arguments.rbegin();
256 arguments = arguments.first(arguments.size() - 1);
257 }
258
259 // Re-check for too many arguments after looking for the callback. If there
260 // are, early-out and rely on normal signature parsing to report the error.
261 if (arguments.size() >= max_size)
262 return;
263
264 switch (arguments.size()) {
265 case 0:
266 // Required argument (message) is missing.
267 // Early-out and rely on normal signature parsing to report this error.
268 return;
269 case 1:
270 // Argument must be the message.
271 message = arguments[0];
272 break;
Devlin Cronin7c723eb62018-04-13 19:38:26273 case 2: {
274 // Assume the first argument is the ID if we don't expect options, or if
275 // the argument could match the ID parameter.
276 // ID could be either a string, or null/undefined (since it's optional).
277 bool could_match_id =
278 arguments[0]->IsString() || arguments[0]->IsNullOrUndefined();
279 if (!allow_options_argument || could_match_id) {
Devlin Croninc4b07fb2017-11-14 20:26:34280 target_id = arguments[0];
281 message = arguments[1];
Devlin Cronin7c723eb62018-04-13 19:38:26282 } else { // Otherwise, the meaning is (message, options).
Devlin Croninc4b07fb2017-11-14 20:26:34283 message = arguments[0];
284 options = arguments[1];
285 }
286 break;
Devlin Cronin7c723eb62018-04-13 19:38:26287 }
Devlin Croninc4b07fb2017-11-14 20:26:34288 case 3:
289 DCHECK(allow_options_argument);
290 // The meaning in this case is unambiguous.
291 target_id = arguments[0];
292 message = arguments[1];
293 options = arguments[2];
294 break;
295 default:
296 NOTREACHED();
297 }
298
299 if (allow_options_argument)
300 *arguments_out = {target_id, message, options, response_callback};
301 else
302 *arguments_out = {target_id, message, response_callback};
303}
304
Devlin Croninb1344722017-11-29 02:04:17305bool IsSendRequestDisabled(ScriptContext* script_context) {
306 const Extension* extension = script_context->extension();
307 return extension && Manifest::IsUnpackedLocation(extension->location()) &&
308 BackgroundInfo::HasLazyBackgroundPage(extension);
309}
310
Devlin Cronin0b875672017-10-06 00:49:21311} // namespace messaging_util
312} // namespace extensions