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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
|
// Copyright (c) 2009 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 <map>
#include <set>
#include <string>
#include <vector>
#include "chrome/renderer/extensions/extension_process_bindings.h"
#include "base/singleton.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_message_bundle.h"
#include "chrome/common/extensions/url_pattern.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "chrome/renderer/extensions/bindings_utils.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/js_only_v8_extensions.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/renderer/render_view.h"
#include "grit/common_resources.h"
#include "grit/renderer_resources.h"
#include "webkit/api/public/WebFrame.h"
#include "webkit/api/public/WebURL.h"
#include "webkit/api/public/WebKit.h"
using bindings_utils::GetStringResource;
using bindings_utils::ContextInfo;
using bindings_utils::ContextList;
using bindings_utils::GetContexts;
using bindings_utils::GetPendingRequestMap;
using bindings_utils::PendingRequest;
using bindings_utils::PendingRequestMap;
using bindings_utils::ExtensionBase;
using WebKit::WebFrame;
namespace {
// A map of extension ID to vector of page action ids.
typedef std::map< std::string, std::vector<std::string> > PageActionIdMap;
// A map of permission name to whether its enabled for this extension.
typedef std::map<std::string, bool> PermissionsMap;
// A map of extension ID to permissions map.
typedef std::map<std::string, PermissionsMap> ExtensionPermissionsMap;
// A map of message name to message.
typedef std::map<std::string, std::string> L10nMessagesMap;
// A map of extension ID to l10n message map.
typedef std::map<std::string, L10nMessagesMap >
ExtensionToL10nMessagesMap;
const char kExtensionName[] = "chrome/ExtensionProcessBindings";
const char* kExtensionDeps[] = {
BaseJsV8Extension::kName,
EventBindings::kName,
JsonSchemaJsV8Extension::kName,
RendererExtensionBindings::kName,
ExtensionApiTestV8Extension::kName,
};
struct SingletonData {
std::set<std::string> function_names_;
PageActionIdMap page_action_ids_;
ExtensionPermissionsMap permissions_;
ExtensionToL10nMessagesMap extension_l10n_messages_map_;
};
static std::set<std::string>* GetFunctionNameSet() {
return &Singleton<SingletonData>()->function_names_;
}
static PageActionIdMap* GetPageActionMap() {
return &Singleton<SingletonData>()->page_action_ids_;
}
static PermissionsMap* GetPermissionsMap(const std::string& extension_id) {
return &Singleton<SingletonData>()->permissions_[extension_id];
}
static ExtensionToL10nMessagesMap* GetExtensionToL10nMessagesMap() {
return &Singleton<SingletonData>()->extension_l10n_messages_map_;
}
static L10nMessagesMap* GetL10nMessagesMap(const std::string extension_id) {
ExtensionToL10nMessagesMap::iterator it =
Singleton<SingletonData>()->extension_l10n_messages_map_.find(extension_id);
if (it != Singleton<SingletonData>()->extension_l10n_messages_map_.end()) {
return &(it->second);
} else {
return NULL;
}
}
class ExtensionImpl : public ExtensionBase {
public:
ExtensionImpl() : ExtensionBase(
kExtensionName, GetStringResource<IDR_EXTENSION_PROCESS_BINDINGS_JS>(),
arraysize(kExtensionDeps), kExtensionDeps) {}
static void SetFunctionNames(const std::vector<std::string>& names) {
std::set<std::string>* name_set = GetFunctionNameSet();
for (size_t i = 0; i < names.size(); ++i) {
name_set->insert(names[i]);
}
}
// Note: do not call this function before or during the chromeHidden.onLoad
// event dispatch. The URL might not have been committed yet and might not
// be an extension URL.
static std::string ExtensionIdForCurrentContext() {
RenderView* renderview = bindings_utils::GetRenderViewForCurrentContext();
DCHECK(renderview);
GURL url = renderview->webview()->mainFrame()->url();
if (url.SchemeIs(chrome::kExtensionScheme))
return url.host();
return std::string();
}
virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
v8::Handle<v8::String> name) {
if (name->Equals(v8::String::New("GetExtensionAPIDefinition"))) {
return v8::FunctionTemplate::New(GetExtensionAPIDefinition);
} else if (name->Equals(v8::String::New("GetExtensionViews"))) {
return v8::FunctionTemplate::New(GetExtensionViews);
} else if (name->Equals(v8::String::New("GetNextRequestId"))) {
return v8::FunctionTemplate::New(GetNextRequestId);
} else if (name->Equals(v8::String::New("OpenChannelToTab"))) {
return v8::FunctionTemplate::New(OpenChannelToTab);
} else if (name->Equals(v8::String::New("GetCurrentPageActions"))) {
return v8::FunctionTemplate::New(GetCurrentPageActions);
} else if (name->Equals(v8::String::New("StartRequest"))) {
return v8::FunctionTemplate::New(StartRequest);
} else if (name->Equals(v8::String::New("GetRenderViewId"))) {
return v8::FunctionTemplate::New(GetRenderViewId);
} else if (name->Equals(v8::String::New("GetL10nMessage"))) {
return v8::FunctionTemplate::New(GetL10nMessage);
}
return ExtensionBase::GetNativeFunction(name);
}
private:
static v8::Handle<v8::Value> GetExtensionAPIDefinition(
const v8::Arguments& args) {
return v8::String::New(GetStringResource<IDR_EXTENSION_API_JSON>());
}
// Returns true is |type| "isa" |match|.
static bool ViewTypeMatches(ViewType::Type type, ViewType::Type match) {
if (type == match)
return true;
// INVALID means match all.
if (match == ViewType::INVALID)
return true;
// TODO(erikkay) for now, special case mole as a type of toolstrip.
// Perhaps this isn't the right long-term thing to do.
if (match == ViewType::EXTENSION_TOOLSTRIP &&
type == ViewType::EXTENSION_MOLE) {
return true;
}
return false;
}
static v8::Handle<v8::Value> GetExtensionViews(const v8::Arguments& args) {
if (args.Length() != 2)
return v8::Undefined();
if (!args[0]->IsInt32() || !args[1]->IsString())
return v8::Undefined();
// |browser_window_id| == -1 means getting views attached to any browser
// window.
int browser_window_id = args[0]->Int32Value();
std::string view_type_string = *v8::String::Utf8Value(args[1]->ToString());
// |view_type| == ViewType::INVALID means getting any type of views.
ViewType::Type view_type = ViewType::INVALID;
if (view_type_string == "TOOLSTRIP") {
view_type = ViewType::EXTENSION_TOOLSTRIP;
} else if (view_type_string == "MOLE") {
view_type = ViewType::EXTENSION_MOLE;
} else if (view_type_string == "BACKGROUND") {
view_type = ViewType::EXTENSION_BACKGROUND_PAGE;
} else if (view_type_string == "TAB") {
view_type = ViewType::TAB_CONTENTS;
} else if (view_type_string != "ALL") {
return v8::Undefined();
}
v8::Local<v8::Array> views = v8::Array::New();
int index = 0;
RenderView::RenderViewSet* render_view_set_pointer =
Singleton<RenderView::RenderViewSet>::get();
DCHECK(render_view_set_pointer->render_view_set_.size() > 0);
v8::Local<v8::Value> window;
std::string current_extension_id = ExtensionIdForCurrentContext();
std::set<RenderView* >::iterator it =
render_view_set_pointer->render_view_set_.begin();
for (; it != render_view_set_pointer->render_view_set_.end(); ++it) {
if (!ViewTypeMatches((*it)->view_type(), view_type))
continue;
GURL url = (*it)->webview()->mainFrame()->url();
if (!url.SchemeIs(chrome::kExtensionScheme))
continue;
std::string extension_id = url.host();
if (extension_id != current_extension_id)
continue;
if (browser_window_id != -1 &&
(*it)->browser_window_id() != browser_window_id) {
continue;
}
v8::Local<v8::Context> context =
(*it)->webview()->mainFrame()->mainWorldScriptContext();
if (!context.IsEmpty()) {
v8::Local<v8::Value> window = context->Global();
DCHECK(!window.IsEmpty());
views->Set(v8::Integer::New(index), window);
index++;
if (view_type == ViewType::EXTENSION_BACKGROUND_PAGE)
break;
}
}
return views;
}
static v8::Handle<v8::Value> GetNextRequestId(const v8::Arguments& args) {
static int next_request_id = 0;
return v8::Integer::New(next_request_id++);
}
// Creates a new messaging channel to the tab with the given ID.
static v8::Handle<v8::Value> OpenChannelToTab(const v8::Arguments& args) {
// Get the current RenderView so that we can send a routed IPC message from
// the correct source.
RenderView* renderview = bindings_utils::GetRenderViewForCurrentContext();
if (!renderview)
return v8::Undefined();
if (args.Length() >= 3 && args[0]->IsInt32() && args[1]->IsString() &&
args[2]->IsString()) {
int tab_id = args[0]->Int32Value();
std::string extension_id = *v8::String::Utf8Value(args[1]->ToString());
std::string channel_name = *v8::String::Utf8Value(args[2]->ToString());
int port_id = -1;
renderview->Send(new ViewHostMsg_OpenChannelToTab(
renderview->routing_id(), tab_id, extension_id, channel_name,
&port_id));
return v8::Integer::New(port_id);
}
return v8::Undefined();
}
static v8::Handle<v8::Value> GetCurrentPageActions(
const v8::Arguments& args) {
std::string extension_id = *v8::String::Utf8Value(args[0]->ToString());
PageActionIdMap* page_action_map = GetPageActionMap();
PageActionIdMap::const_iterator it = page_action_map->find(extension_id);
std::vector<std::string> page_actions;
size_t size = 0;
if (it != page_action_map->end()) {
page_actions = it->second;
size = page_actions.size();
}
v8::Local<v8::Array> page_action_vector = v8::Array::New(size);
for (size_t i = 0; i < size; ++i) {
std::string page_action_id = page_actions[i];
page_action_vector->Set(v8::Integer::New(i),
v8::String::New(page_action_id.c_str()));
}
return page_action_vector;
}
static v8::Handle<v8::Value> GetL10nMessage(const v8::Arguments& args) {
if (args.Length() != 2 || !args[0]->IsString()) {
NOTREACHED() << "Bad arguments";
return v8::Undefined();
}
L10nMessagesMap* l10n_messages =
GetL10nMessagesMap(ExtensionIdForCurrentContext());
if (!l10n_messages)
return v8::Undefined();
std::string message_name = *v8::String::AsciiValue(args[0]);
std::string message =
ExtensionMessageBundle::GetL10nMessage(message_name, *l10n_messages);
std::vector<string16> substitutions;
if (args[1]->IsNull() || args[1]->IsUndefined()) {
// chrome.i18n.getMessage("message_name");
// chrome.i18n.getMessage("message_name", null);
return v8::String::New(message.c_str());
} else if (args[1]->IsString()) {
// chrome.i18n.getMessage("message_name", "one param");
std::string substitute = *v8::String::Utf8Value(args[1]->ToString());
substitutions.push_back(UTF8ToUTF16(substitute));
} else if (args[1]->IsArray()) {
// chrome.i18n.getMessage("message_name", ["more", "params"]);
v8::Array* placeholders = static_cast<v8::Array*>(*args[1]);
uint32_t count = placeholders->Length();
DCHECK(count > 0 && count <= 9);
for (uint32_t i = 0; i < count; ++i) {
std::string substitute =
*v8::String::Utf8Value(
placeholders->Get(v8::Integer::New(i))->ToString());
substitutions.push_back(UTF8ToUTF16(substitute));
}
} else {
NOTREACHED() << "Couldn't parse second parameter.";
return v8::Undefined();
}
return v8::String::New(UTF16ToUTF8(ReplaceStringPlaceholders(
UTF8ToUTF16(message), substitutions, NULL)).c_str());
}
// Starts an API request to the browser, with an optional callback. The
// callback will be dispatched to EventBindings::HandleResponse.
static v8::Handle<v8::Value> StartRequest(const v8::Arguments& args) {
// Get the current RenderView so that we can send a routed IPC message from
// the correct source.
RenderView* renderview = bindings_utils::GetRenderViewForCurrentContext();
if (!renderview)
return v8::Undefined();
if (args.Length() != 4 || !args[0]->IsString() || !args[1]->IsString() ||
!args[2]->IsInt32() || !args[3]->IsBoolean())
return v8::Undefined();
std::string name = *v8::String::AsciiValue(args[0]);
if (GetFunctionNameSet()->find(name) == GetFunctionNameSet()->end()) {
NOTREACHED() << "Unexpected function " << name;
return v8::Undefined();
}
if (!ExtensionProcessBindings::CurrentContextHasPermission(name)) {
return ExtensionProcessBindings::ThrowPermissionDeniedException(name);
}
std::string json_args = *v8::String::Utf8Value(args[1]);
int request_id = args[2]->Int32Value();
bool has_callback = args[3]->BooleanValue();
v8::Persistent<v8::Context> current_context =
v8::Persistent<v8::Context>::New(v8::Context::GetCurrent());
DCHECK(!current_context.IsEmpty());
GetPendingRequestMap()[request_id].reset(new PendingRequest(
current_context, name));
renderview->SendExtensionRequest(name, json_args, request_id, has_callback);
return v8::Undefined();
}
static v8::Handle<v8::Value> GetRenderViewId(const v8::Arguments& args) {
RenderView* renderview = bindings_utils::GetRenderViewForCurrentContext();
if (!renderview)
return v8::Undefined();
return v8::Integer::New(renderview->routing_id());
}
};
} // namespace
v8::Extension* ExtensionProcessBindings::Get() {
static v8::Extension* extension = new ExtensionImpl();
return extension;
}
void ExtensionProcessBindings::SetFunctionNames(
const std::vector<std::string>& names) {
ExtensionImpl::SetFunctionNames(names);
}
// static
void ExtensionProcessBindings::HandleResponse(int request_id, bool success,
const std::string& response,
const std::string& error) {
PendingRequestMap& pending_requests = GetPendingRequestMap();
PendingRequestMap::iterator request = pending_requests.find(request_id);
if (request == pending_requests.end())
return; // The frame went away.
v8::HandleScope handle_scope;
v8::Handle<v8::Value> argv[5];
argv[0] = v8::Integer::New(request_id);
argv[1] = v8::String::New(request->second->name.c_str());
argv[2] = v8::Boolean::New(success);
argv[3] = v8::String::New(response.c_str());
argv[4] = v8::String::New(error.c_str());
v8::Handle<v8::Value> retval = bindings_utils::CallFunctionInContext(
request->second->context, "handleResponse", arraysize(argv), argv);
// In debug, the js will validate the callback parameters and return a
// string if a validation error has occured.
#ifdef _DEBUG
if (!retval.IsEmpty() && !retval->IsUndefined()) {
std::string error = *v8::String::AsciiValue(retval);
DCHECK(false) << error;
}
#endif
pending_requests.erase(request);
}
// static
void ExtensionProcessBindings::SetPageActions(
const std::string& extension_id,
const std::vector<std::string>& page_actions) {
PageActionIdMap& page_action_map = *GetPageActionMap();
if (!page_actions.empty()) {
page_action_map[extension_id] = page_actions;
} else {
if (page_action_map.find(extension_id) != page_action_map.end())
page_action_map.erase(extension_id);
}
}
// static
void ExtensionProcessBindings::SetL10nMessages(
const std::string& extension_id,
const std::map<std::string, std::string>& l10n_messages) {
ExtensionToL10nMessagesMap& l10n_messages_map =
*GetExtensionToL10nMessagesMap();
l10n_messages_map[extension_id] = l10n_messages;
}
// static
void ExtensionProcessBindings::SetAPIPermissions(
const std::string& extension_id,
const std::vector<std::string>& permissions) {
PermissionsMap& permissions_map = *GetPermissionsMap(extension_id);
// Default all the API permissions to off. We will reset them below.
for (size_t i = 0; i < Extension::kNumPermissions; ++i)
permissions_map[Extension::kPermissionNames[i]] = false;
for (size_t i = 0; i < permissions.size(); ++i)
permissions_map[permissions[i]] = true;
}
// static
void ExtensionProcessBindings::SetHostPermissions(
const GURL& extension_url,
const std::vector<URLPattern>& permissions) {
for (size_t i = 0; i < permissions.size(); ++i) {
WebKit::whiteListAccessFromOrigin(
extension_url,
WebKit::WebString::fromUTF8(permissions[i].scheme()),
WebKit::WebString::fromUTF8(permissions[i].host()),
permissions[i].match_subdomains());
}
}
// Given a name like "tabs.onConnect", return the permission name required
// to access that API ("tabs" in this example).
static std::string GetPermissionName(const std::string& function_name) {
size_t first_dot = function_name.find('.');
std::string permission_name = function_name.substr(0, first_dot);
if (permission_name == "windows")
return "tabs"; // windows and tabs are the same permission.
return permission_name;
}
// static
bool ExtensionProcessBindings::CurrentContextHasPermission(
const std::string& function_name) {
std::string extension_id = ExtensionImpl::ExtensionIdForCurrentContext();
PermissionsMap& permissions_map = *GetPermissionsMap(extension_id);
std::string permission_name = GetPermissionName(function_name);
PermissionsMap::iterator it = permissions_map.find(permission_name);
// We explicitly check if the permission entry is present and false, because
// some APIs do not have a required permission entry (ie, "chrome.extension").
return (it == permissions_map.end() || it->second);
}
// static
v8::Handle<v8::Value>
ExtensionProcessBindings::ThrowPermissionDeniedException(
const std::string& function_name) {
static const char kMessage[] =
"You do not have permission to use 'chrome.%s'. Be sure to declare"
" in your manifest what permissions you need.";
std::string permission_name = GetPermissionName(function_name);
std::string error_msg = StringPrintf(kMessage, permission_name.c_str());
return v8::ThrowException(v8::Exception::Error(
v8::String::New(error_msg.c_str())));
}
// static
void ExtensionProcessBindings::SetViewType(WebView* view,
ViewType::Type type) {
DCHECK(type == ViewType::EXTENSION_MOLE ||
type == ViewType::EXTENSION_TOOLSTRIP);
const char* type_str;
if (type == ViewType::EXTENSION_MOLE)
type_str = "mole";
else if (type == ViewType::EXTENSION_TOOLSTRIP)
type_str = "toolstrip";
else
return;
v8::HandleScope handle_scope;
WebFrame* frame = view->mainFrame();
v8::Local<v8::Context> context = frame->mainWorldScriptContext();
v8::Handle<v8::Value> argv[1];
argv[0] = v8::String::New(type_str);
bindings_utils::CallFunctionInContext(context, "setViewType",
arraysize(argv), argv);
}
|