blob: 77d7ad3cf207ceff4d9df8c9d16a2cad9558747a [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"
Devlin Croninc4b07fb2017-11-14 20:26:3417#include "extensions/renderer/script_context.h"
Devlin Cronin0b875672017-10-06 00:49:2118#include "gin/converter.h"
Devlin Cronin37198932017-11-07 20:15:2319#include "gin/dictionary.h"
Blink Reformata30d4232018-04-07 15:31:0620#include "third_party/blink/public/web/web_user_gesture_indicator.h"
Devlin Cronin0b875672017-10-06 00:49:2121
22namespace extensions {
23namespace messaging_util {
24
Devlin Croninc4b07fb2017-11-14 20:26:3425namespace {
26
27constexpr char kExtensionIdRequiredErrorTemplate[] =
28 "chrome.%s() called from a webpage must specify an "
29 "Extension ID (string) for its first argument.";
30
Devlin Croninfe7aae62017-11-16 03:49:5531constexpr char kErrorCouldNotSerialize[] = "Could not serialize message.";
32
Devlin Croninc4b07fb2017-11-14 20:26:3433} // namespace
34
Devlin Cronin37198932017-11-07 20:15:2335const char kSendMessageChannel[] = "chrome.runtime.sendMessage";
36const char kSendRequestChannel[] = "chrome.extension.sendRequest";
37
Devlin Cronin182b0892017-11-10 22:22:1638const char kOnMessageEvent[] = "runtime.onMessage";
39const char kOnMessageExternalEvent[] = "runtime.onMessageExternal";
40const char kOnRequestEvent[] = "extension.onRequest";
41const char kOnRequestExternalEvent[] = "extension.onRequestExternal";
42const char kOnConnectEvent[] = "runtime.onConnect";
43const char kOnConnectExternalEvent[] = "runtime.onConnectExternal";
44
Devlin Cronin37198932017-11-07 20:15:2345const int kNoFrameId = -1;
46
Devlin Cronin0b875672017-10-06 00:49:2147std::unique_ptr<Message> MessageFromV8(v8::Local<v8::Context> context,
Devlin Croninfe7aae62017-11-16 03:49:5548 v8::Local<v8::Value> value,
49 std::string* error_out) {
Devlin Cronin0b875672017-10-06 00:49:2150 DCHECK(!value.IsEmpty());
51 v8::Isolate* isolate = context->GetIsolate();
52 v8::Context::Scope context_scope(context);
53
54 // TODO(devlin): For some reason, we don't use the signature for
55 // Port.postMessage when evaluating the parameters. We probably should, but
56 // we don't know how many extensions that may break. It would be good to
57 // investigate, and, ideally, use the signature.
58
59 if (value->IsUndefined()) {
60 // JSON.stringify won't serialized undefined (it returns undefined), but it
61 // will serialized null. We've always converted undefined to null in JS
62 // bindings, so preserve this behavior for now.
63 value = v8::Null(isolate);
64 }
65
66 bool success = false;
67 v8::Local<v8::String> stringified;
68 {
69 v8::TryCatch try_catch(isolate);
70 success = v8::JSON::Stringify(context, value).ToLocal(&stringified);
71 }
72
Devlin Croninfe7aae62017-11-16 03:49:5573 if (!success) {
74 *error_out = kErrorCouldNotSerialize;
75 return nullptr;
Devlin Cronin0b875672017-10-06 00:49:2176 }
77
Dan Elphick38a508052018-07-23 22:19:5378 return MessageFromJSONString(isolate, stringified, error_out);
Devlin Croninfe7aae62017-11-16 03:49:5579}
80
Mustaq Ahmed7b61d032018-02-14 21:59:0881std::unique_ptr<Message> MessageFromJSONString(
Dan Elphick38a508052018-07-23 22:19:5382 v8::Isolate* isolate,
Mustaq Ahmed7b61d032018-02-14 21:59:0883 v8::Local<v8::String> json,
84 std::string* error_out,
85 blink::WebLocalFrame* web_frame) {
Devlin Croninfe7aae62017-11-16 03:49:5586 std::string message;
Dan Elphick38a508052018-07-23 22:19:5387 message = gin::V8ToString(isolate, json);
Devlin Croninfe7aae62017-11-16 03:49:5588 // JSON.stringify can fail to produce a string value in one of two ways: it
89 // can throw an exception (as with unserializable objects), or it can return
90 // `undefined` (as with e.g. passing a function). If JSON.stringify returns
91 // `undefined`, the v8 API then coerces it to the string value "undefined".
92 // Check for this, and consider it a failure (since we didn't properly
93 // serialize a value).
94 if (message == "undefined") {
95 *error_out = kErrorCouldNotSerialize;
Devlin Cronin0b875672017-10-06 00:49:2196 return nullptr;
Devlin Croninfe7aae62017-11-16 03:49:5597 }
98
99 size_t message_length = message.length();
100
101 // Max bucket at 512 MB - anything over that, and we don't care.
102 static constexpr int kMaxUmaLength = 1024 * 1024 * 512;
103 static constexpr int kMinUmaLength = 1;
104 static constexpr int kBucketCount = 50;
105 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.Messaging.MessageSize",
106 message_length, kMinUmaLength, kMaxUmaLength,
107 kBucketCount);
108
109 // IPC messages will fail at > 128 MB. Restrict extension messages to 64 MB.
110 // A 64 MB JSON-ifiable object is scary enough as is.
111 static constexpr size_t kMaxMessageLength = 1024 * 1024 * 64;
112 if (message_length > kMaxMessageLength) {
113 *error_out = "Message length exceeded maximum allowed length.";
114 return nullptr;
115 }
Devlin Cronin0b875672017-10-06 00:49:21116
117 return std::make_unique<Message>(
Mustaq Ahmed7b61d032018-02-14 21:59:08118 message,
119 blink::WebUserGestureIndicator::IsProcessingUserGesture(web_frame));
Devlin Cronin0b875672017-10-06 00:49:21120}
121
122v8::Local<v8::Value> MessageToV8(v8::Local<v8::Context> context,
123 const Message& message) {
124 v8::Isolate* isolate = context->GetIsolate();
125 v8::Context::Scope context_scope(context);
126
127 v8::Local<v8::String> v8_message_string =
128 gin::StringToV8(isolate, message.data);
129 v8::Local<v8::Value> parsed_message;
130 v8::TryCatch try_catch(isolate);
131 if (!v8::JSON::Parse(context, v8_message_string).ToLocal(&parsed_message)) {
132 NOTREACHED();
133 return v8::Local<v8::Value>();
134 }
135 return parsed_message;
136}
137
Devlin Cronin37198932017-11-07 20:15:23138int ExtractIntegerId(v8::Local<v8::Value> value) {
139 // Account for -0, which is a valid integer, but is stored as a number in v8.
140 DCHECK(value->IsNumber() &&
141 (value->IsInt32() || value.As<v8::Number>()->Value() == 0.0));
142 return value->Int32Value();
143}
144
Devlin Cronin85efd622017-12-05 19:31:57145MessageOptions ParseMessageOptions(v8::Local<v8::Context> context,
146 v8::Local<v8::Object> v8_options,
147 int flags) {
Devlin Cronin37198932017-11-07 20:15:23148 DCHECK(!v8_options.IsEmpty());
149 DCHECK(!v8_options->IsNull());
150
151 v8::Isolate* isolate = context->GetIsolate();
152
153 MessageOptions options;
154
Devlin Cronin37198932017-11-07 20:15:23155 gin::Dictionary options_dict(isolate, v8_options);
156 if ((flags & PARSE_CHANNEL_NAME) != 0) {
157 v8::Local<v8::Value> v8_channel_name;
Devlin Cronin85efd622017-12-05 19:31:57158 bool success = options_dict.Get("name", &v8_channel_name);
159 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23160
161 if (!v8_channel_name->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57162 DCHECK(v8_channel_name->IsString());
Dan Elphick38a508052018-07-23 22:19:53163 options.channel_name = gin::V8ToString(isolate, v8_channel_name);
Devlin Cronin37198932017-11-07 20:15:23164 }
165 }
166
167 if ((flags & PARSE_INCLUDE_TLS_CHANNEL_ID) != 0) {
168 v8::Local<v8::Value> v8_include_tls_channel_id;
Devlin Cronin85efd622017-12-05 19:31:57169 bool success =
170 options_dict.Get("includeTlsChannelId", &v8_include_tls_channel_id);
171 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23172
173 if (!v8_include_tls_channel_id->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57174 DCHECK(v8_include_tls_channel_id->IsBoolean());
Devlin Cronin37198932017-11-07 20:15:23175 options.include_tls_channel_id =
176 v8_include_tls_channel_id->BooleanValue();
177 }
178 }
179
180 if ((flags & PARSE_FRAME_ID) != 0) {
181 v8::Local<v8::Value> v8_frame_id;
Devlin Cronin85efd622017-12-05 19:31:57182 bool success = options_dict.Get("frameId", &v8_frame_id);
183 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23184
185 if (!v8_frame_id->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57186 DCHECK(v8_frame_id->IsInt32());
Devlin Croninf054d0e2018-04-21 00:25:33187 int frame_id = v8_frame_id.As<v8::Int32>()->Value();
188 // NOTE(devlin): JS bindings coerce any negative value to -1. For
189 // backwards compatibility, we do the same here.
190 options.frame_id = frame_id < 0 ? -1 : frame_id;
Devlin Cronin37198932017-11-07 20:15:23191 }
192 }
193
Devlin Cronin85efd622017-12-05 19:31:57194 return options;
Devlin Cronin37198932017-11-07 20:15:23195}
196
Devlin Croninc4b07fb2017-11-14 20:26:34197bool GetTargetExtensionId(ScriptContext* script_context,
198 v8::Local<v8::Value> v8_target_id,
199 const char* method_name,
200 std::string* target_out,
201 std::string* error_out) {
202 DCHECK(!v8_target_id.IsEmpty());
Devlin Cronine4eb1d912018-03-23 14:55:30203 // Argument parsing should guarantee this is null or a string before we reach
204 // this point.
205 DCHECK(v8_target_id->IsNull() || v8_target_id->IsString());
Devlin Croninc4b07fb2017-11-14 20:26:34206
207 std::string target_id;
Devlin Cronine4eb1d912018-03-23 14:55:30208 // If omitted, we use the extension associated with the context.
209 // Note: we deliberately treat the empty string as omitting the id, even
210 // though it's not strictly correct. See https://crbug.com/823577.
211 if (v8_target_id->IsNull() ||
212 (v8_target_id->IsString() &&
213 v8_target_id.As<v8::String>()->Length() == 0)) {
Devlin Croninc4b07fb2017-11-14 20:26:34214 if (!script_context->extension()) {
215 *error_out =
216 base::StringPrintf(kExtensionIdRequiredErrorTemplate, method_name);
217 return false;
218 }
219
Devlin Croninb15f7f02018-01-31 19:37:32220 target_id = script_context->extension()->id();
221 // An extension should never have an invalid id.
222 DCHECK(crx_file::id_util::IdIsValid(target_id));
Devlin Croninc4b07fb2017-11-14 20:26:34223 } else {
224 DCHECK(v8_target_id->IsString());
Dan Elphick38a508052018-07-23 22:19:53225 target_id = gin::V8ToString(script_context->isolate(), v8_target_id);
Devlin Croninb15f7f02018-01-31 19:37:32226 // NOTE(devlin): JS bindings only validate that the extension id is present,
227 // rather than validating its content. This seems better. Let's see how this
228 // goes.
229 if (!crx_file::id_util::IdIsValid(target_id)) {
230 *error_out =
231 base::StringPrintf("Invalid extension id: '%s'", target_id.c_str());
232 return false;
233 }
Devlin Croninc4b07fb2017-11-14 20:26:34234 }
235
Devlin Croninb15f7f02018-01-31 19:37:32236 *target_out = std::move(target_id);
Devlin Croninc4b07fb2017-11-14 20:26:34237 return true;
238}
239
240void MassageSendMessageArguments(
241 v8::Isolate* isolate,
242 bool allow_options_argument,
243 std::vector<v8::Local<v8::Value>>* arguments_out) {
244 base::span<const v8::Local<v8::Value>> arguments = *arguments_out;
245 size_t max_size = allow_options_argument ? 4u : 3u;
246 if (arguments.empty() || arguments.size() > max_size)
247 return;
248
249 v8::Local<v8::Value> target_id = v8::Null(isolate);
250 v8::Local<v8::Value> message = v8::Null(isolate);
251 v8::Local<v8::Value> options;
252 if (allow_options_argument)
253 options = v8::Null(isolate);
254 v8::Local<v8::Value> response_callback = v8::Null(isolate);
255
256 // If the last argument is a function, it is the response callback.
257 // Ignore it for the purposes of further argument parsing.
258 if ((*arguments.rbegin())->IsFunction()) {
259 response_callback = *arguments.rbegin();
260 arguments = arguments.first(arguments.size() - 1);
261 }
262
263 // Re-check for too many arguments after looking for the callback. If there
264 // are, early-out and rely on normal signature parsing to report the error.
265 if (arguments.size() >= max_size)
266 return;
267
268 switch (arguments.size()) {
269 case 0:
270 // Required argument (message) is missing.
271 // Early-out and rely on normal signature parsing to report this error.
272 return;
273 case 1:
274 // Argument must be the message.
275 message = arguments[0];
276 break;
Devlin Cronin7c723eb62018-04-13 19:38:26277 case 2: {
278 // Assume the first argument is the ID if we don't expect options, or if
279 // the argument could match the ID parameter.
280 // ID could be either a string, or null/undefined (since it's optional).
281 bool could_match_id =
282 arguments[0]->IsString() || arguments[0]->IsNullOrUndefined();
283 if (!allow_options_argument || could_match_id) {
Devlin Croninc4b07fb2017-11-14 20:26:34284 target_id = arguments[0];
285 message = arguments[1];
Devlin Cronin7c723eb62018-04-13 19:38:26286 } else { // Otherwise, the meaning is (message, options).
Devlin Croninc4b07fb2017-11-14 20:26:34287 message = arguments[0];
288 options = arguments[1];
289 }
290 break;
Devlin Cronin7c723eb62018-04-13 19:38:26291 }
Devlin Croninc4b07fb2017-11-14 20:26:34292 case 3:
293 DCHECK(allow_options_argument);
294 // The meaning in this case is unambiguous.
295 target_id = arguments[0];
296 message = arguments[1];
297 options = arguments[2];
298 break;
299 default:
300 NOTREACHED();
301 }
302
303 if (allow_options_argument)
304 *arguments_out = {target_id, message, options, response_callback};
305 else
306 *arguments_out = {target_id, message, response_callback};
307}
308
Devlin Croninb1344722017-11-29 02:04:17309bool IsSendRequestDisabled(ScriptContext* script_context) {
310 const Extension* extension = script_context->extension();
311 return extension && Manifest::IsUnpackedLocation(extension->location()) &&
312 BackgroundInfo::HasLazyBackgroundPage(extension);
313}
314
Devlin Cronin0b875672017-10-06 00:49:21315} // namespace messaging_util
316} // namespace extensions