Unload all apps / extensions immediately when deleting a profile.
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blob702b7fc432c68d77f54708e92d9615f18c7168e7
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/extensions/api/extension_action/extension_action_api.h"
22 #include "chrome/browser/extensions/component_loader.h"
23 #include "chrome/browser/extensions/crx_installer.h"
24 #include "chrome/browser/extensions/data_deleter.h"
25 #include "chrome/browser/extensions/extension_disabled_ui.h"
26 #include "chrome/browser/extensions/extension_error_controller.h"
27 #include "chrome/browser/extensions/extension_install_ui.h"
28 #include "chrome/browser/extensions/extension_special_storage_policy.h"
29 #include "chrome/browser/extensions/extension_sync_service.h"
30 #include "chrome/browser/extensions/extension_util.h"
31 #include "chrome/browser/extensions/external_install_ui.h"
32 #include "chrome/browser/extensions/external_provider_impl.h"
33 #include "chrome/browser/extensions/install_verifier.h"
34 #include "chrome/browser/extensions/installed_loader.h"
35 #include "chrome/browser/extensions/pending_extension_manager.h"
36 #include "chrome/browser/extensions/permissions_updater.h"
37 #include "chrome/browser/extensions/shared_module_service.h"
38 #include "chrome/browser/extensions/unpacked_installer.h"
39 #include "chrome/browser/extensions/updater/extension_cache.h"
40 #include "chrome/browser/extensions/updater/extension_updater.h"
41 #include "chrome/browser/profiles/profile.h"
42 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
43 #include "chrome/browser/ui/webui/favicon_source.h"
44 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
45 #include "chrome/browser/ui/webui/theme_source.h"
46 #include "chrome/common/chrome_switches.h"
47 #include "chrome/common/crash_keys.h"
48 #include "chrome/common/extensions/extension_constants.h"
49 #include "chrome/common/extensions/features/feature_channel.h"
50 #include "chrome/common/extensions/manifest_url_handler.h"
51 #include "chrome/common/pref_names.h"
52 #include "chrome/common/url_constants.h"
53 #include "components/startup_metric_utils/startup_metric_utils.h"
54 #include "content/public/browser/notification_service.h"
55 #include "content/public/browser/render_process_host.h"
56 #include "content/public/browser/storage_partition.h"
57 #include "extensions/browser/event_router.h"
58 #include "extensions/browser/extension_host.h"
59 #include "extensions/browser/extension_registry.h"
60 #include "extensions/browser/extension_system.h"
61 #include "extensions/browser/pref_names.h"
62 #include "extensions/browser/runtime_data.h"
63 #include "extensions/browser/update_observer.h"
64 #include "extensions/common/extension_messages.h"
65 #include "extensions/common/feature_switch.h"
66 #include "extensions/common/file_util.h"
67 #include "extensions/common/manifest_constants.h"
68 #include "extensions/common/manifest_handlers/background_info.h"
69 #include "extensions/common/permissions/permission_message_provider.h"
70 #include "extensions/common/permissions/permissions_data.h"
72 #if defined(OS_CHROMEOS)
73 #include "chrome/browser/chromeos/extensions/install_limiter.h"
74 #include "webkit/browser/fileapi/file_system_backend.h"
75 #include "webkit/browser/fileapi/file_system_context.h"
76 #endif
78 using content::BrowserContext;
79 using content::BrowserThread;
80 using content::DevToolsAgentHost;
81 using extensions::CrxInstaller;
82 using extensions::Extension;
83 using extensions::ExtensionIdSet;
84 using extensions::ExtensionInfo;
85 using extensions::ExtensionRegistry;
86 using extensions::ExtensionSet;
87 using extensions::FeatureSwitch;
88 using extensions::InstallVerifier;
89 using extensions::ManagementPolicy;
90 using extensions::Manifest;
91 using extensions::PermissionMessage;
92 using extensions::PermissionMessages;
93 using extensions::PermissionSet;
94 using extensions::SharedModuleInfo;
95 using extensions::SharedModuleService;
96 using extensions::UnloadedExtensionInfo;
98 namespace errors = extensions::manifest_errors;
100 namespace {
102 // Histogram values for logging events related to externally installed
103 // extensions.
104 enum ExternalExtensionEvent {
105 EXTERNAL_EXTENSION_INSTALLED = 0,
106 EXTERNAL_EXTENSION_IGNORED,
107 EXTERNAL_EXTENSION_REENABLED,
108 EXTERNAL_EXTENSION_UNINSTALLED,
109 EXTERNAL_EXTENSION_BUCKET_BOUNDARY,
112 // Prompt the user this many times before considering an extension acknowledged.
113 static const int kMaxExtensionAcknowledgePromptCount = 3;
115 // Wait this many seconds after an extensions becomes idle before updating it.
116 static const int kUpdateIdleDelay = 5;
118 static bool IsCWSSharedModule(const Extension* extension) {
119 return extension->from_webstore() &&
120 SharedModuleInfo::IsSharedModule(extension);
123 class SharedModuleProvider : public extensions::ManagementPolicy::Provider {
124 public:
125 SharedModuleProvider() {}
126 virtual ~SharedModuleProvider() {}
128 virtual std::string GetDebugPolicyProviderName() const OVERRIDE {
129 return "SharedModuleProvider";
132 virtual bool UserMayModifySettings(const Extension* extension,
133 base::string16* error) const OVERRIDE {
134 return !IsCWSSharedModule(extension);
137 virtual bool MustRemainEnabled(const Extension* extension,
138 base::string16* error) const OVERRIDE {
139 return IsCWSSharedModule(extension);
142 private:
143 DISALLOW_COPY_AND_ASSIGN(SharedModuleProvider);
146 } // namespace
148 // ExtensionService.
150 void ExtensionService::CheckExternalUninstall(const std::string& id) {
151 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
153 // Check if the providers know about this extension.
154 extensions::ProviderCollection::const_iterator i;
155 for (i = external_extension_providers_.begin();
156 i != external_extension_providers_.end(); ++i) {
157 DCHECK(i->get()->IsReady());
158 if (i->get()->HasExtension(id))
159 return; // Yup, known extension, don't uninstall.
162 // We get the list of external extensions to check from preferences.
163 // It is possible that an extension has preferences but is not loaded.
164 // For example, an extension that requires experimental permissions
165 // will not be loaded if the experimental command line flag is not used.
166 // In this case, do not uninstall.
167 if (!GetInstalledExtension(id)) {
168 // We can't call UninstallExtension with an unloaded/invalid
169 // extension ID.
170 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
171 << "with id: " << id;
172 return;
174 UninstallExtension(id, true, NULL);
177 void ExtensionService::SetFileTaskRunnerForTesting(
178 base::SequencedTaskRunner* task_runner) {
179 file_task_runner_ = task_runner;
182 void ExtensionService::ClearProvidersForTesting() {
183 external_extension_providers_.clear();
186 void ExtensionService::AddProviderForTesting(
187 extensions::ExternalProviderInterface* test_provider) {
188 CHECK(test_provider);
189 external_extension_providers_.push_back(
190 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
193 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
194 const std::string& id,
195 const std::string& install_parameter,
196 const GURL& update_url,
197 Manifest::Location location,
198 int creation_flags,
199 bool mark_acknowledged) {
200 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
201 CHECK(Extension::IdIsValid(id));
203 if (Manifest::IsExternalLocation(location)) {
204 // All extensions that are not user specific can be cached.
205 extensions::ExtensionCache::GetInstance()->AllowCaching(id);
208 const Extension* extension = GetExtensionById(id, true);
209 if (extension) {
210 // Already installed. Skip this install if the current location has
211 // higher priority than |location|.
212 Manifest::Location current = extension->location();
213 if (current == Manifest::GetHigherPriorityLocation(current, location))
214 return false;
215 // Otherwise, overwrite the current installation.
218 // Add |id| to the set of pending extensions. If it can not be added,
219 // then there is already a pending record from a higher-priority install
220 // source. In this case, signal that this extension will not be
221 // installed by returning false.
222 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
224 install_parameter,
225 update_url,
226 location,
227 creation_flags,
228 mark_acknowledged)) {
229 return false;
232 update_once_all_providers_are_ready_ = true;
233 return true;
236 // static
237 // This function is used to implement the command-line switch
238 // --uninstall-extension, and to uninstall an extension via sync. The LOG
239 // statements within this function are used to inform the user if the uninstall
240 // cannot be done.
241 bool ExtensionService::UninstallExtensionHelper(
242 ExtensionService* extensions_service,
243 const std::string& extension_id) {
244 // We can't call UninstallExtension with an invalid extension ID.
245 if (!extensions_service->GetInstalledExtension(extension_id)) {
246 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
247 << "id: " << extension_id;
248 return false;
251 // The following call to UninstallExtension will not allow an uninstall of a
252 // policy-controlled extension.
253 base::string16 error;
254 if (!extensions_service->UninstallExtension(extension_id, false, &error)) {
255 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
256 << ": " << error;
257 return false;
260 return true;
263 ExtensionService::ExtensionService(Profile* profile,
264 const CommandLine* command_line,
265 const base::FilePath& install_directory,
266 extensions::ExtensionPrefs* extension_prefs,
267 extensions::Blacklist* blacklist,
268 bool autoupdate_enabled,
269 bool extensions_enabled,
270 extensions::OneShotEvent* ready)
271 : extensions::Blacklist::Observer(blacklist),
272 profile_(profile),
273 system_(extensions::ExtensionSystem::Get(profile)),
274 extension_prefs_(extension_prefs),
275 blacklist_(blacklist),
276 extension_sync_service_(NULL),
277 registry_(extensions::ExtensionRegistry::Get(profile)),
278 pending_extension_manager_(profile),
279 install_directory_(install_directory),
280 extensions_enabled_(extensions_enabled),
281 show_extensions_prompts_(true),
282 install_updates_when_idle_(true),
283 ready_(ready),
284 update_once_all_providers_are_ready_(false),
285 browser_terminating_(false),
286 installs_delayed_for_gc_(false),
287 is_first_run_(false),
288 shared_module_service_(new extensions::SharedModuleService(profile_)) {
289 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
291 // Figure out if extension installation should be enabled.
292 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
293 *command_line, profile))
294 extensions_enabled_ = false;
296 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
297 content::NotificationService::AllBrowserContextsAndSources());
298 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
299 content::NotificationService::AllBrowserContextsAndSources());
300 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
301 content::NotificationService::AllBrowserContextsAndSources());
302 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
303 content::NotificationService::AllBrowserContextsAndSources());
304 registrar_.Add(this,
305 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
306 content::Source<Profile>(profile_));
307 pref_change_registrar_.Init(profile->GetPrefs());
308 base::Closure callback =
309 base::Bind(&ExtensionService::OnExtensionInstallPrefChanged,
310 base::Unretained(this));
311 pref_change_registrar_.Add(extensions::pref_names::kInstallAllowList,
312 callback);
313 pref_change_registrar_.Add(extensions::pref_names::kInstallDenyList,
314 callback);
315 pref_change_registrar_.Add(extensions::pref_names::kAllowedTypes, callback);
317 // Set up the ExtensionUpdater
318 if (autoupdate_enabled) {
319 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
320 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
321 base::StringToInt(command_line->GetSwitchValueASCII(
322 switches::kExtensionsUpdateFrequency),
323 &update_frequency);
325 updater_.reset(new extensions::ExtensionUpdater(
326 this,
327 extension_prefs,
328 profile->GetPrefs(),
329 profile,
330 update_frequency,
331 extensions::ExtensionCache::GetInstance()));
334 component_loader_.reset(
335 new extensions::ComponentLoader(this,
336 profile->GetPrefs(),
337 g_browser_process->local_state(),
338 profile));
340 if (extensions_enabled_) {
341 extensions::ExternalProviderImpl::CreateExternalProviders(
342 this, profile_, &external_extension_providers_);
345 // Set this as the ExtensionService for app sorting to ensure it causes syncs
346 // if required.
347 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
349 error_controller_.reset(
350 new extensions::ExtensionErrorController(profile_, is_first_run_));
352 #if defined(ENABLE_EXTENSIONS)
353 extension_action_storage_manager_.reset(
354 new extensions::ExtensionActionStorageManager(profile_));
355 #endif
357 shared_module_policy_provider_.reset(new SharedModuleProvider);
359 // How long is the path to the Extensions directory?
360 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
361 install_directory_.value().length(), 0, 500, 100);
364 const ExtensionSet* ExtensionService::extensions() const {
365 return &registry_->enabled_extensions();
368 const ExtensionSet* ExtensionService::delayed_installs() const {
369 return &delayed_installs_;
372 extensions::PendingExtensionManager*
373 ExtensionService::pending_extension_manager() {
374 return &pending_extension_manager_;
377 ExtensionService::~ExtensionService() {
378 // No need to unload extensions here because they are profile-scoped, and the
379 // profile is in the process of being deleted.
381 extensions::ProviderCollection::const_iterator i;
382 for (i = external_extension_providers_.begin();
383 i != external_extension_providers_.end(); ++i) {
384 extensions::ExternalProviderInterface* provider = i->get();
385 provider->ServiceShutdown();
389 void ExtensionService::Shutdown() {
390 system_->management_policy()->UnregisterProvider(
391 shared_module_policy_provider_.get());
394 const Extension* ExtensionService::GetExtensionById(
395 const std::string& id, bool include_disabled) const {
396 int include_mask = ExtensionRegistry::ENABLED;
397 if (include_disabled) {
398 // Include blacklisted extensions here because there are hundreds of
399 // callers of this function, and many might assume that this includes those
400 // that have been disabled due to blacklisting.
401 include_mask |= ExtensionRegistry::DISABLED |
402 ExtensionRegistry::BLACKLISTED;
404 return registry_->GetExtensionById(id, include_mask);
407 void ExtensionService::Init() {
408 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
410 base::Time begin_time = base::Time::Now();
412 DCHECK(!is_ready()); // Can't redo init.
413 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
415 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
416 if (cmd_line->HasSwitch(switches::kInstallFromWebstore) ||
417 cmd_line->HasSwitch(switches::kLimitedInstallFromWebstore)) {
418 // The sole purpose of this launch is to install a new extension from CWS
419 // and immediately terminate: loading already installed extensions is
420 // unnecessary and may interfere with the inline install dialog (e.g. if an
421 // extension listens to onStartup and opens a window).
422 SetReadyAndNotifyListeners();
423 } else {
424 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
425 component_loader_->LoadAll();
426 extensions::InstalledLoader(this).LoadAllExtensions();
428 ReconcileKnownDisabled();
430 // Attempt to re-enable extensions whose only disable reason is reloading.
431 std::vector<std::string> extensions_to_enable;
432 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
433 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
434 iter != disabled_extensions.end(); ++iter) {
435 const Extension* e = iter->get();
436 if (extension_prefs_->GetDisableReasons(e->id()) ==
437 Extension::DISABLE_RELOAD) {
438 extensions_to_enable.push_back(e->id());
441 for (std::vector<std::string>::iterator it = extensions_to_enable.begin();
442 it != extensions_to_enable.end(); ++it) {
443 EnableExtension(*it);
446 // Finish install (if possible) of extensions that were still delayed while
447 // the browser was shut down.
448 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
449 extension_prefs_->GetAllDelayedInstallInfo());
450 for (size_t i = 0; i < delayed_info->size(); ++i) {
451 ExtensionInfo* info = delayed_info->at(i).get();
452 scoped_refptr<const Extension> extension(NULL);
453 if (info->extension_manifest) {
454 std::string error;
455 extension = Extension::Create(
456 info->extension_path,
457 info->extension_location,
458 *info->extension_manifest,
459 extension_prefs_->GetDelayedInstallCreationFlags(
460 info->extension_id),
461 info->extension_id,
462 &error);
463 if (extension.get())
464 delayed_installs_.Insert(extension);
467 MaybeFinishDelayedInstallations();
469 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
470 extension_prefs_->GetAllDelayedInstallInfo());
471 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
472 delayed_info2->size() - delayed_info->size());
474 SetReadyAndNotifyListeners();
476 // TODO(erikkay) this should probably be deferred to a future point
477 // rather than running immediately at startup.
478 CheckForExternalUpdates();
480 system_->management_policy()->RegisterProvider(
481 shared_module_policy_provider_.get());
483 LoadGreylistFromPrefs();
486 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
487 base::Time::Now() - begin_time);
490 void ExtensionService::LoadGreylistFromPrefs() {
491 scoped_ptr<ExtensionSet> all_extensions =
492 registry_->GenerateInstalledExtensionsSet();
494 for (ExtensionSet::const_iterator it = all_extensions->begin();
495 it != all_extensions->end(); ++it) {
496 extensions::BlacklistState state =
497 extension_prefs_->GetExtensionBlacklistState((*it)->id());
498 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
499 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
500 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
501 greylist_.Insert(*it);
505 bool ExtensionService::UpdateExtension(const std::string& id,
506 const base::FilePath& extension_path,
507 bool file_ownership_passed,
508 CrxInstaller** out_crx_installer) {
509 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
510 if (browser_terminating_) {
511 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
512 // Leak the temp file at extension_path. We don't want to add to the disk
513 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
514 // the file is in the OS temp directory which should be cleaned up for us.
515 return false;
518 const extensions::PendingExtensionInfo* pending_extension_info =
519 pending_extension_manager()->GetById(id);
521 const Extension* extension = GetInstalledExtension(id);
522 if (!pending_extension_info && !extension) {
523 LOG(WARNING) << "Will not update extension " << id
524 << " because it is not installed or pending";
525 // Delete extension_path since we're not creating a CrxInstaller
526 // that would do it for us.
527 if (!GetFileTaskRunner()->PostTask(
528 FROM_HERE,
529 base::Bind(
530 &extensions::file_util::DeleteFile, extension_path, false)))
531 NOTREACHED();
533 return false;
536 // We want a silent install only for non-pending extensions and
537 // pending extensions that have install_silently set.
538 scoped_ptr<ExtensionInstallPrompt> client;
539 if (pending_extension_info && !pending_extension_info->install_silently())
540 client.reset(ExtensionInstallUI::CreateInstallPromptWithProfile(profile_));
542 scoped_refptr<CrxInstaller> installer(
543 CrxInstaller::Create(this, client.Pass()));
544 installer->set_expected_id(id);
545 int creation_flags = Extension::NO_FLAGS;
546 if (pending_extension_info) {
547 installer->set_install_source(pending_extension_info->install_source());
548 if (pending_extension_info->install_silently())
549 installer->set_allow_silent_install(true);
550 if (pending_extension_info->remote_install())
551 installer->set_grant_permissions(false);
552 creation_flags = pending_extension_info->creation_flags();
553 if (pending_extension_info->mark_acknowledged())
554 AcknowledgeExternalExtension(id);
555 } else if (extension) {
556 installer->set_install_source(extension->location());
558 // If the extension was installed from or has migrated to the webstore, or
559 // its auto-update URL is from the webstore, treat it as a webstore install.
560 // Note that we ignore some older extensions with blank auto-update URLs
561 // because we are mostly concerned with restrictions on NaCl extensions,
562 // which are newer.
563 if ((extension && extension->from_webstore()) ||
564 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
565 (!extension && extension_urls::IsWebstoreUpdateUrl(
566 pending_extension_info->update_url()))) {
567 creation_flags |= Extension::FROM_WEBSTORE;
570 // Bookmark apps being updated is kind of a contradiction, but that's because
571 // we mark the default apps as bookmark apps, and they're hosted in the web
572 // store, thus they can get updated. See http://crbug.com/101605 for more
573 // details.
574 if (extension && extension->from_bookmark())
575 creation_flags |= Extension::FROM_BOOKMARK;
577 if (extension && extension->was_installed_by_default())
578 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
580 if (extension && extension->was_installed_by_oem())
581 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
583 if (extension && extension->is_ephemeral())
584 creation_flags |= Extension::IS_EPHEMERAL;
586 installer->set_creation_flags(creation_flags);
588 installer->set_delete_source(file_ownership_passed);
589 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
590 installer->InstallCrx(extension_path);
592 if (out_crx_installer)
593 *out_crx_installer = installer.get();
595 return true;
598 void ExtensionService::ReloadExtension(const std::string extension_id) {
599 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
601 // If the extension is already reloading, don't reload again.
602 if (extension_prefs_->GetDisableReasons(extension_id) &
603 Extension::DISABLE_RELOAD) {
604 return;
607 base::FilePath path;
608 const Extension* current_extension = GetExtensionById(extension_id, false);
610 // Disable the extension if it's loaded. It might not be loaded if it crashed.
611 if (current_extension) {
612 // If the extension has an inspector open for its background page, detach
613 // the inspector and hang onto a cookie for it, so that we can reattach
614 // later.
615 // TODO(yoz): this is not incognito-safe!
616 extensions::ProcessManager* manager = system_->process_manager();
617 extensions::ExtensionHost* host =
618 manager->GetBackgroundHostForExtension(extension_id);
619 if (host && DevToolsAgentHost::HasFor(host->render_view_host())) {
620 // Look for an open inspector for the background page.
621 scoped_refptr<DevToolsAgentHost> agent_host =
622 DevToolsAgentHost::GetOrCreateFor(host->render_view_host());
623 agent_host->DisconnectRenderViewHost();
624 orphaned_dev_tools_[extension_id] = agent_host;
627 path = current_extension->path();
628 // BeingUpgraded is set back to false when the extension is added.
629 system_->runtime_data()->SetBeingUpgraded(current_extension, true);
630 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
631 reloading_extensions_.insert(extension_id);
632 } else {
633 path = unloaded_extension_paths_[extension_id];
636 if (delayed_installs_.Contains(extension_id)) {
637 FinishDelayedInstallation(extension_id);
638 return;
641 // If we're reloading a component extension, use the component extension
642 // loader's reloader.
643 if (component_loader_->Exists(extension_id)) {
644 SetBeingReloaded(extension_id, true);
645 component_loader_->Reload(extension_id);
646 SetBeingReloaded(extension_id, false);
647 return;
650 // Check the installed extensions to see if what we're reloading was already
651 // installed.
652 SetBeingReloaded(extension_id, true);
653 scoped_ptr<ExtensionInfo> installed_extension(
654 extension_prefs_->GetInstalledExtensionInfo(extension_id));
655 if (installed_extension.get() &&
656 installed_extension->extension_manifest.get()) {
657 extensions::InstalledLoader(this).Load(*installed_extension, false);
658 } else {
659 // Otherwise, the extension is unpacked (location LOAD).
660 // We should always be able to remember the extension's path. If it's not in
661 // the map, someone failed to update |unloaded_extension_paths_|.
662 CHECK(!path.empty());
663 extensions::UnpackedInstaller::Create(this)->Load(path);
665 // When reloading is done, mark this extension as done reloading.
666 SetBeingReloaded(extension_id, false);
669 bool ExtensionService::UninstallExtension(const std::string& extension_id,
670 bool external_uninstall,
671 base::string16* error) {
672 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
674 scoped_refptr<const Extension> extension(GetInstalledExtension(extension_id));
676 // Callers should not send us nonexistent extensions.
677 CHECK(extension.get());
679 // Policy change which triggers an uninstall will always set
680 // |external_uninstall| to true so this is the only way to uninstall
681 // managed extensions.
682 // Shared modules being uninstalled will also set |external_uninstall| to true
683 // so that we can guarantee users don't uninstall a shared module.
684 // (crbug.com/273300)
685 // TODO(rdevlin.cronin): This is probably not right. We should do something
686 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
687 // we don't do this.
688 if (!external_uninstall &&
689 !system_->management_policy()->UserMayModifySettings(
690 extension.get(), error)) {
691 content::NotificationService::current()->Notify(
692 chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
693 content::Source<Profile>(profile_),
694 content::Details<const Extension>(extension.get()));
695 return false;
698 syncer::SyncChange sync_change;
699 if (extension_sync_service_) {
700 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
701 extension.get(), is_ready());
704 system_->install_verifier()->Remove(extension->id());
706 if (IsUnacknowledgedExternalExtension(extension.get())) {
707 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
708 EXTERNAL_EXTENSION_UNINSTALLED,
709 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
710 if (extensions::ManifestURL::UpdatesFromGallery(extension.get())) {
711 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
712 EXTERNAL_EXTENSION_UNINSTALLED,
713 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
714 } else {
715 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
716 EXTERNAL_EXTENSION_UNINSTALLED,
717 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
720 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
721 extension->GetType(), 100);
722 RecordPermissionMessagesHistogram(extension.get(),
723 "Extensions.Permissions_Uninstall");
725 // Unload before doing more cleanup to ensure that nothing is hanging on to
726 // any of these resources.
727 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
729 // Tell the backend to start deleting installed extensions on the file thread.
730 if (!Manifest::IsUnpackedLocation(extension->location())) {
731 if (!GetFileTaskRunner()->PostTask(
732 FROM_HERE,
733 base::Bind(&extensions::file_util::UninstallExtension,
734 install_directory_,
735 extension_id)))
736 NOTREACHED();
739 // Do not remove the data of ephemeral apps. They will be garbage collected by
740 // EphemeralAppService.
741 if (!extension->is_ephemeral())
742 extensions::DataDeleter::StartDeleting(profile_, extension.get());
744 UntrackTerminatedExtension(extension_id);
746 // Notify interested parties that we've uninstalled this extension.
747 content::NotificationService::current()->Notify(
748 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
749 content::Source<Profile>(profile_),
750 content::Details<const Extension>(extension.get()));
752 if (extension_sync_service_) {
753 extension_sync_service_->ProcessSyncUninstallExtension(extension_id,
754 sync_change);
757 delayed_installs_.Remove(extension_id);
759 extension_prefs_->OnExtensionUninstalled(extension_id, extension->location(),
760 external_uninstall);
762 // Track the uninstallation.
763 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
765 return true;
768 bool ExtensionService::IsExtensionEnabled(
769 const std::string& extension_id) const {
770 if (registry_->enabled_extensions().Contains(extension_id) ||
771 registry_->terminated_extensions().Contains(extension_id)) {
772 return true;
775 if (registry_->disabled_extensions().Contains(extension_id) ||
776 registry_->blacklisted_extensions().Contains(extension_id)) {
777 return false;
780 // If the extension hasn't been loaded yet, check the prefs for it. Assume
781 // enabled unless otherwise noted.
782 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
783 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
786 void ExtensionService::EnableExtension(const std::string& extension_id) {
787 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
789 if (IsExtensionEnabled(extension_id))
790 return;
791 const Extension* extension =
792 registry_->disabled_extensions().GetByID(extension_id);
794 ManagementPolicy* policy = system_->management_policy();
795 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
796 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
797 return;
800 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
801 extension_prefs_->ClearDisableReasons(extension_id);
803 // This can happen if sync enables an extension that is not
804 // installed yet.
805 if (!extension)
806 return;
808 if (IsUnacknowledgedExternalExtension(extension)) {
809 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
810 EXTERNAL_EXTENSION_REENABLED,
811 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
812 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
813 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
814 EXTERNAL_EXTENSION_REENABLED,
815 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
816 } else {
817 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
818 EXTERNAL_EXTENSION_REENABLED,
819 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
821 AcknowledgeExternalExtension(extension->id());
824 // Move it over to the enabled list.
825 registry_->AddEnabled(make_scoped_refptr(extension));
826 registry_->RemoveDisabled(extension->id());
828 NotifyExtensionLoaded(extension);
830 // Notify listeners that the extension was enabled.
831 content::NotificationService::current()->Notify(
832 chrome::NOTIFICATION_EXTENSION_ENABLED,
833 content::Source<Profile>(profile_),
834 content::Details<const Extension>(extension));
836 if (extension_sync_service_)
837 extension_sync_service_->SyncEnableExtension(*extension);
840 void ExtensionService::DisableExtension(
841 const std::string& extension_id,
842 Extension::DisableReason disable_reason) {
843 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
845 // The extension may have been disabled already.
846 if (!IsExtensionEnabled(extension_id))
847 return;
849 const Extension* extension = GetInstalledExtension(extension_id);
850 // |extension| can be NULL if sync disables an extension that is not
851 // installed yet.
852 if (extension &&
853 disable_reason != Extension::DISABLE_RELOAD &&
854 !system_->management_policy()->UserMayModifySettings(extension, NULL)) {
855 return;
858 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
859 extension_prefs_->AddDisableReason(extension_id, disable_reason);
861 int include_mask =
862 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
863 extension = registry_->GetExtensionById(extension_id, include_mask);
864 if (!extension)
865 return;
867 // The extension is either enabled or terminated.
868 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
869 registry_->terminated_extensions().Contains(extension->id()));
871 // Move it over to the disabled list. Don't send a second unload notification
872 // for terminated extensions being disabled.
873 registry_->AddDisabled(make_scoped_refptr(extension));
874 if (registry_->enabled_extensions().Contains(extension->id())) {
875 registry_->RemoveEnabled(extension->id());
876 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
877 } else {
878 registry_->RemoveTerminated(extension->id());
881 if (extension_sync_service_)
882 extension_sync_service_->SyncDisableExtension(*extension);
885 void ExtensionService::DisableUserExtensions(
886 const std::vector<std::string>& except_ids) {
887 extensions::ManagementPolicy* management_policy =
888 system_->management_policy();
889 extensions::ExtensionList to_disable;
891 // TODO(rlp): Clean up this code. crbug.com/353266.
892 const ExtensionSet& enabled_set = registry_->enabled_extensions();
893 for (ExtensionSet::const_iterator extension = enabled_set.begin();
894 extension != enabled_set.end(); ++extension) {
895 if (management_policy->UserMayModifySettings(extension->get(), NULL) &&
896 extension->get()->location() != Manifest::EXTERNAL_COMPONENT)
897 to_disable.push_back(*extension);
899 const ExtensionSet& terminated_set = registry_->terminated_extensions();
900 for (ExtensionSet::const_iterator extension = terminated_set.begin();
901 extension != terminated_set.end(); ++extension) {
902 if (management_policy->UserMayModifySettings(extension->get(), NULL) &&
903 extension->get()->location() != Manifest::EXTERNAL_COMPONENT)
904 to_disable.push_back(*extension);
907 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
908 extension != to_disable.end(); ++extension) {
909 if ((*extension)->was_installed_by_default() &&
910 extension_urls::IsWebstoreUpdateUrl(
911 extensions::ManifestURL::GetUpdateURL(*extension)))
912 continue;
913 const std::string& id = (*extension)->id();
914 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
915 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
919 void ExtensionService::GrantPermissionsAndEnableExtension(
920 const Extension* extension) {
921 GrantPermissions(extension);
922 RecordPermissionMessagesHistogram(
923 extension, "Extensions.Permissions_ReEnable");
924 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
925 EnableExtension(extension->id());
928 void ExtensionService::GrantPermissions(const Extension* extension) {
929 CHECK(extension);
930 extensions::PermissionsUpdater perms_updater(profile());
931 perms_updater.GrantActivePermissions(extension);
934 // static
935 void ExtensionService::RecordPermissionMessagesHistogram(
936 const Extension* extension, const char* histogram) {
937 // Since this is called from multiple sources, and since the histogram macros
938 // use statics, we need to manually lookup the histogram ourselves.
939 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
940 histogram,
942 PermissionMessage::kEnumBoundary,
943 PermissionMessage::kEnumBoundary + 1,
944 base::HistogramBase::kUmaTargetedHistogramFlag);
946 PermissionMessages permissions =
947 extensions::PermissionsData::GetPermissionMessages(extension);
948 if (permissions.empty()) {
949 counter->Add(PermissionMessage::kNone);
950 } else {
951 for (PermissionMessages::iterator it = permissions.begin();
952 it != permissions.end(); ++it)
953 counter->Add(it->id());
957 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
958 // The ChromeURLRequestContexts need to be first to know that the extension
959 // was loaded, otherwise a race can arise where a renderer that is created
960 // for the extension may try to load an extension URL with an extension id
961 // that the request context doesn't yet know about. The profile is responsible
962 // for ensuring its URLRequestContexts appropriately discover the loaded
963 // extension.
964 system_->RegisterExtensionWithRequestContexts(extension);
966 // Tell renderers about the new extension, unless it's a theme (renderers
967 // don't need to know about themes).
968 if (!extension->is_theme()) {
969 for (content::RenderProcessHost::iterator i(
970 content::RenderProcessHost::AllHostsIterator());
971 !i.IsAtEnd(); i.Advance()) {
972 content::RenderProcessHost* host = i.GetCurrentValue();
973 Profile* host_profile =
974 Profile::FromBrowserContext(host->GetBrowserContext());
975 if (host_profile->GetOriginalProfile() ==
976 profile_->GetOriginalProfile()) {
977 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
978 1, ExtensionMsg_Loaded_Params(extension));
979 host->Send(
980 new ExtensionMsg_Loaded(loaded_extensions));
985 // Tell subsystems that use the EXTENSION_LOADED notification about the new
986 // extension.
988 // NOTE: It is important that this happen after notifying the renderers about
989 // the new extensions so that if we navigate to an extension URL in
990 // ExtensionRegistryObserver::OnLoaded or
991 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
992 // renderer is guaranteed to know about it.
993 registry_->TriggerOnLoaded(extension);
995 content::NotificationService::current()->Notify(
996 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
997 content::Source<Profile>(profile_),
998 content::Details<const Extension>(extension));
1000 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1001 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1002 profile_->GetExtensionSpecialStoragePolicy()->
1003 GrantRightsForExtension(extension);
1005 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1006 // work properly multi-profile. Besides which, it should be using
1007 // ExtensionRegistryObserver. See http://crbug.com/355029.
1008 UpdateActiveExtensionsInCrashReporter();
1010 // If the extension has permission to load chrome://favicon/ resources we need
1011 // to make sure that the FaviconSource is registered with the
1012 // ChromeURLDataManager.
1013 if (extensions::PermissionsData::HasHostPermission(
1014 extension, GURL(chrome::kChromeUIFaviconURL))) {
1015 FaviconSource* favicon_source = new FaviconSource(profile_,
1016 FaviconSource::FAVICON);
1017 content::URLDataSource::Add(profile_, favicon_source);
1020 #if !defined(OS_ANDROID)
1021 // Same for chrome://theme/ resources.
1022 if (extensions::PermissionsData::HasHostPermission(
1023 extension, GURL(chrome::kChromeUIThemeURL))) {
1024 ThemeSource* theme_source = new ThemeSource(profile_);
1025 content::URLDataSource::Add(profile_, theme_source);
1028 // Same for chrome://thumb/ resources.
1029 if (extensions::PermissionsData::HasHostPermission(
1030 extension, GURL(chrome::kChromeUIThumbnailURL))) {
1031 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1032 content::URLDataSource::Add(profile_, thumbnail_source);
1034 #endif
1037 void ExtensionService::NotifyExtensionUnloaded(
1038 const Extension* extension,
1039 UnloadedExtensionInfo::Reason reason) {
1040 UnloadedExtensionInfo details(extension, reason);
1042 registry_->TriggerOnUnloaded(extension, reason);
1044 content::NotificationService::current()->Notify(
1045 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1046 content::Source<Profile>(profile_),
1047 content::Details<UnloadedExtensionInfo>(&details));
1049 for (content::RenderProcessHost::iterator i(
1050 content::RenderProcessHost::AllHostsIterator());
1051 !i.IsAtEnd(); i.Advance()) {
1052 content::RenderProcessHost* host = i.GetCurrentValue();
1053 Profile* host_profile =
1054 Profile::FromBrowserContext(host->GetBrowserContext());
1055 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1056 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1059 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1061 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1062 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1063 profile_->GetExtensionSpecialStoragePolicy()->
1064 RevokeRightsForExtension(extension);
1066 #if defined(OS_CHROMEOS)
1067 // Revoke external file access for the extension from its file system context.
1068 // It is safe to access the extension's storage partition at this point. The
1069 // storage partition may get destroyed only after the extension gets unloaded.
1070 GURL site =
1071 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1072 fileapi::FileSystemContext* filesystem_context =
1073 BrowserContext::GetStoragePartitionForSite(profile_, site)->
1074 GetFileSystemContext();
1075 if (filesystem_context && filesystem_context->external_backend()) {
1076 filesystem_context->external_backend()->
1077 RevokeAccessForExtension(extension->id());
1079 #endif
1081 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1082 // work properly multi-profile. Besides which, it should be using
1083 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1084 UpdateActiveExtensionsInCrashReporter();
1087 Profile* ExtensionService::profile() {
1088 return profile_;
1091 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1092 // Implemented in the .cc file to avoid adding a profile.h dependency to
1093 // extension_service.h.
1094 return profile_;
1097 bool ExtensionService::is_ready() {
1098 return ready_->is_signaled();
1101 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1102 if (file_task_runner_.get())
1103 return file_task_runner_.get();
1105 // We should be able to interrupt any part of extension install process during
1106 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1107 // will be ignored/deleted while we will block on started tasks.
1108 std::string token("ext_install-");
1109 token.append(profile_->GetPath().AsUTF8Unsafe());
1110 file_task_runner_ = BrowserThread::GetBlockingPool()->
1111 GetSequencedTaskRunnerWithShutdownBehavior(
1112 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1113 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1114 return file_task_runner_.get();
1117 extensions::ExtensionUpdater* ExtensionService::updater() {
1118 return updater_.get();
1121 void ExtensionService::CheckManagementPolicy() {
1122 std::vector<std::string> to_unload;
1123 std::map<std::string, Extension::DisableReason> to_disable;
1125 // Loop through the extensions list, finding extensions we need to unload or
1126 // disable.
1127 const ExtensionSet& extensions = registry_->enabled_extensions();
1128 for (ExtensionSet::const_iterator iter = extensions.begin();
1129 iter != extensions.end(); ++iter) {
1130 const Extension* extension = (iter->get());
1131 if (!system_->management_policy()->UserMayLoad(extension, NULL))
1132 to_unload.push_back(extension->id());
1133 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1134 if (system_->management_policy()->MustRemainDisabled(
1135 extension, &disable_reason, NULL))
1136 to_disable[extension->id()] = disable_reason;
1139 for (size_t i = 0; i < to_unload.size(); ++i)
1140 UnloadExtension(to_unload[i], UnloadedExtensionInfo::REASON_DISABLE);
1142 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1143 to_disable.begin(); i != to_disable.end(); ++i)
1144 DisableExtension(i->first, i->second);
1147 void ExtensionService::CheckForUpdatesSoon() {
1148 // This can legitimately happen in unit tests.
1149 if (!updater_.get())
1150 return;
1152 if (AreAllExternalProvidersReady()) {
1153 updater_->CheckSoon();
1154 } else {
1155 // Sync can start updating before all the external providers are ready
1156 // during startup. Start the update as soon as those providers are ready,
1157 // but not before.
1158 update_once_all_providers_are_ready_ = true;
1162 // Some extensions will autoupdate themselves externally from Chrome. These
1163 // are typically part of some larger client application package. To support
1164 // these, the extension will register its location in the the preferences file
1165 // (and also, on Windows, in the registry) and this code will periodically
1166 // check that location for a .crx file, which it will then install locally if
1167 // a new version is available.
1168 // Errors are reported through ExtensionErrorReporter. Succcess is not
1169 // reported.
1170 void ExtensionService::CheckForExternalUpdates() {
1171 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1173 // Note that this installation is intentionally silent (since it didn't
1174 // go through the front-end). Extensions that are registered in this
1175 // way are effectively considered 'pre-bundled', and so implicitly
1176 // trusted. In general, if something has HKLM or filesystem access,
1177 // they could install an extension manually themselves anyway.
1179 // Ask each external extension provider to give us a call back for each
1180 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1181 extensions::ProviderCollection::const_iterator i;
1182 for (i = external_extension_providers_.begin();
1183 i != external_extension_providers_.end(); ++i) {
1184 extensions::ExternalProviderInterface* provider = i->get();
1185 provider->VisitRegisteredExtension();
1188 // Do any required work that we would have done after completion of all
1189 // providers.
1190 if (external_extension_providers_.empty())
1191 OnAllExternalProvidersReady();
1194 void ExtensionService::OnExternalProviderReady(
1195 const extensions::ExternalProviderInterface* provider) {
1196 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1197 CHECK(provider->IsReady());
1199 // An external provider has finished loading. We only take action
1200 // if all of them are finished. So we check them first.
1201 if (AreAllExternalProvidersReady())
1202 OnAllExternalProvidersReady();
1205 bool ExtensionService::AreAllExternalProvidersReady() const {
1206 extensions::ProviderCollection::const_iterator i;
1207 for (i = external_extension_providers_.begin();
1208 i != external_extension_providers_.end(); ++i) {
1209 if (!i->get()->IsReady())
1210 return false;
1212 return true;
1215 void ExtensionService::OnAllExternalProvidersReady() {
1216 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1217 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1218 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1220 // Install any pending extensions.
1221 if (update_once_all_providers_are_ready_ && updater()) {
1222 update_once_all_providers_are_ready_ = false;
1223 extensions::ExtensionUpdater::CheckParams params;
1224 params.callback = external_updates_finished_callback_;
1225 updater()->CheckNow(params);
1228 // Uninstall all the unclaimed extensions.
1229 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1230 extension_prefs_->GetInstalledExtensionsInfo());
1231 for (size_t i = 0; i < extensions_info->size(); ++i) {
1232 ExtensionInfo* info = extensions_info->at(i).get();
1233 if (Manifest::IsExternalLocation(info->extension_location))
1234 CheckExternalUninstall(info->extension_id);
1237 error_controller_->ShowErrorIfNeeded();
1239 UpdateExternalExtensionAlert();
1242 void ExtensionService::AcknowledgeExternalExtension(const std::string& id) {
1243 extension_prefs_->AcknowledgeExternalExtension(id);
1244 UpdateExternalExtensionAlert();
1247 bool ExtensionService::IsUnacknowledgedExternalExtension(
1248 const Extension* extension) {
1249 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1250 return false;
1252 return (Manifest::IsExternalLocation(extension->location()) &&
1253 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id()) &&
1254 !(extension_prefs_->GetDisableReasons(extension->id()) &
1255 Extension::DISABLE_SIDELOAD_WIPEOUT));
1258 void ExtensionService::ReconcileKnownDisabled() {
1259 ExtensionIdSet known_disabled_ids;
1260 if (!extension_prefs_->GetKnownDisabled(&known_disabled_ids)) {
1261 extension_prefs_->SetKnownDisabled(
1262 registry_->disabled_extensions().GetIDs());
1263 UMA_HISTOGRAM_BOOLEAN("Extensions.KnownDisabledInitialized", true);
1264 return;
1267 // Both |known_disabled_ids| and |extensions| are ordered (by definition
1268 // of std::map and std::set). Iterate forward over both sets in parallel
1269 // to find matching IDs and disable the corresponding extensions.
1270 const ExtensionSet& enabled_set = registry_->enabled_extensions();
1271 ExtensionSet::const_iterator extensions_it = enabled_set.begin();
1272 ExtensionIdSet::const_iterator known_disabled_ids_it =
1273 known_disabled_ids.begin();
1274 int known_disabled_count = 0;
1275 while (extensions_it != enabled_set.end() &&
1276 known_disabled_ids_it != known_disabled_ids.end()) {
1277 const std::string& extension_id = extensions_it->get()->id();
1278 const int comparison = extension_id.compare(*known_disabled_ids_it);
1279 if (comparison < 0) {
1280 ++extensions_it;
1281 } else if (comparison > 0) {
1282 ++known_disabled_ids_it;
1283 } else {
1284 ++known_disabled_count;
1285 // Advance |extensions_it| immediately as it will be invalidated upon
1286 // disabling the extension it points to.
1287 ++extensions_it;
1288 ++known_disabled_ids_it;
1289 DisableExtension(extension_id, Extension::DISABLE_KNOWN_DISABLED);
1292 UMA_HISTOGRAM_COUNTS_100("Extensions.KnownDisabledReDisabled",
1293 known_disabled_count);
1295 // Update the list of known disabled to reflect every change to
1296 // |disabled_extensions_| from this point forward.
1297 registry_->SetDisabledModificationCallback(
1298 base::Bind(&extensions::ExtensionPrefs::SetKnownDisabled,
1299 base::Unretained(extension_prefs_)));
1302 void ExtensionService::UpdateExternalExtensionAlert() {
1303 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1304 return;
1306 const Extension* extension = NULL;
1307 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
1308 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
1309 iter != disabled_extensions.end(); ++iter) {
1310 const Extension* e = iter->get();
1311 if (IsUnacknowledgedExternalExtension(e)) {
1312 extension = e;
1313 break;
1317 if (extension) {
1318 if (!extensions::HasExternalInstallError(this)) {
1319 if (extension_prefs_->IncrementAcknowledgePromptCount(extension->id()) >
1320 kMaxExtensionAcknowledgePromptCount) {
1321 // Stop prompting for this extension, and check if there's another
1322 // one that needs prompting.
1323 extension_prefs_->AcknowledgeExternalExtension(extension->id());
1324 UpdateExternalExtensionAlert();
1325 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
1326 EXTERNAL_EXTENSION_IGNORED,
1327 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1328 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
1329 UMA_HISTOGRAM_ENUMERATION(
1330 "Extensions.ExternalExtensionEventWebstore",
1331 EXTERNAL_EXTENSION_IGNORED,
1332 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1333 } else {
1334 UMA_HISTOGRAM_ENUMERATION(
1335 "Extensions.ExternalExtensionEventNonWebstore",
1336 EXTERNAL_EXTENSION_IGNORED,
1337 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1339 return;
1341 if (is_first_run_)
1342 extension_prefs_->SetExternalInstallFirstRun(extension->id());
1343 // first_run is true if the extension was installed during a first run
1344 // (even if it's post-first run now).
1345 bool first_run = extension_prefs_->IsExternalInstallFirstRun(
1346 extension->id());
1347 extensions::AddExternalInstallError(this, extension, first_run);
1349 } else {
1350 extensions::RemoveExternalInstallError(this);
1354 void ExtensionService::UnloadExtension(
1355 const std::string& extension_id,
1356 UnloadedExtensionInfo::Reason reason) {
1357 // Make sure the extension gets deleted after we return from this function.
1358 int include_mask =
1359 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1360 scoped_refptr<const Extension> extension(
1361 registry_->GetExtensionById(extension_id, include_mask));
1363 // This method can be called via PostTask, so the extension may have been
1364 // unloaded by the time this runs.
1365 if (!extension.get()) {
1366 // In case the extension may have crashed/uninstalled. Allow the profile to
1367 // clean up its RequestContexts.
1368 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1369 return;
1372 // Keep information about the extension so that we can reload it later
1373 // even if it's not permanently installed.
1374 unloaded_extension_paths_[extension->id()] = extension->path();
1376 // Clean up if the extension is meant to be enabled after a reload.
1377 reloading_extensions_.erase(extension->id());
1379 if (registry_->disabled_extensions().Contains(extension->id())) {
1380 registry_->RemoveDisabled(extension->id());
1381 // Make sure the profile cleans up its RequestContexts when an already
1382 // disabled extension is unloaded (since they are also tracking the disabled
1383 // extensions).
1384 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1385 // Don't send the unloaded notification. It was sent when the extension
1386 // was disabled.
1387 } else {
1388 // Remove the extension from the enabled list.
1389 registry_->RemoveEnabled(extension->id());
1390 NotifyExtensionUnloaded(extension.get(), reason);
1393 content::NotificationService::current()->Notify(
1394 chrome::NOTIFICATION_EXTENSION_REMOVED,
1395 content::Source<Profile>(profile_),
1396 content::Details<const Extension>(extension.get()));
1399 void ExtensionService::RemoveComponentExtension(
1400 const std::string& extension_id) {
1401 scoped_refptr<const Extension> extension(
1402 GetExtensionById(extension_id, false));
1403 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1404 if (extension.get()) {
1405 content::NotificationService::current()->Notify(
1406 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
1407 content::Source<Profile>(profile_),
1408 content::Details<const Extension>(extension.get()));
1412 void ExtensionService::UnloadAllExtensionsForTest() {
1413 UnloadAllExtensionsInternal();
1416 void ExtensionService::ReloadExtensionsForTest() {
1417 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1418 // warning about calling test code in production.
1419 UnloadAllExtensionsInternal();
1420 component_loader_->LoadAll();
1421 extensions::InstalledLoader(this).LoadAllExtensions();
1422 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1423 // times.
1426 void ExtensionService::SetReadyAndNotifyListeners() {
1427 ready_->Signal();
1428 content::NotificationService::current()->Notify(
1429 chrome::NOTIFICATION_EXTENSIONS_READY,
1430 content::Source<Profile>(profile_),
1431 content::NotificationService::NoDetails());
1434 void ExtensionService::OnLoadedInstalledExtensions() {
1435 if (updater_)
1436 updater_->Start();
1438 OnBlacklistUpdated();
1441 void ExtensionService::AddExtension(const Extension* extension) {
1442 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1443 // default extension state to DISABLED when the --disable-extensions flag
1444 // is set (http://crbug.com/29067).
1445 if (!extensions_enabled() &&
1446 !extension->is_theme() &&
1447 extension->location() != Manifest::COMPONENT &&
1448 !Manifest::IsExternalLocation(extension->location())) {
1449 return;
1452 bool is_extension_upgrade = false;
1453 bool is_extension_installed = false;
1454 const Extension* old = GetInstalledExtension(extension->id());
1455 if (old) {
1456 is_extension_installed = true;
1457 int version_compare_result =
1458 extension->version()->CompareTo(*(old->version()));
1459 is_extension_upgrade = version_compare_result > 0;
1460 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1461 // that we aren't downgrading.
1462 if (!Manifest::IsUnpackedLocation(extension->location()))
1463 CHECK_GE(version_compare_result, 0);
1465 system_->runtime_data()->SetBeingUpgraded(extension, is_extension_upgrade);
1467 // The extension is now loaded, remove its data from unloaded extension map.
1468 unloaded_extension_paths_.erase(extension->id());
1470 // If a terminated extension is loaded, remove it from the terminated list.
1471 UntrackTerminatedExtension(extension->id());
1473 // If the extension was disabled for a reload, then enable it.
1474 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1476 // Check if the extension's privileges have changed and mark the
1477 // extension disabled if necessary.
1478 CheckPermissionsIncrease(extension, is_extension_installed);
1480 if (is_extension_installed && !reloading) {
1481 // To upgrade an extension in place, unload the old one and then load the
1482 // new one. ReloadExtension disables the extension, which is sufficient.
1483 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1486 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1487 // Only prefs is checked for the blacklist. We rely on callers to check the
1488 // blacklist before calling into here, e.g. CrxInstaller checks before
1489 // installation then threads through the install and pending install flow
1490 // of this class, and we check when loading installed extensions.
1491 registry_->AddBlacklisted(extension);
1492 } else if (!reloading &&
1493 extension_prefs_->IsExtensionDisabled(extension->id())) {
1494 registry_->AddDisabled(extension);
1495 if (extension_sync_service_)
1496 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1497 content::NotificationService::current()->Notify(
1498 chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1499 content::Source<Profile>(profile_),
1500 content::Details<const Extension>(extension));
1502 // Show the extension disabled error if a permissions increase or a remote
1503 // installation is the reason it was disabled, and no other reasons exist.
1504 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1505 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1506 Extension::DISABLE_REMOTE_INSTALL;
1507 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1508 extensions::AddExtensionDisabledError(
1509 this,
1510 extension,
1511 extension_prefs_->HasDisableReason(
1512 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1514 } else if (reloading) {
1515 // Replace the old extension with the new version.
1516 CHECK(!registry_->AddDisabled(extension));
1517 EnableExtension(extension->id());
1518 } else {
1519 // All apps that are displayed in the launcher are ordered by their ordinals
1520 // so we must ensure they have valid ordinals.
1521 if (extension->RequiresSortOrdinal()) {
1522 if (!extension->ShouldDisplayInNewTabPage()) {
1523 extension_prefs_->app_sorting()->MarkExtensionAsHidden(extension->id());
1525 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1526 extension->id(), syncer::StringOrdinal());
1529 registry_->AddEnabled(extension);
1530 if (extension_sync_service_)
1531 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1532 NotifyExtensionLoaded(extension);
1534 system_->runtime_data()->SetBeingUpgraded(extension, false);
1537 void ExtensionService::AddComponentExtension(const Extension* extension) {
1538 const std::string old_version_string(
1539 extension_prefs_->GetVersionString(extension->id()));
1540 const Version old_version(old_version_string);
1542 VLOG(1) << "AddComponentExtension " << extension->name();
1543 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1544 VLOG(1) << "Component extension " << extension->name() << " ("
1545 << extension->id() << ") installing/upgrading from '"
1546 << old_version_string << "' to " << extension->version()->GetString();
1548 AddNewOrUpdatedExtension(extension,
1549 Extension::ENABLED_COMPONENT,
1550 extensions::NOT_BLACKLISTED,
1551 syncer::StringOrdinal(),
1552 std::string());
1553 return;
1556 AddExtension(extension);
1559 void ExtensionService::UpdateActivePermissions(const Extension* extension) {
1560 // If the extension has used the optional permissions API, it will have a
1561 // custom set of active permissions defined in the extension prefs. Here,
1562 // we update the extension's active permissions based on the prefs.
1563 scoped_refptr<PermissionSet> active_permissions =
1564 extension_prefs_->GetActivePermissions(extension->id());
1566 if (active_permissions.get()) {
1567 // We restrict the active permissions to be within the bounds defined in the
1568 // extension's manifest.
1569 // a) active permissions must be a subset of optional + default permissions
1570 // b) active permissions must contains all default permissions
1571 scoped_refptr<PermissionSet> total_permissions =
1572 PermissionSet::CreateUnion(
1573 extensions::PermissionsData::GetRequiredPermissions(extension),
1574 extensions::PermissionsData::GetOptionalPermissions(extension));
1576 // Make sure the active permissions contain no more than optional + default.
1577 scoped_refptr<PermissionSet> adjusted_active =
1578 PermissionSet::CreateIntersection(
1579 total_permissions.get(), active_permissions.get());
1581 // Make sure the active permissions contain the default permissions.
1582 adjusted_active = PermissionSet::CreateUnion(
1583 extensions::PermissionsData::GetRequiredPermissions(extension),
1584 adjusted_active.get());
1586 extensions::PermissionsUpdater perms_updater(profile());
1587 perms_updater.UpdateActivePermissions(extension, adjusted_active.get());
1591 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1592 bool is_extension_installed) {
1593 UpdateActivePermissions(extension);
1595 // We keep track of all permissions the user has granted each extension.
1596 // This allows extensions to gracefully support backwards compatibility
1597 // by including unknown permissions in their manifests. When the user
1598 // installs the extension, only the recognized permissions are recorded.
1599 // When the unknown permissions become recognized (e.g., through browser
1600 // upgrade), we can prompt the user to accept these new permissions.
1601 // Extensions can also silently upgrade to less permissions, and then
1602 // silently upgrade to a version that adds these permissions back.
1604 // For example, pretend that Chrome 10 includes a permission "omnibox"
1605 // for an API that adds suggestions to the omnibox. An extension can
1606 // maintain backwards compatibility while still having "omnibox" in the
1607 // manifest. If a user installs the extension on Chrome 9, the browser
1608 // will record the permissions it recognized, not including "omnibox."
1609 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1610 // will disable the extension and prompt the user to approve the increase
1611 // in privileges. The extension could then release a new version that
1612 // removes the "omnibox" permission. When the user upgrades, Chrome will
1613 // still remember that "omnibox" had been granted, so that if the
1614 // extension once again includes "omnibox" in an upgrade, the extension
1615 // can upgrade without requiring this user's approval.
1616 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1618 bool auto_grant_permission =
1619 (!is_extension_installed && extension->was_installed_by_default()) ||
1620 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1621 // Silently grant all active permissions to default apps only on install.
1622 // After install they should behave like other apps.
1623 // Silently grant all active permissions to apps install in kiosk mode on both
1624 // install and update.
1625 if (auto_grant_permission)
1626 GrantPermissions(extension);
1628 bool is_privilege_increase = false;
1629 // We only need to compare the granted permissions to the current permissions
1630 // if the extension is not allowed to silently increase its permissions.
1631 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) &&
1632 !auto_grant_permission) {
1633 // Add all the recognized permissions if the granted permissions list
1634 // hasn't been initialized yet.
1635 scoped_refptr<PermissionSet> granted_permissions =
1636 extension_prefs_->GetGrantedPermissions(extension->id());
1637 CHECK(granted_permissions.get());
1639 // Here, we check if an extension's privileges have increased in a manner
1640 // that requires the user's approval. This could occur because the browser
1641 // upgraded and recognized additional privileges, or an extension upgrades
1642 // to a version that requires additional privileges.
1643 is_privilege_increase =
1644 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1645 granted_permissions,
1646 extension->GetActivePermissions().get(),
1647 extension->GetType());
1650 if (is_extension_installed) {
1651 // If the extension was already disabled, suppress any alerts for becoming
1652 // disabled on permissions increase.
1653 bool previously_disabled =
1654 extension_prefs_->IsExtensionDisabled(extension->id());
1655 // Legacy disabled extensions do not have a disable reason. Infer that if
1656 // there was no permission increase, it was likely disabled by the user.
1657 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1658 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1659 disable_reasons |= Extension::DISABLE_USER_ACTION;
1661 // Extensions that came to us disabled from sync need a similar inference,
1662 // except based on the new version's permissions.
1663 if (previously_disabled &&
1664 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1665 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1666 extension_prefs_->ClearDisableReasons(extension->id());
1667 if (!is_privilege_increase)
1668 disable_reasons |= Extension::DISABLE_USER_ACTION;
1670 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1673 // Extension has changed permissions significantly. Disable it. A
1674 // notification should be sent by the caller. If the extension is already
1675 // disabled because it was installed remotely, don't add another disable
1676 // reason, but instead always set the "did escalate permissions" flag, to
1677 // ensure enabling it will always show a warning.
1678 if (disable_reasons == Extension::DISABLE_REMOTE_INSTALL) {
1679 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1680 } else if (is_privilege_increase) {
1681 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1682 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1683 RecordPermissionMessagesHistogram(
1684 extension, "Extensions.Permissions_AutoDisable");
1686 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1687 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1689 if (disable_reasons != Extension::DISABLE_NONE) {
1690 extension_prefs_->AddDisableReason(
1691 extension->id(),
1692 static_cast<Extension::DisableReason>(disable_reasons));
1696 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1697 std::set<std::string> extension_ids;
1698 const ExtensionSet& extensions = registry_->enabled_extensions();
1699 for (ExtensionSet::const_iterator iter = extensions.begin();
1700 iter != extensions.end(); ++iter) {
1701 const Extension* extension = iter->get();
1702 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1703 extension_ids.insert(extension->id());
1706 // TODO(kalman): This is broken. ExtensionService is per-profile.
1707 // crash_keys::SetActiveExtensions is per-process. See
1708 // http://crbug.com/355029.
1709 crash_keys::SetActiveExtensions(extension_ids);
1712 void ExtensionService::OnExtensionInstalled(
1713 const Extension* extension,
1714 const syncer::StringOrdinal& page_ordinal,
1715 bool has_requirement_errors,
1716 extensions::BlacklistState blacklist_state,
1717 bool wait_for_idle) {
1718 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1720 const std::string& id = extension->id();
1721 bool initial_enable = ShouldEnableOnInstall(extension);
1722 std::string install_parameter;
1723 const extensions::PendingExtensionInfo* pending_extension_info = NULL;
1724 if ((pending_extension_info = pending_extension_manager()->GetById(id))) {
1725 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1726 pending_extension_manager()->Remove(id);
1728 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1729 << id << " of type " << extension->GetType()
1730 << " and update URL "
1731 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1732 << "; not installing";
1734 // Delete the extension directory since we're not going to
1735 // load it.
1736 if (!GetFileTaskRunner()->PostTask(
1737 FROM_HERE,
1738 base::Bind(&extensions::file_util::DeleteFile,
1739 extension->path(),
1740 true))) {
1741 NOTREACHED();
1743 return;
1746 install_parameter = pending_extension_info->install_parameter();
1747 pending_extension_manager()->Remove(id);
1748 } else {
1749 // We explicitly want to re-enable an uninstalled external
1750 // extension; if we're here, that means the user is manually
1751 // installing the extension.
1752 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1753 initial_enable = true;
1757 // Unsupported requirements overrides the management policy.
1758 if (has_requirement_errors) {
1759 initial_enable = false;
1760 extension_prefs_->AddDisableReason(
1761 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1762 // If the extension was disabled because of unsupported requirements but
1763 // now supports all requirements after an update and there are not other
1764 // disable reasons, enable it.
1765 } else if (extension_prefs_->GetDisableReasons(id) ==
1766 Extension::DISABLE_UNSUPPORTED_REQUIREMENT) {
1767 initial_enable = true;
1768 extension_prefs_->ClearDisableReasons(id);
1771 if (blacklist_state == extensions::BLACKLISTED_MALWARE) {
1772 // Installation of a blacklisted extension can happen from sync, policy,
1773 // etc, where to maintain consistency we need to install it, just never
1774 // load it (see AddExtension). Usually it should be the job of callers to
1775 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
1776 // showing the install dialogue).
1777 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1778 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1779 extension->location(),
1780 Manifest::NUM_LOCATIONS);
1783 if (!GetInstalledExtension(extension->id())) {
1784 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1785 extension->GetType(), 100);
1786 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1787 extension->location(), Manifest::NUM_LOCATIONS);
1788 RecordPermissionMessagesHistogram(
1789 extension, "Extensions.Permissions_Install");
1790 } else {
1791 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1792 extension->GetType(), 100);
1793 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1794 extension->location(), Manifest::NUM_LOCATIONS);
1797 // Certain extension locations are specific enough that we can
1798 // auto-acknowledge any extension that came from one of them.
1799 if (Manifest::IsPolicyLocation(extension->location()) ||
1800 extension->location() == Manifest::EXTERNAL_COMPONENT)
1801 AcknowledgeExternalExtension(extension->id());
1802 const Extension::State initial_state =
1803 initial_enable ? Extension::ENABLED : Extension::DISABLED;
1804 const bool blacklisted_for_malware =
1805 blacklist_state == extensions::BLACKLISTED_MALWARE;
1806 if (ShouldDelayExtensionUpdate(id, wait_for_idle)) {
1807 extension_prefs_->SetDelayedInstallInfo(
1808 extension,
1809 initial_state,
1810 blacklisted_for_malware,
1811 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1812 page_ordinal,
1813 install_parameter);
1815 // Transfer ownership of |extension|.
1816 delayed_installs_.Insert(extension);
1818 // Notify observers that app update is available.
1819 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1820 OnAppUpdateAvailable(extension));
1821 return;
1824 extensions::SharedModuleService::ImportStatus status =
1825 shared_module_service_->SatisfyImports(extension);
1826 if (installs_delayed_for_gc_) {
1827 extension_prefs_->SetDelayedInstallInfo(
1828 extension,
1829 initial_state,
1830 blacklisted_for_malware,
1831 extensions::ExtensionPrefs::DELAY_REASON_GC,
1832 page_ordinal,
1833 install_parameter);
1834 delayed_installs_.Insert(extension);
1835 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1836 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1837 extension_prefs_->SetDelayedInstallInfo(
1838 extension,
1839 initial_state,
1840 blacklisted_for_malware,
1841 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1842 page_ordinal,
1843 install_parameter);
1844 delayed_installs_.Insert(extension);
1846 } else {
1847 AddNewOrUpdatedExtension(extension,
1848 initial_state,
1849 blacklist_state,
1850 page_ordinal,
1851 install_parameter);
1855 void ExtensionService::AddNewOrUpdatedExtension(
1856 const Extension* extension,
1857 Extension::State initial_state,
1858 extensions::BlacklistState blacklist_state,
1859 const syncer::StringOrdinal& page_ordinal,
1860 const std::string& install_parameter) {
1861 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1862 const bool blacklisted_for_malware =
1863 blacklist_state == extensions::BLACKLISTED_MALWARE;
1864 extension_prefs_->OnExtensionInstalled(extension,
1865 initial_state,
1866 blacklisted_for_malware,
1867 page_ordinal,
1868 install_parameter);
1869 delayed_installs_.Remove(extension->id());
1870 if (InstallVerifier::NeedsVerification(*extension))
1871 system_->install_verifier()->VerifyExtension(extension->id());
1872 FinishInstallation(extension);
1875 void ExtensionService::MaybeFinishDelayedInstallation(
1876 const std::string& extension_id) {
1877 // Check if the extension already got installed.
1878 if (!delayed_installs_.Contains(extension_id))
1879 return;
1880 extensions::ExtensionPrefs::DelayReason reason =
1881 extension_prefs_->GetDelayedInstallReason(extension_id);
1883 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1884 // preferences files that will not have set this field but it was previously
1885 // only used for idle updates.
1886 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1887 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1888 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1889 return;
1891 const Extension* extension = delayed_installs_.GetByID(extension_id);
1892 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1893 extensions::SharedModuleService::ImportStatus status =
1894 shared_module_service_->SatisfyImports(extension);
1895 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1896 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1897 delayed_installs_.Remove(extension_id);
1898 // Make sure no version of the extension is actually installed, (i.e.,
1899 // that this delayed install was not an update).
1900 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1901 extension_prefs_->DeleteExtensionPrefs(extension_id);
1903 return;
1907 FinishDelayedInstallation(extension_id);
1910 void ExtensionService::FinishDelayedInstallation(
1911 const std::string& extension_id) {
1912 scoped_refptr<const Extension> extension(
1913 GetPendingExtensionUpdate(extension_id));
1914 CHECK(extension.get());
1915 delayed_installs_.Remove(extension_id);
1917 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1918 NOTREACHED();
1920 FinishInstallation(extension.get());
1923 void ExtensionService::FinishInstallation(const Extension* extension) {
1924 const extensions::Extension* existing_extension =
1925 GetInstalledExtension(extension->id());
1926 bool is_update = false;
1927 std::string old_name;
1928 if (existing_extension) {
1929 is_update = true;
1930 old_name = existing_extension->name();
1932 extensions::InstalledExtensionInfo details(extension, is_update, old_name);
1933 content::NotificationService::current()->Notify(
1934 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1935 content::Source<Profile>(profile_),
1936 content::Details<const extensions::InstalledExtensionInfo>(&details));
1938 bool unacknowledged_external = IsUnacknowledgedExternalExtension(extension);
1940 // Unpacked extensions default to allowing file access, but if that has been
1941 // overridden, don't reset the value.
1942 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1943 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1944 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1947 AddExtension(extension);
1949 // If this is a new external extension that was disabled, alert the user
1950 // so he can reenable it. We do this last so that it has already been
1951 // added to our list of extensions.
1952 if (unacknowledged_external && !is_update) {
1953 UpdateExternalExtensionAlert();
1954 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
1955 EXTERNAL_EXTENSION_INSTALLED,
1956 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1957 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
1958 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
1959 EXTERNAL_EXTENSION_INSTALLED,
1960 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1961 } else {
1962 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
1963 EXTERNAL_EXTENSION_INSTALLED,
1964 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1968 // Check extensions that may have been delayed only because this shared module
1969 // was not available.
1970 if (SharedModuleInfo::IsSharedModule(extension)) {
1971 MaybeFinishDelayedInstallations();
1975 const Extension* ExtensionService::GetPendingExtensionUpdate(
1976 const std::string& id) const {
1977 return delayed_installs_.GetByID(id);
1980 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
1981 // No need to check for duplicates; inserting a duplicate is a no-op.
1982 registry_->AddTerminated(make_scoped_refptr(extension));
1983 extensions_being_terminated_.erase(extension->id());
1984 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
1987 void ExtensionService::TerminateExtension(const std::string& extension_id) {
1988 const Extension* extension = GetInstalledExtension(extension_id);
1989 TrackTerminatedExtension(extension);
1992 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
1993 std::string lowercase_id = StringToLowerASCII(id);
1994 const Extension* extension =
1995 registry_->terminated_extensions().GetByID(lowercase_id);
1996 registry_->RemoveTerminated(lowercase_id);
1997 if (extension) {
1998 content::NotificationService::current()->Notify(
1999 chrome::NOTIFICATION_EXTENSION_REMOVED,
2000 content::Source<Profile>(profile_),
2001 content::Details<const Extension>(extension));
2005 const Extension* ExtensionService::GetInstalledExtension(
2006 const std::string& id) const {
2007 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2010 bool ExtensionService::OnExternalExtensionFileFound(
2011 const std::string& id,
2012 const Version* version,
2013 const base::FilePath& path,
2014 Manifest::Location location,
2015 int creation_flags,
2016 bool mark_acknowledged) {
2017 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2018 CHECK(Extension::IdIsValid(id));
2019 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2020 return false;
2022 // Before even bothering to unpack, check and see if we already have this
2023 // version. This is important because these extensions are going to get
2024 // installed on every startup.
2025 const Extension* existing = GetExtensionById(id, true);
2027 if (existing) {
2028 // The default apps will have the location set as INTERNAL. Since older
2029 // default apps are installed as EXTERNAL, we override them. However, if the
2030 // app is already installed as internal, then do the version check.
2031 // TODO(grv) : Remove after Q1-2013.
2032 bool is_default_apps_migration =
2033 (location == Manifest::INTERNAL &&
2034 Manifest::IsExternalLocation(existing->location()));
2036 if (!is_default_apps_migration) {
2037 DCHECK(version);
2039 switch (existing->version()->CompareTo(*version)) {
2040 case -1: // existing version is older, we should upgrade
2041 break;
2042 case 0: // existing version is same, do nothing
2043 return false;
2044 case 1: // existing version is newer, uh-oh
2045 LOG(WARNING) << "Found external version of extension " << id
2046 << "that is older than current version. Current version "
2047 << "is: " << existing->VersionString() << ". New "
2048 << "version is: " << version->GetString()
2049 << ". Keeping current version.";
2050 return false;
2055 // If the extension is already pending, don't start an install.
2056 if (!pending_extension_manager()->AddFromExternalFile(
2057 id, location, *version, creation_flags, mark_acknowledged)) {
2058 return false;
2061 // no client (silent install)
2062 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2063 installer->set_install_source(location);
2064 installer->set_expected_id(id);
2065 installer->set_expected_version(*version);
2066 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2067 installer->set_creation_flags(creation_flags);
2068 #if defined(OS_CHROMEOS)
2069 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2070 #else
2071 installer->InstallCrx(path);
2072 #endif
2074 // Depending on the source, a new external extension might not need a user
2075 // notification on installation. For such extensions, mark them acknowledged
2076 // now to suppress the notification.
2077 if (mark_acknowledged)
2078 AcknowledgeExternalExtension(id);
2080 return true;
2083 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2084 extensions::ExtensionHost* host) {
2085 OrphanedDevTools::iterator iter =
2086 orphaned_dev_tools_.find(host->extension_id());
2087 if (iter == orphaned_dev_tools_.end())
2088 return;
2090 iter->second->ConnectRenderViewHost(host->render_view_host());
2091 orphaned_dev_tools_.erase(iter);
2094 void ExtensionService::Observe(int type,
2095 const content::NotificationSource& source,
2096 const content::NotificationDetails& details) {
2097 switch (type) {
2098 case chrome::NOTIFICATION_APP_TERMINATING:
2099 // Shutdown has started. Don't start any more extension installs.
2100 // (We cannot use ExtensionService::Shutdown() for this because it
2101 // happens too late in browser teardown.)
2102 browser_terminating_ = true;
2103 break;
2104 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2105 if (profile_ !=
2106 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2107 break;
2110 extensions::ExtensionHost* host =
2111 content::Details<extensions::ExtensionHost>(details).ptr();
2113 // If the extension is already being terminated, there is nothing left to
2114 // do.
2115 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2116 break;
2118 // Mark the extension as terminated and Unload it. We want it to
2119 // be in a consistent state: either fully working or not loaded
2120 // at all, but never half-crashed. We do it in a PostTask so
2121 // that other handlers of this notification will still have
2122 // access to the Extension and ExtensionHost.
2123 base::MessageLoop::current()->PostTask(
2124 FROM_HERE,
2125 base::Bind(
2126 &ExtensionService::TrackTerminatedExtension,
2127 AsWeakPtr(),
2128 host->extension()));
2129 break;
2131 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2132 content::RenderProcessHost* process =
2133 content::Source<content::RenderProcessHost>(source).ptr();
2134 Profile* host_profile =
2135 Profile::FromBrowserContext(process->GetBrowserContext());
2136 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2137 break;
2139 extensions::ProcessMap* process_map =
2140 extensions::ProcessMap::Get(profile_);
2141 if (process_map->Contains(process->GetID())) {
2142 // An extension process was terminated, this might have resulted in an
2143 // app or extension becoming idle.
2144 std::set<std::string> extension_ids =
2145 process_map->GetExtensionsInProcess(process->GetID());
2146 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2147 it != extension_ids.end(); ++it) {
2148 if (delayed_installs_.Contains(*it)) {
2149 base::MessageLoop::current()->PostDelayedTask(
2150 FROM_HERE,
2151 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2152 AsWeakPtr(), *it),
2153 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2158 process_map->RemoveAllFromProcess(process->GetID());
2159 BrowserThread::PostTask(
2160 BrowserThread::IO,
2161 FROM_HERE,
2162 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2163 system_->info_map(),
2164 process->GetID()));
2165 break;
2167 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2168 // Notify observers that chrome update is available.
2169 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2170 OnChromeUpdateAvailable());
2171 break;
2173 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2174 OnProfileDestructionStarted();
2175 break;
2178 default:
2179 NOTREACHED() << "Unexpected notification type.";
2183 void ExtensionService::OnExtensionInstallPrefChanged() {
2184 error_controller_->ShowErrorIfNeeded();
2185 CheckManagementPolicy();
2188 bool ExtensionService::IsBeingReloaded(
2189 const std::string& extension_id) const {
2190 return ContainsKey(extensions_being_reloaded_, extension_id);
2193 void ExtensionService::SetBeingReloaded(const std::string& extension_id,
2194 bool isBeingReloaded) {
2195 if (isBeingReloaded)
2196 extensions_being_reloaded_.insert(extension_id);
2197 else
2198 extensions_being_reloaded_.erase(extension_id);
2201 bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) {
2202 // Extensions installed by policy can't be disabled. So even if a previous
2203 // installation disabled the extension, make sure it is now enabled.
2204 // TODO(rlp): Clean up the special case for external components as noted
2205 // in crbug.com/353266. For now, EXTERNAL_COMPONENT apps should be
2206 // default enabled on install as before.
2207 if (system_->management_policy()->MustRemainEnabled(extension, NULL) ||
2208 extension->location() == Manifest::EXTERNAL_COMPONENT) {
2209 return true;
2212 if (extension_prefs_->IsExtensionDisabled(extension->id()))
2213 return false;
2215 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2216 // External extensions are initially disabled. We prompt the user before
2217 // enabling them. Hosted apps are excepted because they are not dangerous
2218 // (they need to be launched by the user anyway).
2219 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2220 Manifest::IsExternalLocation(extension->location()) &&
2221 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2222 return false;
2226 return true;
2229 bool ExtensionService::ShouldDelayExtensionUpdate(
2230 const std::string& extension_id,
2231 bool wait_for_idle) const {
2232 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2234 // If delayed updates are globally disabled, or just for this extension,
2235 // don't delay.
2236 if (!install_updates_when_idle_ || !wait_for_idle)
2237 return false;
2239 const Extension* old = GetInstalledExtension(extension_id);
2240 // If there is no old extension, this is not an update, so don't delay.
2241 if (!old)
2242 return false;
2244 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2245 // Delay installation if the extension listens for the onUpdateAvailable
2246 // event.
2247 return system_->event_router()->ExtensionHasEventListener(
2248 extension_id, kOnUpdateAvailableEvent);
2249 } else {
2250 // Delay installation if the extension is not idle.
2251 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2255 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2256 DCHECK(!installs_delayed_for_gc_);
2257 installs_delayed_for_gc_ = true;
2260 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2261 DCHECK(installs_delayed_for_gc_);
2262 installs_delayed_for_gc_ = false;
2263 MaybeFinishDelayedInstallations();
2266 void ExtensionService::MaybeFinishDelayedInstallations() {
2267 std::vector<std::string> to_be_installed;
2268 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2269 it != delayed_installs_.end();
2270 ++it) {
2271 to_be_installed.push_back((*it)->id());
2273 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2274 it != to_be_installed.end();
2275 ++it) {
2276 MaybeFinishDelayedInstallation(*it);
2280 void ExtensionService::OnBlacklistUpdated() {
2281 blacklist_->GetBlacklistedIDs(
2282 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2283 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2286 void ExtensionService::ManageBlacklist(
2287 const extensions::Blacklist::BlacklistStateMap& state_map) {
2288 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2290 std::set<std::string> blocked;
2291 ExtensionIdSet greylist;
2292 ExtensionIdSet unchanged;
2293 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2294 state_map.begin();
2295 it != state_map.end();
2296 ++it) {
2297 switch (it->second) {
2298 case extensions::NOT_BLACKLISTED:
2299 break;
2301 case extensions::BLACKLISTED_MALWARE:
2302 blocked.insert(it->first);
2303 break;
2305 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2306 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2307 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2308 greylist.insert(it->first);
2309 break;
2311 case extensions::BLACKLISTED_UNKNOWN:
2312 unchanged.insert(it->first);
2313 break;
2317 UpdateBlockedExtensions(blocked, unchanged);
2318 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2320 error_controller_->ShowErrorIfNeeded();
2323 namespace {
2324 void Partition(const ExtensionIdSet& before,
2325 const ExtensionIdSet& after,
2326 const ExtensionIdSet& unchanged,
2327 ExtensionIdSet* no_longer,
2328 ExtensionIdSet* not_yet) {
2329 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2330 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2331 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2333 } // namespace
2335 void ExtensionService::UpdateBlockedExtensions(
2336 const ExtensionIdSet& blocked,
2337 const ExtensionIdSet& unchanged) {
2338 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2339 Partition(registry_->blacklisted_extensions().GetIDs(),
2340 blocked, unchanged,
2341 &no_longer_blocked, &not_yet_blocked);
2343 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2344 it != no_longer_blocked.end(); ++it) {
2345 scoped_refptr<const Extension> extension =
2346 registry_->blacklisted_extensions().GetByID(*it);
2347 if (!extension.get()) {
2348 NOTREACHED() << "Extension " << *it << " no longer blocked, "
2349 << "but it was never blocked.";
2350 continue;
2352 registry_->RemoveBlacklisted(*it);
2353 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2354 AddExtension(extension.get());
2355 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2356 extension->location(),
2357 Manifest::NUM_LOCATIONS);
2360 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2361 it != not_yet_blocked.end(); ++it) {
2362 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2363 if (!extension.get()) {
2364 NOTREACHED() << "Extension " << *it << " needs to be "
2365 << "blacklisted, but it's not installed.";
2366 continue;
2368 registry_->AddBlacklisted(extension);
2369 extension_prefs_->SetExtensionBlacklistState(
2370 extension->id(), extensions::BLACKLISTED_MALWARE);
2371 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2372 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2373 extension->location(), Manifest::NUM_LOCATIONS);
2377 // TODO(oleg): UMA logging
2378 void ExtensionService::UpdateGreylistedExtensions(
2379 const ExtensionIdSet& greylist,
2380 const ExtensionIdSet& unchanged,
2381 const extensions::Blacklist::BlacklistStateMap& state_map) {
2382 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2383 Partition(greylist_.GetIDs(),
2384 greylist, unchanged,
2385 &no_longer_greylisted, &not_yet_greylisted);
2387 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2388 it != no_longer_greylisted.end(); ++it) {
2389 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2390 if (!extension.get()) {
2391 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2392 << "but it was not marked as greylisted.";
2393 continue;
2396 greylist_.Remove(*it);
2397 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2398 extensions::NOT_BLACKLISTED);
2399 if (extension_prefs_->GetDisableReasons(extension->id()) &
2400 extensions::Extension::DISABLE_GREYLIST)
2401 EnableExtension(*it);
2404 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2405 it != not_yet_greylisted.end(); ++it) {
2406 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2407 if (!extension.get()) {
2408 NOTREACHED() << "Extension " << *it << " needs to be "
2409 << "disabled, but it's not installed.";
2410 continue;
2412 greylist_.Insert(extension);
2413 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2414 state_map.find(*it)->second);
2415 if (registry_->enabled_extensions().Contains(extension->id()))
2416 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2420 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2421 update_observers_.AddObserver(observer);
2424 void ExtensionService::RemoveUpdateObserver(
2425 extensions::UpdateObserver* observer) {
2426 update_observers_.RemoveObserver(observer);
2429 // Used only by test code.
2430 void ExtensionService::UnloadAllExtensionsInternal() {
2431 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2433 registry_->ClearAll();
2434 system_->runtime_data()->ClearAll();
2436 // TODO(erikkay) should there be a notification for this? We can't use
2437 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2438 // or uninstalled.
2441 void ExtensionService::OnProfileDestructionStarted() {
2442 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2443 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2444 it != ids_to_unload.end();
2445 ++it) {
2446 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);