forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdispatcher.cc
1588 lines (1384 loc) · 65.9 KB
/
dispatcher.cc
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
// 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 <algorithm>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/debug/alias.h"
#include "base/feature_list.h"
#include "base/lazy_instance.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.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/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/v8_value_converter.h"
#include "extensions/common/api/messaging/message.h"
#include "extensions/common/constants.h"
#include "extensions/common/cors_util.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_api.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/extension_urls.h"
#include "extensions/common/extensions_client.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_developer_mode_only.h"
#include "extensions/common/features/feature_provider.h"
#include "extensions/common/features/feature_session_type.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/background_info.h"
#include "extensions/common/manifest_handlers/options_page_info.h"
#include "extensions/common/mojom/host_id.mojom.h"
#include "extensions/common/permissions/permission_set.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/switches.h"
#include "extensions/grit/extensions_renderer_resources.h"
#include "extensions/renderer/api/automation/automation_internal_custom_bindings.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/dom_activity_logger.h"
#include "extensions/renderer/extension_frame_helper.h"
#include "extensions/renderer/extension_interaction_provider.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/ipc_message_sender.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/native_renderer_messaging_service.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/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/set_icon_natives.h"
#include "extensions/renderer/shared_l10n_map.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/trace_util.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 "extensions/renderer/worker_thread_util.h"
#include "gin/converter.h"
#include "mojo/public/js/grit/mojo_bindings_resources.h"
#include "services/network/public/mojom/cors.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/mojom/frame/user_activation_notification_type.mojom.h"
#include "third_party/blink/public/platform/web_string.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/public/web/modules/service_worker/web_service_worker_context_proxy.h"
#include "third_party/blink/public/web/web_custom_element.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_frame.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_controller.h"
#include "third_party/blink/public/web/web_security_policy.h"
#include "third_party/blink/public/web/web_settings.h"
#include "third_party/blink/public/web/web_v8_features.h"
#include "third_party/blink/public/web/web_view.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "v8/include/v8-context.h"
#include "v8/include/v8-function.h"
#include "v8/include/v8-object.h"
#include "v8/include/v8-primitive.h"
using blink::WebDocument;
using blink::WebSecurityPolicy;
using blink::WebString;
using blink::WebView;
using content::RenderThread;
namespace extensions {
namespace {
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->GetListDeprecated()) {
arguments.push_back(converter->ToV8Value(&arg, 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) {}
// ObjectBackedNativeHandler:
void AddRoutes() override {
RouteHandlerFunction("GetChrome",
base::BindRepeating(&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::NewStringType::kInternalized)
.ToLocalChecked());
v8::Local<v8::Object> global(context()->v8_context()->Global());
// TODO(crbug.com/913942): Possibly replace ToLocalChecked here with
// actual error handling.
v8::Local<v8::Value> chrome(
global->Get(context()->v8_context(), chrome_string).ToLocalChecked());
if (chrome->IsUndefined()) {
chrome = v8::Object::New(context()->isolate());
global->Set(context()->v8_context(), chrome_string, chrome).ToChecked();
}
args.GetReturnValue().Set(chrome);
}
};
class HandleScopeHelper {
public:
HandleScopeHelper(ScriptContext* script_context)
: handle_scope_(script_context->isolate()),
context_scope_(script_context->v8_context()) {}
HandleScopeHelper(const HandleScopeHelper&) = delete;
HandleScopeHelper& operator=(const HandleScopeHelper&) = delete;
private:
v8::HandleScope handle_scope_;
v8::Context::Scope context_scope_;
};
base::LazyInstance<WorkerScriptContextSet>::DestructorAtExit
g_worker_script_context_set = LAZY_INSTANCE_INITIALIZER;
// Creates a new extension from the data in the mojom::ExtensionLoadedParams
// object. A context_id needs to be passed because each browser context can have
// different values for default_policy_blocked/allowed_hosts.
// (see extension_util.cc#GetBrowserContextId)
scoped_refptr<extensions::Extension> ConvertToExtension(
mojom::ExtensionLoadedParamsPtr params,
int context_id,
std::string* error) {
// We pass in the |id| to the create call because it will save work in the
// normal case, and because in tests, extensions may not have paths or keys,
// but it's important to retain the same id.
scoped_refptr<Extension> extension =
Extension::Create(params->path, params->location,
base::Value::AsDictionaryValue(params->manifest),
params->creation_flags, params->id, error);
if (!extension.get())
return extension;
const extensions::PermissionsData* permissions_data =
extension->permissions_data();
permissions_data->SetPermissions(
std::make_unique<const extensions::PermissionSet>(
std::move(params->active_permissions)),
std::make_unique<const extensions::PermissionSet>(
std::move(params->withheld_permissions)));
if (params->uses_default_policy_blocked_allowed_hosts) {
permissions_data->SetUsesDefaultHostRestrictions(context_id);
} else {
permissions_data->SetPolicyHostRestrictions(params->policy_blocked_hosts,
params->policy_allowed_hosts);
}
for (const auto& pair : params->tab_specific_permissions) {
permissions_data->UpdateTabSpecificPermissions(pair.first, pair.second);
}
extension->SetGUID(params->guid);
return extension;
}
} // namespace
Dispatcher::PendingServiceWorker::PendingServiceWorker(
blink::WebServiceWorkerContextProxy* context_proxy)
: task_runner(base::ThreadTaskRunnerHandle::Get()),
context_proxy(context_proxy) {
DCHECK(context_proxy);
}
Dispatcher::PendingServiceWorker::~PendingServiceWorker() = default;
// 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(std::unique_ptr<DispatcherDelegate> delegate)
: delegate_(std::move(delegate)),
content_watcher_(new ContentWatcher()),
source_map_(&ui::ResourceBundle::GetSharedInstance()),
v8_schema_registry_(new V8SchemaRegistry),
activity_logging_enabled_(false),
receiver_(this),
dispatcher_(this) {
bindings_system_ = CreateBindingsSystem(
IPCMessageSender::CreateMainThreadIPCMessageSender());
script_context_set_ =
std::make_unique<ScriptContextSet>(&active_extension_ids_);
user_script_set_manager_ = std::make_unique<UserScriptSetManager>();
script_injection_manager_ =
std::make_unique<ScriptInjectionManager>(user_script_set_manager_.get());
user_script_set_manager_observation_.Observe(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());
// Register WebSecurityPolicy allowlists for the chrome-extension:// scheme.
WebString extension_scheme(WebString::FromASCII(kExtensionScheme));
// 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);
// Register WebSecurityPolicy allowlists for the file:// scheme.
WebString file_scheme(WebString::FromASCII(url::kFileScheme));
// Extensions are allowed to make cross-origin requests to file scheme iff the
// user explicitly grants them access post-installation in the
// chrome://extensions page.
WebSecurityPolicy::RegisterURLSchemeAsSupportingFetchAPI(file_scheme);
// Extension resources, when loaded as the top-level document, should bypass
// Blink's strict first-party origin checks.
WebSecurityPolicy::RegisterURLSchemeAsFirstPartyWhenTopLevel(
extension_scheme);
// Disallow running javascript URLs on the chrome-extension scheme.
WebSecurityPolicy::RegisterURLSchemeAsNotAllowingJavascriptURLs(
extension_scheme);
if (base::FeatureList::IsEnabled(
extensions_features::kAllowSharedArrayBuffersUnconditionally)) {
WebSecurityPolicy::RegisterURLSchemeAsAllowingSharedArrayBuffers(
extension_scheme);
}
// chrome-extension: resources should be allowed to register ServiceWorkers.
WebSecurityPolicy::RegisterURLSchemeAsAllowingServiceWorkers(
extension_scheme);
WebSecurityPolicy::RegisterURLSchemeAsAllowingWasmEvalCSP(extension_scheme);
// 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);
}
EnableCustomElementAllowlist();
}
Dispatcher::~Dispatcher() {
}
// static
WorkerScriptContextSet* Dispatcher::GetWorkerScriptContextSet() {
return &(g_worker_script_context_set.Get());
}
void Dispatcher::OnRenderThreadStarted(content::RenderThread* thread) {
thread->RegisterExtension(extensions::SafeBuiltins::CreateV8Extension());
}
void Dispatcher::OnRenderFrameCreated(content::RenderFrame* render_frame) {
script_injection_manager_->OnRenderFrameCreated(render_frame);
content_watcher_->OnRenderFrameCreated(render_frame);
// The RenderFrame comes with the initial empty document already created.
DidCreateDocumentElement(render_frame->GetWebFrame());
// We run scripts on the empty document.
RunScriptsAtDocumentStart(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,
int32_t 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 |ActivateExtension|.
if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT)
InitOriginPermissions(context->extension());
context->SetModuleSystem(
std::make_unique<ModuleSystem>(context, &source_map_));
ModuleSystem* module_system = context->module_system();
// Enable natives in startup.
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
RegisterNativeHandlers(module_system, context, bindings_system_.get(),
v8_schema_registry_.get());
bindings_system_->DidCreateScriptContext(context);
// Inject custom JS into the platform app context.
if (IsWithinPlatformApp()) {
module_system->Require("platformApp");
}
RequireGuestViewModules(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:
// For service workers this is handled in
// WillEvaluateServiceWorkerOnWorkerThread().
DCHECK(!context->IsForServiceWorker());
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::WEBUI_UNTRUSTED_CONTEXT:
// Extension APIs in untrusted WebUIs are temporary so don't bother
// recording metrics for them.
break;
case Feature::LOCK_SCREEN_EXTENSION_CONTEXT:
UMA_HISTOGRAM_TIMES(
"Extensions.DidCreateScriptContext_LockScreenExtension", elapsed);
break;
}
VLOG(1) << "Num tracked contexts: " << script_context_set_->size();
ExtensionFrameHelper* frame_helper =
ExtensionFrameHelper::Get(content::RenderFrame::FromWebFrame(frame));
if (!frame_helper)
return; // The frame is invisible to extensions.
frame_helper->set_did_create_script_context();
}
void Dispatcher::DidInitializeServiceWorkerContextOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
const GURL& service_worker_scope,
const GURL& script_url) {
if (!script_url.SchemeIs(kExtensionScheme))
return;
{
base::AutoLock lock(service_workers_paused_for_on_loaded_message_lock_);
ExtensionId extension_id =
RendererExtensionRegistry::Get()->GetExtensionOrAppIDByURL(script_url);
// If the extension is already loaded we don't have to suspend the service
// worker. The service worker will continue in
// Dispatcher::WillEvaluateServiceWorkerOnWorkerThread().
if (RendererExtensionRegistry::Get()->GetByID(extension_id))
return;
// Suspend the service worker until loaded message of the extension comes.
// The service worker will be resumed in Dispatcher::OnLoaded().
context_proxy->PauseEvaluation();
service_workers_paused_for_on_loaded_message_.emplace(
extension_id, std::make_unique<PendingServiceWorker>(context_proxy));
}
}
void Dispatcher::WillEvaluateServiceWorkerOnWorkerThread(
blink::WebServiceWorkerContextProxy* context_proxy,
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
const base::TimeTicks start_time = base::TimeTicks::Now();
// TODO(crbug/961821): We may want to give service workers not registered
// by extensions minimal bindings, the same as other webpage-like contexts.
if (!script_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(script_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 (script_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;
}
// Only the script specific in the manifest's background data gets bindings.
//
// TODO(crbug/961821): We may want to give other service workers registered
// by extensions minimal bindings, just as we might want to give them to
// service workers that aren't registered by extensions.
ScriptContext* context = new ScriptContext(
v8_context, nullptr, extension, Feature::BLESSED_EXTENSION_CONTEXT,
extension, Feature::BLESSED_EXTENSION_CONTEXT);
context->set_url(script_url);
context->set_service_worker_scope(service_worker_scope);
context->set_service_worker_version_id(service_worker_version_id);
if (ExtensionsRendererClient::Get()
->ExtensionAPIEnabledForServiceWorkerScript(service_worker_scope,
script_url)) {
WorkerThreadDispatcher* worker_dispatcher = WorkerThreadDispatcher::Get();
std::unique_ptr<IPCMessageSender> ipc_sender =
IPCMessageSender::CreateWorkerThreadIPCMessageSender(
worker_dispatcher, service_worker_version_id);
ActivationSequence worker_activation_sequence =
*RendererExtensionRegistry::Get()->GetWorkerActivationSequence(
extension->id());
worker_dispatcher->AddWorkerData(
service_worker_version_id, worker_activation_sequence, context,
CreateBindingsSystem(std::move(ipc_sender)));
worker_thread_util::SetWorkerContextProxy(context_proxy);
// TODO(lazyboy): Make sure accessing |source_map_| in worker thread is
// safe.
context->SetModuleSystem(
std::make_unique<ModuleSystem>(context, &source_map_));
ModuleSystem* module_system = context->module_system();
// Enable natives in startup.
ModuleSystem::NativesEnabledScope natives_enabled_scope(module_system);
NativeExtensionBindingsSystem* worker_bindings_system =
WorkerThreadDispatcher::GetBindingsSystem();
RegisterNativeHandlers(module_system, context, worker_bindings_system,
WorkerThreadDispatcher::GetV8SchemaRegistry());
worker_bindings_system->DidCreateScriptContext(context);
// TODO(lazyboy): Get rid of RequireGuestViewModules() as this doesn't seem
// necessary for Extension SW.
RequireGuestViewModules(context);
worker_dispatcher->DidInitializeContext(service_worker_version_id);
}
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 =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_SERVICE_WORKER_BINDINGS_JS);
v8::Local<v8::String> script =
v8::String::NewExternalOneByte(
isolate, new StaticV8ExternalOneByteStringResource(script_resource))
.ToLocalChecked();
// 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::BindOnce(&CrashOnException));
// This *should* always be a function (because the script is included as
// part of Chrome). However, it may not be in the case of e.g. binary
// corruption, or if certain JS hooks ran before the script (though that
// should be rare, since this is running right after the context is
// created).
// https://crbug.com/1260773.
if (!result->IsFunction()) {
NOTREACHED();
return;
}
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);
logging->Initialize();
context->AddInvalidationObserver(
base::BindOnce(&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, std::size(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,
int32_t 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();
}
void Dispatcher::DidStartServiceWorkerContextOnWorkerThread(
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
if (!ExtensionsRendererClient::Get()
->ExtensionAPIEnabledForServiceWorkerScript(service_worker_scope,
script_url))
return;
DCHECK(worker_thread_util::IsWorkerThread());
WorkerThreadDispatcher::Get()->DidStartContext(service_worker_scope,
service_worker_version_id);
}
void Dispatcher::WillDestroyServiceWorkerContextOnWorkerThread(
v8::Local<v8::Context> v8_context,
int64_t service_worker_version_id,
const GURL& service_worker_scope,
const GURL& script_url) {
// Note that using ExtensionAPIEnabledForServiceWorkerScript() won't work here
// as RendererExtensionRegistry might have already unloaded this extension.
// Use the existence of ServiceWorkerData as the source of truth instead.
if (!WorkerThreadDispatcher::GetServiceWorkerData()) {
// If extension APIs in service workers aren't enabled, we just need to
// remove the context.
g_worker_script_context_set.Get().Remove(v8_context, script_url);
} else {
// TODO(lazyboy/devlin): Should this cleanup happen in a worker class, like
// WorkerThreadDispatcher? If so, we should move the initialization as well.
ScriptContext* script_context = WorkerThreadDispatcher::GetScriptContext();
NativeExtensionBindingsSystem* worker_bindings_system =
WorkerThreadDispatcher::GetBindingsSystem();
worker_bindings_system->WillReleaseScriptContext(script_context);
WorkerThreadDispatcher::Get()->DidStopContext(service_worker_scope,
service_worker_version_id);
// Note: we have to remove the context (and thus perform invalidation on
// the native handlers) prior to removing the worker data, which destroys
// the associated bindings system.
g_worker_script_context_set.Get().Remove(v8_context, script_url);
WorkerThreadDispatcher::Get()->RemoveWorkerData(service_worker_version_id);
worker_thread_util::SetWorkerContextProxy(nullptr);
}
std::string extension_id =
RendererExtensionRegistry::Get()->GetExtensionOrAppIDByURL(script_url);
{
base::AutoLock lock(service_workers_paused_for_on_loaded_message_lock_);
service_workers_paused_for_on_loaded_message_.erase(extension_id);
}
}
void Dispatcher::DidCreateDocumentElement(blink::WebLocalFrame* frame) {
// Note: use GetEffectiveDocumentURLForContext() and not just
// frame->document()->url() so that this also injects the stylesheet on
// about:blank frames that are hosted in the extension process. (Even though
// this is used to determine whether to inject a stylesheet, we don't use
// GetEffectiveDocumentURLForInjection() because we inject based on whether
// it is an extension context, rather than based on the extension's injection
// permissions.)
GURL effective_document_url =
ScriptContext::GetEffectiveDocumentURLForContext(
frame, frame->GetDocument().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 =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
resource_id);
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->GetDocument().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)) {
std::string extension_css =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_EXTENSION_CSS);
frame->GetDocument().InsertStyleSheet(WebString::FromUTF8(extension_css));
}
}
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::RunScriptsAtDocumentIdle(content::RenderFrame* render_frame) {
ExtensionFrameHelper* frame_helper = ExtensionFrameHelper::Get(render_frame);
if (!frame_helper)
return; // The frame is invisible to extensions.
frame_helper->RunScriptsAtDocumentIdle();
// |frame_helper| and |render_frame| might be dead by now.
}
void Dispatcher::DispatchEventHelper(
const std::string& extension_id,
const std::string& event_name,
const base::ListValue& event_args,
mojom::EventFilteringInfoPtr filtering_info) const {
script_context_set_->ForEach(
extension_id, nullptr,
base::BindRepeating(
&NativeExtensionBindingsSystem::DispatchEventInContext,
base::Unretained(bindings_system_.get()), event_name, &event_args,
base::OwnedRef(std::move(filtering_info))));
}
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::BindRepeating(&CallModuleMethod, module_name, function_name,
&args));
}
void Dispatcher::ExecuteDeclarativeScript(content::RenderFrame* render_frame,
int tab_id,
const ExtensionId& extension_id,
const std::string& script_id,
const GURL& url) {
TRACE_RENDERER_EXTENSION_EVENT("Dispatcher::ExecuteDeclarativeScript",
extension_id);
script_injection_manager_->ExecuteDeclarativeScript(
render_frame, tab_id, extension_id, script_id, url);
}
void Dispatcher::ExecuteCode(mojom::ExecuteCodeParamsPtr param,
mojom::LocalFrame::ExecuteCodeCallback callback,
content::RenderFrame* render_frame) {
TRACE_RENDERER_EXTENSION_EVENT("Dispatcher::ExecuteCode", param->host_id->id);
script_injection_manager_->HandleExecuteCode(
std::move(param), std::move(callback), render_frame);
}
// static
std::vector<Dispatcher::JsResourceInfo> Dispatcher::GetJsResources() {
// Libraries.
std::vector<JsResourceInfo> resources = {
{"appView", IDR_APP_VIEW_JS},
{"appViewElement", IDR_APP_VIEW_ELEMENT_JS},
{"appViewDeny", IDR_APP_VIEW_DENY_JS},
{"entryIdManager", IDR_ENTRY_ID_MANAGER},
{"extensionOptions", IDR_EXTENSION_OPTIONS_JS},
{"extensionOptionsElement", IDR_EXTENSION_OPTIONS_ELEMENT_JS},
{"extensionOptionsAttributes", IDR_EXTENSION_OPTIONS_ATTRIBUTES_JS},
{"extensionOptionsConstants", IDR_EXTENSION_OPTIONS_CONSTANTS_JS},
{"extensionOptionsEvents", IDR_EXTENSION_OPTIONS_EVENTS_JS},
{"feedbackPrivate", IDR_FEEDBACK_PRIVATE_CUSTOM_BINDINGS_JS},
{"fileEntryBindingUtil", IDR_FILE_ENTRY_BINDING_UTIL_JS},
{"fileSystem", IDR_FILE_SYSTEM_CUSTOM_BINDINGS_JS},
{"guestView", IDR_GUEST_VIEW_JS},
{"guestViewAttributes", IDR_GUEST_VIEW_ATTRIBUTES_JS},
{"guestViewContainer", IDR_GUEST_VIEW_CONTAINER_JS},
{"guestViewContainerElement", IDR_GUEST_VIEW_CONTAINER_ELEMENT_JS},
{"guestViewDeny", IDR_GUEST_VIEW_DENY_JS},
{"guestViewEvents", IDR_GUEST_VIEW_EVENTS_JS},
{"safeMethods", IDR_SAFE_METHODS_JS},
{"imageUtil", IDR_IMAGE_UTIL_JS},
{"setIcon", IDR_SET_ICON_JS},
{"test", IDR_TEST_CUSTOM_BINDINGS_JS},
{"test_environment_specific_bindings",
IDR_BROWSER_TEST_ENVIRONMENT_SPECIFIC_BINDINGS_JS},
{"uncaught_exception_handler", IDR_UNCAUGHT_EXCEPTION_HANDLER_JS},
{"utils", IDR_UTILS_JS},
{"webRequest", IDR_WEB_REQUEST_CUSTOM_BINDINGS_JS},
{"webRequestEvent", IDR_WEB_REQUEST_EVENT_JS},
// Note: webView not webview so that this doesn't interfere with the
// chrome.webview API bindings.
{"webView", IDR_WEB_VIEW_JS},
{"webViewElement", IDR_WEB_VIEW_ELEMENT_JS},
{"extensionsWebViewElement", IDR_EXTENSIONS_WEB_VIEW_ELEMENT_JS},
{"webViewDeny", IDR_WEB_VIEW_DENY_JS},
{"webViewActionRequests", IDR_WEB_VIEW_ACTION_REQUESTS_JS},
{"webViewApiMethods", IDR_WEB_VIEW_API_METHODS_JS},
{"webViewAttributes", IDR_WEB_VIEW_ATTRIBUTES_JS},
{"webViewConstants", IDR_WEB_VIEW_CONSTANTS_JS},
{"webViewEvents", IDR_WEB_VIEW_EVENTS_JS},
{"webViewInternal", IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS},
{"keep_alive", IDR_KEEP_ALIVE_JS},
{"mojo_bindings", IDR_MOJO_MOJO_BINDINGS_JS},
#if BUILDFLAG(IS_CHROMEOS_ASH)
{"mojo_bindings_lite", IDR_MOJO_MOJO_BINDINGS_LITE_JS},
#endif
{"extensions/common/mojom/keep_alive.mojom", IDR_KEEP_ALIVE_MOJOM_JS},
// Custom bindings.
{"automation", IDR_AUTOMATION_CUSTOM_BINDINGS_JS},
{"automationEvent", IDR_AUTOMATION_EVENT_JS},
{"automationNode", IDR_AUTOMATION_NODE_JS},
{"automationTreeCache", IDR_AUTOMATION_TREE_CACHE_JS},
{"app.runtime", IDR_APP_RUNTIME_CUSTOM_BINDINGS_JS},
{"app.window", IDR_APP_WINDOW_CUSTOM_BINDINGS_JS},
{"declarativeWebRequest", IDR_DECLARATIVE_WEBREQUEST_CUSTOM_BINDINGS_JS},
{"contextMenus", IDR_CONTEXT_MENUS_CUSTOM_BINDINGS_JS},
{"contextMenusHandlers", IDR_CONTEXT_MENUS_HANDLERS_JS},
{"mimeHandlerPrivate", IDR_MIME_HANDLER_PRIVATE_CUSTOM_BINDINGS_JS},
{"extensions/common/api/mime_handler.mojom", IDR_MIME_HANDLER_MOJOM_JS},
{"mojoPrivate", IDR_MOJO_PRIVATE_CUSTOM_BINDINGS_JS},
{"permissions", IDR_PERMISSIONS_CUSTOM_BINDINGS_JS},
{"printerProvider", IDR_PRINTER_PROVIDER_CUSTOM_BINDINGS_JS},
{"webViewRequest", IDR_WEB_VIEW_REQUEST_CUSTOM_BINDINGS_JS},
// Platform app sources that are not API-specific..
{"platformApp", IDR_PLATFORM_APP_JS},
};
return resources;
}
// NOTE: please use the naming convention "foo_natives" for these.
// static
void Dispatcher::RegisterNativeHandlers(
ModuleSystem* module_system,
ScriptContext* context,
Dispatcher* dispatcher,
NativeExtensionBindingsSystem* bindings_system,
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(
"messaging_natives", std::make_unique<MessagingBindings>(context));
module_system->RegisterNativeHandler(
"apiDefinitions", std::unique_ptr<NativeHandler>(
new ApiDefinitionsNatives(dispatcher, context)));
module_system->RegisterNativeHandler(
"setIcon", std::unique_ptr<NativeHandler>(new SetIconNatives(context)));
module_system->RegisterNativeHandler(
"activityLogger", std::make_unique<APIActivityLogger>(
bindings_system->GetIPCMessageSender(), context));
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(
"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(
"process", std::make_unique<ProcessInfoNativeHandler>(context));
module_system->RegisterNativeHandler(
"runtime",
std::unique_ptr<NativeHandler>(new RuntimeCustomBindings(context)));
module_system->RegisterNativeHandler(
"automationInternal",
std::make_unique<extensions::AutomationInternalCustomBindings>(
context, bindings_system));
}
bool Dispatcher::OnControlMessageReceived(const IPC::Message& message) {
if (WorkerThreadDispatcher::Get()->OnControlMessageReceived(message))
return true;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(Dispatcher, message)
IPC_MESSAGE_HANDLER(ExtensionMsg_DeliverMessage, OnDeliverMessage)
IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnConnect, OnDispatchOnConnect)
IPC_MESSAGE_HANDLER(ExtensionMsg_DispatchOnDisconnect, OnDispatchOnDisconnect)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void Dispatcher::RegisterMojoInterfaces(
blink::AssociatedInterfaceRegistry* associated_interfaces) {
// This base::Unretained() is safe, because:
// 1) the Dispatcher is a RenderThreadObserver and outlives the RenderThread.
// 2) |asscoiated_interfaces| is owned by the RenderThread.
// As well the Dispatcher is owned by the
// ExtensionsRendererClient, which in turn is a leaky LazyInstance (and thus
// never deleted).
associated_interfaces->AddInterface(base::BindRepeating(
&Dispatcher::OnRendererAssociatedRequest, base::Unretained(this)));
associated_interfaces->AddInterface(base::BindRepeating(
&Dispatcher::OnEventDispatcherRequest, base::Unretained(this)));
}
void Dispatcher::UnregisterMojoInterfaces(
blink::AssociatedInterfaceRegistry* associated_interfaces) {
associated_interfaces->RemoveInterface(mojom::Renderer::Name_);
associated_interfaces->RemoveInterface(mojom::EventDispatcher::Name_);
}
void Dispatcher::OnRendererAssociatedRequest(
mojo::PendingAssociatedReceiver<mojom::Renderer> receiver) {