Extract code handling PrinterProviderAPI from PrintPreviewHandler
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blobe13371fb66a1d2b28e4ac85188d77eefb76a2e68
1 // Copyright (c) 2013 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_service.h"
7 #include <algorithm>
8 #include <iterator>
9 #include <set>
11 #include "base/command_line.h"
12 #include "base/metrics/histogram.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/content_settings/content_settings_internal_extension_provider.h"
22 #include "chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h"
23 #include "chrome/browser/extensions/api/content_settings/content_settings_service.h"
24 #include "chrome/browser/extensions/app_data_migrator.h"
25 #include "chrome/browser/extensions/component_loader.h"
26 #include "chrome/browser/extensions/crx_installer.h"
27 #include "chrome/browser/extensions/data_deleter.h"
28 #include "chrome/browser/extensions/extension_action_storage_manager.h"
29 #include "chrome/browser/extensions/extension_assets_manager.h"
30 #include "chrome/browser/extensions/extension_disabled_ui.h"
31 #include "chrome/browser/extensions/extension_error_controller.h"
32 #include "chrome/browser/extensions/extension_special_storage_policy.h"
33 #include "chrome/browser/extensions/extension_sync_service.h"
34 #include "chrome/browser/extensions/extension_util.h"
35 #include "chrome/browser/extensions/external_install_manager.h"
36 #include "chrome/browser/extensions/external_provider_impl.h"
37 #include "chrome/browser/extensions/install_verifier.h"
38 #include "chrome/browser/extensions/installed_loader.h"
39 #include "chrome/browser/extensions/pending_extension_manager.h"
40 #include "chrome/browser/extensions/permissions_updater.h"
41 #include "chrome/browser/extensions/shared_module_service.h"
42 #include "chrome/browser/extensions/unpacked_installer.h"
43 #include "chrome/browser/extensions/updater/chrome_extension_downloader_factory.h"
44 #include "chrome/browser/extensions/updater/extension_updater.h"
45 #include "chrome/browser/google/google_brand.h"
46 #include "chrome/browser/profiles/profile.h"
47 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
48 #include "chrome/browser/ui/webui/favicon_source.h"
49 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
50 #include "chrome/browser/ui/webui/theme_source.h"
51 #include "chrome/common/chrome_switches.h"
52 #include "chrome/common/crash_keys.h"
53 #include "chrome/common/extensions/extension_constants.h"
54 #include "chrome/common/extensions/features/feature_channel.h"
55 #include "chrome/common/url_constants.h"
56 #include "components/content_settings/core/browser/host_content_settings_map.h"
57 #include "components/crx_file/id_util.h"
58 #include "components/startup_metric_utils/startup_metric_utils.h"
59 #include "content/public/browser/devtools_agent_host.h"
60 #include "content/public/browser/notification_service.h"
61 #include "content/public/browser/render_process_host.h"
62 #include "content/public/browser/storage_partition.h"
63 #include "extensions/browser/event_router.h"
64 #include "extensions/browser/extension_host.h"
65 #include "extensions/browser/extension_prefs.h"
66 #include "extensions/browser/extension_registry.h"
67 #include "extensions/browser/extension_system.h"
68 #include "extensions/browser/extensions_browser_client.h"
69 #include "extensions/browser/install_flag.h"
70 #include "extensions/browser/runtime_data.h"
71 #include "extensions/browser/uninstall_reason.h"
72 #include "extensions/browser/update_observer.h"
73 #include "extensions/browser/updater/extension_cache.h"
74 #include "extensions/browser/updater/extension_downloader.h"
75 #include "extensions/common/extension_messages.h"
76 #include "extensions/common/extension_urls.h"
77 #include "extensions/common/feature_switch.h"
78 #include "extensions/common/file_util.h"
79 #include "extensions/common/manifest_constants.h"
80 #include "extensions/common/manifest_handlers/background_info.h"
81 #include "extensions/common/manifest_url_handlers.h"
82 #include "extensions/common/one_shot_event.h"
83 #include "extensions/common/permissions/permission_message_provider.h"
84 #include "extensions/common/permissions/permissions_data.h"
86 #if defined(OS_CHROMEOS)
87 #include "chrome/browser/chromeos/extensions/install_limiter.h"
88 #include "storage/browser/fileapi/file_system_backend.h"
89 #include "storage/browser/fileapi/file_system_context.h"
90 #endif
92 using content::BrowserContext;
93 using content::BrowserThread;
94 using content::DevToolsAgentHost;
95 using extensions::CrxInstaller;
96 using extensions::Extension;
97 using extensions::ExtensionIdSet;
98 using extensions::ExtensionInfo;
99 using extensions::ExtensionRegistry;
100 using extensions::ExtensionSet;
101 using extensions::FeatureSwitch;
102 using extensions::InstallVerifier;
103 using extensions::ManagementPolicy;
104 using extensions::Manifest;
105 using extensions::PermissionMessage;
106 using extensions::PermissionMessages;
107 using extensions::PermissionSet;
108 using extensions::SharedModuleInfo;
109 using extensions::SharedModuleService;
110 using extensions::UnloadedExtensionInfo;
112 namespace errors = extensions::manifest_errors;
114 namespace {
116 // Wait this many seconds after an extensions becomes idle before updating it.
117 const int kUpdateIdleDelay = 5;
119 } // namespace
121 // ExtensionService.
123 void ExtensionService::CheckExternalUninstall(const std::string& id) {
124 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
126 // Check if the providers know about this extension.
127 extensions::ProviderCollection::const_iterator i;
128 for (i = external_extension_providers_.begin();
129 i != external_extension_providers_.end(); ++i) {
130 DCHECK(i->get()->IsReady());
131 if (i->get()->HasExtension(id))
132 return; // Yup, known extension, don't uninstall.
135 // We get the list of external extensions to check from preferences.
136 // It is possible that an extension has preferences but is not loaded.
137 // For example, an extension that requires experimental permissions
138 // will not be loaded if the experimental command line flag is not used.
139 // In this case, do not uninstall.
140 if (!GetInstalledExtension(id)) {
141 // We can't call UninstallExtension with an unloaded/invalid
142 // extension ID.
143 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
144 << "with id: " << id;
145 return;
147 UninstallExtension(id,
148 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
149 base::Bind(&base::DoNothing),
150 NULL);
153 void ExtensionService::SetFileTaskRunnerForTesting(
154 const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
155 file_task_runner_ = task_runner;
158 void ExtensionService::ClearProvidersForTesting() {
159 external_extension_providers_.clear();
162 void ExtensionService::AddProviderForTesting(
163 extensions::ExternalProviderInterface* test_provider) {
164 CHECK(test_provider);
165 external_extension_providers_.push_back(
166 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
169 void ExtensionService::BlacklistExtensionForTest(
170 const std::string& extension_id) {
171 ExtensionIdSet blacklisted;
172 ExtensionIdSet unchanged;
173 blacklisted.insert(extension_id);
174 UpdateBlacklistedExtensions(blacklisted, unchanged);
177 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
178 const std::string& id,
179 const std::string& install_parameter,
180 const GURL& update_url,
181 Manifest::Location location,
182 int creation_flags,
183 bool mark_acknowledged) {
184 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
185 CHECK(crx_file::id_util::IdIsValid(id));
187 if (Manifest::IsExternalLocation(location)) {
188 // All extensions that are not user specific can be cached.
189 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
190 ->AllowCaching(id);
193 const Extension* extension = GetExtensionById(id, true);
194 if (extension) {
195 // Already installed. Skip this install if the current location has
196 // higher priority than |location|.
197 Manifest::Location current = extension->location();
198 if (current == Manifest::GetHigherPriorityLocation(current, location))
199 return false;
200 // Otherwise, overwrite the current installation.
203 // Add |id| to the set of pending extensions. If it can not be added,
204 // then there is already a pending record from a higher-priority install
205 // source. In this case, signal that this extension will not be
206 // installed by returning false.
207 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
209 install_parameter,
210 update_url,
211 location,
212 creation_flags,
213 mark_acknowledged)) {
214 return false;
217 update_once_all_providers_are_ready_ = true;
218 return true;
221 // static
222 // This function is used to uninstall an extension via sync. The LOG statements
223 // within this function are used to inform the user if the uninstall cannot be
224 // done.
225 bool ExtensionService::UninstallExtensionHelper(
226 ExtensionService* extensions_service,
227 const std::string& extension_id,
228 extensions::UninstallReason reason) {
229 // We can't call UninstallExtension with an invalid extension ID.
230 if (!extensions_service->GetInstalledExtension(extension_id)) {
231 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
232 << "id: " << extension_id;
233 return false;
236 // The following call to UninstallExtension will not allow an uninstall of a
237 // policy-controlled extension.
238 base::string16 error;
239 if (!extensions_service->UninstallExtension(
240 extension_id, reason, base::Bind(&base::DoNothing), &error)) {
241 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
242 << ": " << error;
243 return false;
246 return true;
249 ExtensionService::ExtensionService(Profile* profile,
250 const base::CommandLine* command_line,
251 const base::FilePath& install_directory,
252 extensions::ExtensionPrefs* extension_prefs,
253 extensions::Blacklist* blacklist,
254 bool autoupdate_enabled,
255 bool extensions_enabled,
256 extensions::OneShotEvent* ready)
257 : extensions::Blacklist::Observer(blacklist),
258 profile_(profile),
259 system_(extensions::ExtensionSystem::Get(profile)),
260 extension_prefs_(extension_prefs),
261 blacklist_(blacklist),
262 extension_sync_service_(NULL),
263 registry_(extensions::ExtensionRegistry::Get(profile)),
264 pending_extension_manager_(profile),
265 install_directory_(install_directory),
266 extensions_enabled_(extensions_enabled),
267 show_extensions_prompts_(true),
268 install_updates_when_idle_(true),
269 ready_(ready),
270 update_once_all_providers_are_ready_(false),
271 browser_terminating_(false),
272 installs_delayed_for_gc_(false),
273 is_first_run_(false),
274 block_extensions_(false),
275 shared_module_service_(new extensions::SharedModuleService(profile_)),
276 app_data_migrator_(new extensions::AppDataMigrator(profile_, registry_)) {
277 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
279 // Figure out if extension installation should be enabled.
280 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
281 *command_line, profile))
282 extensions_enabled_ = false;
284 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
285 content::NotificationService::AllBrowserContextsAndSources());
286 registrar_.Add(this,
287 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
288 content::NotificationService::AllBrowserContextsAndSources());
289 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
290 content::NotificationService::AllBrowserContextsAndSources());
291 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
292 content::NotificationService::AllBrowserContextsAndSources());
293 registrar_.Add(this,
294 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
295 content::Source<Profile>(profile_));
297 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
298 ->AddObserver(this);
300 // Set up the ExtensionUpdater
301 if (autoupdate_enabled) {
302 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
303 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
304 base::StringToInt(command_line->GetSwitchValueASCII(
305 switches::kExtensionsUpdateFrequency),
306 &update_frequency);
308 updater_.reset(new extensions::ExtensionUpdater(
309 this,
310 extension_prefs,
311 profile->GetPrefs(),
312 profile,
313 update_frequency,
314 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
315 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
316 profile)));
319 component_loader_.reset(
320 new extensions::ComponentLoader(this,
321 profile->GetPrefs(),
322 g_browser_process->local_state(),
323 profile));
325 if (extensions_enabled_) {
326 extensions::ExternalProviderImpl::CreateExternalProviders(
327 this, profile_, &external_extension_providers_);
330 // Set this as the ExtensionService for app sorting to ensure it causes syncs
331 // if required.
332 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
334 error_controller_.reset(
335 new extensions::ExtensionErrorController(profile_, is_first_run_));
336 external_install_manager_.reset(
337 new extensions::ExternalInstallManager(profile_, is_first_run_));
339 extension_action_storage_manager_.reset(
340 new extensions::ExtensionActionStorageManager(profile_));
342 // How long is the path to the Extensions directory?
343 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
344 install_directory_.value().length(), 0, 500, 100);
347 extensions::PendingExtensionManager*
348 ExtensionService::pending_extension_manager() {
349 return &pending_extension_manager_;
352 ExtensionService::~ExtensionService() {
353 // No need to unload extensions here because they are profile-scoped, and the
354 // profile is in the process of being deleted.
356 extensions::ProviderCollection::const_iterator i;
357 for (i = external_extension_providers_.begin();
358 i != external_extension_providers_.end(); ++i) {
359 extensions::ExternalProviderInterface* provider = i->get();
360 provider->ServiceShutdown();
364 void ExtensionService::Shutdown() {
365 extensions::ExtensionManagementFactory::GetInstance()
366 ->GetForBrowserContext(profile())
367 ->RemoveObserver(this);
368 system_->management_policy()->UnregisterProvider(
369 shared_module_policy_provider_.get());
372 const Extension* ExtensionService::GetExtensionById(
373 const std::string& id, bool include_disabled) const {
374 int include_mask = ExtensionRegistry::ENABLED;
375 if (include_disabled) {
376 // Include blacklisted and blocked extensions here because there are
377 // hundreds of callers of this function, and many might assume that this
378 // includes those that have been disabled due to blacklisting or blocking.
379 include_mask |= ExtensionRegistry::DISABLED |
380 ExtensionRegistry::BLACKLISTED | ExtensionRegistry::BLOCKED;
382 return registry_->GetExtensionById(id, include_mask);
385 void ExtensionService::Init() {
386 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
388 base::Time begin_time = base::Time::Now();
390 DCHECK(!is_ready()); // Can't redo init.
391 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
393 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
394 if (cmd_line->HasSwitch(switches::kInstallEphemeralAppFromWebstore)) {
395 // The sole purpose of this launch is to install a new extension from CWS
396 // and immediately terminate: loading already installed extensions is
397 // unnecessary and may interfere with the inline install dialog (e.g. if an
398 // extension listens to onStartup and opens a window).
399 SetReadyAndNotifyListeners();
400 } else {
401 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
402 component_loader_->LoadAll();
403 extensions::InstalledLoader(this).LoadAllExtensions();
405 // Attempt to re-enable extensions whose only disable reason is reloading.
406 std::vector<std::string> extensions_to_enable;
407 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
408 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
409 iter != disabled_extensions.end(); ++iter) {
410 const Extension* e = iter->get();
411 if (extension_prefs_->GetDisableReasons(e->id()) ==
412 Extension::DISABLE_RELOAD) {
413 extensions_to_enable.push_back(e->id());
416 for (std::vector<std::string>::iterator it = extensions_to_enable.begin();
417 it != extensions_to_enable.end(); ++it) {
418 EnableExtension(*it);
421 // Finish install (if possible) of extensions that were still delayed while
422 // the browser was shut down.
423 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
424 extension_prefs_->GetAllDelayedInstallInfo());
425 for (size_t i = 0; i < delayed_info->size(); ++i) {
426 ExtensionInfo* info = delayed_info->at(i).get();
427 scoped_refptr<const Extension> extension(NULL);
428 if (info->extension_manifest) {
429 std::string error;
430 extension = Extension::Create(
431 info->extension_path,
432 info->extension_location,
433 *info->extension_manifest,
434 extension_prefs_->GetDelayedInstallCreationFlags(
435 info->extension_id),
436 info->extension_id,
437 &error);
438 if (extension.get())
439 delayed_installs_.Insert(extension);
442 MaybeFinishDelayedInstallations();
444 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
445 extension_prefs_->GetAllDelayedInstallInfo());
446 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
447 delayed_info2->size() - delayed_info->size());
449 SetReadyAndNotifyListeners();
451 // TODO(erikkay) this should probably be deferred to a future point
452 // rather than running immediately at startup.
453 CheckForExternalUpdates();
455 LoadGreylistFromPrefs();
458 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
459 base::Time::Now() - begin_time);
462 void ExtensionService::LoadGreylistFromPrefs() {
463 scoped_ptr<ExtensionSet> all_extensions =
464 registry_->GenerateInstalledExtensionsSet();
466 for (ExtensionSet::const_iterator it = all_extensions->begin();
467 it != all_extensions->end(); ++it) {
468 extensions::BlacklistState state =
469 extension_prefs_->GetExtensionBlacklistState((*it)->id());
470 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
471 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
472 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
473 greylist_.Insert(*it);
477 bool ExtensionService::UpdateExtension(const extensions::CRXFileInfo& file,
478 bool file_ownership_passed,
479 CrxInstaller** out_crx_installer) {
480 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
481 if (browser_terminating_) {
482 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
483 // Leak the temp file at extension_path. We don't want to add to the disk
484 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
485 // the file is in the OS temp directory which should be cleaned up for us.
486 return false;
489 const std::string& id = file.extension_id;
491 const extensions::PendingExtensionInfo* pending_extension_info =
492 pending_extension_manager()->GetById(id);
494 const Extension* extension = GetInstalledExtension(id);
495 if (!pending_extension_info && !extension) {
496 LOG(WARNING) << "Will not update extension " << id
497 << " because it is not installed or pending";
498 // Delete extension_path since we're not creating a CrxInstaller
499 // that would do it for us.
500 if (!GetFileTaskRunner()->PostTask(
501 FROM_HERE,
502 base::Bind(&extensions::file_util::DeleteFile, file.path, false)))
503 NOTREACHED();
505 return false;
508 scoped_refptr<CrxInstaller> installer(
509 CrxInstaller::Create(this, scoped_ptr<ExtensionInstallPrompt>()));
510 installer->set_expected_id(id);
511 int creation_flags = Extension::NO_FLAGS;
512 if (pending_extension_info) {
513 installer->set_install_source(pending_extension_info->install_source());
514 installer->set_allow_silent_install(true);
515 if (pending_extension_info->remote_install())
516 installer->set_grant_permissions(false);
517 creation_flags = pending_extension_info->creation_flags();
518 if (pending_extension_info->mark_acknowledged())
519 external_install_manager_->AcknowledgeExternalExtension(id);
520 } else if (extension) {
521 installer->set_install_source(extension->location());
523 // If the extension was installed from or has migrated to the webstore, or
524 // its auto-update URL is from the webstore, treat it as a webstore install.
525 // Note that we ignore some older extensions with blank auto-update URLs
526 // because we are mostly concerned with restrictions on NaCl extensions,
527 // which are newer.
528 if ((extension && extension->from_webstore()) ||
529 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
530 (!extension && extension_urls::IsWebstoreUpdateUrl(
531 pending_extension_info->update_url()))) {
532 creation_flags |= Extension::FROM_WEBSTORE;
535 // Bookmark apps being updated is kind of a contradiction, but that's because
536 // we mark the default apps as bookmark apps, and they're hosted in the web
537 // store, thus they can get updated. See http://crbug.com/101605 for more
538 // details.
539 if (extension && extension->from_bookmark())
540 creation_flags |= Extension::FROM_BOOKMARK;
542 if (extension && extension->was_installed_by_default())
543 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
545 if (extension && extension->was_installed_by_oem())
546 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
548 if (extension && extension->was_installed_by_custodian())
549 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
551 if (extension) {
552 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
553 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
556 installer->set_creation_flags(creation_flags);
558 installer->set_delete_source(file_ownership_passed);
559 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
560 installer->InstallCrxFile(file);
562 if (out_crx_installer)
563 *out_crx_installer = installer.get();
565 return true;
568 void ExtensionService::ReloadExtensionImpl(
569 // "transient" because the process of reloading may cause the reference
570 // to become invalid. Instead, use |extension_id|, a copy.
571 const std::string& transient_extension_id,
572 bool be_noisy) {
573 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
575 // If the extension is already reloading, don't reload again.
576 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
577 Extension::DISABLE_RELOAD) {
578 return;
581 // Ignore attempts to reload a blacklisted or blocked extension. Sometimes
582 // this can happen in a convoluted reload sequence triggered by the
583 // termination of a blacklisted or blocked extension and a naive attempt to
584 // reload it. For an example see http://crbug.com/373842.
585 if (registry_->blacklisted_extensions().Contains(transient_extension_id) ||
586 registry_->blocked_extensions().Contains(transient_extension_id)) {
587 return;
590 base::FilePath path;
592 std::string extension_id = transient_extension_id;
593 const Extension* transient_current_extension =
594 GetExtensionById(extension_id, false);
596 // Disable the extension if it's loaded. It might not be loaded if it crashed.
597 if (transient_current_extension) {
598 // If the extension has an inspector open for its background page, detach
599 // the inspector and hang onto a cookie for it, so that we can reattach
600 // later.
601 // TODO(yoz): this is not incognito-safe!
602 extensions::ProcessManager* manager =
603 extensions::ProcessManager::Get(profile_);
604 extensions::ExtensionHost* host =
605 manager->GetBackgroundHostForExtension(extension_id);
606 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
607 // Look for an open inspector for the background page.
608 scoped_refptr<DevToolsAgentHost> agent_host =
609 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
610 agent_host->DisconnectWebContents();
611 orphaned_dev_tools_[extension_id] = agent_host;
614 path = transient_current_extension->path();
615 // BeingUpgraded is set back to false when the extension is added.
616 system_->runtime_data()->SetBeingUpgraded(transient_current_extension->id(),
617 true);
618 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
619 reloading_extensions_.insert(extension_id);
620 } else {
621 std::map<std::string, base::FilePath>::const_iterator iter =
622 unloaded_extension_paths_.find(extension_id);
623 if (iter == unloaded_extension_paths_.end()) {
624 return;
626 path = unloaded_extension_paths_[extension_id];
629 transient_current_extension = NULL;
631 if (delayed_installs_.Contains(extension_id)) {
632 FinishDelayedInstallation(extension_id);
633 return;
636 // If we're reloading a component extension, use the component extension
637 // loader's reloader.
638 if (component_loader_->Exists(extension_id)) {
639 component_loader_->Reload(extension_id);
640 return;
643 // Check the installed extensions to see if what we're reloading was already
644 // installed.
645 scoped_ptr<ExtensionInfo> installed_extension(
646 extension_prefs_->GetInstalledExtensionInfo(extension_id));
647 if (installed_extension.get() &&
648 installed_extension->extension_manifest.get()) {
649 extensions::InstalledLoader(this).Load(*installed_extension, false);
650 } else {
651 // Otherwise, the extension is unpacked (location LOAD).
652 // We should always be able to remember the extension's path. If it's not in
653 // the map, someone failed to update |unloaded_extension_paths_|.
654 CHECK(!path.empty());
655 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
656 extensions::UnpackedInstaller::Create(this);
657 unpacked_installer->set_be_noisy_on_failure(be_noisy);
658 unpacked_installer->Load(path);
662 void ExtensionService::ReloadExtension(const std::string& extension_id) {
663 ReloadExtensionImpl(extension_id, true); // be_noisy
666 void ExtensionService::ReloadExtensionWithQuietFailure(
667 const std::string& extension_id) {
668 ReloadExtensionImpl(extension_id, false); // be_noisy
671 bool ExtensionService::UninstallExtension(
672 // "transient" because the process of uninstalling may cause the reference
673 // to become invalid. Instead, use |extenson->id()|.
674 const std::string& transient_extension_id,
675 extensions::UninstallReason reason,
676 const base::Closure& deletion_done_callback,
677 base::string16* error) {
678 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
680 scoped_refptr<const Extension> extension =
681 GetInstalledExtension(transient_extension_id);
683 // Callers should not send us nonexistent extensions.
684 CHECK(extension.get());
686 ManagementPolicy* by_policy = system_->management_policy();
687 // Policy change which triggers an uninstall will always set
688 // |external_uninstall| to true so this is the only way to uninstall
689 // managed extensions.
690 // Shared modules being uninstalled will also set |external_uninstall| to true
691 // so that we can guarantee users don't uninstall a shared module.
692 // (crbug.com/273300)
693 // TODO(rdevlin.cronin): This is probably not right. We should do something
694 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
695 // we don't do this.
696 bool external_uninstall =
697 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
698 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
699 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
700 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
701 (reason == extensions::UNINSTALL_REASON_SYNC &&
702 extension->was_installed_by_custodian());
703 if (!external_uninstall &&
704 (!by_policy->UserMayModifySettings(extension.get(), error) ||
705 by_policy->MustRemainInstalled(extension.get(), error))) {
706 content::NotificationService::current()->Notify(
707 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
708 content::Source<Profile>(profile_),
709 content::Details<const Extension>(extension.get()));
710 return false;
713 syncer::SyncChange sync_change;
714 // Don't sync the uninstall if we're going to reinstall the extension
715 // momentarily.
716 if (extension_sync_service_ &&
717 reason != extensions::UNINSTALL_REASON_REINSTALL) {
718 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
719 extension.get(), is_ready());
722 system_->install_verifier()->Remove(extension->id());
724 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
725 extension->GetType(), 100);
726 RecordPermissionMessagesHistogram(extension.get(),
727 "Extensions.Permissions_Uninstall2");
729 // Unload before doing more cleanup to ensure that nothing is hanging on to
730 // any of these resources.
731 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
733 // Tell the backend to start deleting installed extensions on the file thread.
734 if (!Manifest::IsUnpackedLocation(extension->location())) {
735 if (!GetFileTaskRunner()->PostTask(
736 FROM_HERE,
737 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
738 extension->id(),
739 profile_,
740 install_directory_,
741 extension->path())))
742 NOTREACHED();
745 extensions::DataDeleter::StartDeleting(
746 profile_, extension.get(), deletion_done_callback);
748 UntrackTerminatedExtension(extension->id());
750 // Notify interested parties that we've uninstalled this extension.
751 content::NotificationService::current()->Notify(
752 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
753 content::Source<Profile>(profile_),
754 content::Details<const Extension>(extension.get()));
755 ExtensionRegistry::Get(profile_)
756 ->TriggerOnUninstalled(extension.get(), reason);
758 if (sync_change.IsValid()) {
759 extension_sync_service_->ProcessSyncUninstallExtension(extension->id(),
760 sync_change);
763 delayed_installs_.Remove(extension->id());
765 extension_prefs_->OnExtensionUninstalled(
766 extension->id(), extension->location(), external_uninstall);
768 // Track the uninstallation.
769 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
771 return true;
774 // static
775 void ExtensionService::UninstallExtensionOnFileThread(
776 const std::string& id,
777 Profile* profile,
778 const base::FilePath& install_dir,
779 const base::FilePath& extension_path) {
780 extensions::ExtensionAssetsManager* assets_manager =
781 extensions::ExtensionAssetsManager::GetInstance();
782 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
785 bool ExtensionService::IsExtensionEnabled(
786 const std::string& extension_id) const {
787 if (registry_->enabled_extensions().Contains(extension_id) ||
788 registry_->terminated_extensions().Contains(extension_id)) {
789 return true;
792 if (registry_->disabled_extensions().Contains(extension_id) ||
793 registry_->blacklisted_extensions().Contains(extension_id) ||
794 registry_->blocked_extensions().Contains(extension_id)) {
795 return false;
798 // Blocked extensions aren't marked as such in prefs, thus if
799 // |block_extensions_| is true then CanBlockExtension() must be called with an
800 // Extension object. If the |extension_id| is not loaded, assume not enabled.
801 if (block_extensions_) {
802 const Extension* extension = GetInstalledExtension(extension_id);
803 if (!extension || CanBlockExtension(extension))
804 return false;
807 // If the extension hasn't been loaded yet, check the prefs for it. Assume
808 // enabled unless otherwise noted.
809 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
810 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
811 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
814 void ExtensionService::EnableExtension(const std::string& extension_id) {
815 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
817 if (IsExtensionEnabled(extension_id))
818 return;
819 const Extension* extension =
820 registry_->disabled_extensions().GetByID(extension_id);
822 ManagementPolicy* policy = system_->management_policy();
823 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
824 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
825 return;
828 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
829 extension_prefs_->ClearDisableReasons(extension_id);
831 // This can happen if sync enables an extension that is not
832 // installed yet.
833 if (!extension)
834 return;
836 // Move it over to the enabled list.
837 registry_->AddEnabled(make_scoped_refptr(extension));
838 registry_->RemoveDisabled(extension->id());
840 NotifyExtensionLoaded(extension);
842 // Notify listeners that the extension was enabled.
843 content::NotificationService::current()->Notify(
844 extensions::NOTIFICATION_EXTENSION_ENABLED,
845 content::Source<Profile>(profile_),
846 content::Details<const Extension>(extension));
848 if (extension_sync_service_)
849 extension_sync_service_->SyncEnableExtension(*extension);
852 void ExtensionService::DisableExtension(
853 const std::string& extension_id,
854 Extension::DisableReason disable_reason) {
855 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
857 // The extension may have been disabled already. Just add a disable reason.
858 if (!IsExtensionEnabled(extension_id)) {
859 extension_prefs_->AddDisableReason(extension_id, disable_reason);
860 return;
863 const Extension* extension = GetInstalledExtension(extension_id);
864 // |extension| can be NULL if sync disables an extension that is not
865 // installed yet.
866 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
867 // can be uninstalled by the browser if the user sets extension-specific
868 // preferences.
869 if (extension &&
870 disable_reason != Extension::DISABLE_RELOAD &&
871 disable_reason != Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY &&
872 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
873 extension->location() != Manifest::EXTERNAL_COMPONENT) {
874 return;
877 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
878 extension_prefs_->AddDisableReason(extension_id, disable_reason);
880 int include_mask =
881 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
882 extension = registry_->GetExtensionById(extension_id, include_mask);
883 if (!extension)
884 return;
886 // The extension is either enabled or terminated.
887 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
888 registry_->terminated_extensions().Contains(extension->id()));
890 // Move it over to the disabled list. Don't send a second unload notification
891 // for terminated extensions being disabled.
892 registry_->AddDisabled(make_scoped_refptr(extension));
893 if (registry_->enabled_extensions().Contains(extension->id())) {
894 registry_->RemoveEnabled(extension->id());
895 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
896 } else {
897 registry_->RemoveTerminated(extension->id());
900 if (extension_sync_service_)
901 extension_sync_service_->SyncDisableExtension(*extension);
904 void ExtensionService::DisableUserExtensions(
905 const std::vector<std::string>& except_ids) {
906 extensions::ManagementPolicy* management_policy =
907 system_->management_policy();
908 extensions::ExtensionList to_disable;
910 const ExtensionSet& enabled_set = registry_->enabled_extensions();
911 for (ExtensionSet::const_iterator extension = enabled_set.begin();
912 extension != enabled_set.end(); ++extension) {
913 if (management_policy->UserMayModifySettings(extension->get(), NULL))
914 to_disable.push_back(*extension);
916 const ExtensionSet& terminated_set = registry_->terminated_extensions();
917 for (ExtensionSet::const_iterator extension = terminated_set.begin();
918 extension != terminated_set.end(); ++extension) {
919 if (management_policy->UserMayModifySettings(extension->get(), NULL))
920 to_disable.push_back(*extension);
923 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
924 extension != to_disable.end(); ++extension) {
925 if ((*extension)->was_installed_by_default() &&
926 extension_urls::IsWebstoreUpdateUrl(
927 extensions::ManifestURL::GetUpdateURL(extension->get())))
928 continue;
929 const std::string& id = (*extension)->id();
930 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
931 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
935 // Extensions that are not locked, components or forced by policy should be
936 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
937 // extensions are now considered both blacklisted and locked.
938 void ExtensionService::BlockAllExtensions() {
939 if (block_extensions_)
940 return;
941 block_extensions_ = true;
943 // Blacklisted extensions are already unloaded, need not be blocked.
944 scoped_ptr<ExtensionSet> extensions =
945 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED |
946 ExtensionRegistry::DISABLED |
947 ExtensionRegistry::TERMINATED);
949 for (const scoped_refptr<const Extension>& extension : *extensions) {
950 const std::string& id = extension->id();
952 if (!CanBlockExtension(extension.get()))
953 continue;
955 registry_->RemoveEnabled(id);
956 registry_->RemoveDisabled(id);
957 registry_->RemoveTerminated(id);
959 registry_->AddBlocked(extension.get());
960 UnloadExtension(id, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL);
964 // All locked extensions should revert to being either enabled or disabled
965 // as appropriate.
966 void ExtensionService::UnblockAllExtensions() {
967 block_extensions_ = false;
968 scoped_ptr<ExtensionSet> to_unblock =
969 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED);
971 for (const scoped_refptr<const Extension>& extension : *to_unblock) {
972 registry_->RemoveBlocked(extension->id());
973 AddExtension(extension.get());
977 void ExtensionService::GrantPermissionsAndEnableExtension(
978 const Extension* extension) {
979 GrantPermissions(extension);
980 RecordPermissionMessagesHistogram(extension,
981 "Extensions.Permissions_ReEnable2");
982 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
983 EnableExtension(extension->id());
986 void ExtensionService::GrantPermissions(const Extension* extension) {
987 CHECK(extension);
988 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
991 // static
992 void ExtensionService::RecordPermissionMessagesHistogram(
993 const Extension* extension, const char* histogram) {
994 // Since this is called from multiple sources, and since the histogram macros
995 // use statics, we need to manually lookup the histogram ourselves.
996 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
997 histogram,
999 PermissionMessage::kEnumBoundary,
1000 PermissionMessage::kEnumBoundary + 1,
1001 base::HistogramBase::kUmaTargetedHistogramFlag);
1003 PermissionMessages permissions =
1004 extension->permissions_data()->GetPermissionMessages();
1005 if (permissions.empty()) {
1006 counter->Add(PermissionMessage::kNone);
1007 } else {
1008 for (PermissionMessages::iterator it = permissions.begin();
1009 it != permissions.end(); ++it)
1010 counter->Add(it->id());
1014 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1015 // The URLRequestContexts need to be first to know that the extension
1016 // was loaded, otherwise a race can arise where a renderer that is created
1017 // for the extension may try to load an extension URL with an extension id
1018 // that the request context doesn't yet know about. The profile is responsible
1019 // for ensuring its URLRequestContexts appropriately discover the loaded
1020 // extension.
1021 system_->RegisterExtensionWithRequestContexts(extension);
1023 // Tell renderers about the new extension, unless it's a theme (renderers
1024 // don't need to know about themes).
1025 if (!extension->is_theme()) {
1026 for (content::RenderProcessHost::iterator i(
1027 content::RenderProcessHost::AllHostsIterator());
1028 !i.IsAtEnd(); i.Advance()) {
1029 content::RenderProcessHost* host = i.GetCurrentValue();
1030 Profile* host_profile =
1031 Profile::FromBrowserContext(host->GetBrowserContext());
1032 if (host_profile->GetOriginalProfile() ==
1033 profile_->GetOriginalProfile()) {
1034 // We don't need to include tab permisisons here, since the extension
1035 // was just loaded.
1036 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1037 1, ExtensionMsg_Loaded_Params(extension,
1038 false /* no tab permissions */));
1039 host->Send(
1040 new ExtensionMsg_Loaded(loaded_extensions));
1045 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1046 // extension.
1048 // NOTE: It is important that this happen after notifying the renderers about
1049 // the new extensions so that if we navigate to an extension URL in
1050 // ExtensionRegistryObserver::OnLoaded or
1051 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1052 // renderer is guaranteed to know about it.
1053 registry_->TriggerOnLoaded(extension);
1055 content::NotificationService::current()->Notify(
1056 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1057 content::Source<Profile>(profile_),
1058 content::Details<const Extension>(extension));
1060 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1061 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1062 profile_->GetExtensionSpecialStoragePolicy()->
1063 GrantRightsForExtension(extension, profile_);
1065 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1066 // work properly multi-profile. Besides which, it should be using
1067 // ExtensionRegistryObserver. See http://crbug.com/355029.
1068 UpdateActiveExtensionsInCrashReporter();
1070 const extensions::PermissionsData* permissions_data =
1071 extension->permissions_data();
1073 // If the extension has permission to load chrome://favicon/ resources we need
1074 // to make sure that the FaviconSource is registered with the
1075 // ChromeURLDataManager.
1076 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1077 FaviconSource* favicon_source = new FaviconSource(profile_,
1078 FaviconSource::FAVICON);
1079 content::URLDataSource::Add(profile_, favicon_source);
1082 // Same for chrome://theme/ resources.
1083 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1084 ThemeSource* theme_source = new ThemeSource(profile_);
1085 content::URLDataSource::Add(profile_, theme_source);
1088 // Same for chrome://thumb/ resources.
1089 if (permissions_data->HasHostPermission(
1090 GURL(chrome::kChromeUIThumbnailURL))) {
1091 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1092 content::URLDataSource::Add(profile_, thumbnail_source);
1096 void ExtensionService::NotifyExtensionUnloaded(
1097 const Extension* extension,
1098 UnloadedExtensionInfo::Reason reason) {
1099 UnloadedExtensionInfo details(extension, reason);
1101 registry_->TriggerOnUnloaded(extension, reason);
1103 content::NotificationService::current()->Notify(
1104 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1105 content::Source<Profile>(profile_),
1106 content::Details<UnloadedExtensionInfo>(&details));
1108 for (content::RenderProcessHost::iterator i(
1109 content::RenderProcessHost::AllHostsIterator());
1110 !i.IsAtEnd(); i.Advance()) {
1111 content::RenderProcessHost* host = i.GetCurrentValue();
1112 Profile* host_profile =
1113 Profile::FromBrowserContext(host->GetBrowserContext());
1114 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1115 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1118 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1120 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1121 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1122 profile_->GetExtensionSpecialStoragePolicy()->
1123 RevokeRightsForExtension(extension);
1125 #if defined(OS_CHROMEOS)
1126 // Revoke external file access for the extension from its file system context.
1127 // It is safe to access the extension's storage partition at this point. The
1128 // storage partition may get destroyed only after the extension gets unloaded.
1129 GURL site =
1130 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1131 storage::FileSystemContext* filesystem_context =
1132 BrowserContext::GetStoragePartitionForSite(profile_, site)
1133 ->GetFileSystemContext();
1134 if (filesystem_context && filesystem_context->external_backend()) {
1135 filesystem_context->external_backend()->
1136 RevokeAccessForExtension(extension->id());
1138 #endif
1140 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1141 // work properly multi-profile. Besides which, it should be using
1142 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1143 UpdateActiveExtensionsInCrashReporter();
1146 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1147 // Implemented in the .cc file to avoid adding a profile.h dependency to
1148 // extension_service.h.
1149 return profile_;
1152 bool ExtensionService::is_ready() {
1153 return ready_->is_signaled();
1156 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1157 if (file_task_runner_.get())
1158 return file_task_runner_.get();
1160 // We should be able to interrupt any part of extension install process during
1161 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1162 // will be ignored/deleted while we will block on started tasks.
1163 std::string token("ext_install-");
1164 token.append(profile_->GetPath().AsUTF8Unsafe());
1165 file_task_runner_ = BrowserThread::GetBlockingPool()->
1166 GetSequencedTaskRunnerWithShutdownBehavior(
1167 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1168 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1169 return file_task_runner_.get();
1172 void ExtensionService::CheckManagementPolicy() {
1173 std::vector<std::string> to_unload;
1174 std::map<std::string, Extension::DisableReason> to_disable;
1175 std::vector<std::string> to_enable;
1177 // Loop through the extensions list, finding extensions we need to unload or
1178 // disable.
1179 for (scoped_refptr<const Extension> extension :
1180 registry_->enabled_extensions()) {
1181 if (!system_->management_policy()->UserMayLoad(extension.get(), nullptr))
1182 to_unload.push_back(extension->id());
1183 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1184 if (system_->management_policy()->MustRemainDisabled(
1185 extension.get(), &disable_reason, nullptr))
1186 to_disable[extension->id()] = disable_reason;
1189 extensions::ExtensionManagement* management =
1190 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1192 // Loop through the disabled extension list, find extensions to re-enable
1193 // automatically. These extensions are exclusive from the |to_disable| and
1194 // |to_unload| lists constructed above, since disabled_extensions() and
1195 // enabled_extensions() are supposed to be mutually exclusive.
1196 for (scoped_refptr<const Extension> extension :
1197 registry_->disabled_extensions()) {
1198 // Find all disabled extensions disabled due to minimum version requirement,
1199 // but now satisfying it.
1200 if (management->CheckMinimumVersion(extension.get(), nullptr) &&
1201 extension_prefs_->HasDisableReason(
1202 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY)) {
1203 // Is DISABLE_UPDATE_REQUIRED_BY_POLICY the *only* reason?
1204 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1205 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1206 // We need to enable those disabled *only* due to minimum version
1207 // requirement.
1208 to_enable.push_back(extension->id());
1210 extension_prefs_->RemoveDisableReason(
1211 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1215 for (const std::string& id : to_unload)
1216 UnloadExtension(id, UnloadedExtensionInfo::REASON_DISABLE);
1218 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1219 to_disable.begin(); i != to_disable.end(); ++i)
1220 DisableExtension(i->first, i->second);
1222 // No extension is getting re-enabled here after disabling/unloading
1223 // because to_enable is mutually exclusive to to_disable + to_unload.
1224 for (const std::string& id : to_enable)
1225 EnableExtension(id);
1227 if (updater_.get()) {
1228 // Find all extensions disabled due to minimum version requirement from
1229 // policy (including the ones that got disabled just now), and check
1230 // for update.
1231 extensions::ExtensionUpdater::CheckParams to_recheck;
1232 for (scoped_refptr<const Extension> extension :
1233 registry_->disabled_extensions()) {
1234 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1235 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1236 // The minimum version check is the only thing holding this extension
1237 // back, so check if it can be updated to fix that.
1238 to_recheck.ids.push_back(extension->id());
1241 if (!to_recheck.ids.empty())
1242 updater_->CheckNow(to_recheck);
1246 void ExtensionService::CheckForUpdatesSoon() {
1247 // This can legitimately happen in unit tests.
1248 if (!updater_.get())
1249 return;
1251 if (AreAllExternalProvidersReady()) {
1252 updater_->CheckSoon();
1253 } else {
1254 // Sync can start updating before all the external providers are ready
1255 // during startup. Start the update as soon as those providers are ready,
1256 // but not before.
1257 update_once_all_providers_are_ready_ = true;
1261 // Some extensions will autoupdate themselves externally from Chrome. These
1262 // are typically part of some larger client application package. To support
1263 // these, the extension will register its location in the the preferences file
1264 // (and also, on Windows, in the registry) and this code will periodically
1265 // check that location for a .crx file, which it will then install locally if
1266 // a new version is available.
1267 // Errors are reported through ExtensionErrorReporter. Succcess is not
1268 // reported.
1269 void ExtensionService::CheckForExternalUpdates() {
1270 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1272 // Note that this installation is intentionally silent (since it didn't
1273 // go through the front-end). Extensions that are registered in this
1274 // way are effectively considered 'pre-bundled', and so implicitly
1275 // trusted. In general, if something has HKLM or filesystem access,
1276 // they could install an extension manually themselves anyway.
1278 // Ask each external extension provider to give us a call back for each
1279 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1280 extensions::ProviderCollection::const_iterator i;
1281 for (i = external_extension_providers_.begin();
1282 i != external_extension_providers_.end(); ++i) {
1283 extensions::ExternalProviderInterface* provider = i->get();
1284 provider->VisitRegisteredExtension();
1287 // Do any required work that we would have done after completion of all
1288 // providers.
1289 if (external_extension_providers_.empty())
1290 OnAllExternalProvidersReady();
1293 void ExtensionService::OnExternalProviderReady(
1294 const extensions::ExternalProviderInterface* provider) {
1295 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1296 CHECK(provider->IsReady());
1298 // An external provider has finished loading. We only take action
1299 // if all of them are finished. So we check them first.
1300 if (AreAllExternalProvidersReady())
1301 OnAllExternalProvidersReady();
1304 bool ExtensionService::AreAllExternalProvidersReady() const {
1305 extensions::ProviderCollection::const_iterator i;
1306 for (i = external_extension_providers_.begin();
1307 i != external_extension_providers_.end(); ++i) {
1308 if (!i->get()->IsReady())
1309 return false;
1311 return true;
1314 void ExtensionService::OnAllExternalProvidersReady() {
1315 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1316 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1317 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1319 // Install any pending extensions.
1320 if (update_once_all_providers_are_ready_ && updater()) {
1321 update_once_all_providers_are_ready_ = false;
1322 extensions::ExtensionUpdater::CheckParams params;
1323 params.callback = external_updates_finished_callback_;
1324 updater()->CheckNow(params);
1327 // Uninstall all the unclaimed extensions.
1328 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1329 extension_prefs_->GetInstalledExtensionsInfo());
1330 for (size_t i = 0; i < extensions_info->size(); ++i) {
1331 ExtensionInfo* info = extensions_info->at(i).get();
1332 if (Manifest::IsExternalLocation(info->extension_location))
1333 CheckExternalUninstall(info->extension_id);
1336 error_controller_->ShowErrorIfNeeded();
1338 external_install_manager_->UpdateExternalExtensionAlert();
1341 void ExtensionService::UnloadExtension(
1342 const std::string& extension_id,
1343 UnloadedExtensionInfo::Reason reason) {
1344 // Make sure the extension gets deleted after we return from this function.
1345 int include_mask =
1346 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1347 scoped_refptr<const Extension> extension(
1348 registry_->GetExtensionById(extension_id, include_mask));
1350 // This method can be called via PostTask, so the extension may have been
1351 // unloaded by the time this runs.
1352 if (!extension.get()) {
1353 // In case the extension may have crashed/uninstalled. Allow the profile to
1354 // clean up its RequestContexts.
1355 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1356 return;
1359 // Keep information about the extension so that we can reload it later
1360 // even if it's not permanently installed.
1361 unloaded_extension_paths_[extension->id()] = extension->path();
1363 // Clean up if the extension is meant to be enabled after a reload.
1364 reloading_extensions_.erase(extension->id());
1366 if (registry_->disabled_extensions().Contains(extension->id())) {
1367 registry_->RemoveDisabled(extension->id());
1368 // Make sure the profile cleans up its RequestContexts when an already
1369 // disabled extension is unloaded (since they are also tracking the disabled
1370 // extensions).
1371 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1372 // Don't send the unloaded notification. It was sent when the extension
1373 // was disabled.
1374 } else {
1375 // Remove the extension from the enabled list.
1376 registry_->RemoveEnabled(extension->id());
1377 NotifyExtensionUnloaded(extension.get(), reason);
1380 content::NotificationService::current()->Notify(
1381 extensions::NOTIFICATION_EXTENSION_REMOVED,
1382 content::Source<Profile>(profile_),
1383 content::Details<const Extension>(extension.get()));
1386 void ExtensionService::RemoveComponentExtension(
1387 const std::string& extension_id) {
1388 scoped_refptr<const Extension> extension(
1389 GetExtensionById(extension_id, false));
1390 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1391 if (extension.get()) {
1392 content::NotificationService::current()->Notify(
1393 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
1394 content::Source<Profile>(profile_),
1395 content::Details<const Extension>(extension.get()));
1396 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1397 extension.get(), extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT);
1401 void ExtensionService::UnloadAllExtensionsForTest() {
1402 UnloadAllExtensionsInternal();
1405 void ExtensionService::ReloadExtensionsForTest() {
1406 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1407 // warning about calling test code in production.
1408 UnloadAllExtensionsInternal();
1409 component_loader_->LoadAll();
1410 extensions::InstalledLoader(this).LoadAllExtensions();
1411 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1412 // times.
1415 void ExtensionService::SetReadyAndNotifyListeners() {
1416 const base::TimeTicks start_time = base::TimeTicks::Now();
1417 ready_->Signal();
1418 content::NotificationService::current()->Notify(
1419 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1420 content::Source<Profile>(profile_),
1421 content::NotificationService::NoDetails());
1422 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceNotifyReadyListenersTime",
1423 base::TimeTicks::Now() - start_time);
1426 void ExtensionService::OnLoadedInstalledExtensions() {
1427 if (updater_)
1428 updater_->Start();
1430 OnBlacklistUpdated();
1433 void ExtensionService::AddExtension(const Extension* extension) {
1434 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1435 // default extension state to DISABLED when the --disable-extensions flag
1436 // is set (http://crbug.com/29067).
1437 if (!extensions_enabled() &&
1438 !extension->is_theme() &&
1439 extension->location() != Manifest::COMPONENT &&
1440 !Manifest::IsExternalLocation(extension->location())) {
1441 return;
1444 bool is_extension_upgrade = false;
1445 bool is_extension_installed = false;
1446 const Extension* old = GetInstalledExtension(extension->id());
1447 if (old) {
1448 is_extension_installed = true;
1449 int version_compare_result =
1450 extension->version()->CompareTo(*(old->version()));
1451 is_extension_upgrade = version_compare_result > 0;
1452 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1453 // that we aren't downgrading.
1454 if (!Manifest::IsUnpackedLocation(extension->location()))
1455 CHECK_GE(version_compare_result, 0);
1457 // If the extension was disabled for a reload, then enable it.
1458 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1460 // Set the upgraded bit; we consider reloads upgrades.
1461 system_->runtime_data()->SetBeingUpgraded(extension->id(),
1462 is_extension_upgrade || reloading);
1464 // The extension is now loaded, remove its data from unloaded extension map.
1465 unloaded_extension_paths_.erase(extension->id());
1467 // If a terminated extension is loaded, remove it from the terminated list.
1468 UntrackTerminatedExtension(extension->id());
1470 // Check if the extension's privileges have changed and mark the
1471 // extension disabled if necessary.
1472 CheckPermissionsIncrease(extension, is_extension_installed);
1474 if (is_extension_installed && !reloading) {
1475 // To upgrade an extension in place, unload the old one and then load the
1476 // new one. ReloadExtension disables the extension, which is sufficient.
1477 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1480 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1481 // Only prefs is checked for the blacklist. We rely on callers to check the
1482 // blacklist before calling into here, e.g. CrxInstaller checks before
1483 // installation then threads through the install and pending install flow
1484 // of this class, and we check when loading installed extensions.
1485 registry_->AddBlacklisted(extension);
1486 } else if (block_extensions_ && CanBlockExtension(extension)) {
1487 registry_->AddBlocked(extension);
1488 } else if (!reloading &&
1489 extension_prefs_->IsExtensionDisabled(extension->id())) {
1490 registry_->AddDisabled(extension);
1491 if (extension_sync_service_)
1492 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1493 content::NotificationService::current()->Notify(
1494 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1495 content::Source<Profile>(profile_),
1496 content::Details<const Extension>(extension));
1498 // Show the extension disabled error if a permissions increase or a remote
1499 // installation is the reason it was disabled, and no other reasons exist.
1500 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1501 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1502 Extension::DISABLE_REMOTE_INSTALL;
1503 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1504 extensions::AddExtensionDisabledError(
1505 this,
1506 extension,
1507 extension_prefs_->HasDisableReason(
1508 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1510 } else if (reloading) {
1511 // Replace the old extension with the new version.
1512 CHECK(!registry_->AddDisabled(extension));
1513 EnableExtension(extension->id());
1514 } else {
1515 // All apps that are displayed in the launcher are ordered by their ordinals
1516 // so we must ensure they have valid ordinals.
1517 if (extension->RequiresSortOrdinal()) {
1518 extension_prefs_->app_sorting()->SetExtensionVisible(
1519 extension->id(),
1520 extension->ShouldDisplayInNewTabPage() &&
1521 !extension_prefs_->IsEphemeralApp(extension->id()));
1522 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1523 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1524 extension->id(), syncer::StringOrdinal());
1528 registry_->AddEnabled(extension);
1529 if (extension_sync_service_)
1530 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1531 NotifyExtensionLoaded(extension);
1533 system_->runtime_data()->SetBeingUpgraded(extension->id(), false);
1536 void ExtensionService::AddComponentExtension(const Extension* extension) {
1537 const std::string old_version_string(
1538 extension_prefs_->GetVersionString(extension->id()));
1539 const Version old_version(old_version_string);
1541 VLOG(1) << "AddComponentExtension " << extension->name();
1542 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1543 VLOG(1) << "Component extension " << extension->name() << " ("
1544 << extension->id() << ") installing/upgrading from '"
1545 << old_version_string << "' to " << extension->version()->GetString();
1547 AddNewOrUpdatedExtension(extension,
1548 Extension::ENABLED,
1549 extensions::kInstallFlagNone,
1550 syncer::StringOrdinal(),
1551 std::string());
1552 return;
1555 AddExtension(extension);
1558 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1559 bool is_extension_installed) {
1560 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1562 // We keep track of all permissions the user has granted each extension.
1563 // This allows extensions to gracefully support backwards compatibility
1564 // by including unknown permissions in their manifests. When the user
1565 // installs the extension, only the recognized permissions are recorded.
1566 // When the unknown permissions become recognized (e.g., through browser
1567 // upgrade), we can prompt the user to accept these new permissions.
1568 // Extensions can also silently upgrade to less permissions, and then
1569 // silently upgrade to a version that adds these permissions back.
1571 // For example, pretend that Chrome 10 includes a permission "omnibox"
1572 // for an API that adds suggestions to the omnibox. An extension can
1573 // maintain backwards compatibility while still having "omnibox" in the
1574 // manifest. If a user installs the extension on Chrome 9, the browser
1575 // will record the permissions it recognized, not including "omnibox."
1576 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1577 // will disable the extension and prompt the user to approve the increase
1578 // in privileges. The extension could then release a new version that
1579 // removes the "omnibox" permission. When the user upgrades, Chrome will
1580 // still remember that "omnibox" had been granted, so that if the
1581 // extension once again includes "omnibox" in an upgrade, the extension
1582 // can upgrade without requiring this user's approval.
1583 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1585 bool auto_grant_permission =
1586 (!is_extension_installed && extension->was_installed_by_default()) ||
1587 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1588 // Silently grant all active permissions to default apps only on install.
1589 // After install they should behave like other apps.
1590 // Silently grant all active permissions to apps install in kiosk mode on both
1591 // install and update.
1592 if (auto_grant_permission)
1593 GrantPermissions(extension);
1595 bool is_privilege_increase = false;
1596 // We only need to compare the granted permissions to the current permissions
1597 // if the extension is not allowed to silently increase its permissions.
1598 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) &&
1599 !auto_grant_permission) {
1600 // Add all the recognized permissions if the granted permissions list
1601 // hasn't been initialized yet.
1602 scoped_refptr<PermissionSet> granted_permissions =
1603 extension_prefs_->GetGrantedPermissions(extension->id());
1604 CHECK(granted_permissions.get());
1606 // Here, we check if an extension's privileges have increased in a manner
1607 // that requires the user's approval. This could occur because the browser
1608 // upgraded and recognized additional privileges, or an extension upgrades
1609 // to a version that requires additional privileges.
1610 is_privilege_increase =
1611 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1612 granted_permissions.get(),
1613 extension->permissions_data()->active_permissions().get(),
1614 extension->GetType());
1617 if (is_extension_installed) {
1618 // If the extension was already disabled, suppress any alerts for becoming
1619 // disabled on permissions increase.
1620 bool previously_disabled =
1621 extension_prefs_->IsExtensionDisabled(extension->id());
1622 // Legacy disabled extensions do not have a disable reason. Infer that if
1623 // there was no permission increase, it was likely disabled by the user.
1624 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1625 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1626 disable_reasons |= Extension::DISABLE_USER_ACTION;
1628 // Extensions that came to us disabled from sync need a similar inference,
1629 // except based on the new version's permissions.
1630 if (previously_disabled &&
1631 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1632 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1633 extension_prefs_->ClearDisableReasons(extension->id());
1634 if (!is_privilege_increase)
1635 disable_reasons |= Extension::DISABLE_USER_ACTION;
1637 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1640 // Extension has changed permissions significantly. Disable it. A
1641 // notification should be sent by the caller. If the extension is already
1642 // disabled because it was installed remotely, don't add another disable
1643 // reason, but instead always set the "did escalate permissions" flag, to
1644 // ensure enabling it will always show a warning.
1645 if (disable_reasons == Extension::DISABLE_REMOTE_INSTALL) {
1646 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1647 } else if (is_privilege_increase) {
1648 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1649 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1650 RecordPermissionMessagesHistogram(extension,
1651 "Extensions.Permissions_AutoDisable2");
1653 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1654 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1656 if (disable_reasons != Extension::DISABLE_NONE) {
1657 extension_prefs_->AddDisableReason(
1658 extension->id(),
1659 static_cast<Extension::DisableReason>(disable_reasons));
1663 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1664 std::set<std::string> extension_ids;
1665 const ExtensionSet& extensions = registry_->enabled_extensions();
1666 for (ExtensionSet::const_iterator iter = extensions.begin();
1667 iter != extensions.end(); ++iter) {
1668 const Extension* extension = iter->get();
1669 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1670 extension_ids.insert(extension->id());
1673 // TODO(kalman): This is broken. ExtensionService is per-profile.
1674 // crash_keys::SetActiveExtensions is per-process. See
1675 // http://crbug.com/355029.
1676 crash_keys::SetActiveExtensions(extension_ids);
1679 void ExtensionService::OnExtensionInstalled(
1680 const Extension* extension,
1681 const syncer::StringOrdinal& page_ordinal,
1682 int install_flags) {
1683 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1685 const std::string& id = extension->id();
1686 int disable_reasons = GetDisableReasonsOnInstalled(extension);
1687 std::string install_parameter;
1688 const extensions::PendingExtensionInfo* pending_extension_info =
1689 pending_extension_manager()->GetById(id);
1690 if (pending_extension_info) {
1691 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1692 pending_extension_manager()->Remove(id);
1694 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1695 << id << " of type " << extension->GetType()
1696 << " and update URL "
1697 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1698 << "; not installing";
1700 // Delete the extension directory since we're not going to
1701 // load it.
1702 if (!GetFileTaskRunner()->PostTask(
1703 FROM_HERE,
1704 base::Bind(&extensions::file_util::DeleteFile,
1705 extension->path(),
1706 true))) {
1707 NOTREACHED();
1709 return;
1712 install_parameter = pending_extension_info->install_parameter();
1713 pending_extension_manager()->Remove(id);
1714 } else {
1715 // We explicitly want to re-enable an uninstalled external
1716 // extension; if we're here, that means the user is manually
1717 // installing the extension.
1718 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1719 disable_reasons = Extension::DISABLE_NONE;
1723 // Unsupported requirements overrides the management policy.
1724 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1725 disable_reasons |= Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1726 } else {
1727 // Requirement is supported now, remove the corresponding disable reason
1728 // instead.
1729 extension_prefs_->RemoveDisableReason(
1730 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1731 disable_reasons &= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1734 // Check if the extension was disabled because of the minimum version
1735 // requirements from enterprise policy, and satisfies it now.
1736 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1737 ->CheckMinimumVersion(extension, nullptr)) {
1738 // And remove the corresponding disable reason.
1739 extension_prefs_->RemoveDisableReason(
1740 id, Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1741 disable_reasons &= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY;
1744 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1745 // Installation of a blacklisted extension can happen from sync, policy,
1746 // etc, where to maintain consistency we need to install it, just never
1747 // load it (see AddExtension). Usually it should be the job of callers to
1748 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
1749 // showing the install dialogue).
1750 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1751 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1752 extension->location(),
1753 Manifest::NUM_LOCATIONS);
1756 if (!GetInstalledExtension(extension->id())) {
1757 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1758 extension->GetType(), 100);
1759 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1760 extension->location(), Manifest::NUM_LOCATIONS);
1761 RecordPermissionMessagesHistogram(extension,
1762 "Extensions.Permissions_Install2");
1763 } else {
1764 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1765 extension->GetType(), 100);
1766 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1767 extension->location(), Manifest::NUM_LOCATIONS);
1769 // A fully installed app cannot be demoted to an ephemeral app.
1770 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1771 !extension_prefs_->IsEphemeralApp(id)) {
1772 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1776 if (disable_reasons)
1777 extension_prefs_->AddDisableReasons(id, disable_reasons);
1779 const Extension::State initial_state =
1780 disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED
1781 : Extension::DISABLED;
1783 if (ShouldDelayExtensionUpdate(
1785 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1786 extension_prefs_->SetDelayedInstallInfo(
1787 extension,
1788 initial_state,
1789 install_flags,
1790 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1791 page_ordinal,
1792 install_parameter);
1794 // Transfer ownership of |extension|.
1795 delayed_installs_.Insert(extension);
1797 // Notify observers that app update is available.
1798 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1799 OnAppUpdateAvailable(extension));
1800 return;
1803 extensions::SharedModuleService::ImportStatus status =
1804 shared_module_service_->SatisfyImports(extension);
1805 if (installs_delayed_for_gc_) {
1806 extension_prefs_->SetDelayedInstallInfo(
1807 extension,
1808 initial_state,
1809 install_flags,
1810 extensions::ExtensionPrefs::DELAY_REASON_GC,
1811 page_ordinal,
1812 install_parameter);
1813 delayed_installs_.Insert(extension);
1814 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1815 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1816 extension_prefs_->SetDelayedInstallInfo(
1817 extension,
1818 initial_state,
1819 install_flags,
1820 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1821 page_ordinal,
1822 install_parameter);
1823 delayed_installs_.Insert(extension);
1825 } else {
1826 AddNewOrUpdatedExtension(extension,
1827 initial_state,
1828 install_flags,
1829 page_ordinal,
1830 install_parameter);
1834 void ExtensionService::OnExtensionManagementSettingsChanged() {
1835 error_controller_->ShowErrorIfNeeded();
1837 // Revokes blocked permissions from active_permissions for all extensions.
1838 extensions::ExtensionManagement* settings =
1839 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1840 CHECK(settings);
1841 scoped_ptr<ExtensionSet> all_extensions(
1842 registry_->GenerateInstalledExtensionsSet());
1843 for (const auto& extension : *all_extensions.get()) {
1844 if (!settings->IsPermissionSetAllowed(
1845 extension.get(),
1846 extension->permissions_data()->active_permissions())) {
1847 extensions::PermissionsUpdater(profile()).RemovePermissions(
1848 extension.get(),
1849 settings->GetBlockedPermissions(extension.get()).get());
1853 CheckManagementPolicy();
1856 void ExtensionService::AddNewOrUpdatedExtension(
1857 const Extension* extension,
1858 Extension::State initial_state,
1859 int install_flags,
1860 const syncer::StringOrdinal& page_ordinal,
1861 const std::string& install_parameter) {
1862 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1863 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1864 extension_prefs_->OnExtensionInstalled(
1865 extension, initial_state, page_ordinal, install_flags, install_parameter);
1866 delayed_installs_.Remove(extension->id());
1867 if (InstallVerifier::NeedsVerification(*extension))
1868 system_->install_verifier()->VerifyExtension(extension->id());
1870 const Extension* old = GetInstalledExtension(extension->id());
1871 if (extensions::AppDataMigrator::NeedsMigration(old, extension)) {
1872 app_data_migrator_->DoMigrationAndReply(
1873 old, extension,
1874 base::Bind(&ExtensionService::FinishInstallation, AsWeakPtr(),
1875 make_scoped_refptr(extension), was_ephemeral));
1876 return;
1879 FinishInstallation(extension, was_ephemeral);
1882 void ExtensionService::MaybeFinishDelayedInstallation(
1883 const std::string& extension_id) {
1884 // Check if the extension already got installed.
1885 if (!delayed_installs_.Contains(extension_id))
1886 return;
1887 extensions::ExtensionPrefs::DelayReason reason =
1888 extension_prefs_->GetDelayedInstallReason(extension_id);
1890 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1891 // preferences files that will not have set this field but it was previously
1892 // only used for idle updates.
1893 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1894 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1895 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1896 return;
1898 const Extension* extension = delayed_installs_.GetByID(extension_id);
1899 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1900 extensions::SharedModuleService::ImportStatus status =
1901 shared_module_service_->SatisfyImports(extension);
1902 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1903 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1904 delayed_installs_.Remove(extension_id);
1905 // Make sure no version of the extension is actually installed, (i.e.,
1906 // that this delayed install was not an update).
1907 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1908 extension_prefs_->DeleteExtensionPrefs(extension_id);
1910 return;
1914 FinishDelayedInstallation(extension_id);
1917 void ExtensionService::FinishDelayedInstallation(
1918 const std::string& extension_id) {
1919 scoped_refptr<const Extension> extension(
1920 GetPendingExtensionUpdate(extension_id));
1921 CHECK(extension.get());
1922 delayed_installs_.Remove(extension_id);
1924 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1925 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1926 NOTREACHED();
1928 FinishInstallation(extension.get(), was_ephemeral);
1931 void ExtensionService::FinishInstallation(
1932 const Extension* extension, bool was_ephemeral) {
1933 const extensions::Extension* existing_extension =
1934 GetInstalledExtension(extension->id());
1935 bool is_update = false;
1936 std::string old_name;
1937 if (existing_extension) {
1938 is_update = true;
1939 old_name = existing_extension->name();
1941 bool from_ephemeral =
1942 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1943 extensions::InstalledExtensionInfo details(
1944 extension, is_update, from_ephemeral, old_name);
1945 content::NotificationService::current()->Notify(
1946 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1947 content::Source<Profile>(profile_),
1948 content::Details<const extensions::InstalledExtensionInfo>(&details));
1950 registry_->TriggerOnWillBeInstalled(
1951 extension, is_update, from_ephemeral, old_name);
1953 // Unpacked extensions default to allowing file access, but if that has been
1954 // overridden, don't reset the value.
1955 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1956 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1957 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1960 AddExtension(extension);
1962 // Notify observers that need to know when an installation is complete.
1963 registry_->TriggerOnInstalled(extension, is_update);
1965 // Check extensions that may have been delayed only because this shared module
1966 // was not available.
1967 if (SharedModuleInfo::IsSharedModule(extension))
1968 MaybeFinishDelayedInstallations();
1971 void ExtensionService::PromoteEphemeralApp(
1972 const extensions::Extension* extension, bool is_from_sync) {
1973 DCHECK(GetInstalledExtension(extension->id()) &&
1974 extension_prefs_->IsEphemeralApp(extension->id()));
1976 if (extension->RequiresSortOrdinal()) {
1977 extension_prefs_->app_sorting()->SetExtensionVisible(
1978 extension->id(), extension->ShouldDisplayInNewTabPage());
1980 if (!is_from_sync) {
1981 // Reset the sort ordinals of the app to ensure it is added to the default
1982 // position, like newly installed apps would.
1983 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
1986 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1987 extension->id(), syncer::StringOrdinal());
1990 // Remove the ephemeral flags from the preferences.
1991 extension_prefs_->OnEphemeralAppPromoted(extension->id());
1993 // Fire install-related events to allow observers to handle the promotion
1994 // of the ephemeral app.
1995 extensions::InstalledExtensionInfo details(
1996 extension,
1997 true /* is update */,
1998 true /* from ephemeral */,
1999 extension->name() /* old name */);
2000 content::NotificationService::current()->Notify(
2001 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2002 content::Source<Profile>(profile_),
2003 content::Details<const extensions::InstalledExtensionInfo>(&details));
2005 registry_->TriggerOnWillBeInstalled(
2006 extension,
2007 true /* is update */,
2008 true /* from ephemeral */,
2009 extension->name() /* old name */);
2011 if (registry_->enabled_extensions().Contains(extension->id())) {
2012 // If the app is already enabled and loaded, fire the load events to allow
2013 // observers to handle the promotion of the ephemeral app.
2014 content::NotificationService::current()->Notify(
2015 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
2016 content::Source<Profile>(profile_),
2017 content::Details<const Extension>(extension));
2019 registry_->TriggerOnLoaded(extension);
2020 } else {
2021 // Cached ephemeral apps may be updated and disabled due to permissions
2022 // increase. The app can be enabled (as long as no other disable reasons
2023 // exist) as the install was user-acknowledged.
2024 int disable_mask = Extension::DISABLE_NONE;
2025 if (!is_from_sync)
2026 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
2028 int other_disable_reasons =
2029 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
2030 if (!other_disable_reasons) {
2031 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
2032 GrantPermissionsAndEnableExtension(extension);
2033 else
2034 EnableExtension(extension->id());
2038 registry_->TriggerOnInstalled(extension, true);
2040 if (!is_from_sync && extension_sync_service_)
2041 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
2044 const Extension* ExtensionService::GetPendingExtensionUpdate(
2045 const std::string& id) const {
2046 return delayed_installs_.GetByID(id);
2049 void ExtensionService::RegisterContentSettings(
2050 HostContentSettingsMap* host_content_settings_map) {
2051 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2052 host_content_settings_map->RegisterProvider(
2053 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
2054 scoped_ptr<content_settings::ObservableProvider>(
2055 new content_settings::InternalExtensionProvider(profile_)));
2057 host_content_settings_map->RegisterProvider(
2058 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
2059 scoped_ptr<content_settings::ObservableProvider>(
2060 new content_settings::CustomExtensionProvider(
2061 extensions::ContentSettingsService::Get(
2062 profile_)->content_settings_store(),
2063 profile_->GetOriginalProfile() != profile_)));
2066 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
2067 // No need to check for duplicates; inserting a duplicate is a no-op.
2068 registry_->AddTerminated(make_scoped_refptr(extension));
2069 extensions_being_terminated_.erase(extension->id());
2070 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2073 void ExtensionService::TerminateExtension(const std::string& extension_id) {
2074 const Extension* extension = GetInstalledExtension(extension_id);
2075 TrackTerminatedExtension(extension);
2078 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2079 std::string lowercase_id = base::StringToLowerASCII(id);
2080 const Extension* extension =
2081 registry_->terminated_extensions().GetByID(lowercase_id);
2082 registry_->RemoveTerminated(lowercase_id);
2083 if (extension) {
2084 content::NotificationService::current()->Notify(
2085 extensions::NOTIFICATION_EXTENSION_REMOVED,
2086 content::Source<Profile>(profile_),
2087 content::Details<const Extension>(extension));
2091 const Extension* ExtensionService::GetInstalledExtension(
2092 const std::string& id) const {
2093 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2096 bool ExtensionService::OnExternalExtensionFileFound(
2097 const std::string& id,
2098 const Version* version,
2099 const base::FilePath& path,
2100 Manifest::Location location,
2101 int creation_flags,
2102 bool mark_acknowledged) {
2103 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2104 CHECK(crx_file::id_util::IdIsValid(id));
2105 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2106 return false;
2108 // Before even bothering to unpack, check and see if we already have this
2109 // version. This is important because these extensions are going to get
2110 // installed on every startup.
2111 const Extension* existing = GetExtensionById(id, true);
2113 if (existing) {
2114 // The default apps will have the location set as INTERNAL. Since older
2115 // default apps are installed as EXTERNAL, we override them. However, if the
2116 // app is already installed as internal, then do the version check.
2117 // TODO(grv) : Remove after Q1-2013.
2118 bool is_default_apps_migration =
2119 (location == Manifest::INTERNAL &&
2120 Manifest::IsExternalLocation(existing->location()));
2122 if (!is_default_apps_migration) {
2123 DCHECK(version);
2125 switch (existing->version()->CompareTo(*version)) {
2126 case -1: // existing version is older, we should upgrade
2127 break;
2128 case 0: // existing version is same, do nothing
2129 return false;
2130 case 1: // existing version is newer, uh-oh
2131 LOG(WARNING) << "Found external version of extension " << id
2132 << "that is older than current version. Current version "
2133 << "is: " << existing->VersionString() << ". New "
2134 << "version is: " << version->GetString()
2135 << ". Keeping current version.";
2136 return false;
2141 // If the extension is already pending, don't start an install.
2142 if (!pending_extension_manager()->AddFromExternalFile(
2143 id, location, *version, creation_flags, mark_acknowledged)) {
2144 return false;
2147 // no client (silent install)
2148 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2149 installer->set_install_source(location);
2150 installer->set_expected_id(id);
2151 installer->set_expected_version(*version);
2152 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2153 installer->set_creation_flags(creation_flags);
2154 #if defined(OS_CHROMEOS)
2155 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2156 #else
2157 installer->InstallCrx(path);
2158 #endif
2160 // Depending on the source, a new external extension might not need a user
2161 // notification on installation. For such extensions, mark them acknowledged
2162 // now to suppress the notification.
2163 if (mark_acknowledged)
2164 external_install_manager_->AcknowledgeExternalExtension(id);
2166 return true;
2169 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2170 extensions::ExtensionHost* host) {
2171 OrphanedDevTools::iterator iter =
2172 orphaned_dev_tools_.find(host->extension_id());
2173 if (iter == orphaned_dev_tools_.end())
2174 return;
2176 iter->second->ConnectWebContents(host->host_contents());
2177 orphaned_dev_tools_.erase(iter);
2180 void ExtensionService::Observe(int type,
2181 const content::NotificationSource& source,
2182 const content::NotificationDetails& details) {
2183 switch (type) {
2184 case chrome::NOTIFICATION_APP_TERMINATING:
2185 // Shutdown has started. Don't start any more extension installs.
2186 // (We cannot use ExtensionService::Shutdown() for this because it
2187 // happens too late in browser teardown.)
2188 browser_terminating_ = true;
2189 break;
2190 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2191 if (profile_ !=
2192 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2193 break;
2196 extensions::ExtensionHost* host =
2197 content::Details<extensions::ExtensionHost>(details).ptr();
2199 // If the extension is already being terminated, there is nothing left to
2200 // do.
2201 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2202 break;
2204 // Mark the extension as terminated and Unload it. We want it to
2205 // be in a consistent state: either fully working or not loaded
2206 // at all, but never half-crashed. We do it in a PostTask so
2207 // that other handlers of this notification will still have
2208 // access to the Extension and ExtensionHost.
2209 base::MessageLoop::current()->PostTask(
2210 FROM_HERE,
2211 base::Bind(
2212 &ExtensionService::TrackTerminatedExtension,
2213 AsWeakPtr(),
2214 host->extension()));
2215 break;
2217 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2218 content::RenderProcessHost* process =
2219 content::Source<content::RenderProcessHost>(source).ptr();
2220 Profile* host_profile =
2221 Profile::FromBrowserContext(process->GetBrowserContext());
2222 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2223 break;
2225 extensions::ProcessMap* process_map =
2226 extensions::ProcessMap::Get(profile_);
2227 if (process_map->Contains(process->GetID())) {
2228 // An extension process was terminated, this might have resulted in an
2229 // app or extension becoming idle.
2230 std::set<std::string> extension_ids =
2231 process_map->GetExtensionsInProcess(process->GetID());
2232 // In addition to the extensions listed in the process map, one of those
2233 // extensions could be referencing a shared module which is waiting for
2234 // idle to update. Check all imports of these extensions, too.
2235 std::set<std::string> import_ids;
2236 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2237 it != extension_ids.end();
2238 ++it) {
2239 const Extension* extension = GetExtensionById(*it, true);
2240 if (!extension)
2241 continue;
2242 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2243 SharedModuleInfo::GetImports(extension);
2244 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2245 for (import_it = imports.begin(); import_it != imports.end();
2246 import_it++) {
2247 import_ids.insert((*import_it).extension_id);
2250 extension_ids.insert(import_ids.begin(), import_ids.end());
2252 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2253 it != extension_ids.end(); ++it) {
2254 if (delayed_installs_.Contains(*it)) {
2255 base::MessageLoop::current()->PostDelayedTask(
2256 FROM_HERE,
2257 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2258 AsWeakPtr(), *it),
2259 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2264 process_map->RemoveAllFromProcess(process->GetID());
2265 BrowserThread::PostTask(
2266 BrowserThread::IO,
2267 FROM_HERE,
2268 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2269 system_->info_map(),
2270 process->GetID()));
2271 break;
2273 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2274 // Notify observers that chrome update is available.
2275 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2276 OnChromeUpdateAvailable());
2277 break;
2279 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2280 OnProfileDestructionStarted();
2281 break;
2284 default:
2285 NOTREACHED() << "Unexpected notification type.";
2289 int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
2290 Extension::DisableReason disable_reason;
2291 // Extensions disabled by management policy should always be disabled, even
2292 // if it's force-installed.
2293 if (system_->management_policy()->MustRemainDisabled(
2294 extension, &disable_reason, nullptr)) {
2295 // A specified reason is required to disable the extension.
2296 DCHECK(disable_reason != Extension::DISABLE_NONE);
2297 return disable_reason;
2300 // Extensions installed by policy can't be disabled. So even if a previous
2301 // installation disabled the extension, make sure it is now enabled.
2302 if (system_->management_policy()->MustRemainEnabled(extension, nullptr))
2303 return Extension::DISABLE_NONE;
2305 // An already disabled extension should inherit the disable reasons and
2306 // remain disabled.
2307 if (extension_prefs_->IsExtensionDisabled(extension->id())) {
2308 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2309 // If an extension was disabled without specified reason, presume it's
2310 // disabled by user.
2311 return disable_reasons == Extension::DISABLE_NONE
2312 ? Extension::DISABLE_USER_ACTION
2313 : disable_reasons;
2316 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2317 // External extensions are initially disabled. We prompt the user before
2318 // enabling them. Hosted apps are excepted because they are not dangerous
2319 // (they need to be launched by the user anyway).
2320 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2321 Manifest::IsExternalLocation(extension->location()) &&
2322 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2323 return Extension::DISABLE_EXTERNAL_EXTENSION;
2327 return Extension::DISABLE_NONE;
2330 // Helper method to determine if an extension can be blocked.
2331 bool ExtensionService::CanBlockExtension(const Extension* extension) const {
2332 DCHECK(extension);
2333 return extension->location() != Manifest::COMPONENT &&
2334 extension->location() != Manifest::EXTERNAL_COMPONENT &&
2335 !system_->management_policy()->MustRemainEnabled(extension, NULL);
2338 bool ExtensionService::ShouldDelayExtensionUpdate(
2339 const std::string& extension_id,
2340 bool install_immediately) const {
2341 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2343 // If delayed updates are globally disabled, or just for this extension,
2344 // don't delay.
2345 if (!install_updates_when_idle_ || install_immediately)
2346 return false;
2348 const Extension* old = GetInstalledExtension(extension_id);
2349 // If there is no old extension, this is not an update, so don't delay.
2350 if (!old)
2351 return false;
2353 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2354 // Delay installation if the extension listens for the onUpdateAvailable
2355 // event.
2356 return system_->event_router()->ExtensionHasEventListener(
2357 extension_id, kOnUpdateAvailableEvent);
2358 } else {
2359 // Delay installation if the extension is not idle.
2360 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2364 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2365 DCHECK(!installs_delayed_for_gc_);
2366 installs_delayed_for_gc_ = true;
2369 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2370 DCHECK(installs_delayed_for_gc_);
2371 installs_delayed_for_gc_ = false;
2372 MaybeFinishDelayedInstallations();
2375 void ExtensionService::MaybeFinishDelayedInstallations() {
2376 std::vector<std::string> to_be_installed;
2377 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2378 it != delayed_installs_.end();
2379 ++it) {
2380 to_be_installed.push_back((*it)->id());
2382 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2383 it != to_be_installed.end();
2384 ++it) {
2385 MaybeFinishDelayedInstallation(*it);
2389 void ExtensionService::OnBlacklistUpdated() {
2390 blacklist_->GetBlacklistedIDs(
2391 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2392 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2395 void ExtensionService::ManageBlacklist(
2396 const extensions::Blacklist::BlacklistStateMap& state_map) {
2397 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2399 std::set<std::string> blacklisted;
2400 ExtensionIdSet greylist;
2401 ExtensionIdSet unchanged;
2402 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2403 state_map.begin();
2404 it != state_map.end();
2405 ++it) {
2406 switch (it->second) {
2407 case extensions::NOT_BLACKLISTED:
2408 break;
2410 case extensions::BLACKLISTED_MALWARE:
2411 blacklisted.insert(it->first);
2412 break;
2414 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2415 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2416 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2417 greylist.insert(it->first);
2418 break;
2420 case extensions::BLACKLISTED_UNKNOWN:
2421 unchanged.insert(it->first);
2422 break;
2426 UpdateBlacklistedExtensions(blacklisted, unchanged);
2427 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2429 error_controller_->ShowErrorIfNeeded();
2432 namespace {
2433 void Partition(const ExtensionIdSet& before,
2434 const ExtensionIdSet& after,
2435 const ExtensionIdSet& unchanged,
2436 ExtensionIdSet* no_longer,
2437 ExtensionIdSet* not_yet) {
2438 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2439 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2440 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2442 } // namespace
2444 void ExtensionService::UpdateBlacklistedExtensions(
2445 const ExtensionIdSet& blacklisted,
2446 const ExtensionIdSet& unchanged) {
2447 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2448 Partition(registry_->blacklisted_extensions().GetIDs(), blacklisted,
2449 unchanged, &no_longer_blocked, &not_yet_blocked);
2451 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2452 it != no_longer_blocked.end(); ++it) {
2453 scoped_refptr<const Extension> extension =
2454 registry_->blacklisted_extensions().GetByID(*it);
2455 if (!extension.get()) {
2456 NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
2457 << "but it was never blacklisted.";
2458 continue;
2460 registry_->RemoveBlacklisted(*it);
2461 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2462 AddExtension(extension.get());
2463 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2464 extension->location(),
2465 Manifest::NUM_LOCATIONS);
2468 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2469 it != not_yet_blocked.end(); ++it) {
2470 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2471 if (!extension.get()) {
2472 NOTREACHED() << "Extension " << *it << " needs to be "
2473 << "blacklisted, but it's not installed.";
2474 continue;
2476 registry_->AddBlacklisted(extension);
2477 extension_prefs_->SetExtensionBlacklistState(
2478 extension->id(), extensions::BLACKLISTED_MALWARE);
2479 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2480 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2481 extension->location(), Manifest::NUM_LOCATIONS);
2485 // TODO(oleg): UMA logging
2486 void ExtensionService::UpdateGreylistedExtensions(
2487 const ExtensionIdSet& greylist,
2488 const ExtensionIdSet& unchanged,
2489 const extensions::Blacklist::BlacklistStateMap& state_map) {
2490 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2491 Partition(greylist_.GetIDs(),
2492 greylist, unchanged,
2493 &no_longer_greylisted, &not_yet_greylisted);
2495 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2496 it != no_longer_greylisted.end(); ++it) {
2497 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2498 if (!extension.get()) {
2499 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2500 << "but it was not marked as greylisted.";
2501 continue;
2504 greylist_.Remove(*it);
2505 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2506 extensions::NOT_BLACKLISTED);
2507 if (extension_prefs_->GetDisableReasons(extension->id()) &
2508 extensions::Extension::DISABLE_GREYLIST)
2509 EnableExtension(*it);
2512 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2513 it != not_yet_greylisted.end(); ++it) {
2514 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2515 if (!extension.get()) {
2516 NOTREACHED() << "Extension " << *it << " needs to be "
2517 << "disabled, but it's not installed.";
2518 continue;
2520 greylist_.Insert(extension);
2521 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2522 state_map.find(*it)->second);
2523 if (registry_->enabled_extensions().Contains(extension->id()))
2524 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2528 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2529 update_observers_.AddObserver(observer);
2532 void ExtensionService::RemoveUpdateObserver(
2533 extensions::UpdateObserver* observer) {
2534 update_observers_.RemoveObserver(observer);
2537 // Used only by test code.
2538 void ExtensionService::UnloadAllExtensionsInternal() {
2539 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2541 registry_->ClearAll();
2542 system_->runtime_data()->ClearAll();
2544 // TODO(erikkay) should there be a notification for this? We can't use
2545 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2546 // or uninstalled.
2549 void ExtensionService::OnProfileDestructionStarted() {
2550 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2551 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2552 it != ids_to_unload.end();
2553 ++it) {
2554 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);