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"
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/callback.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/threading/sequenced_worker_pool.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/time/time.h"
27 #include "base/version.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/chrome_notification_types.h"
30 #include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
31 #include "chrome/browser/extensions/component_loader.h"
32 #include "chrome/browser/extensions/crx_installer.h"
33 #include "chrome/browser/extensions/data_deleter.h"
34 #include "chrome/browser/extensions/extension_disabled_ui.h"
35 #include "chrome/browser/extensions/extension_error_reporter.h"
36 #include "chrome/browser/extensions/extension_error_ui.h"
37 #include "chrome/browser/extensions/extension_install_ui.h"
38 #include "chrome/browser/extensions/extension_special_storage_policy.h"
39 #include "chrome/browser/extensions/extension_sync_service.h"
40 #include "chrome/browser/extensions/extension_util.h"
41 #include "chrome/browser/extensions/external_install_ui.h"
42 #include "chrome/browser/extensions/external_provider_impl.h"
43 #include "chrome/browser/extensions/install_verifier.h"
44 #include "chrome/browser/extensions/installed_loader.h"
45 #include "chrome/browser/extensions/pending_extension_manager.h"
46 #include "chrome/browser/extensions/permissions_updater.h"
47 #include "chrome/browser/extensions/unpacked_installer.h"
48 #include "chrome/browser/extensions/updater/extension_cache.h"
49 #include "chrome/browser/extensions/updater/extension_updater.h"
50 #include "chrome/browser/profiles/profile.h"
51 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
52 #include "chrome/browser/ui/webui/favicon_source.h"
53 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
54 #include "chrome/browser/ui/webui/theme_source.h"
55 #include "chrome/common/chrome_switches.h"
56 #include "chrome/common/crash_keys.h"
57 #include "chrome/common/extensions/extension_constants.h"
58 #include "chrome/common/extensions/extension_file_util.h"
59 #include "chrome/common/extensions/features/feature_channel.h"
60 #include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
61 #include "chrome/common/extensions/manifest_url_handler.h"
62 #include "chrome/common/pref_names.h"
63 #include "chrome/common/url_constants.h"
64 #include "components/startup_metric_utils/startup_metric_utils.h"
65 #include "content/public/browser/browser_thread.h"
66 #include "content/public/browser/devtools_agent_host.h"
67 #include "content/public/browser/notification_service.h"
68 #include "content/public/browser/notification_types.h"
69 #include "content/public/browser/render_process_host.h"
70 #include "content/public/browser/storage_partition.h"
71 #include "content/public/browser/url_data_source.h"
72 #include "extensions/browser/app_sorting.h"
73 #include "extensions/browser/event_router.h"
74 #include "extensions/browser/extension_host.h"
75 #include "extensions/browser/extension_registry.h"
76 #include "extensions/browser/extension_system.h"
77 #include "extensions/browser/extensions_browser_client.h"
78 #include "extensions/browser/external_provider_interface.h"
79 #include "extensions/browser/management_policy.h"
80 #include "extensions/browser/pref_names.h"
81 #include "extensions/browser/process_manager.h"
82 #include "extensions/browser/process_map.h"
83 #include "extensions/browser/runtime_data.h"
84 #include "extensions/browser/update_observer.h"
85 #include "extensions/common/constants.h"
86 #include "extensions/common/error_utils.h"
87 #include "extensions/common/extension.h"
88 #include "extensions/common/extension_messages.h"
89 #include "extensions/common/extensions_client.h"
90 #include "extensions/common/feature_switch.h"
91 #include "extensions/common/manifest.h"
92 #include "extensions/common/manifest_constants.h"
93 #include "extensions/common/manifest_handlers/background_info.h"
94 #include "extensions/common/manifest_handlers/incognito_info.h"
95 #include "extensions/common/manifest_handlers/shared_module_info.h"
96 #include "extensions/common/permissions/permission_message_provider.h"
97 #include "extensions/common/permissions/permissions_data.h"
98 #include "grit/generated_resources.h"
99 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
100 #include "ui/base/webui/web_ui_util.h"
101 #include "url/gurl.h"
102 #include "webkit/browser/database/database_tracker.h"
103 #include "webkit/browser/database/database_util.h"
105 #if defined(OS_CHROMEOS)
106 #include "chrome/browser/chromeos/extensions/install_limiter.h"
107 #include "webkit/browser/fileapi/file_system_backend.h"
108 #include "webkit/browser/fileapi/file_system_context.h"
111 using content::BrowserContext;
112 using content::BrowserThread;
113 using content::DevToolsAgentHost;
114 using extensions::CrxInstaller;
115 using extensions::Extension;
116 using extensions::ExtensionIdSet;
117 using extensions::ExtensionInfo;
118 using extensions::ExtensionRegistry;
119 using extensions::ExtensionSet;
120 using extensions::FeatureSwitch;
121 using extensions::InstallVerifier;
122 using extensions::ManagementPolicy;
123 using extensions::Manifest;
124 using extensions::PermissionMessage;
125 using extensions::PermissionMessages;
126 using extensions::PermissionSet;
127 using extensions::SharedModuleInfo;
128 using extensions::UnloadedExtensionInfo;
130 namespace errors = extensions::manifest_errors;
134 // Histogram values for logging events related to externally installed
136 enum ExternalExtensionEvent {
137 EXTERNAL_EXTENSION_INSTALLED = 0,
138 EXTERNAL_EXTENSION_IGNORED,
139 EXTERNAL_EXTENSION_REENABLED,
140 EXTERNAL_EXTENSION_UNINSTALLED,
141 EXTERNAL_EXTENSION_BUCKET_BOUNDARY,
144 // Prompt the user this many times before considering an extension acknowledged.
145 static const int kMaxExtensionAcknowledgePromptCount = 3;
147 // Wait this many seconds after an extensions becomes idle before updating it.
148 static const int kUpdateIdleDelay = 5;
150 // Wait this many seconds before trying to garbage collect extensions again.
151 static const int kGarbageCollectRetryDelay = 30;
153 // Wait this many seconds after startup to see if there are any extensions
154 // which can be garbage collected.
155 static const int kGarbageCollectStartupDelay = 30;
157 static bool IsSharedModule(const Extension* extension) {
158 return SharedModuleInfo::IsSharedModule(extension);
161 static bool IsCWSSharedModule(const Extension* extension) {
162 return extension->from_webstore() && IsSharedModule(extension);
165 class SharedModuleProvider : public extensions::ManagementPolicy::Provider {
167 SharedModuleProvider() {}
168 virtual ~SharedModuleProvider() {}
170 virtual std::string GetDebugPolicyProviderName() const OVERRIDE {
171 return "SharedModuleProvider";
174 virtual bool UserMayModifySettings(const Extension* extension,
175 base::string16* error) const OVERRIDE {
176 return !IsCWSSharedModule(extension);
179 virtual bool MustRemainEnabled(const Extension* extension,
180 base::string16* error) const OVERRIDE {
181 return IsCWSSharedModule(extension);
185 DISALLOW_COPY_AND_ASSIGN(SharedModuleProvider);
192 void ExtensionService::CheckExternalUninstall(const std::string& id) {
193 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
195 // Check if the providers know about this extension.
196 extensions::ProviderCollection::const_iterator i;
197 for (i = external_extension_providers_.begin();
198 i != external_extension_providers_.end(); ++i) {
199 DCHECK(i->get()->IsReady());
200 if (i->get()->HasExtension(id))
201 return; // Yup, known extension, don't uninstall.
204 // We get the list of external extensions to check from preferences.
205 // It is possible that an extension has preferences but is not loaded.
206 // For example, an extension that requires experimental permissions
207 // will not be loaded if the experimental command line flag is not used.
208 // In this case, do not uninstall.
209 if (!GetInstalledExtension(id)) {
210 // We can't call UninstallExtension with an unloaded/invalid
212 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
213 << "with id: " << id;
216 UninstallExtension(id, true, NULL);
219 void ExtensionService::SetFileTaskRunnerForTesting(
220 base::SequencedTaskRunner* task_runner) {
221 file_task_runner_ = task_runner;
224 void ExtensionService::ClearProvidersForTesting() {
225 external_extension_providers_.clear();
228 void ExtensionService::AddProviderForTesting(
229 extensions::ExternalProviderInterface* test_provider) {
230 CHECK(test_provider);
231 external_extension_providers_.push_back(
232 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
235 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
236 const std::string& id,
237 const std::string& install_parameter,
238 const GURL& update_url,
239 Manifest::Location location,
241 bool mark_acknowledged) {
242 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
243 CHECK(Extension::IdIsValid(id));
245 if (Manifest::IsExternalLocation(location)) {
246 // All extensions that are not user specific can be cached.
247 extensions::ExtensionCache::GetInstance()->AllowCaching(id);
250 const Extension* extension = GetExtensionById(id, true);
252 // Already installed. Skip this install if the current location has
253 // higher priority than |location|.
254 Manifest::Location current = extension->location();
255 if (current == Manifest::GetHigherPriorityLocation(current, location))
257 // Otherwise, overwrite the current installation.
260 // Add |id| to the set of pending extensions. If it can not be added,
261 // then there is already a pending record from a higher-priority install
262 // source. In this case, signal that this extension will not be
263 // installed by returning false.
264 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
270 mark_acknowledged)) {
274 update_once_all_providers_are_ready_ = true;
278 const Extension* ExtensionService::GetInstalledExtensionByUrl(
279 const GURL& url) const {
280 return registry_->enabled_extensions().GetExtensionOrAppByURL(url);
283 const Extension* ExtensionService::GetInstalledApp(const GURL& url) const {
284 const Extension* extension = GetInstalledExtensionByUrl(url);
285 return (extension && extension->is_app()) ? extension : NULL;
288 bool ExtensionService::IsInstalledApp(const GURL& url) const {
289 return !!GetInstalledApp(url);
293 // This function is used to implement the command-line switch
294 // --uninstall-extension, and to uninstall an extension via sync. The LOG
295 // statements within this function are used to inform the user if the uninstall
297 bool ExtensionService::UninstallExtensionHelper(
298 ExtensionService* extensions_service,
299 const std::string& extension_id) {
300 // We can't call UninstallExtension with an invalid extension ID.
301 if (!extensions_service->GetInstalledExtension(extension_id)) {
302 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
303 << "id: " << extension_id;
307 // The following call to UninstallExtension will not allow an uninstall of a
308 // policy-controlled extension.
309 base::string16 error;
310 if (!extensions_service->UninstallExtension(extension_id, false, &error)) {
311 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
319 ExtensionService::ExtensionService(Profile* profile,
320 const CommandLine* command_line,
321 const base::FilePath& install_directory,
322 extensions::ExtensionPrefs* extension_prefs,
323 extensions::Blacklist* blacklist,
324 bool autoupdate_enabled,
325 bool extensions_enabled,
326 extensions::OneShotEvent* ready)
327 : extensions::Blacklist::Observer(blacklist),
329 system_(extensions::ExtensionSystem::Get(profile)),
330 extension_prefs_(extension_prefs),
331 blacklist_(blacklist),
332 extension_sync_service_(NULL),
333 registry_(extensions::ExtensionRegistry::Get(profile)),
334 pending_extension_manager_(*this, profile),
335 install_directory_(install_directory),
336 extensions_enabled_(extensions_enabled),
337 show_extensions_prompts_(true),
338 install_updates_when_idle_(true),
340 update_once_all_providers_are_ready_(false),
341 browser_terminating_(false),
342 installs_delayed_for_gc_(false),
343 is_first_run_(false) {
344 #if defined(OS_CHROMEOS)
345 disable_garbage_collection_ = false;
347 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
349 // Figure out if extension installation should be enabled.
350 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
351 *command_line, profile))
352 extensions_enabled_ = false;
354 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
355 content::NotificationService::AllBrowserContextsAndSources());
356 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
357 content::NotificationService::AllBrowserContextsAndSources());
358 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
359 content::NotificationService::AllBrowserContextsAndSources());
360 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
361 content::NotificationService::AllBrowserContextsAndSources());
362 pref_change_registrar_.Init(profile->GetPrefs());
363 base::Closure callback =
364 base::Bind(&ExtensionService::OnExtensionInstallPrefChanged,
365 base::Unretained(this));
366 pref_change_registrar_.Add(extensions::pref_names::kInstallAllowList,
368 pref_change_registrar_.Add(extensions::pref_names::kInstallDenyList,
370 pref_change_registrar_.Add(extensions::pref_names::kAllowedTypes, callback);
372 // Set up the ExtensionUpdater
373 if (autoupdate_enabled) {
374 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
375 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
376 base::StringToInt(command_line->GetSwitchValueASCII(
377 switches::kExtensionsUpdateFrequency),
380 updater_.reset(new extensions::ExtensionUpdater(
386 extensions::ExtensionCache::GetInstance()));
389 component_loader_.reset(
390 new extensions::ComponentLoader(this,
392 g_browser_process->local_state(),
395 if (extensions_enabled_) {
396 extensions::ExternalProviderImpl::CreateExternalProviders(
397 this, profile_, &external_extension_providers_);
400 // Set this as the ExtensionService for app sorting to ensure it causes syncs
402 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
404 #if defined(ENABLE_EXTENSIONS)
405 extension_action_storage_manager_.reset(
406 new extensions::ExtensionActionStorageManager(profile_));
409 shared_module_policy_provider_.reset(new SharedModuleProvider);
411 // How long is the path to the Extensions directory?
412 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
413 install_directory_.value().length(), 0, 500, 100);
416 const ExtensionSet* ExtensionService::extensions() const {
417 return ®istry_->enabled_extensions();
420 const ExtensionSet* ExtensionService::delayed_installs() const {
421 return &delayed_installs_;
424 extensions::PendingExtensionManager*
425 ExtensionService::pending_extension_manager() {
426 return &pending_extension_manager_;
429 ExtensionService::~ExtensionService() {
430 // No need to unload extensions here because they are profile-scoped, and the
431 // profile is in the process of being deleted.
433 extensions::ProviderCollection::const_iterator i;
434 for (i = external_extension_providers_.begin();
435 i != external_extension_providers_.end(); ++i) {
436 extensions::ExternalProviderInterface* provider = i->get();
437 provider->ServiceShutdown();
441 void ExtensionService::Shutdown() {
442 system_->management_policy()->UnregisterProvider(
443 shared_module_policy_provider_.get());
446 const Extension* ExtensionService::GetExtensionById(
447 const std::string& id, bool include_disabled) const {
448 int include_mask = ExtensionRegistry::ENABLED;
449 if (include_disabled) {
450 // Include blacklisted extensions here because there are hundreds of
451 // callers of this function, and many might assume that this includes those
452 // that have been disabled due to blacklisting.
453 include_mask |= ExtensionRegistry::DISABLED |
454 ExtensionRegistry::BLACKLISTED;
456 return registry_->GetExtensionById(id, include_mask);
459 void ExtensionService::Init() {
460 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
462 base::Time begin_time = base::Time::Now();
464 DCHECK(!is_ready()); // Can't redo init.
465 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
467 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
468 if (cmd_line->HasSwitch(switches::kInstallFromWebstore) ||
469 cmd_line->HasSwitch(switches::kLimitedInstallFromWebstore)) {
470 // The sole purpose of this launch is to install a new extension from CWS
471 // and immediately terminate: loading already installed extensions is
472 // unnecessary and may interfere with the inline install dialog (e.g. if an
473 // extension listens to onStartup and opens a window).
474 SetReadyAndNotifyListeners();
476 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
477 component_loader_->LoadAll();
478 extensions::InstalledLoader(this).LoadAllExtensions();
480 ReconcileKnownDisabled();
482 // Attempt to re-enable extensions whose only disable reason is reloading.
483 std::vector<std::string> extensions_to_enable;
484 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
485 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
486 iter != disabled_extensions.end(); ++iter) {
487 const Extension* e = iter->get();
488 if (extension_prefs_->GetDisableReasons(e->id()) ==
489 Extension::DISABLE_RELOAD) {
490 extensions_to_enable.push_back(e->id());
493 for (std::vector<std::string>::iterator it = extensions_to_enable.begin();
494 it != extensions_to_enable.end(); ++it) {
495 EnableExtension(*it);
498 // Finish install (if possible) of extensions that were still delayed while
499 // the browser was shut down.
500 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
501 extension_prefs_->GetAllDelayedInstallInfo());
502 for (size_t i = 0; i < delayed_info->size(); ++i) {
503 ExtensionInfo* info = delayed_info->at(i).get();
504 scoped_refptr<const Extension> extension(NULL);
505 if (info->extension_manifest) {
507 extension = Extension::Create(
508 info->extension_path,
509 info->extension_location,
510 *info->extension_manifest,
511 extension_prefs_->GetDelayedInstallCreationFlags(
516 delayed_installs_.Insert(extension);
519 MaybeFinishDelayedInstallations();
521 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
522 extension_prefs_->GetAllDelayedInstallInfo());
523 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
524 delayed_info2->size() - delayed_info->size());
526 SetReadyAndNotifyListeners();
528 // TODO(erikkay) this should probably be deferred to a future point
529 // rather than running immediately at startup.
530 CheckForExternalUpdates();
533 base::MessageLoop::current()->PostDelayedTask(
535 base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
536 base::TimeDelta::FromSeconds(kGarbageCollectStartupDelay));
538 if (extension_prefs_->NeedsStorageGarbageCollection()) {
539 GarbageCollectIsolatedStorage();
540 extension_prefs_->SetNeedsStorageGarbageCollection(false);
542 system_->management_policy()->RegisterProvider(
543 shared_module_policy_provider_.get());
545 LoadGreylistFromPrefs();
548 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
549 base::Time::Now() - begin_time);
552 void ExtensionService::LoadGreylistFromPrefs() {
553 scoped_ptr<ExtensionSet> all_extensions =
554 registry_->GenerateInstalledExtensionsSet();
556 for (ExtensionSet::const_iterator it = all_extensions->begin();
557 it != all_extensions->end(); ++it) {
558 extensions::BlacklistState state =
559 extension_prefs_->GetExtensionBlacklistState((*it)->id());
560 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
561 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
562 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
563 greylist_.Insert(*it);
567 bool ExtensionService::UpdateExtension(const std::string& id,
568 const base::FilePath& extension_path,
569 bool file_ownership_passed,
570 const GURL& download_url,
571 CrxInstaller** out_crx_installer) {
572 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
573 if (browser_terminating_) {
574 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
575 // Leak the temp file at extension_path. We don't want to add to the disk
576 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
577 // the file is in the OS temp directory which should be cleaned up for us.
581 const extensions::PendingExtensionInfo* pending_extension_info =
582 pending_extension_manager()->GetById(id);
584 const Extension* extension = GetInstalledExtension(id);
585 if (!pending_extension_info && !extension) {
586 LOG(WARNING) << "Will not update extension " << id
587 << " because it is not installed or pending";
588 // Delete extension_path since we're not creating a CrxInstaller
589 // that would do it for us.
590 if (!GetFileTaskRunner()->PostTask(
593 &extension_file_util::DeleteFile, extension_path, false)))
599 // We want a silent install only for non-pending extensions and
600 // pending extensions that have install_silently set.
601 scoped_ptr<ExtensionInstallPrompt> client;
602 if (pending_extension_info && !pending_extension_info->install_silently())
603 client.reset(ExtensionInstallUI::CreateInstallPromptWithProfile(profile_));
605 scoped_refptr<CrxInstaller> installer(
606 CrxInstaller::Create(this, client.Pass()));
607 installer->set_expected_id(id);
608 int creation_flags = Extension::NO_FLAGS;
609 if (pending_extension_info) {
610 installer->set_install_source(pending_extension_info->install_source());
611 if (pending_extension_info->install_silently())
612 installer->set_allow_silent_install(true);
613 creation_flags = pending_extension_info->creation_flags();
614 if (pending_extension_info->mark_acknowledged())
615 AcknowledgeExternalExtension(id);
616 } else if (extension) {
617 installer->set_install_source(extension->location());
619 // If the extension was installed from or has migrated to the webstore, or
620 // its auto-update URL is from the webstore, treat it as a webstore install.
621 // Note that we ignore some older extensions with blank auto-update URLs
622 // because we are mostly concerned with restrictions on NaCl extensions,
624 if ((extension && extension->from_webstore()) ||
625 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
626 (!extension && extension_urls::IsWebstoreUpdateUrl(
627 pending_extension_info->update_url()))) {
628 creation_flags |= Extension::FROM_WEBSTORE;
631 // Bookmark apps being updated is kind of a contradiction, but that's because
632 // we mark the default apps as bookmark apps, and they're hosted in the web
633 // store, thus they can get updated. See http://crbug.com/101605 for more
635 if (extension && extension->from_bookmark())
636 creation_flags |= Extension::FROM_BOOKMARK;
638 if (extension && extension->was_installed_by_default())
639 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
641 if (extension && extension->was_installed_by_oem())
642 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
644 if (extension && extension->is_ephemeral())
645 creation_flags |= Extension::IS_EPHEMERAL;
647 installer->set_creation_flags(creation_flags);
649 installer->set_delete_source(file_ownership_passed);
650 installer->set_download_url(download_url);
651 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
652 installer->InstallCrx(extension_path);
654 if (out_crx_installer)
655 *out_crx_installer = installer.get();
660 void ExtensionService::ReloadExtension(const std::string extension_id) {
661 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
663 // If the extension is already reloading, don't reload again.
664 if (extension_prefs_->GetDisableReasons(extension_id) &
665 Extension::DISABLE_RELOAD) {
670 const Extension* current_extension = GetExtensionById(extension_id, false);
672 // Disable the extension if it's loaded. It might not be loaded if it crashed.
673 if (current_extension) {
674 // If the extension has an inspector open for its background page, detach
675 // the inspector and hang onto a cookie for it, so that we can reattach
677 // TODO(yoz): this is not incognito-safe!
678 extensions::ProcessManager* manager = system_->process_manager();
679 extensions::ExtensionHost* host =
680 manager->GetBackgroundHostForExtension(extension_id);
681 if (host && DevToolsAgentHost::HasFor(host->render_view_host())) {
682 // Look for an open inspector for the background page.
683 scoped_refptr<DevToolsAgentHost> agent_host =
684 DevToolsAgentHost::GetOrCreateFor(host->render_view_host());
685 agent_host->DisconnectRenderViewHost();
686 orphaned_dev_tools_[extension_id] = agent_host;
689 path = current_extension->path();
690 // BeingUpgraded is set back to false when the extension is added.
691 system_->runtime_data()->SetBeingUpgraded(current_extension, true);
692 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
693 reloading_extensions_.insert(extension_id);
695 path = unloaded_extension_paths_[extension_id];
698 if (delayed_installs_.Contains(extension_id)) {
699 FinishDelayedInstallation(extension_id);
703 // If we're reloading a component extension, use the component extension
704 // loader's reloader.
705 if (component_loader_->Exists(extension_id)) {
706 SetBeingReloaded(extension_id, true);
707 component_loader_->Reload(extension_id);
708 SetBeingReloaded(extension_id, false);
712 // Check the installed extensions to see if what we're reloading was already
714 SetBeingReloaded(extension_id, true);
715 scoped_ptr<ExtensionInfo> installed_extension(
716 extension_prefs_->GetInstalledExtensionInfo(extension_id));
717 if (installed_extension.get() &&
718 installed_extension->extension_manifest.get()) {
719 extensions::InstalledLoader(this).Load(*installed_extension, false);
721 // Otherwise, the extension is unpacked (location LOAD).
722 // We should always be able to remember the extension's path. If it's not in
723 // the map, someone failed to update |unloaded_extension_paths_|.
724 CHECK(!path.empty());
725 extensions::UnpackedInstaller::Create(this)->Load(path);
727 // When reloading is done, mark this extension as done reloading.
728 SetBeingReloaded(extension_id, false);
731 bool ExtensionService::UninstallExtension(
732 std::string extension_id,
733 bool external_uninstall,
734 base::string16* error) {
735 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
737 scoped_refptr<const Extension> extension(GetInstalledExtension(extension_id));
739 // Callers should not send us nonexistent extensions.
740 CHECK(extension.get());
742 // Policy change which triggers an uninstall will always set
743 // |external_uninstall| to true so this is the only way to uninstall
744 // managed extensions.
745 if (!external_uninstall &&
746 !system_->management_policy()->UserMayModifySettings(
747 extension.get(), error)) {
748 content::NotificationService::current()->Notify(
749 chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
750 content::Source<Profile>(profile_),
751 content::Details<const Extension>(extension.get()));
755 syncer::SyncChange sync_change;
756 if (extension_sync_service_) {
757 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
758 extension.get(), is_ready());
761 system_->install_verifier()->Remove(extension->id());
763 if (IsUnacknowledgedExternalExtension(extension.get())) {
764 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
765 EXTERNAL_EXTENSION_UNINSTALLED,
766 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
767 if (extensions::ManifestURL::UpdatesFromGallery(extension.get())) {
768 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
769 EXTERNAL_EXTENSION_UNINSTALLED,
770 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
772 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
773 EXTERNAL_EXTENSION_UNINSTALLED,
774 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
777 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
778 extension->GetType(), 100);
779 RecordPermissionMessagesHistogram(extension.get(),
780 "Extensions.Permissions_Uninstall");
782 // Unload before doing more cleanup to ensure that nothing is hanging on to
783 // any of these resources.
784 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
786 // Tell the backend to start deleting installed extensions on the file thread.
787 if (!Manifest::IsUnpackedLocation(extension->location())) {
788 if (!GetFileTaskRunner()->PostTask(
791 &extension_file_util::UninstallExtension,
797 // Do not remove the data of ephemeral apps. They will be garbage collected by
798 // EphemeralAppService.
799 if (!extension->is_ephemeral())
800 extensions::DataDeleter::StartDeleting(profile_, extension.get());
802 UntrackTerminatedExtension(extension_id);
804 // Notify interested parties that we've uninstalled this extension.
805 content::NotificationService::current()->Notify(
806 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
807 content::Source<Profile>(profile_),
808 content::Details<const Extension>(extension.get()));
810 if (extension_sync_service_) {
811 extension_sync_service_->ProcessSyncUninstallExtension(extension_id,
815 delayed_installs_.Remove(extension_id);
817 PruneSharedModulesOnUninstall(extension.get());
819 extension_prefs_->OnExtensionUninstalled(extension_id, extension->location(),
822 // Track the uninstallation.
823 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
828 bool ExtensionService::IsExtensionEnabled(
829 const std::string& extension_id) const {
830 if (registry_->enabled_extensions().Contains(extension_id) ||
831 registry_->terminated_extensions().Contains(extension_id)) {
835 if (registry_->disabled_extensions().Contains(extension_id) ||
836 registry_->blacklisted_extensions().Contains(extension_id)) {
840 // If the extension hasn't been loaded yet, check the prefs for it. Assume
841 // enabled unless otherwise noted.
842 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
843 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
846 void ExtensionService::EnableExtension(const std::string& extension_id) {
847 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
849 if (IsExtensionEnabled(extension_id))
851 const Extension* extension =
852 registry_->disabled_extensions().GetByID(extension_id);
854 ManagementPolicy* policy = system_->management_policy();
855 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
856 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
860 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
861 extension_prefs_->ClearDisableReasons(extension_id);
863 // This can happen if sync enables an extension that is not
868 if (IsUnacknowledgedExternalExtension(extension)) {
869 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
870 EXTERNAL_EXTENSION_REENABLED,
871 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
872 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
873 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
874 EXTERNAL_EXTENSION_REENABLED,
875 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
877 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
878 EXTERNAL_EXTENSION_REENABLED,
879 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
881 AcknowledgeExternalExtension(extension->id());
884 // Move it over to the enabled list.
885 registry_->AddEnabled(make_scoped_refptr(extension));
886 registry_->RemoveDisabled(extension->id());
888 NotifyExtensionLoaded(extension);
890 // Notify listeners that the extension was enabled.
891 content::NotificationService::current()->Notify(
892 chrome::NOTIFICATION_EXTENSION_ENABLED,
893 content::Source<Profile>(profile_),
894 content::Details<const Extension>(extension));
896 if (extension_sync_service_)
897 extension_sync_service_->SyncEnableExtension(*extension);
900 void ExtensionService::DisableExtension(
901 const std::string& extension_id,
902 Extension::DisableReason disable_reason) {
903 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
905 // The extension may have been disabled already.
906 if (!IsExtensionEnabled(extension_id))
909 const Extension* extension = GetInstalledExtension(extension_id);
910 // |extension| can be NULL if sync disables an extension that is not
913 disable_reason != Extension::DISABLE_RELOAD &&
914 !system_->management_policy()->UserMayModifySettings(extension, NULL)) {
918 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
919 extension_prefs_->AddDisableReason(extension_id, disable_reason);
922 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
923 extension = registry_->GetExtensionById(extension_id, include_mask);
927 // The extension is either enabled or terminated.
928 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
929 registry_->terminated_extensions().Contains(extension->id()));
931 // Move it over to the disabled list. Don't send a second unload notification
932 // for terminated extensions being disabled.
933 registry_->AddDisabled(make_scoped_refptr(extension));
934 if (registry_->enabled_extensions().Contains(extension->id())) {
935 registry_->RemoveEnabled(extension->id());
936 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
938 registry_->RemoveTerminated(extension->id());
941 if (extension_sync_service_)
942 extension_sync_service_->SyncDisableExtension(*extension);
945 void ExtensionService::DisableUserExtensions(
946 const std::vector<std::string>& except_ids) {
947 extensions::ManagementPolicy* management_policy =
948 system_->management_policy();
949 extensions::ExtensionList to_disable;
951 // TODO(rlp): Clean up this code. crbug.com/353266.
952 const ExtensionSet& enabled_set = registry_->enabled_extensions();
953 for (ExtensionSet::const_iterator extension = enabled_set.begin();
954 extension != enabled_set.end(); ++extension) {
955 if (management_policy->UserMayModifySettings(extension->get(), NULL) &&
956 extension->get()->location() != Manifest::EXTERNAL_COMPONENT)
957 to_disable.push_back(*extension);
959 const ExtensionSet& terminated_set = registry_->terminated_extensions();
960 for (ExtensionSet::const_iterator extension = terminated_set.begin();
961 extension != terminated_set.end(); ++extension) {
962 if (management_policy->UserMayModifySettings(extension->get(), NULL) &&
963 extension->get()->location() != Manifest::EXTERNAL_COMPONENT)
964 to_disable.push_back(*extension);
967 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
968 extension != to_disable.end(); ++extension) {
969 if ((*extension)->was_installed_by_default() &&
970 extension_urls::IsWebstoreUpdateUrl(
971 extensions::ManifestURL::GetUpdateURL(*extension)))
973 const std::string& id = (*extension)->id();
974 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
975 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
979 void ExtensionService::GrantPermissionsAndEnableExtension(
980 const Extension* extension) {
981 GrantPermissions(extension);
982 RecordPermissionMessagesHistogram(
983 extension, "Extensions.Permissions_ReEnable");
984 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
985 EnableExtension(extension->id());
988 void ExtensionService::GrantPermissions(const Extension* extension) {
990 extensions::PermissionsUpdater perms_updater(profile());
991 perms_updater.GrantActivePermissions(extension);
995 void ExtensionService::RecordPermissionMessagesHistogram(
996 const Extension* extension, const char* histogram) {
997 // Since this is called from multiple sources, and since the histogram macros
998 // use statics, we need to manually lookup the histogram ourselves.
999 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
1002 PermissionMessage::kEnumBoundary,
1003 PermissionMessage::kEnumBoundary + 1,
1004 base::HistogramBase::kUmaTargetedHistogramFlag);
1006 PermissionMessages permissions =
1007 extensions::PermissionsData::GetPermissionMessages(extension);
1008 if (permissions.empty()) {
1009 counter->Add(PermissionMessage::kNone);
1011 for (PermissionMessages::iterator it = permissions.begin();
1012 it != permissions.end(); ++it)
1013 counter->Add(it->id());
1017 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1018 // The ChromeURLRequestContexts need to be first to know that the extension
1019 // was loaded, otherwise a race can arise where a renderer that is created
1020 // for the extension may try to load an extension URL with an extension id
1021 // that the request context doesn't yet know about. The profile is responsible
1022 // for ensuring its URLRequestContexts appropriately discover the loaded
1024 system_->RegisterExtensionWithRequestContexts(extension);
1026 // Tell renderers about the new extension, unless it's a theme (renderers
1027 // don't need to know about themes).
1028 if (!extension->is_theme()) {
1029 for (content::RenderProcessHost::iterator i(
1030 content::RenderProcessHost::AllHostsIterator());
1031 !i.IsAtEnd(); i.Advance()) {
1032 content::RenderProcessHost* host = i.GetCurrentValue();
1033 Profile* host_profile =
1034 Profile::FromBrowserContext(host->GetBrowserContext());
1035 if (host_profile->GetOriginalProfile() ==
1036 profile_->GetOriginalProfile()) {
1037 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1038 1, ExtensionMsg_Loaded_Params(extension));
1040 new ExtensionMsg_Loaded(loaded_extensions));
1045 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1048 // NOTE: It is important that this happen after notifying the renderers about
1049 // the new extensions so that if we navigate to an extension URL in
1050 // ExtensionRegistryObserver::OnLoaded or NOTIFICATION_EXTENSION_LOADED, the
1051 // renderer is guaranteed to know about it.
1052 registry_->TriggerOnLoaded(extension);
1054 content::NotificationService::current()->Notify(
1055 chrome::NOTIFICATION_EXTENSION_LOADED,
1056 content::Source<Profile>(profile_),
1057 content::Details<const Extension>(extension));
1059 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1060 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1061 profile_->GetExtensionSpecialStoragePolicy()->
1062 GrantRightsForExtension(extension);
1064 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1065 // work properly multi-profile. Besides which, it should be using
1066 // ExtensionRegistryObserver. See http://crbug.com/355029.
1067 UpdateActiveExtensionsInCrashReporter();
1069 // If the extension has permission to load chrome://favicon/ resources we need
1070 // to make sure that the FaviconSource is registered with the
1071 // ChromeURLDataManager.
1072 if (extensions::PermissionsData::HasHostPermission(
1073 extension, GURL(chrome::kChromeUIFaviconURL))) {
1074 FaviconSource* favicon_source = new FaviconSource(profile_,
1075 FaviconSource::FAVICON);
1076 content::URLDataSource::Add(profile_, favicon_source);
1079 #if !defined(OS_ANDROID)
1080 // Same for chrome://theme/ resources.
1081 if (extensions::PermissionsData::HasHostPermission(
1082 extension, GURL(chrome::kChromeUIThemeURL))) {
1083 ThemeSource* theme_source = new ThemeSource(profile_);
1084 content::URLDataSource::Add(profile_, theme_source);
1088 // Same for chrome://thumb/ resources.
1089 if (extensions::PermissionsData::HasHostPermission(
1090 extension, GURL(chrome::kChromeUIThumbnailURL))) {
1091 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1092 content::URLDataSource::Add(profile_, thumbnail_source);
1096 void ExtensionService::NotifyExtensionUnloaded(
1097 const Extension* extension,
1098 UnloadedExtensionInfo::Reason reason) {
1099 registry_->TriggerOnUnloaded(extension);
1101 UnloadedExtensionInfo details(extension, reason);
1102 content::NotificationService::current()->Notify(
1103 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1104 content::Source<Profile>(profile_),
1105 content::Details<UnloadedExtensionInfo>(&details));
1107 for (content::RenderProcessHost::iterator i(
1108 content::RenderProcessHost::AllHostsIterator());
1109 !i.IsAtEnd(); i.Advance()) {
1110 content::RenderProcessHost* host = i.GetCurrentValue();
1111 Profile* host_profile =
1112 Profile::FromBrowserContext(host->GetBrowserContext());
1113 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1114 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1117 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1119 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1120 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1121 profile_->GetExtensionSpecialStoragePolicy()->
1122 RevokeRightsForExtension(extension);
1124 #if defined(OS_CHROMEOS)
1125 // Revoke external file access for the extension from its file system context.
1126 // It is safe to access the extension's storage partition at this point. The
1127 // storage partition may get destroyed only after the extension gets unloaded.
1129 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1130 fileapi::FileSystemContext* filesystem_context =
1131 BrowserContext::GetStoragePartitionForSite(profile_, site)->
1132 GetFileSystemContext();
1133 if (filesystem_context && filesystem_context->external_backend()) {
1134 filesystem_context->external_backend()->
1135 RevokeAccessForExtension(extension->id());
1139 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1140 // work properly multi-profile. Besides which, it should be using
1141 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1142 UpdateActiveExtensionsInCrashReporter();
1145 Profile* ExtensionService::profile() {
1149 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1150 // Implemented in the .cc file to avoid adding a profile.h dependency to
1151 // extension_service.h.
1155 bool ExtensionService::is_ready() {
1156 return ready_->is_signaled();
1159 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1160 if (file_task_runner_.get())
1161 return file_task_runner_.get();
1163 // We should be able to interrupt any part of extension install process during
1164 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1165 // will be ignored/deleted while we will block on started tasks.
1166 std::string token("ext_install-");
1167 token.append(profile_->GetPath().AsUTF8Unsafe());
1168 file_task_runner_ = BrowserThread::GetBlockingPool()->
1169 GetSequencedTaskRunnerWithShutdownBehavior(
1170 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1171 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1172 return file_task_runner_.get();
1175 extensions::ExtensionUpdater* ExtensionService::updater() {
1176 return updater_.get();
1179 void ExtensionService::CheckManagementPolicy() {
1180 std::vector<std::string> to_unload;
1181 std::map<std::string, Extension::DisableReason> to_disable;
1183 // Loop through the extensions list, finding extensions we need to unload or
1185 const ExtensionSet& extensions = registry_->enabled_extensions();
1186 for (ExtensionSet::const_iterator iter = extensions.begin();
1187 iter != extensions.end(); ++iter) {
1188 const Extension* extension = (iter->get());
1189 if (!system_->management_policy()->UserMayLoad(extension, NULL))
1190 to_unload.push_back(extension->id());
1191 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1192 if (system_->management_policy()->MustRemainDisabled(
1193 extension, &disable_reason, NULL))
1194 to_disable[extension->id()] = disable_reason;
1197 for (size_t i = 0; i < to_unload.size(); ++i)
1198 UnloadExtension(to_unload[i], UnloadedExtensionInfo::REASON_DISABLE);
1200 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1201 to_disable.begin(); i != to_disable.end(); ++i)
1202 DisableExtension(i->first, i->second);
1205 void ExtensionService::CheckForUpdatesSoon() {
1207 if (AreAllExternalProvidersReady()) {
1208 updater()->CheckSoon();
1210 // Sync can start updating before all the external providers are ready
1211 // during startup. Start the update as soon as those providers are ready,
1213 update_once_all_providers_are_ready_ = true;
1216 LOG(WARNING) << "CheckForUpdatesSoon() called with auto-update turned off";
1220 // Some extensions will autoupdate themselves externally from Chrome. These
1221 // are typically part of some larger client application package. To support
1222 // these, the extension will register its location in the the preferences file
1223 // (and also, on Windows, in the registry) and this code will periodically
1224 // check that location for a .crx file, which it will then install locally if
1225 // a new version is available.
1226 // Errors are reported through ExtensionErrorReporter. Succcess is not
1228 void ExtensionService::CheckForExternalUpdates() {
1229 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1231 // Note that this installation is intentionally silent (since it didn't
1232 // go through the front-end). Extensions that are registered in this
1233 // way are effectively considered 'pre-bundled', and so implicitly
1234 // trusted. In general, if something has HKLM or filesystem access,
1235 // they could install an extension manually themselves anyway.
1237 // Ask each external extension provider to give us a call back for each
1238 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1239 extensions::ProviderCollection::const_iterator i;
1240 for (i = external_extension_providers_.begin();
1241 i != external_extension_providers_.end(); ++i) {
1242 extensions::ExternalProviderInterface* provider = i->get();
1243 provider->VisitRegisteredExtension();
1246 // Do any required work that we would have done after completion of all
1248 if (external_extension_providers_.empty()) {
1249 OnAllExternalProvidersReady();
1253 void ExtensionService::OnExternalProviderReady(
1254 const extensions::ExternalProviderInterface* provider) {
1255 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1256 CHECK(provider->IsReady());
1258 // An external provider has finished loading. We only take action
1259 // if all of them are finished. So we check them first.
1260 if (AreAllExternalProvidersReady())
1261 OnAllExternalProvidersReady();
1264 bool ExtensionService::AreAllExternalProvidersReady() const {
1265 extensions::ProviderCollection::const_iterator i;
1266 for (i = external_extension_providers_.begin();
1267 i != external_extension_providers_.end(); ++i) {
1268 if (!i->get()->IsReady())
1274 void ExtensionService::OnAllExternalProvidersReady() {
1275 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1276 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1277 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1279 // Install any pending extensions.
1280 if (update_once_all_providers_are_ready_ && updater()) {
1281 update_once_all_providers_are_ready_ = false;
1282 extensions::ExtensionUpdater::CheckParams params;
1283 params.callback = external_updates_finished_callback_;
1284 updater()->CheckNow(params);
1287 // Uninstall all the unclaimed extensions.
1288 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1289 extension_prefs_->GetInstalledExtensionsInfo());
1290 for (size_t i = 0; i < extensions_info->size(); ++i) {
1291 ExtensionInfo* info = extensions_info->at(i).get();
1292 if (Manifest::IsExternalLocation(info->extension_location))
1293 CheckExternalUninstall(info->extension_id);
1295 IdentifyAlertableExtensions();
1298 void ExtensionService::IdentifyAlertableExtensions() {
1299 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1301 // Build up the lists of extensions that require acknowledgment. If this is
1302 // the first time, grandfather extensions that would have caused
1304 extension_error_ui_.reset(ExtensionErrorUI::Create(this));
1306 bool did_show_alert = false;
1307 if (PopulateExtensionErrorUI(extension_error_ui_.get())) {
1308 if (!is_first_run_) {
1309 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1310 did_show_alert = extension_error_ui_->ShowErrorInBubbleView();
1312 // First run. Just acknowledge all the extensions, silently, by
1313 // shortcutting the display of the UI and going straight to the
1314 // callback for pressing the Accept button.
1315 HandleExtensionAlertAccept();
1319 UpdateExternalExtensionAlert();
1321 if (!did_show_alert)
1322 extension_error_ui_.reset();
1325 bool ExtensionService::PopulateExtensionErrorUI(
1326 ExtensionErrorUI* extension_error_ui) {
1327 bool needs_alert = false;
1329 // Extensions that are blacklisted.
1330 const ExtensionSet& blacklisted_set = registry_->blacklisted_extensions();
1331 for (ExtensionSet::const_iterator it = blacklisted_set.begin();
1332 it != blacklisted_set.end(); ++it) {
1333 std::string id = (*it)->id();
1334 if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(id)) {
1335 extension_error_ui->AddBlacklistedExtension(id);
1340 const ExtensionSet& enabled_set = registry_->enabled_extensions();
1341 for (ExtensionSet::const_iterator iter = enabled_set.begin();
1342 iter != enabled_set.end(); ++iter) {
1343 const Extension* e = iter->get();
1345 // Skip for extensions that have pending updates. They will be checked again
1346 // once the pending update is finished.
1347 if (pending_extension_manager()->IsIdPending(e->id()))
1350 // Extensions disabled by policy. Note: this no longer includes blacklisted
1351 // extensions, though we still show the same UI.
1352 if (!system_->management_policy()->UserMayLoad(e, NULL)) {
1353 if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(e->id())) {
1354 extension_error_ui->AddBlacklistedExtension(e->id());
1363 void ExtensionService::HandleExtensionAlertClosed() {
1364 const ExtensionIdSet* extension_ids =
1365 extension_error_ui_->get_blacklisted_extension_ids();
1366 for (ExtensionIdSet::const_iterator iter = extension_ids->begin();
1367 iter != extension_ids->end(); ++iter) {
1368 extension_prefs_->AcknowledgeBlacklistedExtension(*iter);
1370 extension_error_ui_.reset();
1373 void ExtensionService::HandleExtensionAlertAccept() {
1374 extension_error_ui_->Close();
1377 void ExtensionService::AcknowledgeExternalExtension(const std::string& id) {
1378 extension_prefs_->AcknowledgeExternalExtension(id);
1379 UpdateExternalExtensionAlert();
1382 bool ExtensionService::IsUnacknowledgedExternalExtension(
1383 const Extension* extension) {
1384 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1387 return (Manifest::IsExternalLocation(extension->location()) &&
1388 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id()) &&
1389 !(extension_prefs_->GetDisableReasons(extension->id()) &
1390 Extension::DISABLE_SIDELOAD_WIPEOUT));
1393 void ExtensionService::ReconcileKnownDisabled() {
1394 ExtensionIdSet known_disabled_ids;
1395 if (!extension_prefs_->GetKnownDisabled(&known_disabled_ids)) {
1396 extension_prefs_->SetKnownDisabled(
1397 registry_->disabled_extensions().GetIDs());
1398 UMA_HISTOGRAM_BOOLEAN("Extensions.KnownDisabledInitialized", true);
1402 // Both |known_disabled_ids| and |extensions| are ordered (by definition
1403 // of std::map and std::set). Iterate forward over both sets in parallel
1404 // to find matching IDs and disable the corresponding extensions.
1405 const ExtensionSet& enabled_set = registry_->enabled_extensions();
1406 ExtensionSet::const_iterator extensions_it = enabled_set.begin();
1407 ExtensionIdSet::const_iterator known_disabled_ids_it =
1408 known_disabled_ids.begin();
1409 int known_disabled_count = 0;
1410 while (extensions_it != enabled_set.end() &&
1411 known_disabled_ids_it != known_disabled_ids.end()) {
1412 const std::string& extension_id = extensions_it->get()->id();
1413 const int comparison = extension_id.compare(*known_disabled_ids_it);
1414 if (comparison < 0) {
1416 } else if (comparison > 0) {
1417 ++known_disabled_ids_it;
1419 ++known_disabled_count;
1420 // Advance |extensions_it| immediately as it will be invalidated upon
1421 // disabling the extension it points to.
1423 ++known_disabled_ids_it;
1424 DisableExtension(extension_id, Extension::DISABLE_KNOWN_DISABLED);
1427 UMA_HISTOGRAM_COUNTS_100("Extensions.KnownDisabledReDisabled",
1428 known_disabled_count);
1430 // Update the list of known disabled to reflect every change to
1431 // |disabled_extensions_| from this point forward.
1432 registry_->SetDisabledModificationCallback(
1433 base::Bind(&extensions::ExtensionPrefs::SetKnownDisabled,
1434 base::Unretained(extension_prefs_)));
1437 void ExtensionService::HandleExtensionAlertDetails() {
1438 extension_error_ui_->ShowExtensions();
1439 // ShowExtensions may cause the error UI to close synchronously, e.g. if it
1440 // causes a navigation.
1441 if (extension_error_ui_)
1442 extension_error_ui_->Close();
1445 void ExtensionService::UpdateExternalExtensionAlert() {
1446 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1449 const Extension* extension = NULL;
1450 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
1451 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
1452 iter != disabled_extensions.end(); ++iter) {
1453 const Extension* e = iter->get();
1454 if (IsUnacknowledgedExternalExtension(e)) {
1461 if (!extensions::HasExternalInstallError(this)) {
1462 if (extension_prefs_->IncrementAcknowledgePromptCount(extension->id()) >
1463 kMaxExtensionAcknowledgePromptCount) {
1464 // Stop prompting for this extension, and check if there's another
1465 // one that needs prompting.
1466 extension_prefs_->AcknowledgeExternalExtension(extension->id());
1467 UpdateExternalExtensionAlert();
1468 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
1469 EXTERNAL_EXTENSION_IGNORED,
1470 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1471 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
1472 UMA_HISTOGRAM_ENUMERATION(
1473 "Extensions.ExternalExtensionEventWebstore",
1474 EXTERNAL_EXTENSION_IGNORED,
1475 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1477 UMA_HISTOGRAM_ENUMERATION(
1478 "Extensions.ExternalExtensionEventNonWebstore",
1479 EXTERNAL_EXTENSION_IGNORED,
1480 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1485 extension_prefs_->SetExternalInstallFirstRun(extension->id());
1486 // first_run is true if the extension was installed during a first run
1487 // (even if it's post-first run now).
1488 bool first_run = extension_prefs_->IsExternalInstallFirstRun(
1490 extensions::AddExternalInstallError(this, extension, first_run);
1493 extensions::RemoveExternalInstallError(this);
1497 void ExtensionService::UnloadExtension(
1498 const std::string& extension_id,
1499 UnloadedExtensionInfo::Reason reason) {
1500 // Make sure the extension gets deleted after we return from this function.
1502 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1503 scoped_refptr<const Extension> extension(
1504 registry_->GetExtensionById(extension_id, include_mask));
1506 // This method can be called via PostTask, so the extension may have been
1507 // unloaded by the time this runs.
1508 if (!extension.get()) {
1509 // In case the extension may have crashed/uninstalled. Allow the profile to
1510 // clean up its RequestContexts.
1511 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1515 // Keep information about the extension so that we can reload it later
1516 // even if it's not permanently installed.
1517 unloaded_extension_paths_[extension->id()] = extension->path();
1519 // Clean up if the extension is meant to be enabled after a reload.
1520 reloading_extensions_.erase(extension->id());
1522 if (registry_->disabled_extensions().Contains(extension->id())) {
1523 registry_->RemoveDisabled(extension->id());
1524 // Make sure the profile cleans up its RequestContexts when an already
1525 // disabled extension is unloaded (since they are also tracking the disabled
1527 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1528 // Don't send the unloaded notification. It was sent when the extension
1531 // Remove the extension from the enabled list.
1532 registry_->RemoveEnabled(extension->id());
1533 NotifyExtensionUnloaded(extension.get(), reason);
1536 content::NotificationService::current()->Notify(
1537 chrome::NOTIFICATION_EXTENSION_REMOVED,
1538 content::Source<Profile>(profile_),
1539 content::Details<const Extension>(extension.get()));
1542 void ExtensionService::RemoveComponentExtension(
1543 const std::string& extension_id) {
1544 scoped_refptr<const Extension> extension(
1545 GetExtensionById(extension_id, false));
1546 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1547 content::NotificationService::current()->Notify(
1548 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
1549 content::Source<Profile>(profile_),
1550 content::Details<const Extension>(extension.get()));
1553 void ExtensionService::UnloadAllExtensionsForTest() {
1554 UnloadAllExtensionsInternal();
1557 void ExtensionService::ReloadExtensionsForTest() {
1558 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1559 // warning about calling test code in production.
1560 UnloadAllExtensionsInternal();
1561 component_loader_->LoadAll();
1562 extensions::InstalledLoader(this).LoadAllExtensions();
1563 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1567 void ExtensionService::GarbageCollectExtensions() {
1568 #if defined(OS_CHROMEOS)
1569 if (disable_garbage_collection_)
1573 if (extension_prefs_->pref_service()->ReadOnly())
1576 if (pending_extension_manager()->HasPendingExtensions()) {
1577 // Don't garbage collect while there are pending installations, which may
1578 // be using the temporary installation directory. Try to garbage collect
1580 base::MessageLoop::current()->PostDelayedTask(
1582 base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
1583 base::TimeDelta::FromSeconds(kGarbageCollectRetryDelay));
1587 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> info(
1588 extension_prefs_->GetInstalledExtensionsInfo());
1590 std::multimap<std::string, base::FilePath> extension_paths;
1591 for (size_t i = 0; i < info->size(); ++i)
1592 extension_paths.insert(std::make_pair(info->at(i)->extension_id,
1593 info->at(i)->extension_path));
1595 info = extension_prefs_->GetAllDelayedInstallInfo();
1596 for (size_t i = 0; i < info->size(); ++i)
1597 extension_paths.insert(std::make_pair(info->at(i)->extension_id,
1598 info->at(i)->extension_path));
1600 if (!GetFileTaskRunner()->PostTask(
1603 &extension_file_util::GarbageCollectExtensions,
1605 extension_paths))) {
1610 void ExtensionService::SetReadyAndNotifyListeners() {
1612 content::NotificationService::current()->Notify(
1613 chrome::NOTIFICATION_EXTENSIONS_READY,
1614 content::Source<Profile>(profile_),
1615 content::NotificationService::NoDetails());
1618 void ExtensionService::OnLoadedInstalledExtensions() {
1622 OnBlacklistUpdated();
1625 void ExtensionService::AddExtension(const Extension* extension) {
1626 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1627 // default extension state to DISABLED when the --disable-extensions flag
1628 // is set (http://crbug.com/29067).
1629 if (!extensions_enabled() &&
1630 !extension->is_theme() &&
1631 extension->location() != Manifest::COMPONENT &&
1632 !Manifest::IsExternalLocation(extension->location())) {
1636 bool is_extension_upgrade = false;
1637 bool is_extension_installed = false;
1638 const Extension* old = GetInstalledExtension(extension->id());
1640 is_extension_installed = true;
1641 int version_compare_result =
1642 extension->version()->CompareTo(*(old->version()));
1643 is_extension_upgrade = version_compare_result > 0;
1644 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1645 // that we aren't downgrading.
1646 if (!Manifest::IsUnpackedLocation(extension->location()))
1647 CHECK_GE(version_compare_result, 0);
1649 system_->runtime_data()->SetBeingUpgraded(extension, is_extension_upgrade);
1651 // The extension is now loaded, remove its data from unloaded extension map.
1652 unloaded_extension_paths_.erase(extension->id());
1654 // If a terminated extension is loaded, remove it from the terminated list.
1655 UntrackTerminatedExtension(extension->id());
1657 // If the extension was disabled for a reload, then enable it.
1658 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1660 // Check if the extension's privileges have changed and mark the
1661 // extension disabled if necessary.
1662 CheckPermissionsIncrease(extension, is_extension_installed);
1664 if (is_extension_installed && !reloading) {
1665 // To upgrade an extension in place, unload the old one and then load the
1666 // new one. ReloadExtension disables the extension, which is sufficient.
1667 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1670 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1671 // Only prefs is checked for the blacklist. We rely on callers to check the
1672 // blacklist before calling into here, e.g. CrxInstaller checks before
1673 // installation then threads through the install and pending install flow
1674 // of this class, and we check when loading installed extensions.
1675 registry_->AddBlacklisted(extension);
1676 } else if (!reloading &&
1677 extension_prefs_->IsExtensionDisabled(extension->id())) {
1678 registry_->AddDisabled(extension);
1679 if (extension_sync_service_)
1680 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1681 content::NotificationService::current()->Notify(
1682 chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1683 content::Source<Profile>(profile_),
1684 content::Details<const Extension>(extension));
1686 // Show the extension disabled error if a permissions increase was the
1687 // only reason it was disabled.
1688 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1689 Extension::DISABLE_PERMISSIONS_INCREASE) {
1690 extensions::AddExtensionDisabledError(this, extension);
1692 } else if (reloading) {
1693 // Replace the old extension with the new version.
1694 CHECK(!registry_->AddDisabled(extension));
1695 EnableExtension(extension->id());
1697 // All apps that are displayed in the launcher are ordered by their ordinals
1698 // so we must ensure they have valid ordinals.
1699 if (extension->RequiresSortOrdinal()) {
1700 if (!extension->ShouldDisplayInNewTabPage()) {
1701 extension_prefs_->app_sorting()->MarkExtensionAsHidden(extension->id());
1703 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1704 extension->id(), syncer::StringOrdinal());
1707 registry_->AddEnabled(extension);
1708 if (extension_sync_service_)
1709 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1710 NotifyExtensionLoaded(extension);
1712 system_->runtime_data()->SetBeingUpgraded(extension, false);
1715 void ExtensionService::AddComponentExtension(const Extension* extension) {
1716 const std::string old_version_string(
1717 extension_prefs_->GetVersionString(extension->id()));
1718 const Version old_version(old_version_string);
1720 VLOG(1) << "AddComponentExtension " << extension->name();
1721 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1722 VLOG(1) << "Component extension " << extension->name() << " ("
1723 << extension->id() << ") installing/upgrading from '"
1724 << old_version_string << "' to " << extension->version()->GetString();
1726 AddNewOrUpdatedExtension(extension,
1727 Extension::ENABLED_COMPONENT,
1728 extensions::NOT_BLACKLISTED,
1729 syncer::StringOrdinal(),
1734 AddExtension(extension);
1737 void ExtensionService::UpdateActivePermissions(const Extension* extension) {
1738 // If the extension has used the optional permissions API, it will have a
1739 // custom set of active permissions defined in the extension prefs. Here,
1740 // we update the extension's active permissions based on the prefs.
1741 scoped_refptr<PermissionSet> active_permissions =
1742 extension_prefs_->GetActivePermissions(extension->id());
1744 if (active_permissions.get()) {
1745 // We restrict the active permissions to be within the bounds defined in the
1746 // extension's manifest.
1747 // a) active permissions must be a subset of optional + default permissions
1748 // b) active permissions must contains all default permissions
1749 scoped_refptr<PermissionSet> total_permissions =
1750 PermissionSet::CreateUnion(
1751 extensions::PermissionsData::GetRequiredPermissions(extension),
1752 extensions::PermissionsData::GetOptionalPermissions(extension));
1754 // Make sure the active permissions contain no more than optional + default.
1755 scoped_refptr<PermissionSet> adjusted_active =
1756 PermissionSet::CreateIntersection(
1757 total_permissions.get(), active_permissions.get());
1759 // Make sure the active permissions contain the default permissions.
1760 adjusted_active = PermissionSet::CreateUnion(
1761 extensions::PermissionsData::GetRequiredPermissions(extension),
1762 adjusted_active.get());
1764 extensions::PermissionsUpdater perms_updater(profile());
1765 perms_updater.UpdateActivePermissions(extension, adjusted_active.get());
1769 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1770 bool is_extension_installed) {
1771 UpdateActivePermissions(extension);
1773 // We keep track of all permissions the user has granted each extension.
1774 // This allows extensions to gracefully support backwards compatibility
1775 // by including unknown permissions in their manifests. When the user
1776 // installs the extension, only the recognized permissions are recorded.
1777 // When the unknown permissions become recognized (e.g., through browser
1778 // upgrade), we can prompt the user to accept these new permissions.
1779 // Extensions can also silently upgrade to less permissions, and then
1780 // silently upgrade to a version that adds these permissions back.
1782 // For example, pretend that Chrome 10 includes a permission "omnibox"
1783 // for an API that adds suggestions to the omnibox. An extension can
1784 // maintain backwards compatibility while still having "omnibox" in the
1785 // manifest. If a user installs the extension on Chrome 9, the browser
1786 // will record the permissions it recognized, not including "omnibox."
1787 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1788 // will disable the extension and prompt the user to approve the increase
1789 // in privileges. The extension could then release a new version that
1790 // removes the "omnibox" permission. When the user upgrades, Chrome will
1791 // still remember that "omnibox" had been granted, so that if the
1792 // extension once again includes "omnibox" in an upgrade, the extension
1793 // can upgrade without requiring this user's approval.
1794 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1796 bool auto_grant_permission =
1797 (!is_extension_installed && extension->was_installed_by_default()) ||
1798 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1799 // Silently grant all active permissions to default apps only on install.
1800 // After install they should behave like other apps.
1801 // Silently grant all active permissions to apps install in kiosk mode on both
1802 // install and update.
1803 if (auto_grant_permission)
1804 GrantPermissions(extension);
1806 bool is_privilege_increase = false;
1807 // We only need to compare the granted permissions to the current permissions
1808 // if the extension is not allowed to silently increase its permissions.
1809 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) &&
1810 !auto_grant_permission) {
1811 // Add all the recognized permissions if the granted permissions list
1812 // hasn't been initialized yet.
1813 scoped_refptr<PermissionSet> granted_permissions =
1814 extension_prefs_->GetGrantedPermissions(extension->id());
1815 CHECK(granted_permissions.get());
1817 // Here, we check if an extension's privileges have increased in a manner
1818 // that requires the user's approval. This could occur because the browser
1819 // upgraded and recognized additional privileges, or an extension upgrades
1820 // to a version that requires additional privileges.
1821 is_privilege_increase =
1822 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1823 granted_permissions,
1824 extension->GetActivePermissions().get(),
1825 extension->GetType());
1828 if (is_extension_installed) {
1829 // If the extension was already disabled, suppress any alerts for becoming
1830 // disabled on permissions increase.
1831 bool previously_disabled =
1832 extension_prefs_->IsExtensionDisabled(extension->id());
1833 // Legacy disabled extensions do not have a disable reason. Infer that if
1834 // there was no permission increase, it was likely disabled by the user.
1835 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1836 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1837 disable_reasons |= Extension::DISABLE_USER_ACTION;
1839 // Extensions that came to us disabled from sync need a similar inference,
1840 // except based on the new version's permissions.
1841 if (previously_disabled &&
1842 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1843 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1844 extension_prefs_->ClearDisableReasons(extension->id());
1845 if (!is_privilege_increase)
1846 disable_reasons |= Extension::DISABLE_USER_ACTION;
1848 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1851 // Extension has changed permissions significantly. Disable it. A
1852 // notification should be sent by the caller.
1853 if (is_privilege_increase) {
1854 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1855 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1856 RecordPermissionMessagesHistogram(
1857 extension, "Extensions.Permissions_AutoDisable");
1859 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1860 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1862 if (disable_reasons != Extension::DISABLE_NONE) {
1863 extension_prefs_->AddDisableReason(
1865 static_cast<Extension::DisableReason>(disable_reasons));
1869 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1870 std::set<std::string> extension_ids;
1871 const ExtensionSet& extensions = registry_->enabled_extensions();
1872 for (ExtensionSet::const_iterator iter = extensions.begin();
1873 iter != extensions.end(); ++iter) {
1874 const Extension* extension = iter->get();
1875 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1876 extension_ids.insert(extension->id());
1879 // TODO(kalman): This is broken. ExtensionService is per-profile.
1880 // crash_keys::SetActiveExtensions is per-process. See
1881 // http://crbug.com/355029.
1882 crash_keys::SetActiveExtensions(extension_ids);
1885 ExtensionService::ImportStatus ExtensionService::CheckImports(
1886 const extensions::Extension* extension,
1887 std::list<SharedModuleInfo::ImportInfo>* missing_modules,
1888 std::list<SharedModuleInfo::ImportInfo>* outdated_modules) {
1890 DCHECK(missing_modules && missing_modules->empty());
1891 DCHECK(outdated_modules && outdated_modules->empty());
1892 ImportStatus status = IMPORT_STATUS_OK;
1893 if (SharedModuleInfo::ImportsModules(extension)) {
1894 const std::vector<SharedModuleInfo::ImportInfo>& imports =
1895 SharedModuleInfo::GetImports(extension);
1896 std::vector<SharedModuleInfo::ImportInfo>::const_iterator i;
1897 for (i = imports.begin(); i != imports.end(); ++i) {
1898 Version version_required(i->minimum_version);
1899 const Extension* imported_module =
1900 GetExtensionById(i->extension_id, true);
1901 if (!imported_module) {
1902 if (extension->from_webstore()) {
1903 status = IMPORT_STATUS_UNSATISFIED;
1904 missing_modules->push_back(*i);
1906 return IMPORT_STATUS_UNRECOVERABLE;
1908 } else if (!SharedModuleInfo::IsSharedModule(imported_module)) {
1909 return IMPORT_STATUS_UNRECOVERABLE;
1910 } else if (version_required.IsValid() &&
1911 imported_module->version()->CompareTo(version_required) < 0) {
1912 if (imported_module->from_webstore()) {
1913 outdated_modules->push_back(*i);
1914 status = IMPORT_STATUS_UNSATISFIED;
1916 return IMPORT_STATUS_UNRECOVERABLE;
1924 ExtensionService::ImportStatus ExtensionService::SatisfyImports(
1925 const Extension* extension) {
1926 std::list<SharedModuleInfo::ImportInfo> noinstalled;
1927 std::list<SharedModuleInfo::ImportInfo> outdated;
1928 ImportStatus status = CheckImports(extension, &noinstalled, &outdated);
1929 if (status == IMPORT_STATUS_UNRECOVERABLE)
1931 if (status == IMPORT_STATUS_UNSATISFIED) {
1932 std::list<SharedModuleInfo::ImportInfo>::const_iterator iter;
1933 for (iter = noinstalled.begin(); iter != noinstalled.end(); ++iter) {
1934 pending_extension_manager()->AddFromExtensionImport(
1936 extension_urls::GetWebstoreUpdateUrl(),
1939 CheckForUpdatesSoon();
1944 scoped_ptr<const ExtensionSet>
1945 ExtensionService::GetDependentExtensions(const Extension* extension) {
1946 scoped_ptr<ExtensionSet> dependents(new ExtensionSet());
1947 scoped_ptr<ExtensionSet> set_to_check(new ExtensionSet());
1948 if (SharedModuleInfo::IsSharedModule(extension)) {
1949 set_to_check->InsertAll(registry_->disabled_extensions());
1950 set_to_check->InsertAll(delayed_installs_);
1951 set_to_check->InsertAll(registry_->enabled_extensions());
1952 for (ExtensionSet::const_iterator iter = set_to_check->begin();
1953 iter != set_to_check->end(); ++iter) {
1954 if (SharedModuleInfo::ImportsExtensionById(iter->get(),
1956 dependents->Insert(*iter);
1960 return dependents.PassAs<const ExtensionSet>();
1963 void ExtensionService::PruneSharedModulesOnUninstall(
1964 const Extension* extension) {
1965 if (SharedModuleInfo::ImportsModules(extension)) {
1966 const std::vector<SharedModuleInfo::ImportInfo>& imports =
1967 SharedModuleInfo::GetImports(extension);
1968 std::vector<SharedModuleInfo::ImportInfo>::const_iterator i;
1969 for (i = imports.begin(); i != imports.end(); ++i) {
1970 const Extension* imported_module =
1971 GetExtensionById(i->extension_id, true);
1972 if (imported_module && imported_module->from_webstore()) {
1973 scoped_ptr<const ExtensionSet> dependents =
1974 GetDependentExtensions(imported_module);
1975 if (dependents->size() == 0) {
1976 UninstallExtension(i->extension_id, true, NULL);
1983 void ExtensionService::OnExtensionInstalled(
1984 const Extension* extension,
1985 const syncer::StringOrdinal& page_ordinal,
1986 bool has_requirement_errors,
1987 extensions::BlacklistState blacklist_state,
1988 bool wait_for_idle) {
1989 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1991 const std::string& id = extension->id();
1992 bool initial_enable = ShouldEnableOnInstall(extension);
1993 std::string install_parameter;
1994 const extensions::PendingExtensionInfo* pending_extension_info = NULL;
1995 if ((pending_extension_info = pending_extension_manager()->GetById(id))) {
1996 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1997 pending_extension_manager()->Remove(id);
1999 LOG(WARNING) << "ShouldAllowInstall() returned false for "
2000 << id << " of type " << extension->GetType()
2001 << " and update URL "
2002 << extensions::ManifestURL::GetUpdateURL(extension).spec()
2003 << "; not installing";
2005 // Delete the extension directory since we're not going to
2007 if (!GetFileTaskRunner()->PostTask(
2009 base::Bind(&extension_file_util::DeleteFile,
2010 extension->path(), true))) {
2016 install_parameter = pending_extension_info->install_parameter();
2017 pending_extension_manager()->Remove(id);
2019 // We explicitly want to re-enable an uninstalled external
2020 // extension; if we're here, that means the user is manually
2021 // installing the extension.
2022 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
2023 initial_enable = true;
2027 // Unsupported requirements overrides the management policy.
2028 if (has_requirement_errors) {
2029 initial_enable = false;
2030 extension_prefs_->AddDisableReason(
2031 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
2032 // If the extension was disabled because of unsupported requirements but
2033 // now supports all requirements after an update and there are not other
2034 // disable reasons, enable it.
2035 } else if (extension_prefs_->GetDisableReasons(id) ==
2036 Extension::DISABLE_UNSUPPORTED_REQUIREMENT) {
2037 initial_enable = true;
2038 extension_prefs_->ClearDisableReasons(id);
2041 if (blacklist_state == extensions::BLACKLISTED_MALWARE) {
2042 // Installation of a blacklisted extension can happen from sync, policy,
2043 // etc, where to maintain consistency we need to install it, just never
2044 // load it (see AddExtension). Usually it should be the job of callers to
2045 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
2046 // showing the install dialogue).
2047 extension_prefs_->AcknowledgeBlacklistedExtension(id);
2048 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
2049 extension->location(),
2050 Manifest::NUM_LOCATIONS);
2053 if (!GetInstalledExtension(extension->id())) {
2054 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
2055 extension->GetType(), 100);
2056 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
2057 extension->location(), Manifest::NUM_LOCATIONS);
2058 RecordPermissionMessagesHistogram(
2059 extension, "Extensions.Permissions_Install");
2061 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
2062 extension->GetType(), 100);
2063 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
2064 extension->location(), Manifest::NUM_LOCATIONS);
2067 // Certain extension locations are specific enough that we can
2068 // auto-acknowledge any extension that came from one of them.
2069 if (Manifest::IsPolicyLocation(extension->location()) ||
2070 extension->location() == Manifest::EXTERNAL_COMPONENT)
2071 AcknowledgeExternalExtension(extension->id());
2072 const Extension::State initial_state =
2073 initial_enable ? Extension::ENABLED : Extension::DISABLED;
2074 const bool blacklisted_for_malware =
2075 blacklist_state == extensions::BLACKLISTED_MALWARE;
2076 if (ShouldDelayExtensionUpdate(id, wait_for_idle)) {
2077 extension_prefs_->SetDelayedInstallInfo(
2080 blacklisted_for_malware,
2081 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
2085 // Transfer ownership of |extension|.
2086 delayed_installs_.Insert(extension);
2088 // Notify observers that app update is available.
2089 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2090 OnAppUpdateAvailable(extension));
2094 ImportStatus status = SatisfyImports(extension);
2095 if (installs_delayed_for_gc()) {
2096 extension_prefs_->SetDelayedInstallInfo(
2099 blacklisted_for_malware,
2100 extensions::ExtensionPrefs::DELAY_REASON_GC,
2103 delayed_installs_.Insert(extension);
2104 } else if (status != IMPORT_STATUS_OK) {
2105 if (status == IMPORT_STATUS_UNSATISFIED) {
2106 extension_prefs_->SetDelayedInstallInfo(
2109 blacklisted_for_malware,
2110 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
2113 delayed_installs_.Insert(extension);
2116 AddNewOrUpdatedExtension(extension,
2124 void ExtensionService::AddNewOrUpdatedExtension(
2125 const Extension* extension,
2126 Extension::State initial_state,
2127 extensions::BlacklistState blacklist_state,
2128 const syncer::StringOrdinal& page_ordinal,
2129 const std::string& install_parameter) {
2130 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2131 const bool blacklisted_for_malware =
2132 blacklist_state == extensions::BLACKLISTED_MALWARE;
2133 extension_prefs_->OnExtensionInstalled(extension,
2135 blacklisted_for_malware,
2138 delayed_installs_.Remove(extension->id());
2139 if (InstallVerifier::NeedsVerification(*extension))
2140 system_->install_verifier()->VerifyExtension(extension->id());
2141 FinishInstallation(extension);
2144 void ExtensionService::MaybeFinishDelayedInstallation(
2145 const std::string& extension_id) {
2146 // Check if the extension already got installed.
2147 if (!delayed_installs_.Contains(extension_id))
2149 extensions::ExtensionPrefs::DelayReason reason =
2150 extension_prefs_->GetDelayedInstallReason(extension_id);
2152 // Check if the extension is idle. DELAY_REASON_NONE is used for older
2153 // preferences files that will not have set this field but it was previously
2154 // only used for idle updates.
2155 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
2156 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
2157 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
2160 const Extension* extension = delayed_installs_.GetByID(extension_id);
2161 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
2162 ImportStatus status = SatisfyImports(extension);
2163 if (status != IMPORT_STATUS_OK) {
2164 if (status == IMPORT_STATUS_UNRECOVERABLE) {
2165 delayed_installs_.Remove(extension_id);
2166 // Make sure no version of the extension is actually installed, (i.e.,
2167 // that this delayed install was not an update).
2168 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
2169 extension_prefs_->DeleteExtensionPrefs(extension_id);
2175 FinishDelayedInstallation(extension_id);
2178 void ExtensionService::FinishDelayedInstallation(
2179 const std::string& extension_id) {
2180 scoped_refptr<const Extension> extension(
2181 GetPendingExtensionUpdate(extension_id));
2182 CHECK(extension.get());
2183 delayed_installs_.Remove(extension_id);
2185 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
2188 FinishInstallation(extension.get());
2191 void ExtensionService::FinishInstallation(const Extension* extension) {
2192 const extensions::Extension* existing_extension =
2193 GetInstalledExtension(extension->id());
2194 bool is_update = false;
2195 std::string old_name;
2196 if (existing_extension) {
2198 old_name = existing_extension->name();
2200 extensions::InstalledExtensionInfo details(extension, is_update, old_name);
2201 content::NotificationService::current()->Notify(
2202 chrome::NOTIFICATION_EXTENSION_INSTALLED,
2203 content::Source<Profile>(profile_),
2204 content::Details<const extensions::InstalledExtensionInfo>(&details));
2206 bool unacknowledged_external = IsUnacknowledgedExternalExtension(extension);
2208 // Unpacked extensions default to allowing file access, but if that has been
2209 // overridden, don't reset the value.
2210 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
2211 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
2212 extension_prefs_->SetAllowFileAccess(extension->id(), true);
2215 AddExtension(extension);
2217 // If this is a new external extension that was disabled, alert the user
2218 // so he can reenable it. We do this last so that it has already been
2219 // added to our list of extensions.
2220 if (unacknowledged_external && !is_update) {
2221 UpdateExternalExtensionAlert();
2222 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
2223 EXTERNAL_EXTENSION_INSTALLED,
2224 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
2225 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
2226 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
2227 EXTERNAL_EXTENSION_INSTALLED,
2228 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
2230 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
2231 EXTERNAL_EXTENSION_INSTALLED,
2232 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
2236 // Check extensions that may have been delayed only because this shared module
2237 // was not available.
2238 if (SharedModuleInfo::IsSharedModule(extension)) {
2239 MaybeFinishDelayedInstallations();
2243 const Extension* ExtensionService::GetPendingExtensionUpdate(
2244 const std::string& id) const {
2245 return delayed_installs_.GetByID(id);
2248 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
2249 // No need to check for duplicates; inserting a duplicate is a no-op.
2250 registry_->AddTerminated(make_scoped_refptr(extension));
2251 extensions_being_terminated_.erase(extension->id());
2252 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2255 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2256 std::string lowercase_id = StringToLowerASCII(id);
2257 const Extension* extension =
2258 registry_->terminated_extensions().GetByID(lowercase_id);
2259 registry_->RemoveTerminated(lowercase_id);
2261 content::NotificationService::current()->Notify(
2262 chrome::NOTIFICATION_EXTENSION_REMOVED,
2263 content::Source<Profile>(profile_),
2264 content::Details<const Extension>(extension));
2268 const Extension* ExtensionService::GetInstalledExtension(
2269 const std::string& id) const {
2270 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2273 bool ExtensionService::ExtensionBindingsAllowed(const GURL& url) {
2274 // Allow bindings for all packaged extensions and component hosted apps.
2275 const Extension* extension =
2276 registry_->enabled_extensions().GetExtensionOrAppByURL(url);
2277 return extension && (!extension->is_hosted_app() ||
2278 extension->location() == Manifest::COMPONENT);
2281 bool ExtensionService::OnExternalExtensionFileFound(
2282 const std::string& id,
2283 const Version* version,
2284 const base::FilePath& path,
2285 Manifest::Location location,
2287 bool mark_acknowledged) {
2288 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2289 CHECK(Extension::IdIsValid(id));
2290 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2293 // Before even bothering to unpack, check and see if we already have this
2294 // version. This is important because these extensions are going to get
2295 // installed on every startup.
2296 const Extension* existing = GetExtensionById(id, true);
2299 // The default apps will have the location set as INTERNAL. Since older
2300 // default apps are installed as EXTERNAL, we override them. However, if the
2301 // app is already installed as internal, then do the version check.
2302 // TODO(grv) : Remove after Q1-2013.
2303 bool is_default_apps_migration =
2304 (location == Manifest::INTERNAL &&
2305 Manifest::IsExternalLocation(existing->location()));
2307 if (!is_default_apps_migration) {
2310 switch (existing->version()->CompareTo(*version)) {
2311 case -1: // existing version is older, we should upgrade
2313 case 0: // existing version is same, do nothing
2315 case 1: // existing version is newer, uh-oh
2316 LOG(WARNING) << "Found external version of extension " << id
2317 << "that is older than current version. Current version "
2318 << "is: " << existing->VersionString() << ". New "
2319 << "version is: " << version->GetString()
2320 << ". Keeping current version.";
2326 // If the extension is already pending, don't start an install.
2327 if (!pending_extension_manager()->AddFromExternalFile(
2328 id, location, *version, creation_flags, mark_acknowledged)) {
2332 // no client (silent install)
2333 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2334 installer->set_install_source(location);
2335 installer->set_expected_id(id);
2336 installer->set_expected_version(*version);
2337 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2338 installer->set_creation_flags(creation_flags);
2339 #if defined(OS_CHROMEOS)
2340 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2342 installer->InstallCrx(path);
2345 // Depending on the source, a new external extension might not need a user
2346 // notification on installation. For such extensions, mark them acknowledged
2347 // now to suppress the notification.
2348 if (mark_acknowledged)
2349 AcknowledgeExternalExtension(id);
2354 void ExtensionService::ReportExtensionLoadError(
2355 const base::FilePath& extension_path,
2356 const std::string &error,
2358 content::NotificationService::current()->Notify(
2359 chrome::NOTIFICATION_EXTENSION_LOAD_ERROR,
2360 content::Source<Profile>(profile_),
2361 content::Details<const std::string>(&error));
2363 std::string path_str = base::UTF16ToUTF8(extension_path.LossyDisplayName());
2365 std::string retry_prompt;
2367 retry_prompt = "\n\nWould you like to retry?";
2369 base::string16 message = base::UTF8ToUTF16(
2370 base::StringPrintf("Could not load extension from '%s'. %s%s",
2373 retry_prompt.c_str()));
2374 ExtensionErrorReporter::GetInstance()->ReportError(message, be_noisy, &retry);
2375 std::pair<bool, const base::FilePath&> details(retry, extension_path);
2376 content::NotificationService::current()->Notify(
2377 chrome::NOTIFICATION_EXTENSION_LOAD_RETRY,
2378 content::Source<Profile>(profile_),
2379 content::Details<std::pair<bool, const base::FilePath&> >(&details));
2382 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2383 extensions::ExtensionHost* host) {
2384 OrphanedDevTools::iterator iter =
2385 orphaned_dev_tools_.find(host->extension_id());
2386 if (iter == orphaned_dev_tools_.end())
2389 iter->second->ConnectRenderViewHost(host->render_view_host());
2390 orphaned_dev_tools_.erase(iter);
2393 void ExtensionService::Observe(int type,
2394 const content::NotificationSource& source,
2395 const content::NotificationDetails& details) {
2397 case chrome::NOTIFICATION_APP_TERMINATING:
2398 // Shutdown has started. Don't start any more extension installs.
2399 // (We cannot use ExtensionService::Shutdown() for this because it
2400 // happens too late in browser teardown.)
2401 browser_terminating_ = true;
2403 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2405 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2409 extensions::ExtensionHost* host =
2410 content::Details<extensions::ExtensionHost>(details).ptr();
2412 // If the extension is already being terminated, there is nothing left to
2414 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2417 // Mark the extension as terminated and Unload it. We want it to
2418 // be in a consistent state: either fully working or not loaded
2419 // at all, but never half-crashed. We do it in a PostTask so
2420 // that other handlers of this notification will still have
2421 // access to the Extension and ExtensionHost.
2422 base::MessageLoop::current()->PostTask(
2425 &ExtensionService::TrackTerminatedExtension,
2427 host->extension()));
2430 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2431 content::RenderProcessHost* process =
2432 content::Source<content::RenderProcessHost>(source).ptr();
2433 Profile* host_profile =
2434 Profile::FromBrowserContext(process->GetBrowserContext());
2435 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2438 extensions::ProcessMap* process_map =
2439 extensions::ProcessMap::Get(profile_);
2440 if (process_map->Contains(process->GetID())) {
2441 // An extension process was terminated, this might have resulted in an
2442 // app or extension becoming idle.
2443 std::set<std::string> extension_ids =
2444 process_map->GetExtensionsInProcess(process->GetID());
2445 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2446 it != extension_ids.end(); ++it) {
2447 if (delayed_installs_.Contains(*it)) {
2448 base::MessageLoop::current()->PostDelayedTask(
2450 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2452 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2457 process_map->RemoveAllFromProcess(process->GetID());
2458 BrowserThread::PostTask(
2461 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2462 system_->info_map(),
2466 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2467 // Notify observers that chrome update is available.
2468 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2469 OnChromeUpdateAvailable());
2474 NOTREACHED() << "Unexpected notification type.";
2478 void ExtensionService::OnExtensionInstallPrefChanged() {
2479 IdentifyAlertableExtensions();
2480 CheckManagementPolicy();
2483 bool ExtensionService::IsBeingReloaded(
2484 const std::string& extension_id) const {
2485 return ContainsKey(extensions_being_reloaded_, extension_id);
2488 void ExtensionService::SetBeingReloaded(const std::string& extension_id,
2489 bool isBeingReloaded) {
2490 if (isBeingReloaded)
2491 extensions_being_reloaded_.insert(extension_id);
2493 extensions_being_reloaded_.erase(extension_id);
2496 bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) {
2497 // Extensions installed by policy can't be disabled. So even if a previous
2498 // installation disabled the extension, make sure it is now enabled.
2499 // TODO(rlp): Clean up the special case for external components as noted
2500 // in crbug.com/353266. For now, EXTERNAL_COMPONENT apps should be
2501 // default enabled on install as before.
2502 if (system_->management_policy()->MustRemainEnabled(extension, NULL) ||
2503 extension->location() == Manifest::EXTERNAL_COMPONENT) {
2507 if (extension_prefs_->IsExtensionDisabled(extension->id()))
2510 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2511 // External extensions are initially disabled. We prompt the user before
2512 // enabling them. Hosted apps are excepted because they are not dangerous
2513 // (they need to be launched by the user anyway).
2514 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2515 Manifest::IsExternalLocation(extension->location()) &&
2516 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2524 bool ExtensionService::ShouldDelayExtensionUpdate(
2525 const std::string& extension_id,
2526 bool wait_for_idle) const {
2527 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2529 // If delayed updates are globally disabled, or just for this extension,
2531 if (!install_updates_when_idle_ || !wait_for_idle)
2534 const Extension* old = GetInstalledExtension(extension_id);
2535 // If there is no old extension, this is not an update, so don't delay.
2539 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2540 // Delay installation if the extension listens for the onUpdateAvailable
2542 return system_->event_router()->ExtensionHasEventListener(
2543 extension_id, kOnUpdateAvailableEvent);
2545 // Delay installation if the extension is not idle.
2546 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2550 void ExtensionService::GarbageCollectIsolatedStorage() {
2551 scoped_ptr<base::hash_set<base::FilePath> > active_paths(
2552 new base::hash_set<base::FilePath>());
2553 const ExtensionSet& extensions = registry_->enabled_extensions();
2554 for (ExtensionSet::const_iterator it = extensions.begin();
2555 it != extensions.end(); ++it) {
2556 if (extensions::AppIsolationInfo::HasIsolatedStorage(it->get())) {
2557 active_paths->insert(BrowserContext::GetStoragePartitionForSite(
2559 extensions::util::GetSiteForExtensionId(
2560 (*it)->id(), profile()))->GetPath());
2564 // The data of ephemeral apps can outlive their cache lifetime. Ensure
2565 // they are not garbage collected.
2566 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> evicted_apps_info(
2567 extension_prefs_->GetEvictedEphemeralAppsInfo());
2568 for (size_t i = 0; i < evicted_apps_info->size(); ++i) {
2569 extensions::ExtensionInfo* info = evicted_apps_info->at(i).get();
2570 if (extensions::util::HasIsolatedStorage(*info)) {
2571 active_paths->insert(BrowserContext::GetStoragePartitionForSite(
2573 extensions::util::GetSiteForExtensionId(
2574 info->extension_id, profile()))->GetPath());
2578 DCHECK(!installs_delayed_for_gc());
2579 set_installs_delayed_for_gc(true);
2580 BrowserContext::GarbageCollectStoragePartitions(
2581 profile_, active_paths.Pass(),
2582 base::Bind(&ExtensionService::OnGarbageCollectIsolatedStorageFinished,
2586 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2587 set_installs_delayed_for_gc(false);
2588 MaybeFinishDelayedInstallations();
2591 void ExtensionService::MaybeFinishDelayedInstallations() {
2592 std::vector<std::string> to_be_installed;
2593 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2594 it != delayed_installs_.end();
2596 to_be_installed.push_back((*it)->id());
2598 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2599 it != to_be_installed.end();
2601 MaybeFinishDelayedInstallation(*it);
2605 void ExtensionService::OnBlacklistUpdated() {
2606 blacklist_->GetBlacklistedIDs(
2607 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2608 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2611 void ExtensionService::ManageBlacklist(
2612 const extensions::Blacklist::BlacklistStateMap& state_map) {
2613 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2615 std::set<std::string> blocked;
2616 ExtensionIdSet greylist;
2617 ExtensionIdSet unchanged;
2618 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2620 it != state_map.end();
2622 switch (it->second) {
2623 case extensions::NOT_BLACKLISTED:
2626 case extensions::BLACKLISTED_MALWARE:
2627 blocked.insert(it->first);
2630 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2631 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2632 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2633 greylist.insert(it->first);
2636 case extensions::BLACKLISTED_UNKNOWN:
2637 unchanged.insert(it->first);
2642 UpdateBlockedExtensions(blocked, unchanged);
2643 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2645 IdentifyAlertableExtensions();
2649 void Partition(const ExtensionIdSet& before,
2650 const ExtensionIdSet& after,
2651 const ExtensionIdSet& unchanged,
2652 ExtensionIdSet* no_longer,
2653 ExtensionIdSet* not_yet) {
2654 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2655 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2656 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2660 void ExtensionService::UpdateBlockedExtensions(
2661 const ExtensionIdSet& blocked,
2662 const ExtensionIdSet& unchanged) {
2663 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2664 Partition(registry_->blacklisted_extensions().GetIDs(),
2666 &no_longer_blocked, ¬_yet_blocked);
2668 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2669 it != no_longer_blocked.end(); ++it) {
2670 scoped_refptr<const Extension> extension =
2671 registry_->blacklisted_extensions().GetByID(*it);
2672 if (!extension.get()) {
2673 NOTREACHED() << "Extension " << *it << " no longer blocked, "
2674 << "but it was never blocked.";
2677 registry_->RemoveBlacklisted(*it);
2678 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2679 AddExtension(extension.get());
2680 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2681 extension->location(),
2682 Manifest::NUM_LOCATIONS);
2685 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2686 it != not_yet_blocked.end(); ++it) {
2687 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2688 if (!extension.get()) {
2689 NOTREACHED() << "Extension " << *it << " needs to be "
2690 << "blacklisted, but it's not installed.";
2693 registry_->AddBlacklisted(extension);
2694 extension_prefs_->SetExtensionBlacklistState(
2695 extension->id(), extensions::BLACKLISTED_MALWARE);
2696 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2697 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2698 extension->location(), Manifest::NUM_LOCATIONS);
2702 // TODO(oleg): UMA logging
2703 void ExtensionService::UpdateGreylistedExtensions(
2704 const ExtensionIdSet& greylist,
2705 const ExtensionIdSet& unchanged,
2706 const extensions::Blacklist::BlacklistStateMap& state_map) {
2707 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2708 Partition(greylist_.GetIDs(),
2709 greylist, unchanged,
2710 &no_longer_greylisted, ¬_yet_greylisted);
2712 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2713 it != no_longer_greylisted.end(); ++it) {
2714 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2715 if (!extension.get()) {
2716 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2717 << "but it was not marked as greylisted.";
2721 greylist_.Remove(*it);
2722 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2723 extensions::NOT_BLACKLISTED);
2724 if (extension_prefs_->GetDisableReasons(extension->id()) &
2725 extensions::Extension::DISABLE_GREYLIST)
2726 EnableExtension(*it);
2729 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2730 it != not_yet_greylisted.end(); ++it) {
2731 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2732 if (!extension.get()) {
2733 NOTREACHED() << "Extension " << *it << " needs to be "
2734 << "disabled, but it's not installed.";
2737 greylist_.Insert(extension);
2738 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2739 state_map.find(*it)->second);
2740 if (registry_->enabled_extensions().Contains(extension->id()))
2741 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2745 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2746 update_observers_.AddObserver(observer);
2749 void ExtensionService::RemoveUpdateObserver(
2750 extensions::UpdateObserver* observer) {
2751 update_observers_.RemoveObserver(observer);
2754 // Used only by test code.
2755 void ExtensionService::UnloadAllExtensionsInternal() {
2756 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2758 registry_->ClearAll();
2759 system_->runtime_data()->ClearAll();
2761 // TODO(erikkay) should there be a notification for this? We can't use
2762 // EXTENSION_UNLOADED since that implies that the extension has been disabled