blob: 95f41742b2dc06e14c176d49b2512f8dbaa48104 [file] [log] [blame]
[email protected]3c220782014-05-20 01:59:461// 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.
4
5#include "extensions/renderer/script_injection.h"
6
[email protected]ac2f89372014-06-23 21:44:257#include <map>
[email protected]3c220782014-05-20 01:59:468
9#include "base/lazy_instance.h"
[email protected]c11e6592014-06-27 17:07:3410#include "base/metrics/histogram.h"
11#include "base/timer/elapsed_timer.h"
12#include "base/values.h"
mek87e0ab52015-02-13 01:18:2613#include "content/public/child/v8_value_converter.h"
[email protected]f8abc6e42014-06-24 21:14:4314#include "content/public/renderer/render_view.h"
[email protected]f8abc6e42014-06-24 21:14:4315#include "extensions/common/extension_messages.h"
hanxia5c856cf2015-02-13 20:51:5816#include "extensions/common/host_id.h"
[email protected]ac2f89372014-06-23 21:44:2517#include "extensions/common/manifest_handlers/csp_info.h"
[email protected]c11e6592014-06-27 17:07:3418#include "extensions/renderer/dom_activity_logger.h"
19#include "extensions/renderer/extension_groups.h"
hanxia5c856cf2015-02-13 20:51:5820#include "extensions/renderer/extension_injection_host.h"
[email protected]ac2f89372014-06-23 21:44:2521#include "extensions/renderer/extensions_renderer_client.h"
kozyatinskiyc8bc9a582015-03-06 09:33:4122#include "extensions/renderer/script_injection_callback.h"
23#include "extensions/renderer/script_injection_manager.h"
24#include "extensions/renderer/scripts_run_info.h"
[email protected]c11e6592014-06-27 17:07:3425#include "third_party/WebKit/public/platform/WebString.h"
26#include "third_party/WebKit/public/web/WebDocument.h"
dcheng2e449172014-09-24 04:30:5627#include "third_party/WebKit/public/web/WebLocalFrame.h"
[email protected]c11e6592014-06-27 17:07:3428#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
29#include "third_party/WebKit/public/web/WebScriptSource.h"
[email protected]ac2f89372014-06-23 21:44:2530#include "third_party/WebKit/public/web/WebSecurityOrigin.h"
[email protected]c11e6592014-06-27 17:07:3431#include "url/gurl.h"
[email protected]3c220782014-05-20 01:59:4632
33namespace extensions {
34
35namespace {
36
hanxia5c856cf2015-02-13 20:51:5837using IsolatedWorldMap = std::map<std::string, int>;
[email protected]ac2f89372014-06-23 21:44:2538base::LazyInstance<IsolatedWorldMap> g_isolated_worlds =
[email protected]3c220782014-05-20 01:59:4639 LAZY_INSTANCE_INITIALIZER;
40
[email protected]d2056002014-07-03 06:18:0641const int64 kInvalidRequestId = -1;
[email protected]f8abc6e42014-06-24 21:14:4342
43// The id of the next pending injection.
44int64 g_next_pending_id = 0;
45
[email protected]c11e6592014-06-27 17:07:3446// Append all the child frames of |parent_frame| to |frames_vector|.
47void AppendAllChildFrames(blink::WebFrame* parent_frame,
48 std::vector<blink::WebFrame*>* frames_vector) {
49 DCHECK(parent_frame);
50 for (blink::WebFrame* child_frame = parent_frame->firstChild(); child_frame;
51 child_frame = child_frame->nextSibling()) {
52 frames_vector->push_back(child_frame);
53 AppendAllChildFrames(child_frame, frames_vector);
54 }
[email protected]3c220782014-05-20 01:59:4655}
56
hanxia5c856cf2015-02-13 20:51:5857// Gets the isolated world ID to use for the given |injection_host|
58// in the given |frame|. If no isolated world has been created for that
59// |injection_host| one will be created and initialized.
60int GetIsolatedWorldIdForInstance(const InjectionHost* injection_host,
61 blink::WebLocalFrame* frame) {
[email protected]ac2f89372014-06-23 21:44:2562 static int g_next_isolated_world_id =
63 ExtensionsRendererClient::Get()->GetLowestIsolatedWorldId();
[email protected]0d8d6972014-06-03 22:41:0264
[email protected]ac2f89372014-06-23 21:44:2565 IsolatedWorldMap& isolated_worlds = g_isolated_worlds.Get();
[email protected]0d8d6972014-06-03 22:41:0266
[email protected]ac2f89372014-06-23 21:44:2567 int id = 0;
hanxia5c856cf2015-02-13 20:51:5868 const std::string& key = injection_host->id().id();
69 IsolatedWorldMap::iterator iter = isolated_worlds.find(key);
[email protected]ac2f89372014-06-23 21:44:2570 if (iter != isolated_worlds.end()) {
71 id = iter->second;
72 } else {
73 id = g_next_isolated_world_id++;
74 // This map will tend to pile up over time, but realistically, you're never
hanxia5c856cf2015-02-13 20:51:5875 // going to have enough injection hosts for it to matter.
76 isolated_worlds[key] = id;
[email protected]0d8d6972014-06-03 22:41:0277 }
78
[email protected]ac2f89372014-06-23 21:44:2579 // We need to set the isolated world origin and CSP even if it's not a new
80 // world since these are stored per frame, and we might not have used this
81 // isolated world in this frame before.
82 frame->setIsolatedWorldSecurityOrigin(
hanxia5c856cf2015-02-13 20:51:5883 id, blink::WebSecurityOrigin::create(injection_host->url()));
[email protected]ac2f89372014-06-23 21:44:2584 frame->setIsolatedWorldContentSecurityPolicy(
hanxia5c856cf2015-02-13 20:51:5885 id, blink::WebString::fromUTF8(
86 injection_host->GetContentSecurityPolicy()));
lushnikovb53144f32014-09-03 07:43:5687 frame->setIsolatedWorldHumanReadableName(
hanxia5c856cf2015-02-13 20:51:5888 id, blink::WebString::fromUTF8(injection_host->name()));
[email protected]ac2f89372014-06-23 21:44:2589
90 return id;
[email protected]0d8d6972014-06-03 22:41:0291}
92
[email protected]c11e6592014-06-27 17:07:3493} // namespace
94
[email protected]ac2f89372014-06-23 21:44:2595// static
hanxia5c856cf2015-02-13 20:51:5896std::string ScriptInjection::GetHostIdForIsolatedWorld(int isolated_world_id) {
97 const IsolatedWorldMap& isolated_worlds = g_isolated_worlds.Get();
[email protected]0d8d6972014-06-03 22:41:0298
hanxia5c856cf2015-02-13 20:51:5899 for (const auto& iter : isolated_worlds) {
100 if (iter.second == isolated_world_id)
101 return iter.first;
[email protected]3c220782014-05-20 01:59:46102 }
[email protected]ac2f89372014-06-23 21:44:25103 return std::string();
[email protected]3c220782014-05-20 01:59:46104}
105
[email protected]ac2f89372014-06-23 21:44:25106// static
hanxia5c856cf2015-02-13 20:51:58107void ScriptInjection::RemoveIsolatedWorld(const std::string& host_id) {
108 g_isolated_worlds.Get().erase(host_id);
[email protected]3c220782014-05-20 01:59:46109}
110
[email protected]f8abc6e42014-06-24 21:14:43111ScriptInjection::ScriptInjection(
[email protected]c11e6592014-06-27 17:07:34112 scoped_ptr<ScriptInjector> injector,
dcheng2e449172014-09-24 04:30:56113 blink::WebLocalFrame* web_frame,
hanxi9b841662015-03-04 14:36:41114 scoped_ptr<const InjectionHost> injection_host,
[email protected]f8abc6e42014-06-24 21:14:43115 UserScript::RunLocation run_location,
116 int tab_id)
[email protected]c11e6592014-06-27 17:07:34117 : injector_(injector.Pass()),
118 web_frame_(web_frame),
hanxi9b841662015-03-04 14:36:41119 injection_host_(injection_host.Pass()),
[email protected]f8abc6e42014-06-24 21:14:43120 run_location_(run_location),
121 tab_id_(tab_id),
[email protected]d2056002014-07-03 06:18:06122 request_id_(kInvalidRequestId),
kozyatinskiyc8bc9a582015-03-06 09:33:41123 complete_(false),
124 running_frames_(0),
125 execution_results_(new base::ListValue()),
126 all_injections_started_(false),
127 script_injection_manager_(nullptr) {
hanxi9b841662015-03-04 14:36:41128 CHECK(injection_host_.get());
[email protected]f8abc6e42014-06-24 21:14:43129}
130
131ScriptInjection::~ScriptInjection() {
132 if (!complete_)
[email protected]c11e6592014-06-27 17:07:34133 injector_->OnWillNotInject(ScriptInjector::WONT_INJECT);
[email protected]f8abc6e42014-06-24 21:14:43134}
135
kozyatinskiyc8bc9a582015-03-06 09:33:41136ScriptInjection::InjectionResult ScriptInjection::TryToInject(
137 UserScript::RunLocation current_location,
138 ScriptsRunInfo* scripts_run_info,
139 ScriptInjectionManager* manager) {
[email protected]f8abc6e42014-06-24 21:14:43140 if (current_location < run_location_)
kozyatinskiyc8bc9a582015-03-06 09:33:41141 return INJECTION_WAITING; // Wait for the right location.
[email protected]f8abc6e42014-06-24 21:14:43142
kozyatinskiyc8bc9a582015-03-06 09:33:41143 if (request_id_ != kInvalidRequestId) {
144 // We're waiting for permission right now, try again later.
145 return INJECTION_WAITING;
146 }
[email protected]f8abc6e42014-06-24 21:14:43147
hanxi9b841662015-03-04 14:36:41148 if (!injection_host_) {
[email protected]c11e6592014-06-27 17:07:34149 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
kozyatinskiyc8bc9a582015-03-06 09:33:41150 return INJECTION_FINISHED; // We're done.
[email protected]f8abc6e42014-06-24 21:14:43151 }
152
hanxi9b841662015-03-04 14:36:41153 switch (injector_->CanExecuteOnFrame(
154 injection_host_.get(), web_frame_, tab_id_,
155 web_frame_->top()->document().url())) {
[email protected]23a85362014-07-07 23:26:19156 case PermissionsData::ACCESS_DENIED:
[email protected]c11e6592014-06-27 17:07:34157 NotifyWillNotInject(ScriptInjector::NOT_ALLOWED);
kozyatinskiyc8bc9a582015-03-06 09:33:41158 return INJECTION_FINISHED; // We're done.
[email protected]23a85362014-07-07 23:26:19159 case PermissionsData::ACCESS_WITHHELD:
rdevlin.cronin958e9f82015-02-17 21:57:14160 SendInjectionMessage(true /* request permission */);
kozyatinskiyc8bc9a582015-03-06 09:33:41161 return INJECTION_WAITING; // Wait around for permission.
[email protected]23a85362014-07-07 23:26:19162 case PermissionsData::ACCESS_ALLOWED:
kozyatinskiyc8bc9a582015-03-06 09:33:41163 InjectionResult result = Inject(scripts_run_info);
164 // If the injection is blocked, we need to set the manager so we can
165 // notify it upon completion.
166 if (result == INJECTION_BLOCKED)
167 script_injection_manager_ = manager;
168 return result;
[email protected]f8abc6e42014-06-24 21:14:43169 }
170
rdevlin.cronin958e9f82015-02-17 21:57:14171 NOTREACHED();
kozyatinskiyc8bc9a582015-03-06 09:33:41172 return INJECTION_FINISHED;
[email protected]f8abc6e42014-06-24 21:14:43173}
174
kozyatinskiyc8bc9a582015-03-06 09:33:41175ScriptInjection::InjectionResult ScriptInjection::OnPermissionGranted(
176 ScriptsRunInfo* scripts_run_info) {
hanxi9b841662015-03-04 14:36:41177 if (!injection_host_) {
[email protected]c11e6592014-06-27 17:07:34178 NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
kozyatinskiyc8bc9a582015-03-06 09:33:41179 return INJECTION_FINISHED;
[email protected]f8abc6e42014-06-24 21:14:43180 }
181
kozyatinskiyc8bc9a582015-03-06 09:33:41182 return Inject(scripts_run_info);
[email protected]f8abc6e42014-06-24 21:14:43183}
184
hanxi9b841662015-03-04 14:36:41185void ScriptInjection::OnHostRemoved() {
186 injection_host_.reset(nullptr);
187}
188
rdevlin.cronin958e9f82015-02-17 21:57:14189void ScriptInjection::SendInjectionMessage(bool request_permission) {
[email protected]f8abc6e42014-06-24 21:14:43190 content::RenderView* render_view =
191 content::RenderView::FromWebView(web_frame()->top()->view());
192
[email protected]23a85362014-07-07 23:26:19193 // If we are just notifying the browser of the injection, then send an
[email protected]f8abc6e42014-06-24 21:14:43194 // invalid request (which is treated like a notification).
rdevlin.cronin958e9f82015-02-17 21:57:14195 request_id_ = request_permission ? g_next_pending_id++ : kInvalidRequestId;
[email protected]f8abc6e42014-06-24 21:14:43196 render_view->Send(new ExtensionHostMsg_RequestScriptInjectionPermission(
197 render_view->GetRoutingID(),
hanxi9b841662015-03-04 14:36:41198 host_id().id(),
[email protected]23a85362014-07-07 23:26:19199 injector_->script_type(),
[email protected]c11e6592014-06-27 17:07:34200 request_id_));
[email protected]f8abc6e42014-06-24 21:14:43201}
202
[email protected]c11e6592014-06-27 17:07:34203void ScriptInjection::NotifyWillNotInject(
204 ScriptInjector::InjectFailureReason reason) {
[email protected]f8abc6e42014-06-24 21:14:43205 complete_ = true;
[email protected]c11e6592014-06-27 17:07:34206 injector_->OnWillNotInject(reason);
[email protected]f8abc6e42014-06-24 21:14:43207}
208
kozyatinskiyc8bc9a582015-03-06 09:33:41209ScriptInjection::InjectionResult ScriptInjection::Inject(
210 ScriptsRunInfo* scripts_run_info) {
hanxi9b841662015-03-04 14:36:41211 DCHECK(injection_host_);
[email protected]c11e6592014-06-27 17:07:34212 DCHECK(scripts_run_info);
213 DCHECK(!complete_);
214
hanxi9b841662015-03-04 14:36:41215 if (injection_host_->ShouldNotifyBrowserOfInjection())
rdevlin.cronin958e9f82015-02-17 21:57:14216 SendInjectionMessage(false /* don't request permission */);
[email protected]23a85362014-07-07 23:26:19217
[email protected]c11e6592014-06-27 17:07:34218 std::vector<blink::WebFrame*> frame_vector;
219 frame_vector.push_back(web_frame_);
220 if (injector_->ShouldExecuteInChildFrames())
221 AppendAllChildFrames(web_frame_, &frame_vector);
222
[email protected]c11e6592014-06-27 17:07:34223 bool inject_js = injector_->ShouldInjectJs(run_location_);
224 bool inject_css = injector_->ShouldInjectCss(run_location_);
225 DCHECK(inject_js || inject_css);
226
[email protected]c11e6592014-06-27 17:07:34227 GURL top_url = web_frame_->top()->document().url();
228 for (std::vector<blink::WebFrame*>::iterator iter = frame_vector.begin();
229 iter != frame_vector.end();
230 ++iter) {
dcheng2e449172014-09-24 04:30:56231 // TODO(dcheng): Unfortunately, the code as written won't work in an OOPI
232 // world. This is just a temporary hack to make things compile.
233 blink::WebLocalFrame* frame = (*iter)->toWebLocalFrame();
[email protected]c11e6592014-06-27 17:07:34234
235 // We recheck access here in the renderer for extra safety against races
236 // with navigation, but different frames can have different URLs, and the
hanxia5c856cf2015-02-13 20:51:58237 // injection host might only have access to a subset of them.
238 // For child frames, we just skip ones the injection host doesn't have
239 // access to and carry on.
[email protected]23a85362014-07-07 23:26:19240 // Note: we don't consider ACCESS_WITHHELD because there is nowhere to
[email protected]c11e6592014-06-27 17:07:34241 // surface a request for a child frame.
242 // TODO(rdevlin.cronin): We should ask for permission somehow.
hanxi9b841662015-03-04 14:36:41243 if (injector_->CanExecuteOnFrame(
244 injection_host_.get(), frame, tab_id_, top_url) ==
245 PermissionsData::ACCESS_DENIED) {
[email protected]c11e6592014-06-27 17:07:34246 DCHECK(frame->parent());
247 continue;
248 }
249 if (inject_js)
kozyatinskiyc8bc9a582015-03-06 09:33:41250 InjectJs(frame);
[email protected]c11e6592014-06-27 17:07:34251 if (inject_css)
252 InjectCss(frame);
253 }
254
kozyatinskiyc8bc9a582015-03-06 09:33:41255 all_injections_started_ = true;
256 injector_->GetRunInfo(scripts_run_info, run_location_);
257 scripts_run_info->num_blocking_js = running_frames_;
258 TryToFinish();
259 return complete_ ? INJECTION_FINISHED : INJECTION_BLOCKED;
[email protected]c11e6592014-06-27 17:07:34260}
261
kozyatinskiyc8bc9a582015-03-06 09:33:41262void ScriptInjection::InjectJs(blink::WebLocalFrame* frame) {
263 ++running_frames_;
[email protected]c11e6592014-06-27 17:07:34264 std::vector<blink::WebScriptSource> sources =
265 injector_->GetJsSources(run_location_);
266 bool in_main_world = injector_->ShouldExecuteInMainWorld();
267 int world_id = in_main_world
268 ? DOMActivityLogger::kMainWorldId
hanxi9b841662015-03-04 14:36:41269 : GetIsolatedWorldIdForInstance(injection_host_.get(),
270 frame);
kozyatinskiyc8bc9a582015-03-06 09:33:41271 bool is_user_gesture = injector_->IsUserGesture();
272
273 scoped_ptr<blink::WebScriptExecutionCallback> callback(
274 new ScriptInjectionCallback(this, frame));
[email protected]c11e6592014-06-27 17:07:34275
276 base::ElapsedTimer exec_timer;
hanxi9b841662015-03-04 14:36:41277 if (injection_host_->id().type() == HostID::EXTENSIONS)
278 DOMActivityLogger::AttachToWorld(world_id, injection_host_->id().id());
[email protected]c11e6592014-06-27 17:07:34279 if (in_main_world) {
280 // We only inject in the main world for javascript: urls.
281 DCHECK_EQ(1u, sources.size());
282
kozyatinskiyc8bc9a582015-03-06 09:33:41283 frame->requestExecuteScriptAndReturnValue(sources.front(),
284 is_user_gesture,
285 callback.release());
286 } else {
287 frame->requestExecuteScriptInIsolatedWorld(world_id,
288 &sources.front(),
289 sources.size(),
290 EXTENSION_GROUP_CONTENT_SCRIPTS,
291 is_user_gesture,
292 callback.release());
[email protected]c11e6592014-06-27 17:07:34293 }
294
hanxi9b841662015-03-04 14:36:41295 if (injection_host_->id().type() == HostID::EXTENSIONS)
hanxia5c856cf2015-02-13 20:51:58296 UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer.Elapsed());
kozyatinskiyc8bc9a582015-03-06 09:33:41297}
[email protected]c11e6592014-06-27 17:07:34298
kozyatinskiyc8bc9a582015-03-06 09:33:41299void ScriptInjection::OnJsInjectionCompleted(
300 blink::WebLocalFrame* frame,
301 const blink::WebVector<v8::Local<v8::Value> >& results) {
302 DCHECK(running_frames_ > 0);
303 --running_frames_;
304
305 bool expects_results = injector_->ExpectsResults();
[email protected]c11e6592014-06-27 17:07:34306 if (expects_results) {
kozyatinskiyc8bc9a582015-03-06 09:33:41307 v8::Local<v8::Value> script_value;
308 if (!results.isEmpty())
309 script_value = results[0];
[email protected]c11e6592014-06-27 17:07:34310 // Right now, we only support returning single results (per frame).
311 scoped_ptr<content::V8ValueConverter> v8_converter(
312 content::V8ValueConverter::create());
313 // It's safe to always use the main world context when converting
314 // here. V8ValueConverterImpl shouldn't actually care about the
315 // context scope, and it switches to v8::Object's creation context
316 // when encountered.
317 v8::Local<v8::Context> context = frame->mainWorldScriptContext();
318 scoped_ptr<base::Value> result(
319 v8_converter->FromV8Value(script_value, context));
kozyatinskiyc8bc9a582015-03-06 09:33:41320 if (!result.get())
321 result.reset(base::Value::CreateNullValue());
322 // We guarantee that the main frame's result is at the first index, but
323 // any sub frames results do not have guaranteed order.
324 execution_results_->Insert(
325 frame == web_frame_ ? 0 : execution_results_->GetSize(),
326 result.release());
327 }
328 TryToFinish();
329}
330
331void ScriptInjection::TryToFinish() {
332 if (all_injections_started_ && running_frames_ == 0) {
333 complete_ = true;
334 injector_->OnInjectionComplete(execution_results_.Pass(),
335 run_location_);
336
337 // This object can be destroyed after next line.
338 if (script_injection_manager_)
339 script_injection_manager_->OnInjectionFinished(this);
[email protected]c11e6592014-06-27 17:07:34340 }
341}
342
dcheng2e449172014-09-24 04:30:56343void ScriptInjection::InjectCss(blink::WebLocalFrame* frame) {
[email protected]c11e6592014-06-27 17:07:34344 std::vector<std::string> css_sources =
345 injector_->GetCssSources(run_location_);
346 for (std::vector<std::string>::const_iterator iter = css_sources.begin();
347 iter != css_sources.end();
348 ++iter) {
349 frame->document().insertStyleSheet(blink::WebString::fromUTF8(*iter));
350 }
[email protected]f8abc6e42014-06-24 21:14:43351}
352
[email protected]3c220782014-05-20 01:59:46353} // namespace extensions