#include "extensions/renderer/script_injection.h"
-#include <vector>
+#include <map>
#include "base/lazy_instance.h"
#include "base/metrics/histogram.h"
-#include "content/public/common/url_constants.h"
+#include "base/timer/elapsed_timer.h"
+#include "base/values.h"
#include "content/public/renderer/render_view.h"
+#include "content/public/renderer/v8_value_converter.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/feature_switch.h"
-#include "extensions/common/permissions/permissions_data.h"
+#include "extensions/common/manifest_handlers/csp_info.h"
#include "extensions/renderer/dom_activity_logger.h"
#include "extensions/renderer/extension_groups.h"
-#include "extensions/renderer/extension_helper.h"
-#include "extensions/renderer/script_context.h"
-#include "extensions/renderer/user_script_slave.h"
-#include "grit/extensions_renderer_resources.h"
+#include "extensions/renderer/extensions_renderer_client.h"
+#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/web/WebDocument.h"
#include "third_party/WebKit/public/web/WebFrame.h"
+#include "third_party/WebKit/public/web/WebScopedUserGesture.h"
#include "third_party/WebKit/public/web/WebScriptSource.h"
-#include "third_party/WebKit/public/web/WebView.h"
-#include "ui/base/resource/resource_bundle.h"
+#include "third_party/WebKit/public/web/WebSecurityOrigin.h"
#include "url/gurl.h"
namespace extensions {
namespace {
-// The id of the next pending injection.
-int64 g_next_pending_id = 0;
+typedef std::map<std::string, int> IsolatedWorldMap;
+base::LazyInstance<IsolatedWorldMap> g_isolated_worlds =
+ LAZY_INSTANCE_INITIALIZER;
-// The number of an invalid request, which is used if the feature to delay
-// script injection is not enabled.
const int64 kInvalidRequestId = -1;
-// These two strings are injected before and after the Greasemonkey API and
-// user script to wrap it in an anonymous scope.
-const char kUserScriptHead[] = "(function (unsafeWindow) {\n";
-const char kUserScriptTail[] = "\n})(window);";
-
-// Greasemonkey API source that is injected with the scripts.
-struct GreasemonkeyApiJsString {
- GreasemonkeyApiJsString();
- blink::WebScriptSource source;
-};
-
-// The below constructor, monstrous as it is, just makes a WebScriptSource from
-// the GreasemonkeyApiJs resource.
-GreasemonkeyApiJsString::GreasemonkeyApiJsString()
- : source(blink::WebScriptSource(blink::WebString::fromUTF8(
- ResourceBundle::GetSharedInstance().GetRawDataResource(
- IDR_GREASEMONKEY_API_JS).as_string()))) {
-}
-
-base::LazyInstance<GreasemonkeyApiJsString> g_greasemonkey_api =
- LAZY_INSTANCE_INITIALIZER;
-
-} // namespace
+// The id of the next pending injection.
+int64 g_next_pending_id = 0;
-ScriptInjection::ScriptsRunInfo::ScriptsRunInfo() : num_css(0u), num_js(0u) {
+bool ShouldNotifyBrowserOfInjections() {
+ return !FeatureSwitch::scripts_require_action()->IsEnabled();
}
-ScriptInjection::ScriptsRunInfo::~ScriptsRunInfo() {
+// Append all the child frames of |parent_frame| to |frames_vector|.
+void AppendAllChildFrames(blink::WebFrame* parent_frame,
+ std::vector<blink::WebFrame*>* frames_vector) {
+ DCHECK(parent_frame);
+ for (blink::WebFrame* child_frame = parent_frame->firstChild(); child_frame;
+ child_frame = child_frame->nextSibling()) {
+ frames_vector->push_back(child_frame);
+ AppendAllChildFrames(child_frame, frames_vector);
+ }
}
-struct ScriptInjection::PendingInjection {
- PendingInjection(blink::WebFrame* web_frame,
- UserScript::RunLocation run_location,
- int page_id);
- ~PendingInjection();
-
- // The globally-unique id of this request.
- int64 id;
-
- // The pointer to the web frame into which the script should be injected.
- // This is weak, but safe because we remove pending requests when a frame is
- // terminated.
- blink::WebFrame* web_frame;
-
- // The run location to inject at.
- // Note: This could be a lie - we might inject well after this run location
- // has come and gone. But we need to know it to know which scripts to inject.
- UserScript::RunLocation run_location;
+// Gets the isolated world ID to use for the given |extension| in the given
+// |frame|. If no isolated world has been created for that extension,
+// one will be created and initialized.
+int GetIsolatedWorldIdForExtension(const Extension* extension,
+ blink::WebFrame* frame) {
+ static int g_next_isolated_world_id =
+ ExtensionsRendererClient::Get()->GetLowestIsolatedWorldId();
+
+ IsolatedWorldMap& isolated_worlds = g_isolated_worlds.Get();
+
+ int id = 0;
+ IsolatedWorldMap::iterator iter = isolated_worlds.find(extension->id());
+ if (iter != isolated_worlds.end()) {
+ id = iter->second;
+ } else {
+ id = g_next_isolated_world_id++;
+ // This map will tend to pile up over time, but realistically, you're never
+ // going to have enough extensions for it to matter.
+ isolated_worlds[extension->id()] = id;
+ }
- // The corresponding page id, to protect against races.
- int page_id;
-};
+ // We need to set the isolated world origin and CSP even if it's not a new
+ // world since these are stored per frame, and we might not have used this
+ // isolated world in this frame before.
+ frame->setIsolatedWorldSecurityOrigin(
+ id, blink::WebSecurityOrigin::create(extension->url()));
+ frame->setIsolatedWorldContentSecurityPolicy(
+ id,
+ blink::WebString::fromUTF8(CSPInfo::GetContentSecurityPolicy(extension)));
-ScriptInjection::PendingInjection::PendingInjection(
- blink::WebFrame* web_frame,
- UserScript::RunLocation run_location,
- int page_id)
- : id(g_next_pending_id++),
- web_frame(web_frame),
- run_location(run_location),
- page_id(page_id) {
+ return id;
}
-ScriptInjection::PendingInjection::~PendingInjection() {
-}
+} // namespace
// static
-GURL ScriptInjection::GetDocumentUrlForFrame(blink::WebFrame* frame) {
- GURL data_source_url = ScriptContext::GetDataSourceURLForFrame(frame);
- if (!data_source_url.is_empty() && frame->isViewSourceModeEnabled()) {
- data_source_url = GURL(content::kViewSourceScheme + std::string(":") +
- data_source_url.spec());
+std::string ScriptInjection::GetExtensionIdForIsolatedWorld(
+ int isolated_world_id) {
+ IsolatedWorldMap& isolated_worlds = g_isolated_worlds.Get();
+
+ for (IsolatedWorldMap::iterator iter = isolated_worlds.begin();
+ iter != isolated_worlds.end();
+ ++iter) {
+ if (iter->second == isolated_world_id)
+ return iter->first;
}
+ return std::string();
+}
- return data_source_url;
+// static
+void ScriptInjection::RemoveIsolatedWorld(const std::string& extension_id) {
+ g_isolated_worlds.Get().erase(extension_id);
}
ScriptInjection::ScriptInjection(
- scoped_ptr<UserScript> script,
- UserScriptSlave* user_script_slave)
- : script_(script.Pass()),
- extension_id_(script_->extension_id()),
- user_script_slave_(user_script_slave),
- is_standalone_or_emulate_greasemonkey_(
- script_->is_standalone() || script_->emulate_greasemonkey()) {
+ scoped_ptr<ScriptInjector> injector,
+ blink::WebFrame* web_frame,
+ const std::string& extension_id,
+ UserScript::RunLocation run_location,
+ int tab_id)
+ : injector_(injector.Pass()),
+ web_frame_(web_frame),
+ extension_id_(extension_id),
+ run_location_(run_location),
+ tab_id_(tab_id),
+ request_id_(kInvalidRequestId),
+ complete_(false) {
}
ScriptInjection::~ScriptInjection() {
+ if (!complete_)
+ injector_->OnWillNotInject(ScriptInjector::WONT_INJECT);
}
-void ScriptInjection::InjectIfAllowed(blink::WebFrame* frame,
- UserScript::RunLocation run_location,
- const GURL& document_url,
- ScriptsRunInfo* scripts_run_info) {
- if (!WantsToRun(frame, run_location, document_url))
- return;
-
- const Extension* extension = user_script_slave_->GetExtension(extension_id_);
- DCHECK(extension); // WantsToRun() should be false if there's no extension.
-
- // We use the top render view here (instead of the render view for the
- // frame), because script injection on any frame requires permission for
- // the top frame. Additionally, if we have to show any UI for permissions,
- // it should only be done on the top frame.
- content::RenderView* top_render_view =
- content::RenderView::FromWebView(frame->top()->view());
-
- int tab_id = ExtensionHelper::Get(top_render_view)->tab_id();
-
- // By default, we allow injection.
- bool should_inject = true;
-
- // Check if the extension requires user consent for injection *and* we have a
- // valid tab id (if we don't have a tab id, we have no UI surface to ask for
- // user consent).
- if (tab_id != -1 &&
- extension->permissions_data()->RequiresActionForScriptExecution(
- extension, tab_id, frame->top()->document().url())) {
- int64 request_id = kInvalidRequestId;
- int page_id = top_render_view->GetPageId();
-
- // We only delay the injection if the feature is enabled.
- // Otherwise, we simply treat this as a notification by passing an invalid
- // id.
- if (FeatureSwitch::scripts_require_action()->IsEnabled()) {
- should_inject = false;
- ScopedVector<PendingInjection>::iterator pending_injection =
- pending_injections_.insert(
- pending_injections_.end(),
- new PendingInjection(frame, run_location, page_id));
- request_id = (*pending_injection)->id;
- }
+bool ScriptInjection::TryToInject(UserScript::RunLocation current_location,
+ const Extension* extension,
+ ScriptsRunInfo* scripts_run_info) {
+ if (current_location < run_location_)
+ return false; // Wait for the right location.
- top_render_view->Send(
- new ExtensionHostMsg_RequestContentScriptPermission(
- top_render_view->GetRoutingID(),
- extension->id(),
- page_id,
- request_id));
- }
-
- if (should_inject)
- Inject(frame, run_location, scripts_run_info);
-}
+ if (request_id_ != kInvalidRequestId)
+ return false; // We're waiting for permission right now, try again later.
-bool ScriptInjection::NotifyScriptPermitted(
- int64 request_id,
- content::RenderView* render_view,
- ScriptsRunInfo* scripts_run_info,
- blink::WebFrame** frame_out) {
- ScopedVector<PendingInjection>::iterator iter = pending_injections_.begin();
- while (iter != pending_injections_.end() && (*iter)->id != request_id)
- ++iter;
-
- // No matching request.
- if (iter == pending_injections_.end())
- return false;
+ if (!extension) {
+ NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
+ return true; // We're done.
+ }
- // We found the request, so pull it out of the pending list.
- scoped_ptr<PendingInjection> pending_injection(*iter);
- pending_injections_.weak_erase(iter);
+ switch (injector_->CanExecuteOnFrame(
+ extension, web_frame_, tab_id_, web_frame_->top()->document().url())) {
+ case PermissionsData::ACCESS_DENIED:
+ NotifyWillNotInject(ScriptInjector::NOT_ALLOWED);
+ return true; // We're done.
+ case PermissionsData::ACCESS_WITHHELD:
+ RequestPermission();
+ return false; // Wait around for permission.
+ case PermissionsData::ACCESS_ALLOWED:
+ Inject(extension, scripts_run_info);
+ return true; // We're done!
+ }
- // Ensure the Page ID and Extension are still valid. Otherwise, don't inject.
- if (render_view->GetPageId() != pending_injection->page_id)
- return false;
+ // Some compilers don't realize that we always return from the switch() above.
+ // Make them happy.
+ return false;
+}
- const Extension* extension = user_script_slave_->GetExtension(extension_id_);
- if (!extension)
+bool ScriptInjection::OnPermissionGranted(const Extension* extension,
+ ScriptsRunInfo* scripts_run_info) {
+ if (!extension) {
+ NotifyWillNotInject(ScriptInjector::EXTENSION_REMOVED);
return false;
+ }
- // Everything matches! Inject the script.
- if (frame_out)
- *frame_out = pending_injection->web_frame;
- Inject(pending_injection->web_frame,
- pending_injection->run_location,
- scripts_run_info);
+ Inject(extension, scripts_run_info);
return true;
}
-void ScriptInjection::FrameDetached(blink::WebFrame* frame) {
- // Any pending injections associated with the given frame will never run.
- // Remove them.
- for (ScopedVector<PendingInjection>::iterator iter =
- pending_injections_.begin();
- iter != pending_injections_.end();) {
- if ((*iter)->web_frame == frame)
- iter = pending_injections_.erase(iter);
- else
- ++iter;
- }
+void ScriptInjection::RequestPermission() {
+ content::RenderView* render_view =
+ content::RenderView::FromWebView(web_frame()->top()->view());
+
+ // If we are just notifying the browser of the injection, then send an
+ // invalid request (which is treated like a notification).
+ request_id_ = ShouldNotifyBrowserOfInjections() ? kInvalidRequestId
+ : g_next_pending_id++;
+ render_view->Send(new ExtensionHostMsg_RequestScriptInjectionPermission(
+ render_view->GetRoutingID(),
+ extension_id_,
+ injector_->script_type(),
+ request_id_));
}
-void ScriptInjection::SetScript(scoped_ptr<UserScript> script) {
- script_.reset(script.release());
+void ScriptInjection::NotifyWillNotInject(
+ ScriptInjector::InjectFailureReason reason) {
+ complete_ = true;
+ injector_->OnWillNotInject(reason);
}
-bool ScriptInjection::WantsToRun(blink::WebFrame* frame,
- UserScript::RunLocation run_location,
- const GURL& document_url) const {
- if (frame->parent() && !script_->match_all_frames())
- return false; // Only match subframes if the script declared it wanted to.
+void ScriptInjection::Inject(const Extension* extension,
+ ScriptsRunInfo* scripts_run_info) {
+ DCHECK(extension);
+ DCHECK(scripts_run_info);
+ DCHECK(!complete_);
- const Extension* extension = user_script_slave_->GetExtension(extension_id_);
- // Since extension info is sent separately from user script info, they can
- // be out of sync. We just ignore this situation.
- if (!extension)
- return false;
+ if (ShouldNotifyBrowserOfInjections())
+ RequestPermission();
- // Content scripts are not tab-specific.
- static const int kNoTabId = -1;
- // We don't have a process id in this context.
- static const int kNoProcessId = -1;
+ std::vector<blink::WebFrame*> frame_vector;
+ frame_vector.push_back(web_frame_);
+ if (injector_->ShouldExecuteInChildFrames())
+ AppendAllChildFrames(web_frame_, &frame_vector);
- GURL effective_document_url = ScriptContext::GetEffectiveDocumentURL(
- frame, document_url, script_->match_about_blank());
+ scoped_ptr<blink::WebScopedUserGesture> gesture;
+ if (injector_->IsUserGesture())
+ gesture.reset(new blink::WebScopedUserGesture());
- if (!script_->MatchesURL(effective_document_url))
- return false;
+ bool inject_js = injector_->ShouldInjectJs(run_location_);
+ bool inject_css = injector_->ShouldInjectCss(run_location_);
+ DCHECK(inject_js || inject_css);
- if (!extension->permissions_data()->CanRunContentScriptOnPage(
- extension,
- effective_document_url,
- frame->top()->document().url(),
- kNoTabId,
- kNoProcessId,
- NULL /* ignore error */)) {
- return false;
+ scoped_ptr<base::ListValue> execution_results(new base::ListValue());
+ GURL top_url = web_frame_->top()->document().url();
+ for (std::vector<blink::WebFrame*>::iterator iter = frame_vector.begin();
+ iter != frame_vector.end();
+ ++iter) {
+ blink::WebFrame* frame = *iter;
+
+ // We recheck access here in the renderer for extra safety against races
+ // with navigation, but different frames can have different URLs, and the
+ // extension might only have access to a subset of them.
+ // For child frames, we just skip ones the extension doesn't have access
+ // to and carry on.
+ // Note: we don't consider ACCESS_WITHHELD because there is nowhere to
+ // surface a request for a child frame.
+ // TODO(rdevlin.cronin): We should ask for permission somehow.
+ if (injector_->CanExecuteOnFrame(extension, frame, tab_id_, top_url) ==
+ PermissionsData::ACCESS_DENIED) {
+ DCHECK(frame->parent());
+ continue;
+ }
+ if (inject_js)
+ InjectJs(extension, frame, execution_results.get());
+ if (inject_css)
+ InjectCss(frame);
}
- return ShouldInjectCSS(run_location) || ShouldInjectJS(run_location);
+ complete_ = true;
+ injector_->OnInjectionComplete(execution_results.Pass(),
+ scripts_run_info,
+ run_location_);
}
-void ScriptInjection::Inject(blink::WebFrame* frame,
- UserScript::RunLocation run_location,
- ScriptsRunInfo* scripts_run_info) const {
- DCHECK(frame);
- DCHECK(scripts_run_info);
- DCHECK(WantsToRun(frame, run_location, GetDocumentUrlForFrame(frame)));
- DCHECK(user_script_slave_->GetExtension(extension_id_));
-
- if (ShouldInjectCSS(run_location))
- InjectCSS(frame, scripts_run_info);
- if (ShouldInjectJS(run_location))
- InjectJS(frame, scripts_run_info);
-}
-
-bool ScriptInjection::ShouldInjectJS(UserScript::RunLocation run_location)
- const {
- return !script_->js_scripts().empty() &&
- script_->run_location() == run_location;
-}
-
-bool ScriptInjection::ShouldInjectCSS(UserScript::RunLocation run_location)
- const {
- return !script_->css_scripts().empty() &&
- run_location == UserScript::DOCUMENT_START;
-}
+void ScriptInjection::InjectJs(const Extension* extension,
+ blink::WebFrame* frame,
+ base::ListValue* execution_results) {
+ std::vector<blink::WebScriptSource> sources =
+ injector_->GetJsSources(run_location_);
+ bool in_main_world = injector_->ShouldExecuteInMainWorld();
+ int world_id = in_main_world
+ ? DOMActivityLogger::kMainWorldId
+ : GetIsolatedWorldIdForExtension(extension, frame);
+ bool expects_results = injector_->ExpectsResults();
-void ScriptInjection::InjectJS(blink::WebFrame* frame,
- ScriptsRunInfo* scripts_run_info) const {
- const UserScript::FileList& js_scripts = script_->js_scripts();
- std::vector<blink::WebScriptSource> sources;
- scripts_run_info->num_js += js_scripts.size();
- for (UserScript::FileList::const_iterator iter = js_scripts.begin();
- iter != js_scripts.end();
- ++iter) {
- std::string content = iter->GetContent().as_string();
-
- // We add this dumb function wrapper for standalone user script to
- // emulate what Greasemonkey does.
- // TODO(aa): I think that maybe "is_standalone" scripts don't exist
- // anymore. Investigate.
- if (is_standalone_or_emulate_greasemonkey_) {
- content.insert(0, kUserScriptHead);
- content += kUserScriptTail;
- }
- sources.push_back(blink::WebScriptSource(
- blink::WebString::fromUTF8(content), iter->url()));
+ base::ElapsedTimer exec_timer;
+ DOMActivityLogger::AttachToWorld(world_id, extension->id());
+ v8::HandleScope scope(v8::Isolate::GetCurrent());
+ v8::Local<v8::Value> script_value;
+ if (in_main_world) {
+ // We only inject in the main world for javascript: urls.
+ DCHECK_EQ(1u, sources.size());
+
+ const blink::WebScriptSource& source = sources.front();
+ if (expects_results)
+ script_value = frame->executeScriptAndReturnValue(source);
+ else
+ frame->executeScript(source);
+ } else { // in isolated world
+ scoped_ptr<blink::WebVector<v8::Local<v8::Value> > > results;
+ if (expects_results)
+ results.reset(new blink::WebVector<v8::Local<v8::Value> >());
+ frame->executeScriptInIsolatedWorld(world_id,
+ &sources.front(),
+ sources.size(),
+ EXTENSION_GROUP_CONTENT_SCRIPTS,
+ results.get());
+ if (expects_results && !results->isEmpty())
+ script_value = (*results)[0];
}
- // Emulate Greasemonkey API for scripts that were converted to extensions
- // and "standalone" user scripts.
- if (is_standalone_or_emulate_greasemonkey_)
- sources.insert(sources.begin(), g_greasemonkey_api.Get().source);
-
- int isolated_world_id =
- user_script_slave_->GetIsolatedWorldIdForExtension(
- user_script_slave_->GetExtension(extension_id_), frame);
- base::ElapsedTimer exec_timer;
- DOMActivityLogger::AttachToWorld(isolated_world_id, extension_id_);
- frame->executeScriptInIsolatedWorld(isolated_world_id,
- &sources.front(),
- sources.size(),
- EXTENSION_GROUP_CONTENT_SCRIPTS);
UMA_HISTOGRAM_TIMES("Extensions.InjectScriptTime", exec_timer.Elapsed());
- for (std::vector<blink::WebScriptSource>::const_iterator iter =
- sources.begin();
- iter != sources.end();
- ++iter) {
- scripts_run_info->executing_scripts[extension_id_].insert(
- GURL(iter->url).path());
+ if (expects_results) {
+ // Right now, we only support returning single results (per frame).
+ scoped_ptr<content::V8ValueConverter> v8_converter(
+ content::V8ValueConverter::create());
+ // It's safe to always use the main world context when converting
+ // here. V8ValueConverterImpl shouldn't actually care about the
+ // context scope, and it switches to v8::Object's creation context
+ // when encountered.
+ v8::Local<v8::Context> context = frame->mainWorldScriptContext();
+ scoped_ptr<base::Value> result(
+ v8_converter->FromV8Value(script_value, context));
+ // Always append an execution result (i.e. no result == null result)
+ // so that |execution_results| lines up with the frames.
+ execution_results->Append(result.get() ? result.release()
+ : base::Value::CreateNullValue());
}
}
-void ScriptInjection::InjectCSS(blink::WebFrame* frame,
- ScriptsRunInfo* scripts_run_info) const {
- const UserScript::FileList& css_scripts = script_->css_scripts();
- scripts_run_info->num_css += css_scripts.size();
- for (UserScript::FileList::const_iterator iter = css_scripts.begin();
- iter != css_scripts.end();
+void ScriptInjection::InjectCss(blink::WebFrame* frame) {
+ std::vector<std::string> css_sources =
+ injector_->GetCssSources(run_location_);
+ for (std::vector<std::string>::const_iterator iter = css_sources.begin();
+ iter != css_sources.end();
++iter) {
- frame->document().insertStyleSheet(
- blink::WebString::fromUTF8(iter->GetContent().as_string()));
+ frame->document().insertStyleSheet(blink::WebString::fromUTF8(*iter));
}
}