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/files/file_enumerator.h"
9 #include "base/files/file_util.h"
10 #include "base/location.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/sequenced_task_runner.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/thread_task_runner_handle.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/extensions/extension_garbage_collector_factory.h"
20 #include "chrome/browser/extensions/extension_service.h"
21 #include "chrome/browser/extensions/extension_util.h"
22 #include "chrome/browser/extensions/install_tracker.h"
23 #include "chrome/browser/extensions/pending_extension_manager.h"
24 #include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
25 #include "components/crx_file/id_util.h"
26 #include "content/public/browser/browser_context.h"
27 #include "content/public/browser/browser_thread.h"
28 #include "content/public/browser/storage_partition.h"
29 #include "extensions/browser/extension_prefs.h"
30 #include "extensions/browser/extension_registry.h"
31 #include "extensions/browser/extension_system.h"
32 #include "extensions/common/extension.h"
33 #include "extensions/common/file_util.h"
34 #include "extensions/common/one_shot_event.h"
36 namespace extensions
{
40 // Wait this many seconds before trying to garbage collect extensions again.
41 const int kGarbageCollectRetryDelayInSeconds
= 30;
43 // Wait this many seconds after startup to see if there are any extensions
44 // which can be garbage collected.
45 const int kGarbageCollectStartupDelay
= 30;
47 typedef std::multimap
<std::string
, base::FilePath
> ExtensionPathsMultimap
;
49 void CheckExtensionDirectory(const base::FilePath
& path
,
50 const ExtensionPathsMultimap
& extension_paths
) {
51 base::FilePath basename
= path
.BaseName();
52 // Clean up temporary files left if Chrome crashed or quit in the middle
53 // of an extension install.
54 if (basename
.value() == file_util::kTempDirectoryName
) {
55 base::DeleteFile(path
, true); // Recursive.
59 // Parse directory name as a potential extension ID.
60 std::string extension_id
;
61 if (base::IsStringASCII(basename
.value())) {
62 extension_id
= base::UTF16ToASCII(basename
.LossyDisplayName());
63 if (!crx_file::id_util::IdIsValid(extension_id
))
67 // Delete directories that aren't valid IDs.
68 if (extension_id
.empty()) {
69 base::DeleteFile(path
, true); // Recursive.
73 typedef ExtensionPathsMultimap::const_iterator Iter
;
74 std::pair
<Iter
, Iter
> iter_pair
= extension_paths
.equal_range(extension_id
);
76 // If there is no entry in the prefs file, just delete the directory and
77 // move on. This can legitimately happen when an uninstall does not
78 // complete, for example, when a plugin is in use at uninstall time.
79 if (iter_pair
.first
== iter_pair
.second
) {
80 base::DeleteFile(path
, true); // Recursive.
84 // Clean up old version directories.
85 base::FileEnumerator
versions_enumerator(
86 path
, false /* Not recursive */, base::FileEnumerator::DIRECTORIES
);
87 for (base::FilePath version_dir
= versions_enumerator
.Next();
89 version_dir
= versions_enumerator
.Next()) {
90 bool known_version
= false;
91 for (Iter iter
= iter_pair
.first
; iter
!= iter_pair
.second
; ++iter
) {
92 if (version_dir
.BaseName() == iter
->second
.BaseName()) {
98 base::DeleteFile(version_dir
, true); // Recursive.
104 ExtensionGarbageCollector::ExtensionGarbageCollector(
105 content::BrowserContext
* context
)
106 : context_(context
), crx_installs_in_progress_(0), weak_factory_(this) {
108 ExtensionSystem
* extension_system
= ExtensionSystem::Get(context_
);
109 DCHECK(extension_system
);
111 extension_system
->ready().PostDelayed(
113 base::Bind(&ExtensionGarbageCollector::GarbageCollectExtensions
,
114 weak_factory_
.GetWeakPtr()),
115 base::TimeDelta::FromSeconds(kGarbageCollectStartupDelay
));
117 extension_system
->ready().Post(
120 &ExtensionGarbageCollector::GarbageCollectIsolatedStorageIfNeeded
,
121 weak_factory_
.GetWeakPtr()));
123 InstallTracker::Get(context_
)->AddObserver(this);
126 ExtensionGarbageCollector::~ExtensionGarbageCollector() {}
129 ExtensionGarbageCollector
* ExtensionGarbageCollector::Get(
130 content::BrowserContext
* context
) {
131 return ExtensionGarbageCollectorFactory::GetForBrowserContext(context
);
134 void ExtensionGarbageCollector::Shutdown() {
135 InstallTracker::Get(context_
)->RemoveObserver(this);
138 void ExtensionGarbageCollector::GarbageCollectExtensionsForTest() {
139 GarbageCollectExtensions();
143 void ExtensionGarbageCollector::GarbageCollectExtensionsOnFileThread(
144 const base::FilePath
& install_directory
,
145 const ExtensionPathsMultimap
& extension_paths
) {
146 DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
148 // Nothing to clean up if it doesn't exist.
149 if (!base::DirectoryExists(install_directory
))
152 base::FileEnumerator
enumerator(install_directory
,
153 false, // Not recursive.
154 base::FileEnumerator::DIRECTORIES
);
156 for (base::FilePath extension_path
= enumerator
.Next();
157 !extension_path
.empty();
158 extension_path
= enumerator
.Next()) {
159 CheckExtensionDirectory(extension_path
, extension_paths
);
163 void ExtensionGarbageCollector::GarbageCollectExtensions() {
164 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
166 ExtensionPrefs
* extension_prefs
= ExtensionPrefs::Get(context_
);
167 DCHECK(extension_prefs
);
169 if (extension_prefs
->pref_service()->ReadOnly())
172 if (crx_installs_in_progress_
> 0) {
173 // Don't garbage collect while there are installations in progress,
174 // which may be using the temporary installation directory. Try to garbage
175 // collect again later.
176 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
178 base::Bind(&ExtensionGarbageCollector::GarbageCollectExtensions
,
179 weak_factory_
.GetWeakPtr()),
180 base::TimeDelta::FromSeconds(kGarbageCollectRetryDelayInSeconds
));
184 scoped_ptr
<ExtensionPrefs::ExtensionsInfo
> info(
185 extension_prefs
->GetInstalledExtensionsInfo());
186 std::multimap
<std::string
, base::FilePath
> extension_paths
;
187 for (size_t i
= 0; i
< info
->size(); ++i
) {
188 extension_paths
.insert(
189 std::make_pair(info
->at(i
)->extension_id
, info
->at(i
)->extension_path
));
192 info
= extension_prefs
->GetAllDelayedInstallInfo();
193 for (size_t i
= 0; i
< info
->size(); ++i
) {
194 extension_paths
.insert(
195 std::make_pair(info
->at(i
)->extension_id
, info
->at(i
)->extension_path
));
198 ExtensionService
* service
=
199 ExtensionSystem::Get(context_
)->extension_service();
200 if (!service
->GetFileTaskRunner()->PostTask(
202 base::Bind(&GarbageCollectExtensionsOnFileThread
,
203 service
->install_directory(),
209 void ExtensionGarbageCollector::GarbageCollectIsolatedStorageIfNeeded() {
210 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
212 ExtensionPrefs
* extension_prefs
= ExtensionPrefs::Get(context_
);
213 DCHECK(extension_prefs
);
214 if (!extension_prefs
->NeedsStorageGarbageCollection())
216 extension_prefs
->SetNeedsStorageGarbageCollection(false);
218 scoped_ptr
<base::hash_set
<base::FilePath
> > active_paths(
219 new base::hash_set
<base::FilePath
>());
220 scoped_ptr
<ExtensionSet
> extensions
=
221 ExtensionRegistry::Get(context_
)->GenerateInstalledExtensionsSet();
222 for (ExtensionSet::const_iterator iter
= extensions
->begin();
223 iter
!= extensions
->end();
225 if (AppIsolationInfo::HasIsolatedStorage(iter
->get())) {
226 active_paths
->insert(
227 content::BrowserContext::GetStoragePartitionForSite(
228 context_
, util::GetSiteForExtensionId((*iter
)->id(), context_
))
233 ExtensionService
* service
=
234 ExtensionSystem::Get(context_
)->extension_service();
235 service
->OnGarbageCollectIsolatedStorageStart();
236 content::BrowserContext::GarbageCollectStoragePartitions(
239 base::Bind(&ExtensionService::OnGarbageCollectIsolatedStorageFinished
,
240 service
->AsWeakPtr()));
243 void ExtensionGarbageCollector::OnBeginCrxInstall(
244 const std::string
& extension_id
) {
245 crx_installs_in_progress_
++;
248 void ExtensionGarbageCollector::OnFinishCrxInstall(
249 const std::string
& extension_id
,
251 crx_installs_in_progress_
--;
252 if (crx_installs_in_progress_
< 0) {
253 // This can only happen if there is a mismatch in our begin/finish
257 // Don't let the count go negative to avoid garbage collecting when
258 // an install is actually in progress.
259 crx_installs_in_progress_
= 0;
263 } // namespace extensions