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 "chrome/browser/extensions/extension_garbage_collector.h"
8 #include "base/file_util.h"
9 #include "base/files/file_enumerator.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/sequenced_task_runner.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/time/time.h"
17 #include "chrome/browser/extensions/extension_garbage_collector_factory.h"
18 #include "chrome/browser/extensions/extension_service.h"
19 #include "chrome/browser/extensions/extension_util.h"
20 #include "chrome/browser/extensions/install_tracker.h"
21 #include "chrome/browser/extensions/pending_extension_manager.h"
22 #include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
23 #include "content/public/browser/browser_context.h"
24 #include "content/public/browser/browser_thread.h"
25 #include "content/public/browser/storage_partition.h"
26 #include "extensions/browser/extension_prefs.h"
27 #include "extensions/browser/extension_registry.h"
28 #include "extensions/browser/extension_system.h"
29 #include "extensions/common/extension.h"
30 #include "extensions/common/file_util.h"
32 namespace extensions
{
36 // Wait this many seconds before trying to garbage collect extensions again.
37 const int kGarbageCollectRetryDelayInSeconds
= 30;
39 // Wait this many seconds after startup to see if there are any extensions
40 // which can be garbage collected.
41 const int kGarbageCollectStartupDelay
= 30;
43 typedef std::multimap
<std::string
, base::FilePath
> ExtensionPathsMultimap
;
45 void CheckExtensionDirectory(const base::FilePath
& path
,
46 const ExtensionPathsMultimap
& extension_paths
) {
47 base::FilePath basename
= path
.BaseName();
48 // Clean up temporary files left if Chrome crashed or quit in the middle
49 // of an extension install.
50 if (basename
.value() == file_util::kTempDirectoryName
) {
51 base::DeleteFile(path
, true); // Recursive.
55 // Parse directory name as a potential extension ID.
56 std::string extension_id
;
57 if (base::IsStringASCII(basename
.value())) {
58 extension_id
= base::UTF16ToASCII(basename
.LossyDisplayName());
59 if (!Extension::IdIsValid(extension_id
))
63 // Delete directories that aren't valid IDs.
64 if (extension_id
.empty()) {
65 base::DeleteFile(path
, true); // Recursive.
69 typedef ExtensionPathsMultimap::const_iterator Iter
;
70 std::pair
<Iter
, Iter
> iter_pair
= extension_paths
.equal_range(extension_id
);
72 // If there is no entry in the prefs file, just delete the directory and
73 // move on. This can legitimately happen when an uninstall does not
74 // complete, for example, when a plugin is in use at uninstall time.
75 if (iter_pair
.first
== iter_pair
.second
) {
76 base::DeleteFile(path
, true); // Recursive.
80 // Clean up old version directories.
81 base::FileEnumerator
versions_enumerator(
82 path
, false /* Not recursive */, base::FileEnumerator::DIRECTORIES
);
83 for (base::FilePath version_dir
= versions_enumerator
.Next();
85 version_dir
= versions_enumerator
.Next()) {
86 bool known_version
= false;
87 for (Iter iter
= iter_pair
.first
; iter
!= iter_pair
.second
; ++iter
) {
88 if (version_dir
.BaseName() == iter
->second
.BaseName()) {
94 base::DeleteFile(version_dir
, true); // Recursive.
98 void GarbageCollectExtensionsOnFileThread(
99 const base::FilePath
& install_directory
,
100 const ExtensionPathsMultimap
& extension_paths
) {
101 DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
103 // Nothing to clean up if it doesn't exist.
104 if (!base::DirectoryExists(install_directory
))
107 base::FileEnumerator
enumerator(install_directory
,
108 false, // Not recursive.
109 base::FileEnumerator::DIRECTORIES
);
111 for (base::FilePath extension_path
= enumerator
.Next();
112 !extension_path
.empty();
113 extension_path
= enumerator
.Next()) {
114 CheckExtensionDirectory(extension_path
, extension_paths
);
120 ExtensionGarbageCollector::ExtensionGarbageCollector(
121 content::BrowserContext
* context
)
122 : context_(context
), crx_installs_in_progress_(0), weak_factory_(this) {
123 #if defined(OS_CHROMEOS)
124 disable_garbage_collection_
= false;
127 ExtensionSystem
* extension_system
= ExtensionSystem::Get(context_
);
128 DCHECK(extension_system
);
130 extension_system
->ready().PostDelayed(
132 base::Bind(&ExtensionGarbageCollector::GarbageCollectExtensions
,
133 weak_factory_
.GetWeakPtr()),
134 base::TimeDelta::FromSeconds(kGarbageCollectStartupDelay
));
136 extension_system
->ready().Post(
139 &ExtensionGarbageCollector::GarbageCollectIsolatedStorageIfNeeded
,
140 weak_factory_
.GetWeakPtr()));
142 InstallTracker::Get(context_
)->AddObserver(this);
145 ExtensionGarbageCollector::~ExtensionGarbageCollector() {}
148 ExtensionGarbageCollector
* ExtensionGarbageCollector::Get(
149 content::BrowserContext
* context
) {
150 return ExtensionGarbageCollectorFactory::GetForBrowserContext(context
);
153 void ExtensionGarbageCollector::Shutdown() {
154 InstallTracker::Get(context_
)->RemoveObserver(this);
157 void ExtensionGarbageCollector::GarbageCollectExtensionsForTest() {
158 GarbageCollectExtensions();
161 void ExtensionGarbageCollector::GarbageCollectExtensions() {
162 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
164 #if defined(OS_CHROMEOS)
165 if (disable_garbage_collection_
)
169 ExtensionPrefs
* extension_prefs
= ExtensionPrefs::Get(context_
);
170 DCHECK(extension_prefs
);
172 if (extension_prefs
->pref_service()->ReadOnly())
175 if (crx_installs_in_progress_
> 0) {
176 // Don't garbage collect while there are installations in progress,
177 // which may be using the temporary installation directory. Try to garbage
178 // collect again later.
179 base::MessageLoop::current()->PostDelayedTask(
181 base::Bind(&ExtensionGarbageCollector::GarbageCollectExtensions
,
182 weak_factory_
.GetWeakPtr()),
183 base::TimeDelta::FromSeconds(kGarbageCollectRetryDelayInSeconds
));
187 scoped_ptr
<ExtensionPrefs::ExtensionsInfo
> info(
188 extension_prefs
->GetInstalledExtensionsInfo());
189 std::multimap
<std::string
, base::FilePath
> extension_paths
;
190 for (size_t i
= 0; i
< info
->size(); ++i
) {
191 extension_paths
.insert(
192 std::make_pair(info
->at(i
)->extension_id
, info
->at(i
)->extension_path
));
195 info
= extension_prefs
->GetAllDelayedInstallInfo();
196 for (size_t i
= 0; i
< info
->size(); ++i
) {
197 extension_paths
.insert(
198 std::make_pair(info
->at(i
)->extension_id
, info
->at(i
)->extension_path
));
201 ExtensionService
* service
=
202 ExtensionSystem::Get(context_
)->extension_service();
203 if (!service
->GetFileTaskRunner()->PostTask(
205 base::Bind(&GarbageCollectExtensionsOnFileThread
,
206 service
->install_directory(),
212 void ExtensionGarbageCollector::GarbageCollectIsolatedStorageIfNeeded() {
213 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
215 ExtensionPrefs
* extension_prefs
= ExtensionPrefs::Get(context_
);
216 DCHECK(extension_prefs
);
217 if (!extension_prefs
->NeedsStorageGarbageCollection())
219 extension_prefs
->SetNeedsStorageGarbageCollection(false);
221 scoped_ptr
<base::hash_set
<base::FilePath
> > active_paths(
222 new base::hash_set
<base::FilePath
>());
223 scoped_ptr
<ExtensionSet
> extensions
=
224 ExtensionRegistry::Get(context_
)->GenerateInstalledExtensionsSet();
225 for (ExtensionSet::const_iterator iter
= extensions
->begin();
226 iter
!= extensions
->end();
228 if (AppIsolationInfo::HasIsolatedStorage(iter
->get())) {
229 active_paths
->insert(
230 content::BrowserContext::GetStoragePartitionForSite(
231 context_
, util::GetSiteForExtensionId((*iter
)->id(), context_
))
236 // The data of ephemeral apps can outlive their cache lifetime. Ensure
237 // they are not garbage collected.
238 scoped_ptr
<ExtensionPrefs::ExtensionsInfo
> evicted_apps_info(
239 extension_prefs
->GetEvictedEphemeralAppsInfo());
240 for (size_t i
= 0; i
< evicted_apps_info
->size(); ++i
) {
241 ExtensionInfo
* info
= evicted_apps_info
->at(i
).get();
242 if (util::HasIsolatedStorage(*info
)) {
243 active_paths
->insert(content::BrowserContext::GetStoragePartitionForSite(
245 util::GetSiteForExtensionId(
246 info
->extension_id
, context_
))->GetPath());
250 ExtensionService
* service
=
251 ExtensionSystem::Get(context_
)->extension_service();
252 service
->OnGarbageCollectIsolatedStorageStart();
253 content::BrowserContext::GarbageCollectStoragePartitions(
256 base::Bind(&ExtensionService::OnGarbageCollectIsolatedStorageFinished
,
257 service
->AsWeakPtr()));
260 void ExtensionGarbageCollector::OnBeginCrxInstall(
261 const std::string
& extension_id
) {
262 crx_installs_in_progress_
++;
265 void ExtensionGarbageCollector::OnFinishCrxInstall(
266 const std::string
& extension_id
,
268 crx_installs_in_progress_
--;
269 if (crx_installs_in_progress_
< 0) {
270 // This can only happen if there is a mismatch in our begin/finish
274 // Don't let the count go negative to avoid garbage collecting when
275 // an install is actually in progress.
276 crx_installs_in_progress_
= 0;
280 } // namespace extensions