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 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
|
// Copyright 2014 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 "extensions/renderer/dispatcher.h"
#include <stddef.h>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/debug/alias.h"
#include "base/feature_list.h"
#include "base/lazy_instance.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics_action.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "content/grit/content_resources.h"
#include "content/public/child/v8_value_converter.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "extensions/common/api/messaging/message.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_api.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/extension_urls.h"
#include "extensions/common/feature_switch.h"
#include "extensions/common/features/behavior_feature.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/features/feature_provider.h"
#include "extensions/common/features/feature_util.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/background_info.h"
#include "extensions/common/manifest_handlers/content_capabilities_handler.h"
#include "extensions/common/manifest_handlers/options_page_info.h"
#include "extensions/common/message_bundle.h"
#include "extensions/common/permissions/permission_set.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/switches.h"
#include "extensions/common/view_type.h"
#include "extensions/renderer/api_activity_logger.h"
#include "extensions/renderer/api_definitions_natives.h"
#include "extensions/renderer/app_window_custom_bindings.h"
#include "extensions/renderer/blob_native_handler.h"
#include "extensions/renderer/content_watcher.h"
#include "extensions/renderer/context_menus_custom_bindings.h"
#include "extensions/renderer/dispatcher_delegate.h"
#include "extensions/renderer/display_source_custom_bindings.h"
#include "extensions/renderer/document_custom_bindings.h"
#include "extensions/renderer/dom_activity_logger.h"
#include "extensions/renderer/event_bindings.h"
#include "extensions/renderer/extension_frame_helper.h"
#include "extensions/renderer/extension_helper.h"
#include "extensions/renderer/extensions_renderer_client.h"
#include "extensions/renderer/file_system_natives.h"
#include "extensions/renderer/guest_view/guest_view_internal_custom_bindings.h"
#include "extensions/renderer/id_generator_custom_bindings.h"
#include "extensions/renderer/js_extension_bindings_system.h"
#include "extensions/renderer/logging_native_handler.h"
#include "extensions/renderer/messaging_bindings.h"
#include "extensions/renderer/module_system.h"
#include "extensions/renderer/native_extension_bindings_system.h"
#include "extensions/renderer/process_info_native_handler.h"
#include "extensions/renderer/render_frame_observer_natives.h"
#include "extensions/renderer/renderer_extension_registry.h"
#include "extensions/renderer/request_sender.h"
#include "extensions/renderer/runtime_custom_bindings.h"
#include "extensions/renderer/safe_builtins.h"
#include "extensions/renderer/script_context.h"
#include "extensions/renderer/script_context_set.h"
#include "extensions/renderer/script_injection.h"
#include "extensions/renderer/script_injection_manager.h"
#include "extensions/renderer/send_request_natives.h"
#include "extensions/renderer/service_worker_request_sender.h"
#include "extensions/renderer/set_icon_natives.h"
#include "extensions/renderer/static_v8_external_one_byte_string_resource.h"
#include "extensions/renderer/test_features_native_handler.h"
#include "extensions/renderer/test_native_handler.h"
#include "extensions/renderer/user_gestures_native_handler.h"
#include "extensions/renderer/utils_native_handler.h"
#include "extensions/renderer/v8_context_native_handler.h"
#include "extensions/renderer/v8_helpers.h"
#include "extensions/renderer/wake_event_page.h"
#include "extensions/renderer/worker_script_context_set.h"
#include "extensions/renderer/worker_thread_dispatcher.h"
#include "gin/converter.h"
#include "grit/extensions_renderer_resources.h"
#include "mojo/public/js/constants.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURLRequest.h"
#include "third_party/WebKit/public/web/WebCustomElement.h"
#include "third_party/WebKit/public/web/WebDataSource.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
#include "third_party/WebKit/public/web/WebScriptController.h"
#include "third_party/WebKit/public/web/WebSecurityPolicy.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "v8/include/v8.h"
using base::UserMetricsAction;
using blink::WebDataSource;
using blink::WebDocument;
using blink::WebScopedUserGesture;
using blink::WebSecurityPolicy;
using blink::WebString;
using blink::WebVector;
using blink::WebView;
using content::RenderThread;
namespace extensions {
namespace {
static const int64_t kInitialExtensionIdleHandlerDelayMs = 5 * 1000;
static const int64_t kMaxExtensionIdleHandlerDelayMs = 5 * 60 * 1000;
static const char kOnSuspendEvent[] = "runtime.onSuspend";
static const char kOnSuspendCanceledEvent[] = "runtime.onSuspendCanceled";
void CrashOnException(const v8::TryCatch& trycatch) {
NOTREACHED();
};
// Calls a method |method_name| in a module |module_name| belonging to the
// module system from |context|. Intended as a callback target from
// ScriptContextSet::ForEach.
void CallModuleMethod(const std::string& module_name,
const std::string& method_name,
const base::ListValue* args,
ScriptContext* context) {
v8::HandleScope handle_scope(context->isolate());
v8::Context::Scope context_scope(context->v8_context());
std::unique_ptr<content::V8ValueConverter> converter(
content::V8ValueConverter::create());
std::vector<v8::Local<v8::Value>> arguments;
for (const auto& arg : *args) {
arguments.push_back(converter->ToV8Value(arg.get(), context->v8_context()));
}
context->module_system()->CallModuleMethodSafe(
module_name, method_name, &arguments);
}
// This handles the "chrome." root API object in script contexts.
class ChromeNativeHandler : public ObjectBackedNativeHandler {
public:
explicit ChromeNativeHandler(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetChrome",
base::Bind(&ChromeNativeHandler::GetChrome, base::Unretained(this)));
}
void GetChrome(const v8::FunctionCallbackInfo<v8::Value>& args) {
// Check for the chrome property. If one doesn't exist, create one.
v8::Local<v8::String> chrome_string(
v8::String::NewFromUtf8(context()->isolate(), "chrome"));
v8::Local<v8::Object> global(context()->v8_context()->Global());
v8::Local<v8::Value> chrome(global->Get(chrome_string));
if (chrome->IsUndefined()) {
chrome = v8::Object::New(context()->isolate());
global->Set(chrome_string, chrome);
}
args.GetReturnValue().Set(chrome);
}
};
// Handler for sending IPCs with native extension bindings. Only used for
// the main thread.
void SendRequestIPC(ScriptContext* context,
const ExtensionHostMsg_Request_Params& params) {
content::RenderFrame* frame = context->GetRenderFrame();
if (!frame)
return;
// TODO(devlin): Handle IO-thread messages.
frame->Send(new ExtensionHostMsg_Request(frame->GetRoutingID(), params));
}
// Sends a notification to the browser that an event either has or no longer has
// listeners associated with it. Note that we only do this for the first added/
// last removed listener, rather than for each subsequent listener; the browser
// only cares if an event has >0 associated listeners.
// TODO(devlin): Use this in EventBindings, too, and add logic for lazy
// background pages.
void SendEventListenersIPC(binding::EventListenersChanged changed,
ScriptContext* context,
const std::string& event_name) {
if (changed == binding::EventListenersChanged::HAS_LISTENERS) {
content::RenderThread::Get()->Send(new ExtensionHostMsg_AddListener(
context->GetExtensionID(), context->url(), event_name));
} else {
DCHECK_EQ(binding::EventListenersChanged::NO_LISTENERS, changed);
content::RenderThread::Get()->Send(new ExtensionHostMsg_RemoveListener(
context->GetExtensionID(), context->url(), event_name));
}
}
base::LazyInstance<WorkerScriptContextSet> g_worker_script_context_set =
LAZY_INSTANCE_INITIALIZER;
} // namespace
// Note that we can't use Blink public APIs in the constructor becase Blink
// is not initialized at the point we create Dispatcher.
Dispatcher::Dispatcher(DispatcherDelegate* delegate)
: delegate_(delegate),
content_watcher_(new ContentWatcher()),
source_map_(&ResourceBundle::GetSharedInstance()),
v8_schema_registry_(new V8SchemaRegistry),
user_script_set_manager_observer_(this),
activity_logging_enabled_(false) {
const base::CommandLine& command_line =
*(base::CommandLine::ForCurrentProcess());
if (FeatureSwitch::native_crx_bindings()->IsEnabled()) {
bindings_system_ = base::MakeUnique<NativeExtensionBindingsSystem>(
base::Bind(&SendRequestIPC), base::Bind(&SendEventListenersIPC));
} else {
bindings_system_ = base::MakeUnique<JsExtensionBindingsSystem>(
&source_map_, base::MakeUnique<RequestSender>());
}
set_idle_notifications_ =
command_line.HasSwitch(switches::kExtensionProcess) ||
command_line.HasSwitch(::switches::kSingleProcess);
if (set_idle_notifications_) {
RenderThread::Get()->SetIdleNotificationDelayInMs(
kInitialExtensionIdleHandlerDelayMs);
}
script_context_set_.reset(new ScriptContextSet(&active_extension_ids_));
user_script_set_manager_.reset(new UserScriptSetManager());
script_injection_manager_.reset(
new ScriptInjectionManager(user_script_set_manager_.get()));
user_script_set_manager_observer_.Add(user_script_set_manager_.get());
PopulateSourceMap();
WakeEventPage::Get()->Init(RenderThread::Get());
// Ideally this should be done after checking
// ExtensionAPIEnabledInExtensionServiceWorkers(), but the Dispatcher is
// created so early that sending an IPC from browser/ process to synchronize
// this enabled-ness is too late.
WorkerThreadDispatcher::Get()->Init(RenderThread::Get());
RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension());
// Register WebSecurityPolicy whitelists for the chrome-extension:// scheme.
WebString extension_scheme(base::ASCIIToUTF16(kExtensionScheme));
// Resources should bypass Content Security Policy checks when included in
// protected resources. TODO(kalman): What are "protected resources"?
WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
extension_scheme);
// Extension resources are HTTP-like and safe to expose to the fetch API. The
// rules for the fetch API are consistent with XHR.
WebSecurityPolicy::registerURLSchemeAsSupportingFetchAPI(extension_scheme);
// Extension resources, when loaded as the top-level document, should bypass
// Blink's strict first-party origin checks.
WebSecurityPolicy::registerURLSchemeAsFirstPartyWhenTopLevel(
extension_scheme);
// For extensions, we want to ensure we call the IdleHandler every so often,
// even if the extension keeps up activity.
if (set_idle_notifications_) {
forced_idle_timer_.reset(new base::RepeatingTimer);
forced_idle_timer_->Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kMaxExtensionIdleHandlerDelayMs),
RenderThread::Get(),
&RenderThread::IdleHandler);
}
// Initialize host permissions for any extensions that were activated before
// WebKit was initialized.
for (const std::string& extension_id : active_extension_ids_) {
const Extension* extension =
RendererExtensionRegistry::Get()->GetByID(extension_id);
CHECK(extension);
InitOriginPermissions(extension);
}
EnableCustomElementWhiteList();
}
Dispatcher::~Dispatcher() {
}
void Dispatcher::OnRenderFrameCreated(content::RenderFrame* render_frame) {
script_injection_manager_->OnRenderFrameCreated(render_frame);
}
bool Dispatcher::IsExtensionActive(const std::string& extension_id) const {
bool is_active =
active_extension_ids_.find(extension_id) != active_extension_ids_.end();
if (is_active)
CHECK(RendererExtensionRegistry::Get()->Contains(extension_id));
return is_active;
}
void Dispatcher::DidCreateScriptContext(
blink::WebLocalFrame* frame,
const v8::Local<v8::Context>& v8_context,
int world_id) {
const base::TimeTicks start_time = base::TimeTicks::Now();
ScriptContext* context =
script_context_set_->Register(frame, v8_context, world_id);
// Initialize origin permissions for content scripts, which can't be
// initialized in |OnActivateExtension|.
if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT)
InitOriginPermissions(context->extension());
{
std::unique_ptr<ModuleSystem> module_system(
new ModuleSystem(context, &source_map_));
context->set_module_system(std::move(module_system));
}
ModuleSystem* module_system = context->module_system();
// Enable natives in startup.
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
RegisterNativeHandlers(module_system, context,
bindings_system_->GetRequestSender(),
v8_schema_registry_.get());
bindings_system_->DidCreateScriptContext(context);
UpdateBindingsForContext(context);
// Inject custom JS into the platform app context.
if (IsWithinPlatformApp()) {
module_system->Require("platformApp");
}
RequireGuestViewModules(context);
delegate_->RequireAdditionalModules(context);
const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
switch (context->context_type()) {
case Feature::UNSPECIFIED_CONTEXT:
UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified",
elapsed);
break;
case Feature::BLESSED_EXTENSION_CONTEXT:
UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Blessed", elapsed);
break;
case Feature::UNBLESSED_EXTENSION_CONTEXT:
UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unblessed",
elapsed);
break;
case Feature::CONTENT_SCRIPT_CONTEXT:
UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_ContentScript",
elapsed);
break;
case Feature::WEB_PAGE_CONTEXT:
UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebPage", elapsed);
break;
case Feature::BLESSED_WEB_PAGE_CONTEXT:
UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_BlessedWebPage",
elapsed);
break;
case Feature::WEBUI_CONTEXT:
UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_WebUI", elapsed);
break;
case Feature::SERVICE_WORKER_CONTEXT:
// Handled in DidInitializeServiceWorkerContextOnWorkerThread().
NOTREACHED();
break;
}
VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
}
void Dispatcher::DidInitializeServiceWorkerContextOnWorkerThread(
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& url) {
const base::TimeTicks start_time = base::TimeTicks::Now();
if (!url.SchemeIs(kExtensionScheme)) {
// Early-out if this isn't a chrome-extension:// scheme, because looking up
// the extension registry is unnecessary if it's not. Checking this will
// also skip over hosted apps, which is the desired behavior - hosted app
// service workers are not our concern.
return;
}
const Extension* extension =
RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(url);
if (!extension) {
// TODO(kalman): This is no good. Instead we need to either:
//
// - Hold onto the v8::Context and create the ScriptContext and install
// our bindings when this extension is loaded.
// - Deal with there being an extension ID (url.host()) but no
// extension associated with it, then document that getBackgroundClient
// may fail if the extension hasn't loaded yet.
//
// The former is safer, but is unfriendly to caching (e.g. session restore).
// It seems to contradict the service worker idiom.
//
// The latter is friendly to caching, but running extension code without an
// installed extension makes me nervous, and means that we won't be able to
// expose arbitrary (i.e. capability-checked) extension APIs to service
// workers. We will probably need to relax some assertions - we just need
// to find them.
//
// Perhaps this could be solved with our own event on the service worker
// saying that an extension is ready, and documenting that extension APIs
// won't work before that event has fired?
return;
}
ScriptContext* context = new ScriptContext(
v8_context, nullptr, extension, Feature::SERVICE_WORKER_CONTEXT,
extension, Feature::SERVICE_WORKER_CONTEXT);
context->set_url(url);
if (ExtensionsClient::Get()->ExtensionAPIEnabledInExtensionServiceWorkers()) {
WorkerThreadDispatcher::Get()->AddWorkerData(service_worker_version_id,
&source_map_);
// TODO(lazyboy): Make sure accessing |source_map_| in worker thread is
// safe.
context->set_module_system(
base::MakeUnique<ModuleSystem>(context, &source_map_));
ModuleSystem* module_system = context->module_system();
// Enable natives in startup.
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
ExtensionBindingsSystem* worker_bindings_system =
WorkerThreadDispatcher::GetBindingsSystem();
RegisterNativeHandlers(module_system, context,
worker_bindings_system->GetRequestSender(),
WorkerThreadDispatcher::GetV8SchemaRegistry());
worker_bindings_system->DidCreateScriptContext(context);
worker_bindings_system->UpdateBindingsForContext(context);
// TODO(lazyboy): Get rid of RequireGuestViewModules() as this doesn't seem
// necessary for Extension SW.
RequireGuestViewModules(context);
delegate_->RequireAdditionalModules(context);
}
g_worker_script_context_set.Get().Insert(base::WrapUnique(context));
v8::Isolate* isolate = context->isolate();
// Fetch the source code for service_worker_bindings.js.
base::StringPiece script_resource =
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_SERVICE_WORKER_BINDINGS_JS);
v8::Local<v8::String> script = v8::String::NewExternal(
isolate, new StaticV8ExternalOneByteStringResource(script_resource));
// Run service_worker.js to get the main function.
v8::Local<v8::Function> main_function;
{
v8::Local<v8::Value> result = context->RunScript(
v8_helpers::ToV8StringUnsafe(isolate, "service_worker"), script,
base::Bind(&CrashOnException));
CHECK(result->IsFunction());
main_function = result.As<v8::Function>();
}
// Expose CHECK/DCHECK/NOTREACHED to the main function with a
// LoggingNativeHandler. Admire the neat base::Bind trick to both Invalidate
// and delete the native handler.
LoggingNativeHandler* logging = new LoggingNativeHandler(context);
context->AddInvalidationObserver(
base::Bind(&NativeHandler::Invalidate, base::Owned(logging)));
// Execute the main function with its dependencies passed in as arguments.
v8::Local<v8::Value> args[] = {
// The extension's background URL.
v8_helpers::ToV8StringUnsafe(
isolate, BackgroundInfo::GetBackgroundURL(extension).spec()),
// The wake-event-page native function.
WakeEventPage::Get()->GetForContext(context),
// The logging module.
logging->NewInstance(),
};
context->SafeCallFunction(main_function, arraysize(args), args);
const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time;
UMA_HISTOGRAM_TIMES(
"Extensions.DidInitializeServiceWorkerContextOnWorkerThread", elapsed);
}
void Dispatcher::WillReleaseScriptContext(
blink::WebLocalFrame* frame,
const v8::Local<v8::Context>& v8_context,
int world_id) {
ScriptContext* context = script_context_set_->GetByV8Context(v8_context);
if (!context)
return;
bindings_system_->WillReleaseScriptContext(context);
script_context_set_->Remove(context);
VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
}
// static
void Dispatcher::WillDestroyServiceWorkerContextOnWorkerThread(
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& url) {
if (url.SchemeIs(kExtensionScheme)) {
// See comment in DidInitializeServiceWorkerContextOnWorkerThread.
g_worker_script_context_set.Get().Remove(v8_context, url);
// TODO(devlin): We're not calling
// ExtensionBindingsSystem::WillReleaseScriptContext() here. This should be
// fine, since the entire bindings system is being destroyed when we
// remove the worker data, but we might want to notify the system anyway.
}
if (ExtensionsClient::Get()->ExtensionAPIEnabledInExtensionServiceWorkers())
WorkerThreadDispatcher::Get()->RemoveWorkerData(service_worker_version_id);
}
void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) {
// Note: use GetEffectiveDocumentURL not just frame->document()->url()
// so that this also injects the stylesheet on about:blank frames that
// are hosted in the extension process.
GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
frame, frame->document().url(), true /* match_about_blank */);
const Extension* extension =
RendererExtensionRegistry::Get()->GetExtensionOrAppByURL(
effective_document_url);
if (extension &&
(extension->is_extension() || extension->is_platform_app())) {
int resource_id = extension->is_platform_app() ? IDR_PLATFORM_APP_CSS
: IDR_EXTENSION_FONTS_CSS;
std::string stylesheet = ResourceBundle::GetSharedInstance()
.GetRawDataResource(resource_id)
.as_string();
base::ReplaceFirstSubstringAfterOffset(
&stylesheet, 0, "$FONTFAMILY", system_font_family_);
base::ReplaceFirstSubstringAfterOffset(
&stylesheet, 0, "$FONTSIZE", system_font_size_);
// Blink doesn't let us define an additional user agent stylesheet, so
// we insert the default platform app or extension stylesheet into all
// documents that are loaded in each app or extension.
frame->document().insertStyleSheet(WebString::fromUTF8(stylesheet));
}
// If this is an extension options page, and the extension has opted into
// using Chrome styles, then insert the Chrome extension stylesheet.
if (extension && extension->is_extension() &&
OptionsPageInfo::ShouldUseChromeStyle(extension) &&
effective_document_url == OptionsPageInfo::GetOptionsPage(extension)) {
base::StringPiece extension_css =
ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_EXTENSION_CSS);
frame->document().insertStyleSheet(
WebString::fromUTF8(extension_css.data(), extension_css.length()));
}
// In testing, the document lifetime events can happen after the render
// process shutdown event.
// See: http://crbug.com/21508 and http://crbug.com/500851
if (content_watcher_) {
content_watcher_->DidCreateDocumentElement(frame);
}
}
void Dispatcher::RunScriptsAtDocumentStart(content::RenderFrame* render_frame) {
ExtensionFrameHelper* frame_helper = ExtensionFrameHelper::Get(render_frame);
if (!frame_helper)
return; // The frame is invisible to extensions.
frame_helper->RunScriptsAtDocumentStart();
// |frame_helper| and |render_frame| might be dead by now.
}
void Dispatcher::RunScriptsAtDocumentEnd(content::RenderFrame* render_frame) {
ExtensionFrameHelper* frame_helper = ExtensionFrameHelper::Get(render_frame);
if (!frame_helper)
return; // The frame is invisible to extensions.
frame_helper->RunScriptsAtDocumentEnd();
// |frame_helper| and |render_frame| might be dead by now.
}
void Dispatcher::OnExtensionResponse(int request_id,
bool success,
const base::ListValue& response,
const std::string& error) {
bindings_system_->HandleResponse(request_id, success, response, error);
}
void Dispatcher::DispatchEvent(
const std::string& extension_id,
const std::string& event_name,
const base::ListValue& event_args,
const base::DictionaryValue& filtering_info) const {
script_context_set_->ForEach(
extension_id, nullptr,
base::Bind(&ExtensionBindingsSystem::DispatchEventInContext,
base::Unretained(bindings_system_.get()), event_name,
&event_args, &filtering_info));
// Reset the idle handler each time there's any activity like event or message
// dispatch.
// TODO(devlin): It's likely this is totally wrong. See
// https://groups.google.com/a/chromium.org/forum/#!msg/scheduler-dev/iTRVbcmmpAs/pfqyUyEeAAAJ
if (set_idle_notifications_) {
RenderThread::Get()->ScheduleIdleHandler(
kInitialExtensionIdleHandlerDelayMs);
}
}
void Dispatcher::InvokeModuleSystemMethod(content::RenderFrame* render_frame,
const std::string& extension_id,
const std::string& module_name,
const std::string& function_name,
const base::ListValue& args) {
script_context_set_->ForEach(
extension_id, render_frame,
base::Bind(&CallModuleMethod, module_name, function_name, &args));
// Reset the idle handler each time there's any activity like event or message
// dispatch.
// TODO(devlin): It's likely this is totally wrong. See
// https://groups.google.com/a/chromium.org/forum/#!msg/scheduler-dev/iTRVbcmmpAs/pfqyUyEeAAAJ
if (set_idle_notifications_) {
RenderThread::Get()->ScheduleIdleHandler(
kInitialExtensionIdleHandlerDelayMs);
}
}
// static
std::vector<std::pair<std::string, int> > Dispatcher::GetJsResources() {
std::vector<std::pair<std::string, int> > resources;
// Libraries.
resources.push_back(std::make_pair("appView", IDR_APP_VIEW_JS));
resources.push_back(std::make_pair("entryIdManager", IDR_ENTRY_ID_MANAGER));
resources.push_back(std::make_pair(kEventBindings, IDR_EVENT_BINDINGS_JS));
resources.push_back(std::make_pair("extensionOptions",
IDR_EXTENSION_OPTIONS_JS));
resources.push_back(std::make_pair("extensionOptionsAttributes",
IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS));
resources.push_back(std::make_pair("extensionOptionsConstants",
IDR_EXTENSION_OPTIONS_CONSTANTS_JS));
resources.push_back(std::make_pair("extensionOptionsEvents",
IDR_EXTENSION_OPTIONS_EVENTS_JS));
resources.push_back(std::make_pair("extensionView", IDR_EXTENSION_VIEW_JS));
resources.push_back(std::make_pair("extensionViewApiMethods",
IDR_EXTENSION_VIEW_API_METHODS_JS));
resources.push_back(std::make_pair("extensionViewAttributes",
IDR_EXTENSION_VIEW_ATTRIBUTES_JS));
resources.push_back(std::make_pair("extensionViewConstants",
IDR_EXTENSION_VIEW_CONSTANTS_JS));
resources.push_back(std::make_pair("extensionViewEvents",
IDR_EXTENSION_VIEW_EVENTS_JS));
resources.push_back(std::make_pair(
"extensionViewInternal", IDR_EXTENSION_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
resources.push_back(std::make_pair("guestView", IDR_GUEST_VIEW_JS));
resources.push_back(std::make_pair("guestViewAttributes",
IDR_GUEST_VIEW_ATTRIBUTES_JS));
resources.push_back(std::make_pair("guestViewContainer",
IDR_GUEST_VIEW_CONTAINER_JS));
resources.push_back(std::make_pair("guestViewDeny", IDR_GUEST_VIEW_DENY_JS));
resources.push_back(std::make_pair("guestViewEvents",
IDR_GUEST_VIEW_EVENTS_JS));
if (base::FeatureList::IsEnabled(::features::kGuestViewCrossProcessFrames)) {
resources.push_back(std::make_pair("guestViewIframe",
IDR_GUEST_VIEW_IFRAME_JS));
resources.push_back(std::make_pair("guestViewIframeContainer",
IDR_GUEST_VIEW_IFRAME_CONTAINER_JS));
}
resources.push_back(std::make_pair("imageUtil", IDR_IMAGE_UTIL_JS));
resources.push_back(std::make_pair("json_schema", IDR_JSON_SCHEMA_JS));
resources.push_back(std::make_pair("lastError", IDR_LAST_ERROR_JS));
resources.push_back(std::make_pair("messaging", IDR_MESSAGING_JS));
resources.push_back(std::make_pair("messaging_utils",
IDR_MESSAGING_UTILS_JS));
resources.push_back(std::make_pair(kSchemaUtils, IDR_SCHEMA_UTILS_JS));
resources.push_back(std::make_pair("sendRequest", IDR_SEND_REQUEST_JS));
resources.push_back(std::make_pair("setIcon", IDR_SET_ICON_JS));
resources.push_back(std::make_pair("test", IDR_TEST_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("test_environment_specific_bindings",
IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS));
resources.push_back(std::make_pair("uncaught_exception_handler",
IDR_UNCAUGHT_EXCEPTION_HANDLER_JS));
resources.push_back(std::make_pair("utils", IDR_UTILS_JS));
resources.push_back(std::make_pair("webRequest",
IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("webRequestInternal",
IDR_WEB_REQUEST_INTERNAL_CUSTOM_BINDINGS_JS));
// Note: webView not webview so that this doesn't interfere with the
// chrome.webview API bindings.
resources.push_back(std::make_pair("webView", IDR_WEB_VIEW_JS));
resources.push_back(std::make_pair("webViewActionRequests",
IDR_WEB_VIEW_ACTION_REQUESTS_JS));
resources.push_back(std::make_pair("webViewApiMethods",
IDR_WEB_VIEW_API_METHODS_JS));
resources.push_back(std::make_pair("webViewAttributes",
IDR_WEB_VIEW_ATTRIBUTES_JS));
resources.push_back(std::make_pair("webViewConstants",
IDR_WEB_VIEW_CONSTANTS_JS));
resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS));
resources.push_back(std::make_pair("webViewInternal",
IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair(mojo::kBindingsModuleName, IDR_MOJO_BINDINGS_JS));
resources.push_back(
std::make_pair(mojo::kBufferModuleName, IDR_MOJO_BUFFER_JS));
resources.push_back(
std::make_pair(mojo::kCodecModuleName, IDR_MOJO_CODEC_JS));
resources.push_back(
std::make_pair(mojo::kConnectorModuleName, IDR_MOJO_CONNECTOR_JS));
resources.push_back(std::make_pair(mojo::kInterfaceTypesModuleName,
IDR_MOJO_INTERFACE_TYPES_JS));
resources.push_back(
std::make_pair(mojo::kRouterModuleName, IDR_MOJO_ROUTER_JS));
resources.push_back(
std::make_pair(mojo::kUnicodeModuleName, IDR_MOJO_UNICODE_JS));
resources.push_back(
std::make_pair(mojo::kValidatorModuleName, IDR_MOJO_VALIDATOR_JS));
resources.push_back(std::make_pair("async_waiter", IDR_ASYNC_WAITER_JS));
resources.push_back(std::make_pair("keep_alive", IDR_KEEP_ALIVE_JS));
resources.push_back(std::make_pair("extensions/common/mojo/keep_alive.mojom",
IDR_KEEP_ALIVE_MOJOM_JS));
// Custom bindings.
resources.push_back(
std::make_pair("app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("declarativeWebRequest",
IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("displaySource",
IDR_DISPLAY_SOURCE_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS));
resources.push_back(
std::make_pair("extension", IDR_EXTENSION_CUSTOM_BINDINGS_JS));
resources.push_back(std::make_pair("i18n", IDR_I18N_CUSTOM_BINDINGS_JS));
resources.push_back(std::make_pair(
"mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS));
resources.push_back(std::make_pair("extensions/common/api/mime_handler.mojom",
IDR_MIME_HANDLER_MOJOM_JS));
resources.push_back(
std::make_pair("mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS));
resources.push_back(std::make_pair("printerProvider",
IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("runtime", IDR_RUNTIME_CUSTOM_BINDINGS_JS));
resources.push_back(
std::make_pair("webViewRequest",
IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS));
resources.push_back(std::make_pair("binding", IDR_BINDING_JS));
// Custom types sources.
resources.push_back(std::make_pair("StorageArea", IDR_STORAGE_AREA_JS));
// Platform app sources that are not API-specific..
resources.push_back(std::make_pair("platformApp", IDR_PLATFORM_APP_JS));
#if defined(ENABLE_MEDIA_ROUTER)
resources.push_back(
std::make_pair("chrome/browser/media/router/mojo/media_router.mojom",
IDR_MEDIA_ROUTER_MOJOM_JS));
resources.push_back(
std::make_pair("mojo/common/time.mojom", IDR_MOJO_TIME_MOJOM_JS));
resources.push_back(
std::make_pair("media_router_bindings", IDR_MEDIA_ROUTER_BINDINGS_JS));
#endif // defined(ENABLE_MEDIA_ROUTER)
return resources;
}
// NOTE: please use the naming convention "foo_natives" for these.
// static
void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
ScriptContext* context,
Dispatcher* dispatcher,
RequestSender* request_sender,
V8SchemaRegistry* v8_schema_registry) {
module_system->RegisterNativeHandler(
"chrome",
std::unique_ptr<NativeHandler>(new ChromeNativeHandler(context)));
module_system->RegisterNativeHandler(
"logging",
std::unique_ptr<NativeHandler>(new LoggingNativeHandler(context)));
module_system->RegisterNativeHandler("schema_registry",
v8_schema_registry->AsNativeHandler());
module_system->RegisterNativeHandler(
"test_features",
std::unique_ptr<NativeHandler>(new TestFeaturesNativeHandler(context)));
module_system->RegisterNativeHandler(
"test_native_handler",
std::unique_ptr<NativeHandler>(new TestNativeHandler(context)));
module_system->RegisterNativeHandler(
"user_gestures",
std::unique_ptr<NativeHandler>(new UserGesturesNativeHandler(context)));
module_system->RegisterNativeHandler(
"utils", std::unique_ptr<NativeHandler>(new UtilsNativeHandler(context)));
module_system->RegisterNativeHandler(
"v8_context",
std::unique_ptr<NativeHandler>(new V8ContextNativeHandler(context)));
module_system->RegisterNativeHandler(
"event_natives",
std::unique_ptr<NativeHandler>(new EventBindings(context)));
module_system->RegisterNativeHandler(
"messaging_natives", base::MakeUnique<MessagingBindings>(context));
module_system->RegisterNativeHandler(
"apiDefinitions", std::unique_ptr<NativeHandler>(
new ApiDefinitionsNatives(dispatcher, context)));
module_system->RegisterNativeHandler(
"sendRequest", std::unique_ptr<NativeHandler>(
new SendRequestNatives(request_sender, context)));
module_system->RegisterNativeHandler(
"setIcon", std::unique_ptr<NativeHandler>(new SetIconNatives(context)));
module_system->RegisterNativeHandler(
"activityLogger", std::unique_ptr<NativeHandler>(
new APIActivityLogger(context, dispatcher)));
module_system->RegisterNativeHandler(
"renderFrameObserverNatives",
std::unique_ptr<NativeHandler>(new RenderFrameObserverNatives(context)));
// Natives used by multiple APIs.
module_system->RegisterNativeHandler(
"file_system_natives",
std::unique_ptr<NativeHandler>(new FileSystemNatives(context)));
// Custom bindings.
module_system->RegisterNativeHandler(
"app_window_natives",
std::unique_ptr<NativeHandler>(new AppWindowCustomBindings(context)));
module_system->RegisterNativeHandler(
"blob_natives",
std::unique_ptr<NativeHandler>(new BlobNativeHandler(context)));
module_system->RegisterNativeHandler(
"context_menus",
std::unique_ptr<NativeHandler>(new ContextMenusCustomBindings(context)));
module_system->RegisterNativeHandler(
"document_natives",
std::unique_ptr<NativeHandler>(new DocumentCustomBindings(context)));
module_system->RegisterNativeHandler(
"guest_view_internal", std::unique_ptr<NativeHandler>(
new GuestViewInternalCustomBindings(context)));
module_system->RegisterNativeHandler(
"id_generator",
std::unique_ptr<NativeHandler>(new IdGeneratorCustomBindings(context)));
module_system->RegisterNativeHandler(
"runtime",
std::unique_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
module_system->RegisterNativeHandler(
"display_source",
std::unique_ptr<NativeHandler>(new DisplaySourceCustomBindings(context)));
}
bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
IPC_MESSAGE_HANDLER(ExtensionMsg_ActivateExtension, OnActivateExtension)
IPC_MESSAGE_HANDLER(ExtensionMsg_CancelSuspend, OnCancelSuspend)
IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
IPC_MESSAGE_HANDLER(ExtensionMsg_Loaded, OnLoaded)
IPC_MESSAGE_HANDLER(ExtensionMsg_MessageInvoke, OnMessageInvoke)
IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchEvent, OnDispatchEvent)
IPC_MESSAGE_HANDLER(ExtensionMsg_SetSessionInfo, OnSetSessionInfo)
IPC_MESSAGE_HANDLER(ExtensionMsg_SetScriptingWhitelist,
OnSetScriptingWhitelist)
IPC_MESSAGE_HANDLER(ExtensionMsg_SetSystemFont, OnSetSystemFont)
IPC_MESSAGE_HANDLER(ExtensionMsg_SetWebViewPartitionID,
OnSetWebViewPartitionID)
IPC_MESSAGE_HANDLER(ExtensionMsg_ShouldSuspend, OnShouldSuspend)
IPC_MESSAGE_HANDLER(ExtensionMsg_Suspend, OnSuspend)
IPC_MESSAGE_HANDLER(ExtensionMsg_TransferBlobs, OnTransferBlobs)
IPC_MESSAGE_HANDLER(ExtensionMsg_Unloaded, OnUnloaded)
IPC_MESSAGE_HANDLER(ExtensionMsg_UpdatePermissions, OnUpdatePermissions)
IPC_MESSAGE_HANDLER(ExtensionMsg_UpdateTabSpecificPermissions,
OnUpdateTabSpecificPermissions)
IPC_MESSAGE_HANDLER(ExtensionMsg_ClearTabSpecificPermissions,
OnClearTabSpecificPermissions)
IPC_MESSAGE_HANDLER(ExtensionMsg_SetActivityLoggingEnabled,
OnSetActivityLoggingEnabled)
IPC_MESSAGE_FORWARD(ExtensionMsg_WatchPages,
content_watcher_.get(),
ContentWatcher::OnWatchPages)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void Dispatcher::IdleNotification() {
if (set_idle_notifications_ && forced_idle_timer_) {
// Dampen the forced delay as well if the extension stays idle for long
// periods of time. (forced_idle_timer_ can be NULL after
// OnRenderProcessShutdown has been called.)
int64_t forced_delay_ms =
std::max(RenderThread::Get()->GetIdleNotificationDelayInMs(),
kMaxExtensionIdleHandlerDelayMs);
forced_idle_timer_->Stop();
forced_idle_timer_->Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(forced_delay_ms),
RenderThread::Get(),
&RenderThread::IdleHandler);
}
}
void Dispatcher::OnRenderProcessShutdown() {
v8_schema_registry_.reset();
forced_idle_timer_.reset();
content_watcher_.reset();
script_context_set_->ForEach(
std::string(), nullptr,
base::Bind(&ScriptContextSet::Remove,
base::Unretained(script_context_set_.get())));
}
void Dispatcher::OnActivateExtension(const std::string& extension_id) {
const Extension* extension =
RendererExtensionRegistry::Get()->GetByID(extension_id);
if (!extension) {
NOTREACHED();
// Extension was activated but was never loaded. This probably means that
// the renderer failed to load it (or the browser failed to tell us when it
// did). Failures shouldn't happen, but instead of crashing there (which
// executes on all renderers) be conservative and only crash in the renderer
// of the extension which failed to load; this one.
std::string& error = extension_load_errors_[extension_id];
char minidump[256];
base::debug::Alias(&minidump);
base::snprintf(minidump,
arraysize(minidump),
"e::dispatcher:%s:%s",
extension_id.c_str(),
error.c_str());
LOG(FATAL) << extension_id << " was never loaded: " << error;
}
active_extension_ids_.insert(extension_id);
// This is called when starting a new extension page, so start the idle
// handler ticking.
RenderThread::Get()->ScheduleIdleHandler(kInitialExtensionIdleHandlerDelayMs);
if (activity_logging_enabled_) {
DOMActivityLogger::AttachToWorld(DOMActivityLogger::kMainWorldId,
extension_id);
}
InitOriginPermissions(extension);
UpdateActiveExtensions();
}
void Dispatcher::OnCancelSuspend(const std::string& extension_id) {
DispatchEvent(extension_id, kOnSuspendCanceledEvent, base::ListValue(),
base::DictionaryValue());
}
void Dispatcher::OnDeliverMessage(const PortId& target_port_id,
const Message& message) {
MessagingBindings::DeliverMessage(*script_context_set_, target_port_id,
message,
NULL); // All render frames.
}
void Dispatcher::OnDispatchOnConnect(
const PortId& target_port_id,
const std::string& channel_name,
const ExtensionMsg_TabConnectionInfo& source,
const ExtensionMsg_ExternalConnectionInfo& info,
const std::string& tls_channel_id) {
DCHECK(!target_port_id.is_opener);
MessagingBindings::DispatchOnConnect(*script_context_set_, target_port_id,
channel_name, source, info,
tls_channel_id,
NULL); // All render frames.
}
void Dispatcher::OnDispatchOnDisconnect(const PortId& port_id,
const std::string& error_message) {
MessagingBindings::DispatchOnDisconnect(*script_context_set_, port_id,
error_message,
NULL); // All render frames.
}
void Dispatcher::OnLoaded(
const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions) {
for (const auto& param : loaded_extensions) {
std::string error;
scoped_refptr<const Extension> extension = param.ConvertToExtension(&error);
if (!extension.get()) {
NOTREACHED() << error;
// Note: in tests |param.id| has been observed to be empty (see comment
// just below) so this isn't all that reliable.
extension_load_errors_[param.id] = error;
continue;
}
RendererExtensionRegistry* extension_registry =
RendererExtensionRegistry::Get();
// TODO(kalman): This test is deliberately not a CHECK (though I wish it
// could be) and uses extension->id() not params.id:
// 1. For some reason params.id can be empty. I've only seen it with
// the webstore extension, in tests, and I've spent some time trying to
// figure out why - but cost/benefit won.
// 2. The browser only sends this IPC to RenderProcessHosts once, but the
// Dispatcher is attached to a RenderThread. Presumably there is a
// mismatch there. In theory one would think it's possible for the
// browser to figure this out itself - but again, cost/benefit.
if (!extension_registry->Insert(extension)) {
// TODO(devlin): This may be fixed by crbug.com/528026. Monitor, and
// consider making this a release CHECK.
NOTREACHED();
}
}
// Update the available bindings for all contexts. These may have changed if
// an externally_connectable extension was loaded that can connect to an
// open webpage.
UpdateBindings("");
}
void Dispatcher::OnMessageInvoke(const std::string& extension_id,
const std::string& module_name,
const std::string& function_name,
const base::ListValue& args) {
InvokeModuleSystemMethod(nullptr, extension_id, module_name, function_name,
args);
}
void Dispatcher::OnDispatchEvent(
const ExtensionMsg_DispatchEvent_Params& params,
const base::ListValue& event_args) {
std::unique_ptr<WebScopedUserGesture> web_user_gesture;
if (params.is_user_gesture)
web_user_gesture.reset(new WebScopedUserGesture(nullptr));
DispatchEvent(params.extension_id, params.event_name, event_args,
params.filtering_info);
// Tell the browser process when an event has been dispatched with a lazy
// background page active.
const Extension* extension =
RendererExtensionRegistry::Get()->GetByID(params.extension_id);
if (extension && BackgroundInfo::HasLazyBackgroundPage(extension)) {
content::RenderFrame* background_frame =
ExtensionFrameHelper::GetBackgroundPageFrame(params.extension_id);
if (background_frame) {
background_frame->Send(new ExtensionHostMsg_EventAck(
background_frame->GetRoutingID(), params.event_id));
}
}
}
void Dispatcher::OnSetSessionInfo(version_info::Channel channel,
FeatureSessionType session_type) {
SetCurrentChannel(channel);
SetCurrentFeatureSessionType(session_type);
if (feature_util::ExtensionServiceWorkersEnabled()) {
// chrome-extension: resources should be allowed to register ServiceWorkers.
blink::WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
blink::WebString::fromUTF8(extensions::kExtensionScheme));
}
}
void Dispatcher::OnSetScriptingWhitelist(
const ExtensionsClient::ScriptingWhitelist& extension_ids) {
ExtensionsClient::Get()->SetScriptingWhitelist(extension_ids);
}
void Dispatcher::OnSetSystemFont(const std::string& font_family,
const std::string& font_size) {
system_font_family_ = font_family;
system_font_size_ = font_size;
}
void Dispatcher::OnSetWebViewPartitionID(const std::string& partition_id) {
// |webview_partition_id_| cannot be changed once set.
CHECK(webview_partition_id_.empty() || webview_partition_id_ == partition_id);
webview_partition_id_ = partition_id;
}
void Dispatcher::OnShouldSuspend(const std::string& extension_id,
uint64_t sequence_id) {
RenderThread::Get()->Send(
new ExtensionHostMsg_ShouldSuspendAck(extension_id, sequence_id));
}
void Dispatcher::OnSuspend(const std::string& extension_id) {
// Dispatch the suspend event. This doesn't go through the standard event
// dispatch machinery because it requires special handling. We need to let
// the browser know when we are starting and stopping the event dispatch, so
// that it still considers the extension idle despite any activity the suspend
// event creates.
DispatchEvent(extension_id, kOnSuspendEvent, base::ListValue(),
base::DictionaryValue());
RenderThread::Get()->Send(new ExtensionHostMsg_SuspendAck(extension_id));
}
void Dispatcher::OnTransferBlobs(const std::vector<std::string>& blob_uuids) {
RenderThread::Get()->Send(new ExtensionHostMsg_TransferBlobsAck(blob_uuids));
}
void Dispatcher::OnUnloaded(const std::string& id) {
// See comment in OnLoaded for why it would be nice, but perhaps incorrect,
// to CHECK here rather than guarding.
// TODO(devlin): This may be fixed by crbug.com/528026. Monitor, and
// consider making this a release CHECK.
if (!RendererExtensionRegistry::Get()->Remove(id)) {
NOTREACHED();
return;
}
active_extension_ids_.erase(id);
script_injection_manager_->OnExtensionUnloaded(id);
// If the extension is later reloaded with a different set of permissions,
// we'd like it to get a new isolated world ID, so that it can pick up the
// changed origin whitelist.
ScriptInjection::RemoveIsolatedWorld(id);
// Invalidate all of the contexts that were removed.
// TODO(kalman): add an invalidation observer interface to ScriptContext.
std::set<ScriptContext*> removed_contexts =
script_context_set_->OnExtensionUnloaded(id);
for (ScriptContext* context : removed_contexts) {
bindings_system_->WillReleaseScriptContext(context);
}
// Update the available bindings for the remaining contexts. These may have
// changed if an externally_connectable extension is unloaded and a webpage
// is no longer accessible.
UpdateBindings("");
// Invalidates the messages map for the extension in case the extension is
// reloaded with a new messages map.
EraseL10nMessagesMap(id);
// We don't do anything with existing platform-app stylesheets. They will
// stay resident, but the URL pattern corresponding to the unloaded
// extension's URL just won't match anything anymore.
}
void Dispatcher::OnUpdatePermissions(
const ExtensionMsg_UpdatePermissions_Params& params) {
const Extension* extension =
RendererExtensionRegistry::Get()->GetByID(params.extension_id);
if (!extension)
return;
std::unique_ptr<const PermissionSet> active =
params.active_permissions.ToPermissionSet();
std::unique_ptr<const PermissionSet> withheld =
params.withheld_permissions.ToPermissionSet();
UpdateOriginPermissions(
extension->url(),
extension->permissions_data()->GetEffectiveHostPermissions(),
active->effective_hosts());
extension->permissions_data()->SetPermissions(std::move(active),
std::move(withheld));
UpdateBindings(extension->id());
}
void Dispatcher::OnUpdateTabSpecificPermissions(const GURL& visible_url,
const std::string& extension_id,
const URLPatternSet& new_hosts,
bool update_origin_whitelist,
int tab_id) {
const Extension* extension =
RendererExtensionRegistry::Get()->GetByID(extension_id);
if (!extension)
return;
URLPatternSet old_effective =
extension->permissions_data()->GetEffectiveHostPermissions();
extension->permissions_data()->UpdateTabSpecificPermissions(
tab_id,
extensions::PermissionSet(extensions::APIPermissionSet(),
extensions::ManifestPermissionSet(), new_hosts,
extensions::URLPatternSet()));
if (update_origin_whitelist) {
UpdateOriginPermissions(
extension->url(),
old_effective,
extension->permissions_data()->GetEffectiveHostPermissions());
}
}
void Dispatcher::OnClearTabSpecificPermissions(
const std::vector<std::string>& extension_ids,
bool update_origin_whitelist,
int tab_id) {
for (const std::string& id : extension_ids) {
const Extension* extension = RendererExtensionRegistry::Get()->GetByID(id);
if (extension) {
URLPatternSet old_effective =
extension->permissions_data()->GetEffectiveHostPermissions();
extension->permissions_data()->ClearTabSpecificPermissions(tab_id);
if (update_origin_whitelist) {
UpdateOriginPermissions(
extension->url(),
old_effective,
extension->permissions_data()->GetEffectiveHostPermissions());
}
}
}
}
void Dispatcher::OnSetActivityLoggingEnabled(bool enabled) {
activity_logging_enabled_ = enabled;
if (enabled) {
for (const std::string& id : active_extension_ids_)
DOMActivityLogger::AttachToWorld(DOMActivityLogger::kMainWorldId, id);
}
script_injection_manager_->set_activity_logging_enabled(enabled);
user_script_set_manager_->set_activity_logging_enabled(enabled);
}
void Dispatcher::OnUserScriptsUpdated(const std::set<HostID>& changed_hosts) {
UpdateActiveExtensions();
}
void Dispatcher::UpdateActiveExtensions() {
std::set<std::string> active_extensions = active_extension_ids_;
user_script_set_manager_->GetAllActiveExtensionIds(&active_extensions);
delegate_->OnActiveExtensionsUpdated(active_extensions);
}
void Dispatcher::InitOriginPermissions(const Extension* extension) {
delegate_->InitOriginPermissions(extension,
IsExtensionActive(extension->id()));
UpdateOriginPermissions(
extension->url(),
URLPatternSet(), // No old permissions.
extension->permissions_data()->GetEffectiveHostPermissions());
}
void Dispatcher::UpdateOriginPermissions(const GURL& extension_url,
const URLPatternSet& old_patterns,
const URLPatternSet& new_patterns) {
static const char* kSchemes[] = {
url::kHttpScheme,
url::kHttpsScheme,
url::kFileScheme,
content::kChromeUIScheme,
url::kFtpScheme,
#if defined(OS_CHROMEOS)
content::kExternalFileScheme,
#endif
extensions::kExtensionScheme,
};
for (size_t i = 0; i < arraysize(kSchemes); ++i) {
const char* scheme = kSchemes[i];
// Remove all old patterns...
for (URLPatternSet::const_iterator pattern = old_patterns.begin();
pattern != old_patterns.end(); ++pattern) {
if (pattern->MatchesScheme(scheme)) {
WebSecurityPolicy::removeOriginAccessWhitelistEntry(
extension_url,
WebString::fromUTF8(scheme),
WebString::fromUTF8(pattern->host()),
pattern->match_subdomains());
}
}
// ...And add the new ones.
for (URLPatternSet::const_iterator pattern = new_patterns.begin();
pattern != new_patterns.end(); ++pattern) {
if (pattern->MatchesScheme(scheme)) {
WebSecurityPolicy::addOriginAccessWhitelistEntry(
extension_url,
WebString::fromUTF8(scheme),
WebString::fromUTF8(pattern->host()),
pattern->match_subdomains());
}
}
}
}
void Dispatcher::EnableCustomElementWhiteList() {
blink::WebCustomElement::addEmbedderCustomElementName("appview");
blink::WebCustomElement::addEmbedderCustomElementName("appviewbrowserplugin");
blink::WebCustomElement::addEmbedderCustomElementName("extensionoptions");
blink::WebCustomElement::addEmbedderCustomElementName(
"extensionoptionsbrowserplugin");
blink::WebCustomElement::addEmbedderCustomElementName("extensionview");
blink::WebCustomElement::addEmbedderCustomElementName(
"extensionviewbrowserplugin");
blink::WebCustomElement::addEmbedderCustomElementName("webview");
blink::WebCustomElement::addEmbedderCustomElementName("webviewbrowserplugin");
}
void Dispatcher::UpdateBindings(const std::string& extension_id) {
script_context_set().ForEach(extension_id,
base::Bind(&Dispatcher::UpdateBindingsForContext,
base::Unretained(this)));
}
void Dispatcher::UpdateBindingsForContext(ScriptContext* context) {
bindings_system_->UpdateBindingsForContext(context);
Feature::Context context_type = context->context_type();
if (context_type == Feature::WEB_PAGE_CONTEXT ||
context_type == Feature::BLESSED_WEB_PAGE_CONTEXT) {
UpdateContentCapabilities(context);
}
}
// NOTE: please use the naming convention "foo_natives" for these.
void Dispatcher::RegisterNativeHandlers(ModuleSystem* module_system,
ScriptContext* context,
RequestSender* request_sender,
V8SchemaRegistry* v8_schema_registry) {
RegisterNativeHandlers(module_system, context, this, request_sender,
v8_schema_registry);
const Extension* extension = context->extension();
int manifest_version = extension ? extension->manifest_version() : 1;
bool is_component_extension =
extension && Manifest::IsComponentLocation(extension->location());
bool send_request_disabled =
(extension && Manifest::IsUnpackedLocation(extension->location()) &&
BackgroundInfo::HasLazyBackgroundPage(extension));
module_system->RegisterNativeHandler(
"process",
std::unique_ptr<NativeHandler>(new ProcessInfoNativeHandler(
context, context->GetExtensionID(),
context->GetContextTypeDescription(),
ExtensionsRendererClient::Get()->IsIncognitoProcess(),
is_component_extension, manifest_version, send_request_disabled)));
delegate_->RegisterNativeHandlers(this, module_system, context);
}
void Dispatcher::UpdateContentCapabilities(ScriptContext* context) {
APIPermissionSet permissions;
for (const auto& extension :
*RendererExtensionRegistry::Get()->GetMainThreadExtensionSet()) {
blink::WebLocalFrame* web_frame = context->web_frame();
GURL url = context->url();
// We allow about:blank pages to take on the privileges of their parents if
// they aren't sandboxed.
if (web_frame && !web_frame->getSecurityOrigin().isUnique())
url = ScriptContext::GetEffectiveDocumentURL(web_frame, url, true);
const ContentCapabilitiesInfo& info =
ContentCapabilitiesInfo::Get(extension.get());
if (info.url_patterns.MatchesURL(url)) {
APIPermissionSet new_permissions;
APIPermissionSet::Union(permissions, info.permissions, &new_permissions);
permissions = new_permissions;
}
}
context->set_content_capabilities(permissions);
}
void Dispatcher::PopulateSourceMap() {
const std::vector<std::pair<std::string, int> > resources = GetJsResources();
for (std::vector<std::pair<std::string, int> >::const_iterator resource =
resources.begin();
resource != resources.end();
++resource) {
source_map_.RegisterSource(resource->first, resource->second);
}
delegate_->PopulateSourceMap(&source_map_);
}
bool Dispatcher::IsWithinPlatformApp() {
for (std::set<std::string>::iterator iter = active_extension_ids_.begin();
iter != active_extension_ids_.end();
++iter) {
const Extension* extension =
RendererExtensionRegistry::Get()->GetByID(*iter);
if (extension && extension->is_platform_app())
return true;
}
return false;
}
void Dispatcher::RequireGuestViewModules(ScriptContext* context) {
Feature::Context context_type = context->context_type();
ModuleSystem* module_system = context->module_system();
bool requires_guest_view_module = false;
// Require AppView.
if (context->GetAvailability("appViewEmbedderInternal").is_available()) {
requires_guest_view_module = true;
module_system->Require("appView");
}
// Require ExtensionOptions.
if (context->GetAvailability("extensionOptionsInternal").is_available()) {
requires_guest_view_module = true;
module_system->Require("extensionOptions");
module_system->Require("extensionOptionsAttributes");
}
// Require ExtensionView.
if (context->GetAvailability("extensionViewInternal").is_available()) {
requires_guest_view_module = true;
module_system->Require("extensionView");
module_system->Require("extensionViewApiMethods");
module_system->Require("extensionViewAttributes");
}
// Require WebView.
if (context->GetAvailability("webViewInternal").is_available()) {
requires_guest_view_module = true;
module_system->Require("webView");
module_system->Require("webViewApiMethods");
module_system->Require("webViewAttributes");
}
if (requires_guest_view_module &&
base::FeatureList::IsEnabled(::features::kGuestViewCrossProcessFrames)) {
module_system->Require("guestViewIframe");
module_system->Require("guestViewIframeContainer");
}
// The "guestViewDeny" module must always be loaded last. It registers
// error-providing custom elements for the GuestView types that are not
// available, and thus all of those types must have been checked and loaded
// (or not loaded) beforehand.
if (context_type == Feature::BLESSED_EXTENSION_CONTEXT) {
module_system->Require("guestViewDeny");
}
}
} // namespace extensions
|