blob: b96dff1282e977bb7f94ee29e6945eb4612345ad [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 Cronin0b875672017-10-06 00:49:2112#include "extensions/common/api/messaging/message.h"
Devlin Croninc4b07fb2017-11-14 20:26:3413#include "extensions/common/extension.h"
Devlin Croninb1344722017-11-29 02:04:1714#include "extensions/common/manifest.h"
15#include "extensions/common/manifest_handlers/background_info.h"
Devlin Croninc4b07fb2017-11-14 20:26:3416#include "extensions/renderer/script_context.h"
Devlin Cronin0b875672017-10-06 00:49:2117#include "gin/converter.h"
Devlin Cronin37198932017-11-07 20:15:2318#include "gin/dictionary.h"
Devlin Cronin0b875672017-10-06 00:49:2119#include "third_party/WebKit/public/web/WebUserGestureIndicator.h"
20
21namespace extensions {
22namespace messaging_util {
23
Devlin Croninc4b07fb2017-11-14 20:26:3424namespace {
25
26constexpr char kExtensionIdRequiredErrorTemplate[] =
27 "chrome.%s() called from a webpage must specify an "
28 "Extension ID (string) for its first argument.";
29
Devlin Croninfe7aae62017-11-16 03:49:5530constexpr char kErrorCouldNotSerialize[] = "Could not serialize message.";
31
Devlin Croninc4b07fb2017-11-14 20:26:3432} // namespace
33
Devlin Cronin37198932017-11-07 20:15:2334const char kSendMessageChannel[] = "chrome.runtime.sendMessage";
35const char kSendRequestChannel[] = "chrome.extension.sendRequest";
36
Devlin Cronin182b0892017-11-10 22:22:1637const char kOnMessageEvent[] = "runtime.onMessage";
38const char kOnMessageExternalEvent[] = "runtime.onMessageExternal";
39const char kOnRequestEvent[] = "extension.onRequest";
40const char kOnRequestExternalEvent[] = "extension.onRequestExternal";
41const char kOnConnectEvent[] = "runtime.onConnect";
42const char kOnConnectExternalEvent[] = "runtime.onConnectExternal";
43
Devlin Cronin37198932017-11-07 20:15:2344const int kNoFrameId = -1;
45
Devlin Cronin0b875672017-10-06 00:49:2146std::unique_ptr<Message> MessageFromV8(v8::Local<v8::Context> context,
Devlin Croninfe7aae62017-11-16 03:49:5547 v8::Local<v8::Value> value,
48 std::string* error_out) {
Devlin Cronin0b875672017-10-06 00:49:2149 DCHECK(!value.IsEmpty());
50 v8::Isolate* isolate = context->GetIsolate();
51 v8::Context::Scope context_scope(context);
52
53 // TODO(devlin): For some reason, we don't use the signature for
54 // Port.postMessage when evaluating the parameters. We probably should, but
55 // we don't know how many extensions that may break. It would be good to
56 // investigate, and, ideally, use the signature.
57
58 if (value->IsUndefined()) {
59 // JSON.stringify won't serialized undefined (it returns undefined), but it
60 // will serialized null. We've always converted undefined to null in JS
61 // bindings, so preserve this behavior for now.
62 value = v8::Null(isolate);
63 }
64
65 bool success = false;
66 v8::Local<v8::String> stringified;
67 {
68 v8::TryCatch try_catch(isolate);
69 success = v8::JSON::Stringify(context, value).ToLocal(&stringified);
70 }
71
Devlin Croninfe7aae62017-11-16 03:49:5572 if (!success) {
73 *error_out = kErrorCouldNotSerialize;
74 return nullptr;
Devlin Cronin0b875672017-10-06 00:49:2175 }
76
Devlin Croninfe7aae62017-11-16 03:49:5577 return MessageFromJSONString(stringified, error_out);
78}
79
80std::unique_ptr<Message> MessageFromJSONString(v8::Local<v8::String> json,
81 std::string* error_out) {
82 std::string message;
83 message = gin::V8ToString(json);
84 // JSON.stringify can fail to produce a string value in one of two ways: it
85 // can throw an exception (as with unserializable objects), or it can return
86 // `undefined` (as with e.g. passing a function). If JSON.stringify returns
87 // `undefined`, the v8 API then coerces it to the string value "undefined".
88 // Check for this, and consider it a failure (since we didn't properly
89 // serialize a value).
90 if (message == "undefined") {
91 *error_out = kErrorCouldNotSerialize;
Devlin Cronin0b875672017-10-06 00:49:2192 return nullptr;
Devlin Croninfe7aae62017-11-16 03:49:5593 }
94
95 size_t message_length = message.length();
96
97 // Max bucket at 512 MB - anything over that, and we don't care.
98 static constexpr int kMaxUmaLength = 1024 * 1024 * 512;
99 static constexpr int kMinUmaLength = 1;
100 static constexpr int kBucketCount = 50;
101 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.Messaging.MessageSize",
102 message_length, kMinUmaLength, kMaxUmaLength,
103 kBucketCount);
104
105 // IPC messages will fail at > 128 MB. Restrict extension messages to 64 MB.
106 // A 64 MB JSON-ifiable object is scary enough as is.
107 static constexpr size_t kMaxMessageLength = 1024 * 1024 * 64;
108 if (message_length > kMaxMessageLength) {
109 *error_out = "Message length exceeded maximum allowed length.";
110 return nullptr;
111 }
Devlin Cronin0b875672017-10-06 00:49:21112
113 return std::make_unique<Message>(
114 message, blink::WebUserGestureIndicator::IsProcessingUserGesture());
115}
116
117v8::Local<v8::Value> MessageToV8(v8::Local<v8::Context> context,
118 const Message& message) {
119 v8::Isolate* isolate = context->GetIsolate();
120 v8::Context::Scope context_scope(context);
121
122 v8::Local<v8::String> v8_message_string =
123 gin::StringToV8(isolate, message.data);
124 v8::Local<v8::Value> parsed_message;
125 v8::TryCatch try_catch(isolate);
126 if (!v8::JSON::Parse(context, v8_message_string).ToLocal(&parsed_message)) {
127 NOTREACHED();
128 return v8::Local<v8::Value>();
129 }
130 return parsed_message;
131}
132
Devlin Cronin37198932017-11-07 20:15:23133int ExtractIntegerId(v8::Local<v8::Value> value) {
134 // Account for -0, which is a valid integer, but is stored as a number in v8.
135 DCHECK(value->IsNumber() &&
136 (value->IsInt32() || value.As<v8::Number>()->Value() == 0.0));
137 return value->Int32Value();
138}
139
Devlin Cronin85efd622017-12-05 19:31:57140MessageOptions ParseMessageOptions(v8::Local<v8::Context> context,
141 v8::Local<v8::Object> v8_options,
142 int flags) {
Devlin Cronin37198932017-11-07 20:15:23143 DCHECK(!v8_options.IsEmpty());
144 DCHECK(!v8_options->IsNull());
145
146 v8::Isolate* isolate = context->GetIsolate();
147
148 MessageOptions options;
149
Devlin Cronin37198932017-11-07 20:15:23150 gin::Dictionary options_dict(isolate, v8_options);
151 if ((flags & PARSE_CHANNEL_NAME) != 0) {
152 v8::Local<v8::Value> v8_channel_name;
Devlin Cronin85efd622017-12-05 19:31:57153 bool success = options_dict.Get("name", &v8_channel_name);
154 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23155
156 if (!v8_channel_name->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57157 DCHECK(v8_channel_name->IsString());
Devlin Cronin37198932017-11-07 20:15:23158 options.channel_name = gin::V8ToString(v8_channel_name);
159 }
160 }
161
162 if ((flags & PARSE_INCLUDE_TLS_CHANNEL_ID) != 0) {
163 v8::Local<v8::Value> v8_include_tls_channel_id;
Devlin Cronin85efd622017-12-05 19:31:57164 bool success =
165 options_dict.Get("includeTlsChannelId", &v8_include_tls_channel_id);
166 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23167
168 if (!v8_include_tls_channel_id->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57169 DCHECK(v8_include_tls_channel_id->IsBoolean());
Devlin Cronin37198932017-11-07 20:15:23170 options.include_tls_channel_id =
171 v8_include_tls_channel_id->BooleanValue();
172 }
173 }
174
175 if ((flags & PARSE_FRAME_ID) != 0) {
176 v8::Local<v8::Value> v8_frame_id;
Devlin Cronin85efd622017-12-05 19:31:57177 bool success = options_dict.Get("frameId", &v8_frame_id);
178 DCHECK(success);
Devlin Cronin37198932017-11-07 20:15:23179
180 if (!v8_frame_id->IsUndefined()) {
Devlin Cronin85efd622017-12-05 19:31:57181 DCHECK(v8_frame_id->IsInt32());
Devlin Cronin37198932017-11-07 20:15:23182 options.frame_id = v8_frame_id->Int32Value();
183 }
184 }
185
Devlin Cronin85efd622017-12-05 19:31:57186 return options;
Devlin Cronin37198932017-11-07 20:15:23187}
188
Devlin Croninc4b07fb2017-11-14 20:26:34189bool GetTargetExtensionId(ScriptContext* script_context,
190 v8::Local<v8::Value> v8_target_id,
191 const char* method_name,
192 std::string* target_out,
193 std::string* error_out) {
194 DCHECK(!v8_target_id.IsEmpty());
195
196 std::string target_id;
197 if (v8_target_id->IsNull()) {
198 if (!script_context->extension()) {
199 *error_out =
200 base::StringPrintf(kExtensionIdRequiredErrorTemplate, method_name);
201 return false;
202 }
203
204 *target_out = script_context->extension()->id();
205 } else {
206 DCHECK(v8_target_id->IsString());
207 *target_out = gin::V8ToString(v8_target_id);
208 }
209
210 return true;
211}
212
213void MassageSendMessageArguments(
214 v8::Isolate* isolate,
215 bool allow_options_argument,
216 std::vector<v8::Local<v8::Value>>* arguments_out) {
217 base::span<const v8::Local<v8::Value>> arguments = *arguments_out;
218 size_t max_size = allow_options_argument ? 4u : 3u;
219 if (arguments.empty() || arguments.size() > max_size)
220 return;
221
222 v8::Local<v8::Value> target_id = v8::Null(isolate);
223 v8::Local<v8::Value> message = v8::Null(isolate);
224 v8::Local<v8::Value> options;
225 if (allow_options_argument)
226 options = v8::Null(isolate);
227 v8::Local<v8::Value> response_callback = v8::Null(isolate);
228
229 // If the last argument is a function, it is the response callback.
230 // Ignore it for the purposes of further argument parsing.
231 if ((*arguments.rbegin())->IsFunction()) {
232 response_callback = *arguments.rbegin();
233 arguments = arguments.first(arguments.size() - 1);
234 }
235
236 // Re-check for too many arguments after looking for the callback. If there
237 // are, early-out and rely on normal signature parsing to report the error.
238 if (arguments.size() >= max_size)
239 return;
240
241 switch (arguments.size()) {
242 case 0:
243 // Required argument (message) is missing.
244 // Early-out and rely on normal signature parsing to report this error.
245 return;
246 case 1:
247 // Argument must be the message.
248 message = arguments[0];
249 break;
250 case 2:
251 // Assume the meaning is (id, message) if id would be a string, or if
252 // the options argument isn't expected.
253 // Otherwise the meaning is (message, options).
254 if (!allow_options_argument || arguments[0]->IsString()) {
255 target_id = arguments[0];
256 message = arguments[1];
257 } else {
258 message = arguments[0];
259 options = arguments[1];
260 }
261 break;
262 case 3:
263 DCHECK(allow_options_argument);
264 // The meaning in this case is unambiguous.
265 target_id = arguments[0];
266 message = arguments[1];
267 options = arguments[2];
268 break;
269 default:
270 NOTREACHED();
271 }
272
273 if (allow_options_argument)
274 *arguments_out = {target_id, message, options, response_callback};
275 else
276 *arguments_out = {target_id, message, response_callback};
277}
278
Devlin Croninb1344722017-11-29 02:04:17279bool IsSendRequestDisabled(ScriptContext* script_context) {
280 const Extension* extension = script_context->extension();
281 return extension && Manifest::IsUnpackedLocation(extension->location()) &&
282 BackgroundInfo::HasLazyBackgroundPage(extension);
283}
284
Devlin Cronin0b875672017-10-06 00:49:21285} // namespace messaging_util
286} // namespace extensions