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/browser/user_script_loader.h"
10 #include "base/version.h"
11 #include "content/public/browser/browser_context.h"
12 #include "content/public/browser/browser_thread.h"
13 #include "content/public/browser/notification_service.h"
14 #include "content/public/browser/notification_types.h"
15 #include "content/public/browser/render_process_host.h"
16 #include "extensions/browser/extensions_browser_client.h"
17 #include "extensions/browser/notification_types.h"
18 #include "extensions/common/extension_messages.h"
20 using content::BrowserThread
;
21 using content::BrowserContext
;
23 namespace extensions
{
27 // Helper function to parse greasesmonkey headers
28 bool GetDeclarationValue(const base::StringPiece
& line
,
29 const base::StringPiece
& prefix
,
31 base::StringPiece::size_type index
= line
.find(prefix
);
32 if (index
== base::StringPiece::npos
)
35 std::string
temp(line
.data() + index
+ prefix
.length(),
36 line
.length() - index
- prefix
.length());
38 if (temp
.empty() || !IsWhitespace(temp
[0]))
41 base::TrimWhitespaceASCII(temp
, base::TRIM_ALL
, value
);
48 bool UserScriptLoader::ParseMetadataHeader(const base::StringPiece
& script_text
,
50 // http://wiki.greasespot.net/Metadata_block
51 base::StringPiece line
;
52 size_t line_start
= 0;
53 size_t line_end
= line_start
;
54 bool in_metadata
= false;
56 static const base::StringPiece
kUserScriptBegin("// ==UserScript==");
57 static const base::StringPiece
kUserScriptEng("// ==/UserScript==");
58 static const base::StringPiece
kNamespaceDeclaration("// @namespace");
59 static const base::StringPiece
kNameDeclaration("// @name");
60 static const base::StringPiece
kVersionDeclaration("// @version");
61 static const base::StringPiece
kDescriptionDeclaration("// @description");
62 static const base::StringPiece
kIncludeDeclaration("// @include");
63 static const base::StringPiece
kExcludeDeclaration("// @exclude");
64 static const base::StringPiece
kMatchDeclaration("// @match");
65 static const base::StringPiece
kExcludeMatchDeclaration("// @exclude_match");
66 static const base::StringPiece
kRunAtDeclaration("// @run-at");
67 static const base::StringPiece
kRunAtDocumentStartValue("document-start");
68 static const base::StringPiece
kRunAtDocumentEndValue("document-end");
69 static const base::StringPiece
kRunAtDocumentIdleValue("document-idle");
71 while (line_start
< script_text
.length()) {
72 line_end
= script_text
.find('\n', line_start
);
74 // Handle the case where there is no trailing newline in the file.
75 if (line_end
== std::string::npos
)
76 line_end
= script_text
.length() - 1;
78 line
.set(script_text
.data() + line_start
, line_end
- line_start
);
81 if (line
.starts_with(kUserScriptBegin
))
84 if (line
.starts_with(kUserScriptEng
))
88 if (GetDeclarationValue(line
, kIncludeDeclaration
, &value
)) {
89 // We escape some characters that MatchPattern() considers special.
90 ReplaceSubstringsAfterOffset(&value
, 0, "\\", "\\\\");
91 ReplaceSubstringsAfterOffset(&value
, 0, "?", "\\?");
92 script
->add_glob(value
);
93 } else if (GetDeclarationValue(line
, kExcludeDeclaration
, &value
)) {
94 ReplaceSubstringsAfterOffset(&value
, 0, "\\", "\\\\");
95 ReplaceSubstringsAfterOffset(&value
, 0, "?", "\\?");
96 script
->add_exclude_glob(value
);
97 } else if (GetDeclarationValue(line
, kNamespaceDeclaration
, &value
)) {
98 script
->set_name_space(value
);
99 } else if (GetDeclarationValue(line
, kNameDeclaration
, &value
)) {
100 script
->set_name(value
);
101 } else if (GetDeclarationValue(line
, kVersionDeclaration
, &value
)) {
102 Version
version(value
);
103 if (version
.IsValid())
104 script
->set_version(version
.GetString());
105 } else if (GetDeclarationValue(line
, kDescriptionDeclaration
, &value
)) {
106 script
->set_description(value
);
107 } else if (GetDeclarationValue(line
, kMatchDeclaration
, &value
)) {
108 URLPattern
pattern(UserScript::ValidUserScriptSchemes());
109 if (URLPattern::PARSE_SUCCESS
!= pattern
.Parse(value
))
111 script
->add_url_pattern(pattern
);
112 } else if (GetDeclarationValue(line
, kExcludeMatchDeclaration
, &value
)) {
113 URLPattern
exclude(UserScript::ValidUserScriptSchemes());
114 if (URLPattern::PARSE_SUCCESS
!= exclude
.Parse(value
))
116 script
->add_exclude_url_pattern(exclude
);
117 } else if (GetDeclarationValue(line
, kRunAtDeclaration
, &value
)) {
118 if (value
== kRunAtDocumentStartValue
)
119 script
->set_run_location(UserScript::DOCUMENT_START
);
120 else if (value
== kRunAtDocumentEndValue
)
121 script
->set_run_location(UserScript::DOCUMENT_END
);
122 else if (value
== kRunAtDocumentIdleValue
)
123 script
->set_run_location(UserScript::DOCUMENT_IDLE
);
128 // TODO(aa): Handle more types of metadata.
131 line_start
= line_end
+ 1;
134 // If no patterns were specified, default to @include *. This is what
135 // Greasemonkey does.
136 if (script
->globs().empty() && script
->url_patterns().is_empty())
137 script
->add_glob("*");
142 UserScriptLoader::UserScriptLoader(BrowserContext
* browser_context
,
143 const HostID
& host_id
)
144 : user_scripts_(new UserScriptList()),
145 clear_scripts_(false),
147 pending_load_(false),
148 browser_context_(browser_context
),
150 weak_factory_(this) {
152 content::NOTIFICATION_RENDERER_PROCESS_CREATED
,
153 content::NotificationService::AllBrowserContextsAndSources());
156 UserScriptLoader::~UserScriptLoader() {
159 void UserScriptLoader::AddScripts(const std::set
<UserScript
>& scripts
) {
160 for (std::set
<UserScript
>::const_iterator it
= scripts
.begin();
163 removed_scripts_
.erase(*it
);
164 added_scripts_
.insert(*it
);
169 void UserScriptLoader::AddScripts(const std::set
<UserScript
>& scripts
,
170 int render_process_id
,
171 int render_view_id
) {
175 void UserScriptLoader::RemoveScripts(const std::set
<UserScript
>& scripts
) {
176 for (std::set
<UserScript
>::const_iterator it
= scripts
.begin();
179 added_scripts_
.erase(*it
);
180 removed_scripts_
.insert(*it
);
185 void UserScriptLoader::ClearScripts() {
186 clear_scripts_
= true;
187 added_scripts_
.clear();
188 removed_scripts_
.clear();
192 void UserScriptLoader::Observe(int type
,
193 const content::NotificationSource
& source
,
194 const content::NotificationDetails
& details
) {
195 DCHECK_EQ(type
, content::NOTIFICATION_RENDERER_PROCESS_CREATED
);
196 content::RenderProcessHost
* process
=
197 content::Source
<content::RenderProcessHost
>(source
).ptr();
198 if (!ExtensionsBrowserClient::Get()->IsSameContext(
199 browser_context_
, process
->GetBrowserContext()))
201 if (scripts_ready()) {
202 SendUpdate(process
, shared_memory_
.get(),
203 std::set
<HostID
>()); // Include all hosts.
207 bool UserScriptLoader::ScriptsMayHaveChanged() const {
208 // Scripts may have changed if there are scripts added, scripts removed, or
209 // if scripts were cleared and either:
210 // (1) A load is in progress (which may result in a non-zero number of
211 // scripts that need to be cleared), or
212 // (2) The current set of scripts is non-empty (so they need to be cleared).
213 return (added_scripts_
.size() ||
214 removed_scripts_
.size() ||
216 (is_loading() || user_scripts_
->size())));
219 void UserScriptLoader::AttemptLoad() {
220 if (ready_
&& ScriptsMayHaveChanged()) {
222 pending_load_
= true;
228 void UserScriptLoader::StartLoad() {
229 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
230 DCHECK(!is_loading());
232 // If scripts were marked for clearing before adding and removing, then clear
234 if (clear_scripts_
) {
235 user_scripts_
->clear();
237 for (UserScriptList::iterator it
= user_scripts_
->begin();
238 it
!= user_scripts_
->end();) {
239 if (removed_scripts_
.count(*it
))
240 it
= user_scripts_
->erase(it
);
246 user_scripts_
->insert(
247 user_scripts_
->end(), added_scripts_
.begin(), added_scripts_
.end());
249 std::set
<int> added_script_ids
;
250 for (std::set
<UserScript
>::const_iterator it
= added_scripts_
.begin();
251 it
!= added_scripts_
.end();
253 added_script_ids
.insert(it
->id());
256 // Expand |changed_hosts_| for OnScriptsLoaded, which will use it in
257 // its IPC message. This must be done before we clear |added_scripts_| and
258 // |removed_scripts_| below.
259 std::set
<UserScript
> changed_scripts(added_scripts_
);
260 changed_scripts
.insert(removed_scripts_
.begin(), removed_scripts_
.end());
261 for (const UserScript
& script
: changed_scripts
)
262 changed_hosts_
.insert(script
.host_id());
264 LoadScripts(user_scripts_
.Pass(), changed_hosts_
, added_script_ids
,
265 base::Bind(&UserScriptLoader::OnScriptsLoaded
,
266 weak_factory_
.GetWeakPtr()));
268 clear_scripts_
= false;
269 added_scripts_
.clear();
270 removed_scripts_
.clear();
271 user_scripts_
.reset();
275 scoped_ptr
<base::SharedMemory
> UserScriptLoader::Serialize(
276 const UserScriptList
& scripts
) {
278 pickle
.WriteSizeT(scripts
.size());
279 for (const UserScript
& script
: scripts
) {
280 // TODO(aa): This can be replaced by sending content script metadata to
281 // renderers along with other extension data in ExtensionMsg_Loaded.
282 // See crbug.com/70516.
283 script
.Pickle(&pickle
);
284 // Write scripts as 'data' so that we can read it out in the slave without
285 // allocating a new string.
286 for (const UserScript::File
& script_file
: script
.js_scripts()) {
287 base::StringPiece contents
= script_file
.GetContent();
288 pickle
.WriteData(contents
.data(), contents
.length());
290 for (const UserScript::File
& script_file
: script
.css_scripts()) {
291 base::StringPiece contents
= script_file
.GetContent();
292 pickle
.WriteData(contents
.data(), contents
.length());
296 // Create the shared memory object.
297 base::SharedMemory shared_memory
;
299 base::SharedMemoryCreateOptions options
;
300 options
.size
= pickle
.size();
301 options
.share_read_only
= true;
302 if (!shared_memory
.Create(options
))
303 return scoped_ptr
<base::SharedMemory
>();
305 if (!shared_memory
.Map(pickle
.size()))
306 return scoped_ptr
<base::SharedMemory
>();
308 // Copy the pickle to shared memory.
309 memcpy(shared_memory
.memory(), pickle
.data(), pickle
.size());
311 base::SharedMemoryHandle readonly_handle
;
312 if (!shared_memory
.ShareReadOnlyToProcess(base::GetCurrentProcessHandle(),
314 return scoped_ptr
<base::SharedMemory
>();
316 return make_scoped_ptr(new base::SharedMemory(readonly_handle
,
317 /*read_only=*/true));
320 void UserScriptLoader::SetReady(bool ready
) {
321 bool was_ready
= ready_
;
323 if (ready_
&& !was_ready
)
327 void UserScriptLoader::OnScriptsLoaded(
328 scoped_ptr
<UserScriptList
> user_scripts
,
329 scoped_ptr
<base::SharedMemory
> shared_memory
) {
330 user_scripts_
.reset(user_scripts
.release());
332 // While we were loading, there were further changes. Don't bother
333 // notifying about these scripts and instead just immediately reload.
334 pending_load_
= false;
339 if (shared_memory
.get() == NULL
) {
340 // This can happen if we run out of file descriptors. In that case, we
341 // have a choice between silently omitting all user scripts for new tabs,
342 // by nulling out shared_memory_, or only silently omitting new ones by
343 // leaving the existing object in place. The second seems less bad, even
344 // though it removes the possibility that freeing the shared memory block
345 // would open up enough FDs for long enough for a retry to succeed.
347 // Pretend the extension change didn't happen.
351 // We've got scripts ready to go.
352 shared_memory_
.reset(shared_memory
.release());
354 for (content::RenderProcessHost::iterator
i(
355 content::RenderProcessHost::AllHostsIterator());
356 !i
.IsAtEnd(); i
.Advance()) {
357 SendUpdate(i
.GetCurrentValue(), shared_memory_
.get(), changed_hosts_
);
359 changed_hosts_
.clear();
361 content::NotificationService::current()->Notify(
362 extensions::NOTIFICATION_USER_SCRIPTS_UPDATED
,
363 content::Source
<BrowserContext
>(browser_context_
),
364 content::Details
<base::SharedMemory
>(shared_memory_
.get()));
367 void UserScriptLoader::SendUpdate(content::RenderProcessHost
* process
,
368 base::SharedMemory
* shared_memory
,
369 const std::set
<HostID
>& changed_hosts
) {
370 // Don't allow injection of extensions' content scripts into <webview>.
371 if (process
->IsIsolatedGuest() && host_id().id().empty())
374 // Make sure we only send user scripts to processes in our browser_context.
375 if (!ExtensionsBrowserClient::Get()->IsSameContext(
376 browser_context_
, process
->GetBrowserContext()))
379 // If the process is being started asynchronously, early return. We'll end up
380 // calling InitUserScripts when it's created which will call this again.
381 base::ProcessHandle handle
= process
->GetHandle();
385 base::SharedMemoryHandle handle_for_process
;
386 if (!shared_memory
->ShareToProcess(handle
, &handle_for_process
))
387 return; // This can legitimately fail if the renderer asserts at startup.
389 if (base::SharedMemory::IsHandleValid(handle_for_process
)) {
390 process
->Send(new ExtensionMsg_UpdateUserScripts(handle_for_process
,
391 host_id(), changed_hosts
));
395 } // namespace extensions