1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/renderer/script_injection.h"
9 #include "base/lazy_instance.h"
10 #include "base/metrics/histogram.h"
11 #include "base/timer/elapsed_timer.h"
12 #include "base/values.h"
13 #include "content/public/child/v8_value_converter.h"
14 #include "content/public/renderer/render_view.h"
15 #include "extensions/common/extension_messages.h"
16 #include "extensions/common/host_id.h"
17 #include "extensions/common/manifest_handlers/csp_info.h"
18 #include "extensions/renderer/dom_activity_logger.h"
19 #include "extensions/renderer/extension_groups.h"
20 #include "extensions/renderer/extension_injection_host.h"
21 #include "extensions/renderer/extensions_renderer_client.h"
22 #include "third_party/WebKit/public/platform/WebString.h"
23 #include "third_party/WebKit/public/web/WebDocument.h"
24 #include "third_party/WebKit/public/web/WebLocalFrame.h"
25 #include "third_party/WebKit/public/web/WebScopedUserGesture.h"
26 #include "third_party/WebKit/public/web/WebScriptSource.h"
27 #include "third_party/WebKit/public/web/WebSecurityOrigin.h"
30 namespace extensions
{
34 using IsolatedWorldMap
= std::map
<std::string
, int>;
35 base::LazyInstance
<IsolatedWorldMap
> g_isolated_worlds
=
36 LAZY_INSTANCE_INITIALIZER
;
38 const int64 kInvalidRequestId
= -1;
40 // The id of the next pending injection.
41 int64 g_next_pending_id
= 0;
43 // Append all the child frames of |parent_frame| to |frames_vector|.
44 void AppendAllChildFrames(blink::WebFrame
* parent_frame
,
45 std::vector
<blink::WebFrame
*>* frames_vector
) {
47 for (blink::WebFrame
* child_frame
= parent_frame
->firstChild(); child_frame
;
48 child_frame
= child_frame
->nextSibling()) {
49 frames_vector
->push_back(child_frame
);
50 AppendAllChildFrames(child_frame
, frames_vector
);
54 // Gets the isolated world ID to use for the given |injection_host|
55 // in the given |frame|. If no isolated world has been created for that
56 // |injection_host| one will be created and initialized.
57 int GetIsolatedWorldIdForInstance(const InjectionHost
* injection_host
,
58 blink::WebLocalFrame
* frame
) {
59 static int g_next_isolated_world_id
=
60 ExtensionsRendererClient::Get()->GetLowestIsolatedWorldId();
62 IsolatedWorldMap
& isolated_worlds
= g_isolated_worlds
.Get();
65 const std::string
& key
= injection_host
->id().id();
66 IsolatedWorldMap::iterator iter
= isolated_worlds
.find(key
);
67 if (iter
!= isolated_worlds
.end()) {
70 id
= g_next_isolated_world_id
++;
71 // This map will tend to pile up over time, but realistically, you're never
72 // going to have enough injection hosts for it to matter.
73 isolated_worlds
[key
] = id
;
76 // We need to set the isolated world origin and CSP even if it's not a new
77 // world since these are stored per frame, and we might not have used this
78 // isolated world in this frame before.
79 frame
->setIsolatedWorldSecurityOrigin(
80 id
, blink::WebSecurityOrigin::create(injection_host
->url()));
81 frame
->setIsolatedWorldContentSecurityPolicy(
82 id
, blink::WebString::fromUTF8(
83 injection_host
->GetContentSecurityPolicy()));
84 frame
->setIsolatedWorldHumanReadableName(
85 id
, blink::WebString::fromUTF8(injection_host
->name()));
93 std::string
ScriptInjection::GetHostIdForIsolatedWorld(int isolated_world_id
) {
94 const IsolatedWorldMap
& isolated_worlds
= g_isolated_worlds
.Get();
96 for (const auto& iter
: isolated_worlds
) {
97 if (iter
.second
== isolated_world_id
)
100 return std::string();
104 void ScriptInjection::RemoveIsolatedWorld(const std::string
& host_id
) {
105 g_isolated_worlds
.Get().erase(host_id
);
108 ScriptInjection::ScriptInjection(
109 scoped_ptr
<ScriptInjector
> injector
,
110 blink::WebLocalFrame
* web_frame
,
111 const HostID
& host_id
,
112 UserScript::RunLocation run_location
,
114 : injector_(injector
.Pass()),
115 web_frame_(web_frame
),
117 run_location_(run_location
),
119 request_id_(kInvalidRequestId
),
123 ScriptInjection::~ScriptInjection() {
125 injector_
->OnWillNotInject(ScriptInjector::WONT_INJECT
);
128 bool ScriptInjection::TryToInject(UserScript::RunLocation current_location
,
129 const InjectionHost
* injection_host
,
130 ScriptsRunInfo
* scripts_run_info
) {
131 if (current_location
< run_location_
)
132 return false; // Wait for the right location.
134 if (request_id_
!= kInvalidRequestId
)
135 return false; // We're waiting for permission right now, try again later.
137 if (!injection_host
) {
138 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED
);
139 return true; // We're done.
142 switch (injector_
->CanExecuteOnFrame(injection_host
, web_frame_
, tab_id_
,
143 web_frame_
->top()->document().url())) {
144 case PermissionsData::ACCESS_DENIED
:
145 NotifyWillNotInject(ScriptInjector::NOT_ALLOWED
);
146 return true; // We're done.
147 case PermissionsData::ACCESS_WITHHELD
:
148 SendInjectionMessage(true /* request permission */);
149 return false; // Wait around for permission.
150 case PermissionsData::ACCESS_ALLOWED
:
151 Inject(injection_host
, scripts_run_info
);
152 return true; // We're done!
159 bool ScriptInjection::OnPermissionGranted(const InjectionHost
* injection_host
,
160 ScriptsRunInfo
* scripts_run_info
) {
161 if (!injection_host
) {
162 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED
);
166 Inject(injection_host
, scripts_run_info
);
170 void ScriptInjection::SendInjectionMessage(bool request_permission
) {
171 content::RenderView
* render_view
=
172 content::RenderView::FromWebView(web_frame()->top()->view());
174 // If we are just notifying the browser of the injection, then send an
175 // invalid request (which is treated like a notification).
176 request_id_
= request_permission
? g_next_pending_id
++ : kInvalidRequestId
;
177 render_view
->Send(new ExtensionHostMsg_RequestScriptInjectionPermission(
178 render_view
->GetRoutingID(),
180 injector_
->script_type(),
184 void ScriptInjection::NotifyWillNotInject(
185 ScriptInjector::InjectFailureReason reason
) {
187 injector_
->OnWillNotInject(reason
);
190 void ScriptInjection::Inject(const InjectionHost
* injection_host
,
191 ScriptsRunInfo
* scripts_run_info
) {
192 DCHECK(injection_host
);
193 DCHECK(scripts_run_info
);
196 if (injection_host
->ShouldNotifyBrowserOfInjection())
197 SendInjectionMessage(false /* don't request permission */);
199 std::vector
<blink::WebFrame
*> frame_vector
;
200 frame_vector
.push_back(web_frame_
);
201 if (injector_
->ShouldExecuteInChildFrames())
202 AppendAllChildFrames(web_frame_
, &frame_vector
);
204 scoped_ptr
<blink::WebScopedUserGesture
> gesture
;
205 if (injector_
->IsUserGesture())
206 gesture
.reset(new blink::WebScopedUserGesture());
208 bool inject_js
= injector_
->ShouldInjectJs(run_location_
);
209 bool inject_css
= injector_
->ShouldInjectCss(run_location_
);
210 DCHECK(inject_js
|| inject_css
);
212 scoped_ptr
<base::ListValue
> execution_results(new base::ListValue());
213 GURL top_url
= web_frame_
->top()->document().url();
214 for (std::vector
<blink::WebFrame
*>::iterator iter
= frame_vector
.begin();
215 iter
!= frame_vector
.end();
217 // TODO(dcheng): Unfortunately, the code as written won't work in an OOPI
218 // world. This is just a temporary hack to make things compile.
219 blink::WebLocalFrame
* frame
= (*iter
)->toWebLocalFrame();
221 // We recheck access here in the renderer for extra safety against races
222 // with navigation, but different frames can have different URLs, and the
223 // injection host might only have access to a subset of them.
224 // For child frames, we just skip ones the injection host doesn't have
225 // access to and carry on.
226 // Note: we don't consider ACCESS_WITHHELD because there is nowhere to
227 // surface a request for a child frame.
228 // TODO(rdevlin.cronin): We should ask for permission somehow.
229 if (injector_
->CanExecuteOnFrame(injection_host
, frame
, tab_id_
, top_url
) ==
230 PermissionsData::ACCESS_DENIED
) {
231 DCHECK(frame
->parent());
235 InjectJs(injection_host
, frame
, execution_results
.get());
242 // TODO(hanxi): don't log these metrics for webUIs' injections.
243 injector_
->OnInjectionComplete(execution_results
.Pass(),
248 void ScriptInjection::InjectJs(const InjectionHost
* injection_host
,
249 blink::WebLocalFrame
* frame
,
250 base::ListValue
* execution_results
) {
251 std::vector
<blink::WebScriptSource
> sources
=
252 injector_
->GetJsSources(run_location_
);
253 bool in_main_world
= injector_
->ShouldExecuteInMainWorld();
254 int world_id
= in_main_world
255 ? DOMActivityLogger::kMainWorldId
256 : GetIsolatedWorldIdForInstance(injection_host
, frame
);
257 bool expects_results
= injector_
->ExpectsResults();
259 base::ElapsedTimer exec_timer
;
260 if (injection_host
->id().type() == HostID::EXTENSIONS
)
261 DOMActivityLogger::AttachToWorld(world_id
, injection_host
->id().id());
262 v8::HandleScope
scope(v8::Isolate::GetCurrent());
263 v8::Local
<v8::Value
> script_value
;
265 // We only inject in the main world for javascript: urls.
266 DCHECK_EQ(1u, sources
.size());
268 const blink::WebScriptSource
& source
= sources
.front();
270 script_value
= frame
->executeScriptAndReturnValue(source
);
272 frame
->executeScript(source
);
273 } else { // in isolated world
274 scoped_ptr
<blink::WebVector
<v8::Local
<v8::Value
> > > results
;
276 results
.reset(new blink::WebVector
<v8::Local
<v8::Value
> >());
277 frame
->executeScriptInIsolatedWorld(world_id
,
280 EXTENSION_GROUP_CONTENT_SCRIPTS
,
282 if (expects_results
&& !results
->isEmpty())
283 script_value
= (*results
)[0];
286 if (injection_host
->id().type() == HostID::EXTENSIONS
)
287 UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer
.Elapsed());
289 if (expects_results
) {
290 // Right now, we only support returning single results (per frame).
291 scoped_ptr
<content::V8ValueConverter
> v8_converter(
292 content::V8ValueConverter::create());
293 // It's safe to always use the main world context when converting
294 // here. V8ValueConverterImpl shouldn't actually care about the
295 // context scope, and it switches to v8::Object's creation context
297 v8::Local
<v8::Context
> context
= frame
->mainWorldScriptContext();
298 scoped_ptr
<base::Value
> result(
299 v8_converter
->FromV8Value(script_value
, context
));
300 // Always append an execution result (i.e. no result == null result)
301 // so that |execution_results| lines up with the frames.
302 execution_results
->Append(result
.get() ? result
.release()
303 : base::Value::CreateNullValue());
307 void ScriptInjection::InjectCss(blink::WebLocalFrame
* frame
) {
308 std::vector
<std::string
> css_sources
=
309 injector_
->GetCssSources(run_location_
);
310 for (std::vector
<std::string
>::const_iterator iter
= css_sources
.begin();
311 iter
!= css_sources
.end();
313 frame
->document().insertStyleSheet(blink::WebString::fromUTF8(*iter
));
317 } // namespace extensions