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/command_line.h"
12 #include "base/metrics/histogram.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/content_settings/content_settings_custom_extension_provider.h"
22 #include "chrome/browser/content_settings/content_settings_internal_extension_provider.h"
23 #include "chrome/browser/extensions/api/content_settings/content_settings_service.h"
24 #include "chrome/browser/extensions/component_loader.h"
25 #include "chrome/browser/extensions/crx_installer.h"
26 #include "chrome/browser/extensions/data_deleter.h"
27 #include "chrome/browser/extensions/extension_action_storage_manager.h"
28 #include "chrome/browser/extensions/extension_assets_manager.h"
29 #include "chrome/browser/extensions/extension_disabled_ui.h"
30 #include "chrome/browser/extensions/extension_error_controller.h"
31 #include "chrome/browser/extensions/extension_special_storage_policy.h"
32 #include "chrome/browser/extensions/extension_sync_service.h"
33 #include "chrome/browser/extensions/extension_util.h"
34 #include "chrome/browser/extensions/external_install_manager.h"
35 #include "chrome/browser/extensions/external_provider_impl.h"
36 #include "chrome/browser/extensions/install_verifier.h"
37 #include "chrome/browser/extensions/installed_loader.h"
38 #include "chrome/browser/extensions/pending_extension_manager.h"
39 #include "chrome/browser/extensions/permissions_updater.h"
40 #include "chrome/browser/extensions/shared_module_service.h"
41 #include "chrome/browser/extensions/unpacked_installer.h"
42 #include "chrome/browser/extensions/updater/chrome_extension_downloader_factory.h"
43 #include "chrome/browser/extensions/updater/extension_updater.h"
44 #include "chrome/browser/google/google_brand.h"
45 #include "chrome/browser/profiles/profile.h"
46 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
47 #include "chrome/browser/ui/webui/favicon_source.h"
48 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
49 #include "chrome/browser/ui/webui/theme_source.h"
50 #include "chrome/common/chrome_switches.h"
51 #include "chrome/common/crash_keys.h"
52 #include "chrome/common/extensions/extension_constants.h"
53 #include "chrome/common/extensions/features/feature_channel.h"
54 #include "chrome/common/url_constants.h"
55 #include "components/content_settings/core/browser/host_content_settings_map.h"
56 #include "components/crx_file/id_util.h"
57 #include "components/startup_metric_utils/startup_metric_utils.h"
58 #include "content/public/browser/devtools_agent_host.h"
59 #include "content/public/browser/notification_service.h"
60 #include "content/public/browser/render_process_host.h"
61 #include "content/public/browser/storage_partition.h"
62 #include "extensions/browser/event_router.h"
63 #include "extensions/browser/extension_host.h"
64 #include "extensions/browser/extension_prefs.h"
65 #include "extensions/browser/extension_registry.h"
66 #include "extensions/browser/extension_system.h"
67 #include "extensions/browser/extensions_browser_client.h"
68 #include "extensions/browser/install_flag.h"
69 #include "extensions/browser/runtime_data.h"
70 #include "extensions/browser/uninstall_reason.h"
71 #include "extensions/browser/update_observer.h"
72 #include "extensions/browser/updater/extension_cache.h"
73 #include "extensions/browser/updater/extension_downloader.h"
74 #include "extensions/common/extension_messages.h"
75 #include "extensions/common/extension_urls.h"
76 #include "extensions/common/feature_switch.h"
77 #include "extensions/common/file_util.h"
78 #include "extensions/common/manifest_constants.h"
79 #include "extensions/common/manifest_handlers/background_info.h"
80 #include "extensions/common/manifest_url_handlers.h"
81 #include "extensions/common/one_shot_event.h"
82 #include "extensions/common/permissions/permission_message_provider.h"
83 #include "extensions/common/permissions/permissions_data.h"
85 #if defined(OS_CHROMEOS)
86 #include "chrome/browser/chromeos/extensions/install_limiter.h"
87 #include "storage/browser/fileapi/file_system_backend.h"
88 #include "storage/browser/fileapi/file_system_context.h"
91 using content::BrowserContext;
92 using content::BrowserThread;
93 using content::DevToolsAgentHost;
94 using extensions::CrxInstaller;
95 using extensions::Extension;
96 using extensions::ExtensionIdSet;
97 using extensions::ExtensionInfo;
98 using extensions::ExtensionRegistry;
99 using extensions::ExtensionSet;
100 using extensions::FeatureSwitch;
101 using extensions::InstallVerifier;
102 using extensions::ManagementPolicy;
103 using extensions::Manifest;
104 using extensions::PermissionMessage;
105 using extensions::PermissionMessages;
106 using extensions::PermissionSet;
107 using extensions::SharedModuleInfo;
108 using extensions::SharedModuleService;
109 using extensions::UnloadedExtensionInfo;
111 namespace errors = extensions::manifest_errors;
115 // Wait this many seconds after an extensions becomes idle before updating it.
116 const int kUpdateIdleDelay = 5;
122 void ExtensionService::CheckExternalUninstall(const std::string& id) {
123 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
125 // Check if the providers know about this extension.
126 extensions::ProviderCollection::const_iterator i;
127 for (i = external_extension_providers_.begin();
128 i != external_extension_providers_.end(); ++i) {
129 DCHECK(i->get()->IsReady());
130 if (i->get()->HasExtension(id))
131 return; // Yup, known extension, don't uninstall.
134 // We get the list of external extensions to check from preferences.
135 // It is possible that an extension has preferences but is not loaded.
136 // For example, an extension that requires experimental permissions
137 // will not be loaded if the experimental command line flag is not used.
138 // In this case, do not uninstall.
139 if (!GetInstalledExtension(id)) {
140 // We can't call UninstallExtension with an unloaded/invalid
142 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
143 << "with id: " << id;
146 UninstallExtension(id,
147 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
148 base::Bind(&base::DoNothing),
152 void ExtensionService::SetFileTaskRunnerForTesting(
153 const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
154 file_task_runner_ = task_runner;
157 void ExtensionService::ClearProvidersForTesting() {
158 external_extension_providers_.clear();
161 void ExtensionService::AddProviderForTesting(
162 extensions::ExternalProviderInterface* test_provider) {
163 CHECK(test_provider);
164 external_extension_providers_.push_back(
165 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
168 void ExtensionService::BlacklistExtensionForTest(
169 const std::string& extension_id) {
170 ExtensionIdSet blocked;
171 ExtensionIdSet unchanged;
172 blocked.insert(extension_id);
173 UpdateBlockedExtensions(blocked, unchanged);
176 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
177 const std::string& id,
178 const std::string& install_parameter,
179 const GURL& update_url,
180 Manifest::Location location,
182 bool mark_acknowledged) {
183 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
184 CHECK(crx_file::id_util::IdIsValid(id));
186 if (Manifest::IsExternalLocation(location)) {
187 // All extensions that are not user specific can be cached.
188 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
192 const Extension* extension = GetExtensionById(id, true);
194 // Already installed. Skip this install if the current location has
195 // higher priority than |location|.
196 Manifest::Location current = extension->location();
197 if (current == Manifest::GetHigherPriorityLocation(current, location))
199 // Otherwise, overwrite the current installation.
202 // Add |id| to the set of pending extensions. If it can not be added,
203 // then there is already a pending record from a higher-priority install
204 // source. In this case, signal that this extension will not be
205 // installed by returning false.
206 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
212 mark_acknowledged)) {
216 update_once_all_providers_are_ready_ = true;
221 // This function is used to uninstall an extension via sync. The LOG statements
222 // within this function are used to inform the user if the uninstall cannot be
224 bool ExtensionService::UninstallExtensionHelper(
225 ExtensionService* extensions_service,
226 const std::string& extension_id,
227 extensions::UninstallReason reason) {
228 // We can't call UninstallExtension with an invalid extension ID.
229 if (!extensions_service->GetInstalledExtension(extension_id)) {
230 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
231 << "id: " << extension_id;
235 // The following call to UninstallExtension will not allow an uninstall of a
236 // policy-controlled extension.
237 base::string16 error;
238 if (!extensions_service->UninstallExtension(
239 extension_id, reason, base::Bind(&base::DoNothing), &error)) {
240 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
248 ExtensionService::ExtensionService(Profile* profile,
249 const CommandLine* command_line,
250 const base::FilePath& install_directory,
251 extensions::ExtensionPrefs* extension_prefs,
252 extensions::Blacklist* blacklist,
253 bool autoupdate_enabled,
254 bool extensions_enabled,
255 extensions::OneShotEvent* ready)
256 : extensions::Blacklist::Observer(blacklist),
258 system_(extensions::ExtensionSystem::Get(profile)),
259 extension_prefs_(extension_prefs),
260 blacklist_(blacklist),
261 extension_sync_service_(NULL),
262 registry_(extensions::ExtensionRegistry::Get(profile)),
263 pending_extension_manager_(profile),
264 install_directory_(install_directory),
265 extensions_enabled_(extensions_enabled),
266 show_extensions_prompts_(true),
267 install_updates_when_idle_(true),
269 update_once_all_providers_are_ready_(false),
270 browser_terminating_(false),
271 installs_delayed_for_gc_(false),
272 is_first_run_(false),
273 shared_module_service_(new extensions::SharedModuleService(profile_)) {
274 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
276 // Figure out if extension installation should be enabled.
277 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
278 *command_line, profile))
279 extensions_enabled_ = false;
281 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
282 content::NotificationService::AllBrowserContextsAndSources());
284 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
285 content::NotificationService::AllBrowserContextsAndSources());
286 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
287 content::NotificationService::AllBrowserContextsAndSources());
288 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
289 content::NotificationService::AllBrowserContextsAndSources());
291 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
292 content::Source<Profile>(profile_));
294 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
297 // Set up the ExtensionUpdater
298 if (autoupdate_enabled) {
299 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
300 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
301 base::StringToInt(command_line->GetSwitchValueASCII(
302 switches::kExtensionsUpdateFrequency),
305 updater_.reset(new extensions::ExtensionUpdater(
311 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
312 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
316 component_loader_.reset(
317 new extensions::ComponentLoader(this,
319 g_browser_process->local_state(),
322 if (extensions_enabled_) {
323 extensions::ExternalProviderImpl::CreateExternalProviders(
324 this, profile_, &external_extension_providers_);
327 // Set this as the ExtensionService for app sorting to ensure it causes syncs
329 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
331 error_controller_.reset(
332 new extensions::ExtensionErrorController(profile_, is_first_run_));
333 external_install_manager_.reset(
334 new extensions::ExternalInstallManager(profile_, is_first_run_));
336 extension_action_storage_manager_.reset(
337 new extensions::ExtensionActionStorageManager(profile_));
339 // How long is the path to the Extensions directory?
340 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
341 install_directory_.value().length(), 0, 500, 100);
344 const ExtensionSet* ExtensionService::extensions() const {
345 return ®istry_->enabled_extensions();
348 extensions::PendingExtensionManager*
349 ExtensionService::pending_extension_manager() {
350 return &pending_extension_manager_;
353 ExtensionService::~ExtensionService() {
354 // No need to unload extensions here because they are profile-scoped, and the
355 // profile is in the process of being deleted.
357 extensions::ProviderCollection::const_iterator i;
358 for (i = external_extension_providers_.begin();
359 i != external_extension_providers_.end(); ++i) {
360 extensions::ExternalProviderInterface* provider = i->get();
361 provider->ServiceShutdown();
365 void ExtensionService::Shutdown() {
366 extensions::ExtensionManagementFactory::GetInstance()
367 ->GetForBrowserContext(profile())
368 ->RemoveObserver(this);
369 system_->management_policy()->UnregisterProvider(
370 shared_module_policy_provider_.get());
373 const Extension* ExtensionService::GetExtensionById(
374 const std::string& id, bool include_disabled) const {
375 int include_mask = ExtensionRegistry::ENABLED;
376 if (include_disabled) {
377 // Include blacklisted extensions here because there are hundreds of
378 // callers of this function, and many might assume that this includes those
379 // that have been disabled due to blacklisting.
380 include_mask |= ExtensionRegistry::DISABLED |
381 ExtensionRegistry::BLACKLISTED;
383 return registry_->GetExtensionById(id, include_mask);
386 void ExtensionService::Init() {
387 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
389 base::Time begin_time = base::Time::Now();
391 DCHECK(!is_ready()); // Can't redo init.
392 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
394 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
395 if (cmd_line->HasSwitch(switches::kInstallEphemeralAppFromWebstore)) {
396 // The sole purpose of this launch is to install a new extension from CWS
397 // and immediately terminate: loading already installed extensions is
398 // unnecessary and may interfere with the inline install dialog (e.g. if an
399 // extension listens to onStartup and opens a window).
400 SetReadyAndNotifyListeners();
402 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
403 component_loader_->LoadAll();
404 extensions::InstalledLoader(this).LoadAllExtensions();
406 // Attempt to re-enable extensions whose only disable reason is reloading.
407 std::vector<std::string> extensions_to_enable;
408 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
409 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
410 iter != disabled_extensions.end(); ++iter) {
411 const Extension* e = iter->get();
412 if (extension_prefs_->GetDisableReasons(e->id()) ==
413 Extension::DISABLE_RELOAD) {
414 extensions_to_enable.push_back(e->id());
417 for (std::vector<std::string>::iterator it = extensions_to_enable.begin();
418 it != extensions_to_enable.end(); ++it) {
419 EnableExtension(*it);
422 // Finish install (if possible) of extensions that were still delayed while
423 // the browser was shut down.
424 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
425 extension_prefs_->GetAllDelayedInstallInfo());
426 for (size_t i = 0; i < delayed_info->size(); ++i) {
427 ExtensionInfo* info = delayed_info->at(i).get();
428 scoped_refptr<const Extension> extension(NULL);
429 if (info->extension_manifest) {
431 extension = Extension::Create(
432 info->extension_path,
433 info->extension_location,
434 *info->extension_manifest,
435 extension_prefs_->GetDelayedInstallCreationFlags(
440 delayed_installs_.Insert(extension);
443 MaybeFinishDelayedInstallations();
445 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
446 extension_prefs_->GetAllDelayedInstallInfo());
447 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
448 delayed_info2->size() - delayed_info->size());
450 SetReadyAndNotifyListeners();
452 // TODO(erikkay) this should probably be deferred to a future point
453 // rather than running immediately at startup.
454 CheckForExternalUpdates();
456 LoadGreylistFromPrefs();
459 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
460 base::Time::Now() - begin_time);
463 void ExtensionService::LoadGreylistFromPrefs() {
464 scoped_ptr<ExtensionSet> all_extensions =
465 registry_->GenerateInstalledExtensionsSet();
467 for (ExtensionSet::const_iterator it = all_extensions->begin();
468 it != all_extensions->end(); ++it) {
469 extensions::BlacklistState state =
470 extension_prefs_->GetExtensionBlacklistState((*it)->id());
471 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
472 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
473 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
474 greylist_.Insert(*it);
478 bool ExtensionService::UpdateExtension(const std::string& id,
479 const base::FilePath& extension_path,
480 bool file_ownership_passed,
481 CrxInstaller** out_crx_installer) {
482 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
483 if (browser_terminating_) {
484 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
485 // Leak the temp file at extension_path. We don't want to add to the disk
486 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
487 // the file is in the OS temp directory which should be cleaned up for us.
491 const extensions::PendingExtensionInfo* pending_extension_info =
492 pending_extension_manager()->GetById(id);
494 const Extension* extension = GetInstalledExtension(id);
495 if (!pending_extension_info && !extension) {
496 LOG(WARNING) << "Will not update extension " << id
497 << " because it is not installed or pending";
498 // Delete extension_path since we're not creating a CrxInstaller
499 // that would do it for us.
500 if (!GetFileTaskRunner()->PostTask(
503 &extensions::file_util::DeleteFile, extension_path, false)))
509 scoped_refptr<CrxInstaller> installer(
510 CrxInstaller::Create(this, scoped_ptr<ExtensionInstallPrompt>()));
511 installer->set_expected_id(id);
512 int creation_flags = Extension::NO_FLAGS;
513 if (pending_extension_info) {
514 installer->set_install_source(pending_extension_info->install_source());
515 installer->set_allow_silent_install(true);
516 if (pending_extension_info->remote_install())
517 installer->set_grant_permissions(false);
518 creation_flags = pending_extension_info->creation_flags();
519 if (pending_extension_info->mark_acknowledged())
520 external_install_manager_->AcknowledgeExternalExtension(id);
521 } else if (extension) {
522 installer->set_install_source(extension->location());
524 // If the extension was installed from or has migrated to the webstore, or
525 // its auto-update URL is from the webstore, treat it as a webstore install.
526 // Note that we ignore some older extensions with blank auto-update URLs
527 // because we are mostly concerned with restrictions on NaCl extensions,
529 if ((extension && extension->from_webstore()) ||
530 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
531 (!extension && extension_urls::IsWebstoreUpdateUrl(
532 pending_extension_info->update_url()))) {
533 creation_flags |= Extension::FROM_WEBSTORE;
536 // Bookmark apps being updated is kind of a contradiction, but that's because
537 // we mark the default apps as bookmark apps, and they're hosted in the web
538 // store, thus they can get updated. See http://crbug.com/101605 for more
540 if (extension && extension->from_bookmark())
541 creation_flags |= Extension::FROM_BOOKMARK;
543 if (extension && extension->was_installed_by_default())
544 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
546 if (extension && extension->was_installed_by_oem())
547 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
549 if (extension && extension->was_installed_by_custodian())
550 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
553 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
554 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
557 installer->set_creation_flags(creation_flags);
559 installer->set_delete_source(file_ownership_passed);
560 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
561 installer->InstallCrx(extension_path);
563 if (out_crx_installer)
564 *out_crx_installer = installer.get();
569 void ExtensionService::ReloadExtensionImpl(
570 // "transient" because the process of reloading may cause the reference
571 // to become invalid. Instead, use |extension_id|, a copy.
572 const std::string& transient_extension_id,
574 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
576 // If the extension is already reloading, don't reload again.
577 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
578 Extension::DISABLE_RELOAD) {
582 // Ignore attempts to reload a blacklisted extension. Sometimes this can
583 // happen in a convoluted reload sequence triggered by the termination of a
584 // blacklisted extension and a naive attempt to reload it. For an example see
585 // http://crbug.com/373842.
586 if (registry_->blacklisted_extensions().Contains(transient_extension_id))
591 std::string extension_id = transient_extension_id;
592 const Extension* transient_current_extension =
593 GetExtensionById(extension_id, false);
595 // Disable the extension if it's loaded. It might not be loaded if it crashed.
596 if (transient_current_extension) {
597 // If the extension has an inspector open for its background page, detach
598 // the inspector and hang onto a cookie for it, so that we can reattach
600 // TODO(yoz): this is not incognito-safe!
601 extensions::ProcessManager* manager =
602 extensions::ProcessManager::Get(profile_);
603 extensions::ExtensionHost* host =
604 manager->GetBackgroundHostForExtension(extension_id);
605 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
606 // Look for an open inspector for the background page.
607 scoped_refptr<DevToolsAgentHost> agent_host =
608 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
609 agent_host->DisconnectWebContents();
610 orphaned_dev_tools_[extension_id] = agent_host;
613 path = transient_current_extension->path();
614 // BeingUpgraded is set back to false when the extension is added.
615 system_->runtime_data()->SetBeingUpgraded(transient_current_extension,
617 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
618 reloading_extensions_.insert(extension_id);
620 std::map<std::string, base::FilePath>::const_iterator iter =
621 unloaded_extension_paths_.find(extension_id);
622 if (iter == unloaded_extension_paths_.end()) {
625 path = unloaded_extension_paths_[extension_id];
628 transient_current_extension = NULL;
630 if (delayed_installs_.Contains(extension_id)) {
631 FinishDelayedInstallation(extension_id);
635 // If we're reloading a component extension, use the component extension
636 // loader's reloader.
637 if (component_loader_->Exists(extension_id)) {
638 component_loader_->Reload(extension_id);
642 // Check the installed extensions to see if what we're reloading was already
644 scoped_ptr<ExtensionInfo> installed_extension(
645 extension_prefs_->GetInstalledExtensionInfo(extension_id));
646 if (installed_extension.get() &&
647 installed_extension->extension_manifest.get()) {
648 extensions::InstalledLoader(this).Load(*installed_extension, false);
650 // Otherwise, the extension is unpacked (location LOAD).
651 // We should always be able to remember the extension's path. If it's not in
652 // the map, someone failed to update |unloaded_extension_paths_|.
653 CHECK(!path.empty());
654 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
655 extensions::UnpackedInstaller::Create(this);
656 unpacked_installer->set_be_noisy_on_failure(be_noisy);
657 unpacked_installer->Load(path);
661 void ExtensionService::ReloadExtension(const std::string& extension_id) {
662 ReloadExtensionImpl(extension_id, true); // be_noisy
665 void ExtensionService::ReloadExtensionWithQuietFailure(
666 const std::string& extension_id) {
667 ReloadExtensionImpl(extension_id, false); // be_noisy
670 bool ExtensionService::UninstallExtension(
671 // "transient" because the process of uninstalling may cause the reference
672 // to become invalid. Instead, use |extenson->id()|.
673 const std::string& transient_extension_id,
674 extensions::UninstallReason reason,
675 const base::Closure& deletion_done_callback,
676 base::string16* error) {
677 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
679 scoped_refptr<const Extension> extension =
680 GetInstalledExtension(transient_extension_id);
682 // Callers should not send us nonexistent extensions.
683 CHECK(extension.get());
685 ManagementPolicy* by_policy = system_->management_policy();
686 // Policy change which triggers an uninstall will always set
687 // |external_uninstall| to true so this is the only way to uninstall
688 // managed extensions.
689 // Shared modules being uninstalled will also set |external_uninstall| to true
690 // so that we can guarantee users don't uninstall a shared module.
691 // (crbug.com/273300)
692 // TODO(rdevlin.cronin): This is probably not right. We should do something
693 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
695 bool external_uninstall =
696 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
697 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
698 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
699 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
700 (reason == extensions::UNINSTALL_REASON_SYNC &&
701 extension->was_installed_by_custodian());
702 if (!external_uninstall &&
703 (!by_policy->UserMayModifySettings(extension.get(), error) ||
704 by_policy->MustRemainInstalled(extension.get(), error))) {
705 content::NotificationService::current()->Notify(
706 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
707 content::Source<Profile>(profile_),
708 content::Details<const Extension>(extension.get()));
712 syncer::SyncChange sync_change;
713 // Don't sync the uninstall if we're going to reinstall the extension
715 if (extension_sync_service_ &&
716 reason != extensions::UNINSTALL_REASON_REINSTALL) {
717 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
718 extension.get(), is_ready());
721 system_->install_verifier()->Remove(extension->id());
723 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
724 extension->GetType(), 100);
725 RecordPermissionMessagesHistogram(extension.get(),
726 "Extensions.Permissions_Uninstall2");
728 // Unload before doing more cleanup to ensure that nothing is hanging on to
729 // any of these resources.
730 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
732 // Tell the backend to start deleting installed extensions on the file thread.
733 if (!Manifest::IsUnpackedLocation(extension->location())) {
734 if (!GetFileTaskRunner()->PostTask(
736 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
744 extensions::DataDeleter::StartDeleting(
745 profile_, extension.get(), deletion_done_callback);
747 UntrackTerminatedExtension(extension->id());
749 // Notify interested parties that we've uninstalled this extension.
750 content::NotificationService::current()->Notify(
751 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
752 content::Source<Profile>(profile_),
753 content::Details<const Extension>(extension.get()));
754 ExtensionRegistry::Get(profile_)
755 ->TriggerOnUninstalled(extension.get(), reason);
757 if (sync_change.IsValid()) {
758 extension_sync_service_->ProcessSyncUninstallExtension(extension->id(),
762 delayed_installs_.Remove(extension->id());
764 extension_prefs_->OnExtensionUninstalled(
765 extension->id(), extension->location(), external_uninstall);
767 // Track the uninstallation.
768 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
774 void ExtensionService::UninstallExtensionOnFileThread(
775 const std::string& id,
777 const base::FilePath& install_dir,
778 const base::FilePath& extension_path) {
779 extensions::ExtensionAssetsManager* assets_manager =
780 extensions::ExtensionAssetsManager::GetInstance();
781 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
784 bool ExtensionService::IsExtensionEnabled(
785 const std::string& extension_id) const {
786 if (registry_->enabled_extensions().Contains(extension_id) ||
787 registry_->terminated_extensions().Contains(extension_id)) {
791 if (registry_->disabled_extensions().Contains(extension_id) ||
792 registry_->blacklisted_extensions().Contains(extension_id)) {
796 // If the extension hasn't been loaded yet, check the prefs for it. Assume
797 // enabled unless otherwise noted.
798 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
799 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
800 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
803 void ExtensionService::EnableExtension(const std::string& extension_id) {
804 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
806 if (IsExtensionEnabled(extension_id))
808 const Extension* extension =
809 registry_->disabled_extensions().GetByID(extension_id);
811 ManagementPolicy* policy = system_->management_policy();
812 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
813 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
817 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
818 extension_prefs_->ClearDisableReasons(extension_id);
820 // This can happen if sync enables an extension that is not
825 // Move it over to the enabled list.
826 registry_->AddEnabled(make_scoped_refptr(extension));
827 registry_->RemoveDisabled(extension->id());
829 NotifyExtensionLoaded(extension);
831 // Notify listeners that the extension was enabled.
832 content::NotificationService::current()->Notify(
833 extensions::NOTIFICATION_EXTENSION_ENABLED,
834 content::Source<Profile>(profile_),
835 content::Details<const Extension>(extension));
837 if (extension_sync_service_)
838 extension_sync_service_->SyncEnableExtension(*extension);
841 void ExtensionService::DisableExtension(
842 const std::string& extension_id,
843 Extension::DisableReason disable_reason) {
844 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
846 // The extension may have been disabled already. Just add a disable reason.
847 if (!IsExtensionEnabled(extension_id)) {
848 extension_prefs_->AddDisableReason(extension_id, disable_reason);
852 const Extension* extension = GetInstalledExtension(extension_id);
853 // |extension| can be NULL if sync disables an extension that is not
855 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
856 // can be uninstalled by the browser if the user sets extension-specific
859 disable_reason != Extension::DISABLE_RELOAD &&
860 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
861 extension->location() != Manifest::EXTERNAL_COMPONENT) {
865 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
866 extension_prefs_->AddDisableReason(extension_id, disable_reason);
869 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
870 extension = registry_->GetExtensionById(extension_id, include_mask);
874 // The extension is either enabled or terminated.
875 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
876 registry_->terminated_extensions().Contains(extension->id()));
878 // Move it over to the disabled list. Don't send a second unload notification
879 // for terminated extensions being disabled.
880 registry_->AddDisabled(make_scoped_refptr(extension));
881 if (registry_->enabled_extensions().Contains(extension->id())) {
882 registry_->RemoveEnabled(extension->id());
883 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
885 registry_->RemoveTerminated(extension->id());
888 if (extension_sync_service_)
889 extension_sync_service_->SyncDisableExtension(*extension);
892 void ExtensionService::DisableUserExtensions(
893 const std::vector<std::string>& except_ids) {
894 extensions::ManagementPolicy* management_policy =
895 system_->management_policy();
896 extensions::ExtensionList to_disable;
898 const ExtensionSet& enabled_set = registry_->enabled_extensions();
899 for (ExtensionSet::const_iterator extension = enabled_set.begin();
900 extension != enabled_set.end(); ++extension) {
901 if (management_policy->UserMayModifySettings(extension->get(), NULL))
902 to_disable.push_back(*extension);
904 const ExtensionSet& terminated_set = registry_->terminated_extensions();
905 for (ExtensionSet::const_iterator extension = terminated_set.begin();
906 extension != terminated_set.end(); ++extension) {
907 if (management_policy->UserMayModifySettings(extension->get(), NULL))
908 to_disable.push_back(*extension);
911 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
912 extension != to_disable.end(); ++extension) {
913 if ((*extension)->was_installed_by_default() &&
914 extension_urls::IsWebstoreUpdateUrl(
915 extensions::ManifestURL::GetUpdateURL(extension->get())))
917 const std::string& id = (*extension)->id();
918 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
919 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
923 void ExtensionService::GrantPermissionsAndEnableExtension(
924 const Extension* extension) {
925 GrantPermissions(extension);
926 RecordPermissionMessagesHistogram(extension,
927 "Extensions.Permissions_ReEnable2");
928 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
929 EnableExtension(extension->id());
932 void ExtensionService::GrantPermissions(const Extension* extension) {
934 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
938 void ExtensionService::RecordPermissionMessagesHistogram(
939 const Extension* extension, const char* histogram) {
940 // Since this is called from multiple sources, and since the histogram macros
941 // use statics, we need to manually lookup the histogram ourselves.
942 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
945 PermissionMessage::kEnumBoundary,
946 PermissionMessage::kEnumBoundary + 1,
947 base::HistogramBase::kUmaTargetedHistogramFlag);
949 PermissionMessages permissions =
950 extension->permissions_data()->GetPermissionMessages();
951 if (permissions.empty()) {
952 counter->Add(PermissionMessage::kNone);
954 for (PermissionMessages::iterator it = permissions.begin();
955 it != permissions.end(); ++it)
956 counter->Add(it->id());
960 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
961 // The URLRequestContexts need to be first to know that the extension
962 // was loaded, otherwise a race can arise where a renderer that is created
963 // for the extension may try to load an extension URL with an extension id
964 // that the request context doesn't yet know about. The profile is responsible
965 // for ensuring its URLRequestContexts appropriately discover the loaded
967 system_->RegisterExtensionWithRequestContexts(extension);
969 // Tell renderers about the new extension, unless it's a theme (renderers
970 // don't need to know about themes).
971 if (!extension->is_theme()) {
972 for (content::RenderProcessHost::iterator i(
973 content::RenderProcessHost::AllHostsIterator());
974 !i.IsAtEnd(); i.Advance()) {
975 content::RenderProcessHost* host = i.GetCurrentValue();
976 Profile* host_profile =
977 Profile::FromBrowserContext(host->GetBrowserContext());
978 if (host_profile->GetOriginalProfile() ==
979 profile_->GetOriginalProfile()) {
980 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
981 1, ExtensionMsg_Loaded_Params(extension));
983 new ExtensionMsg_Loaded(loaded_extensions));
988 // Tell subsystems that use the EXTENSION_LOADED notification about the new
991 // NOTE: It is important that this happen after notifying the renderers about
992 // the new extensions so that if we navigate to an extension URL in
993 // ExtensionRegistryObserver::OnLoaded or
994 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
995 // renderer is guaranteed to know about it.
996 registry_->TriggerOnLoaded(extension);
998 content::NotificationService::current()->Notify(
999 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1000 content::Source<Profile>(profile_),
1001 content::Details<const Extension>(extension));
1003 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1004 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1005 profile_->GetExtensionSpecialStoragePolicy()->
1006 GrantRightsForExtension(extension, profile_);
1008 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1009 // work properly multi-profile. Besides which, it should be using
1010 // ExtensionRegistryObserver. See http://crbug.com/355029.
1011 UpdateActiveExtensionsInCrashReporter();
1013 const extensions::PermissionsData* permissions_data =
1014 extension->permissions_data();
1016 // If the extension has permission to load chrome://favicon/ resources we need
1017 // to make sure that the FaviconSource is registered with the
1018 // ChromeURLDataManager.
1019 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1020 FaviconSource* favicon_source = new FaviconSource(profile_,
1021 FaviconSource::FAVICON);
1022 content::URLDataSource::Add(profile_, favicon_source);
1025 // Same for chrome://theme/ resources.
1026 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1027 ThemeSource* theme_source = new ThemeSource(profile_);
1028 content::URLDataSource::Add(profile_, theme_source);
1031 // Same for chrome://thumb/ resources.
1032 if (permissions_data->HasHostPermission(
1033 GURL(chrome::kChromeUIThumbnailURL))) {
1034 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1035 content::URLDataSource::Add(profile_, thumbnail_source);
1039 void ExtensionService::NotifyExtensionUnloaded(
1040 const Extension* extension,
1041 UnloadedExtensionInfo::Reason reason) {
1042 UnloadedExtensionInfo details(extension, reason);
1044 registry_->TriggerOnUnloaded(extension, reason);
1046 content::NotificationService::current()->Notify(
1047 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1048 content::Source<Profile>(profile_),
1049 content::Details<UnloadedExtensionInfo>(&details));
1051 for (content::RenderProcessHost::iterator i(
1052 content::RenderProcessHost::AllHostsIterator());
1053 !i.IsAtEnd(); i.Advance()) {
1054 content::RenderProcessHost* host = i.GetCurrentValue();
1055 Profile* host_profile =
1056 Profile::FromBrowserContext(host->GetBrowserContext());
1057 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1058 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1061 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1063 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1064 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1065 profile_->GetExtensionSpecialStoragePolicy()->
1066 RevokeRightsForExtension(extension);
1068 #if defined(OS_CHROMEOS)
1069 // Revoke external file access for the extension from its file system context.
1070 // It is safe to access the extension's storage partition at this point. The
1071 // storage partition may get destroyed only after the extension gets unloaded.
1073 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1074 storage::FileSystemContext* filesystem_context =
1075 BrowserContext::GetStoragePartitionForSite(profile_, site)
1076 ->GetFileSystemContext();
1077 if (filesystem_context && filesystem_context->external_backend()) {
1078 filesystem_context->external_backend()->
1079 RevokeAccessForExtension(extension->id());
1083 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1084 // work properly multi-profile. Besides which, it should be using
1085 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1086 UpdateActiveExtensionsInCrashReporter();
1089 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1090 // Implemented in the .cc file to avoid adding a profile.h dependency to
1091 // extension_service.h.
1095 bool ExtensionService::is_ready() {
1096 return ready_->is_signaled();
1099 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1100 if (file_task_runner_.get())
1101 return file_task_runner_.get();
1103 // We should be able to interrupt any part of extension install process during
1104 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1105 // will be ignored/deleted while we will block on started tasks.
1106 std::string token("ext_install-");
1107 token.append(profile_->GetPath().AsUTF8Unsafe());
1108 file_task_runner_ = BrowserThread::GetBlockingPool()->
1109 GetSequencedTaskRunnerWithShutdownBehavior(
1110 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1111 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1112 return file_task_runner_.get();
1115 void ExtensionService::CheckManagementPolicy() {
1116 std::vector<std::string> to_unload;
1117 std::map<std::string, Extension::DisableReason> to_disable;
1119 // Loop through the extensions list, finding extensions we need to unload or
1121 const ExtensionSet& extensions = registry_->enabled_extensions();
1122 for (ExtensionSet::const_iterator iter = extensions.begin();
1123 iter != extensions.end(); ++iter) {
1124 const Extension* extension = (iter->get());
1125 if (!system_->management_policy()->UserMayLoad(extension, NULL))
1126 to_unload.push_back(extension->id());
1127 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1128 if (system_->management_policy()->MustRemainDisabled(
1129 extension, &disable_reason, NULL))
1130 to_disable[extension->id()] = disable_reason;
1133 for (size_t i = 0; i < to_unload.size(); ++i)
1134 UnloadExtension(to_unload[i], UnloadedExtensionInfo::REASON_DISABLE);
1136 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1137 to_disable.begin(); i != to_disable.end(); ++i)
1138 DisableExtension(i->first, i->second);
1141 void ExtensionService::CheckForUpdatesSoon() {
1142 // This can legitimately happen in unit tests.
1143 if (!updater_.get())
1146 if (AreAllExternalProvidersReady()) {
1147 updater_->CheckSoon();
1149 // Sync can start updating before all the external providers are ready
1150 // during startup. Start the update as soon as those providers are ready,
1152 update_once_all_providers_are_ready_ = true;
1156 // Some extensions will autoupdate themselves externally from Chrome. These
1157 // are typically part of some larger client application package. To support
1158 // these, the extension will register its location in the the preferences file
1159 // (and also, on Windows, in the registry) and this code will periodically
1160 // check that location for a .crx file, which it will then install locally if
1161 // a new version is available.
1162 // Errors are reported through ExtensionErrorReporter. Succcess is not
1164 void ExtensionService::CheckForExternalUpdates() {
1165 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1167 // Note that this installation is intentionally silent (since it didn't
1168 // go through the front-end). Extensions that are registered in this
1169 // way are effectively considered 'pre-bundled', and so implicitly
1170 // trusted. In general, if something has HKLM or filesystem access,
1171 // they could install an extension manually themselves anyway.
1173 // Ask each external extension provider to give us a call back for each
1174 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1175 extensions::ProviderCollection::const_iterator i;
1176 for (i = external_extension_providers_.begin();
1177 i != external_extension_providers_.end(); ++i) {
1178 extensions::ExternalProviderInterface* provider = i->get();
1179 provider->VisitRegisteredExtension();
1182 // Do any required work that we would have done after completion of all
1184 if (external_extension_providers_.empty())
1185 OnAllExternalProvidersReady();
1188 void ExtensionService::OnExternalProviderReady(
1189 const extensions::ExternalProviderInterface* provider) {
1190 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1191 CHECK(provider->IsReady());
1193 // An external provider has finished loading. We only take action
1194 // if all of them are finished. So we check them first.
1195 if (AreAllExternalProvidersReady())
1196 OnAllExternalProvidersReady();
1199 bool ExtensionService::AreAllExternalProvidersReady() const {
1200 extensions::ProviderCollection::const_iterator i;
1201 for (i = external_extension_providers_.begin();
1202 i != external_extension_providers_.end(); ++i) {
1203 if (!i->get()->IsReady())
1209 void ExtensionService::OnAllExternalProvidersReady() {
1210 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1211 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1212 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1214 // Install any pending extensions.
1215 if (update_once_all_providers_are_ready_ && updater()) {
1216 update_once_all_providers_are_ready_ = false;
1217 extensions::ExtensionUpdater::CheckParams params;
1218 params.callback = external_updates_finished_callback_;
1219 updater()->CheckNow(params);
1222 // Uninstall all the unclaimed extensions.
1223 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1224 extension_prefs_->GetInstalledExtensionsInfo());
1225 for (size_t i = 0; i < extensions_info->size(); ++i) {
1226 ExtensionInfo* info = extensions_info->at(i).get();
1227 if (Manifest::IsExternalLocation(info->extension_location))
1228 CheckExternalUninstall(info->extension_id);
1231 error_controller_->ShowErrorIfNeeded();
1233 external_install_manager_->UpdateExternalExtensionAlert();
1236 void ExtensionService::UnloadExtension(
1237 const std::string& extension_id,
1238 UnloadedExtensionInfo::Reason reason) {
1239 // Make sure the extension gets deleted after we return from this function.
1241 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1242 scoped_refptr<const Extension> extension(
1243 registry_->GetExtensionById(extension_id, include_mask));
1245 // This method can be called via PostTask, so the extension may have been
1246 // unloaded by the time this runs.
1247 if (!extension.get()) {
1248 // In case the extension may have crashed/uninstalled. Allow the profile to
1249 // clean up its RequestContexts.
1250 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1254 // Keep information about the extension so that we can reload it later
1255 // even if it's not permanently installed.
1256 unloaded_extension_paths_[extension->id()] = extension->path();
1258 // Clean up if the extension is meant to be enabled after a reload.
1259 reloading_extensions_.erase(extension->id());
1261 if (registry_->disabled_extensions().Contains(extension->id())) {
1262 registry_->RemoveDisabled(extension->id());
1263 // Make sure the profile cleans up its RequestContexts when an already
1264 // disabled extension is unloaded (since they are also tracking the disabled
1266 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1267 // Don't send the unloaded notification. It was sent when the extension
1270 // Remove the extension from the enabled list.
1271 registry_->RemoveEnabled(extension->id());
1272 NotifyExtensionUnloaded(extension.get(), reason);
1275 content::NotificationService::current()->Notify(
1276 extensions::NOTIFICATION_EXTENSION_REMOVED,
1277 content::Source<Profile>(profile_),
1278 content::Details<const Extension>(extension.get()));
1281 void ExtensionService::RemoveComponentExtension(
1282 const std::string& extension_id) {
1283 scoped_refptr<const Extension> extension(
1284 GetExtensionById(extension_id, false));
1285 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1286 if (extension.get()) {
1287 content::NotificationService::current()->Notify(
1288 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
1289 content::Source<Profile>(profile_),
1290 content::Details<const Extension>(extension.get()));
1291 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1292 extension.get(), extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT);
1296 void ExtensionService::UnloadAllExtensionsForTest() {
1297 UnloadAllExtensionsInternal();
1300 void ExtensionService::ReloadExtensionsForTest() {
1301 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1302 // warning about calling test code in production.
1303 UnloadAllExtensionsInternal();
1304 component_loader_->LoadAll();
1305 extensions::InstalledLoader(this).LoadAllExtensions();
1306 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1310 void ExtensionService::SetReadyAndNotifyListeners() {
1312 content::NotificationService::current()->Notify(
1313 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1314 content::Source<Profile>(profile_),
1315 content::NotificationService::NoDetails());
1318 void ExtensionService::OnLoadedInstalledExtensions() {
1322 OnBlacklistUpdated();
1325 void ExtensionService::AddExtension(const Extension* extension) {
1326 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1327 // default extension state to DISABLED when the --disable-extensions flag
1328 // is set (http://crbug.com/29067).
1329 if (!extensions_enabled() &&
1330 !extension->is_theme() &&
1331 extension->location() != Manifest::COMPONENT &&
1332 !Manifest::IsExternalLocation(extension->location())) {
1336 bool is_extension_upgrade = false;
1337 bool is_extension_installed = false;
1338 const Extension* old = GetInstalledExtension(extension->id());
1340 is_extension_installed = true;
1341 int version_compare_result =
1342 extension->version()->CompareTo(*(old->version()));
1343 is_extension_upgrade = version_compare_result > 0;
1344 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1345 // that we aren't downgrading.
1346 if (!Manifest::IsUnpackedLocation(extension->location()))
1347 CHECK_GE(version_compare_result, 0);
1349 system_->runtime_data()->SetBeingUpgraded(extension, is_extension_upgrade);
1351 // The extension is now loaded, remove its data from unloaded extension map.
1352 unloaded_extension_paths_.erase(extension->id());
1354 // If a terminated extension is loaded, remove it from the terminated list.
1355 UntrackTerminatedExtension(extension->id());
1357 // If the extension was disabled for a reload, then enable it.
1358 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1360 // Check if the extension's privileges have changed and mark the
1361 // extension disabled if necessary.
1362 CheckPermissionsIncrease(extension, is_extension_installed);
1364 if (is_extension_installed && !reloading) {
1365 // To upgrade an extension in place, unload the old one and then load the
1366 // new one. ReloadExtension disables the extension, which is sufficient.
1367 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1370 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1371 // Only prefs is checked for the blacklist. We rely on callers to check the
1372 // blacklist before calling into here, e.g. CrxInstaller checks before
1373 // installation then threads through the install and pending install flow
1374 // of this class, and we check when loading installed extensions.
1375 registry_->AddBlacklisted(extension);
1376 } else if (!reloading &&
1377 extension_prefs_->IsExtensionDisabled(extension->id())) {
1378 registry_->AddDisabled(extension);
1379 if (extension_sync_service_)
1380 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1381 content::NotificationService::current()->Notify(
1382 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1383 content::Source<Profile>(profile_),
1384 content::Details<const Extension>(extension));
1386 // Show the extension disabled error if a permissions increase or a remote
1387 // installation is the reason it was disabled, and no other reasons exist.
1388 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1389 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1390 Extension::DISABLE_REMOTE_INSTALL;
1391 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1392 extensions::AddExtensionDisabledError(
1395 extension_prefs_->HasDisableReason(
1396 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1398 } else if (reloading) {
1399 // Replace the old extension with the new version.
1400 CHECK(!registry_->AddDisabled(extension));
1401 EnableExtension(extension->id());
1403 // All apps that are displayed in the launcher are ordered by their ordinals
1404 // so we must ensure they have valid ordinals.
1405 if (extension->RequiresSortOrdinal()) {
1406 extension_prefs_->app_sorting()->SetExtensionVisible(
1408 extension->ShouldDisplayInNewTabPage() &&
1409 !extension_prefs_->IsEphemeralApp(extension->id()));
1410 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1411 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1412 extension->id(), syncer::StringOrdinal());
1416 registry_->AddEnabled(extension);
1417 if (extension_sync_service_)
1418 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1419 NotifyExtensionLoaded(extension);
1421 system_->runtime_data()->SetBeingUpgraded(extension, false);
1424 void ExtensionService::AddComponentExtension(const Extension* extension) {
1425 const std::string old_version_string(
1426 extension_prefs_->GetVersionString(extension->id()));
1427 const Version old_version(old_version_string);
1429 VLOG(1) << "AddComponentExtension " << extension->name();
1430 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1431 VLOG(1) << "Component extension " << extension->name() << " ("
1432 << extension->id() << ") installing/upgrading from '"
1433 << old_version_string << "' to " << extension->version()->GetString();
1435 AddNewOrUpdatedExtension(extension,
1437 extensions::kInstallFlagNone,
1438 syncer::StringOrdinal(),
1443 AddExtension(extension);
1446 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1447 bool is_extension_installed) {
1448 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1450 // We keep track of all permissions the user has granted each extension.
1451 // This allows extensions to gracefully support backwards compatibility
1452 // by including unknown permissions in their manifests. When the user
1453 // installs the extension, only the recognized permissions are recorded.
1454 // When the unknown permissions become recognized (e.g., through browser
1455 // upgrade), we can prompt the user to accept these new permissions.
1456 // Extensions can also silently upgrade to less permissions, and then
1457 // silently upgrade to a version that adds these permissions back.
1459 // For example, pretend that Chrome 10 includes a permission "omnibox"
1460 // for an API that adds suggestions to the omnibox. An extension can
1461 // maintain backwards compatibility while still having "omnibox" in the
1462 // manifest. If a user installs the extension on Chrome 9, the browser
1463 // will record the permissions it recognized, not including "omnibox."
1464 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1465 // will disable the extension and prompt the user to approve the increase
1466 // in privileges. The extension could then release a new version that
1467 // removes the "omnibox" permission. When the user upgrades, Chrome will
1468 // still remember that "omnibox" had been granted, so that if the
1469 // extension once again includes "omnibox" in an upgrade, the extension
1470 // can upgrade without requiring this user's approval.
1471 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1473 bool auto_grant_permission =
1474 (!is_extension_installed && extension->was_installed_by_default()) ||
1475 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1476 // Silently grant all active permissions to default apps only on install.
1477 // After install they should behave like other apps.
1478 // Silently grant all active permissions to apps install in kiosk mode on both
1479 // install and update.
1480 if (auto_grant_permission)
1481 GrantPermissions(extension);
1483 bool is_privilege_increase = false;
1484 // We only need to compare the granted permissions to the current permissions
1485 // if the extension is not allowed to silently increase its permissions.
1486 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) &&
1487 !auto_grant_permission) {
1488 // Add all the recognized permissions if the granted permissions list
1489 // hasn't been initialized yet.
1490 scoped_refptr<PermissionSet> granted_permissions =
1491 extension_prefs_->GetGrantedPermissions(extension->id());
1492 CHECK(granted_permissions.get());
1494 // Here, we check if an extension's privileges have increased in a manner
1495 // that requires the user's approval. This could occur because the browser
1496 // upgraded and recognized additional privileges, or an extension upgrades
1497 // to a version that requires additional privileges.
1498 is_privilege_increase =
1499 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1500 granted_permissions.get(),
1501 extension->permissions_data()->active_permissions().get(),
1502 extension->GetType());
1505 if (is_extension_installed) {
1506 // If the extension was already disabled, suppress any alerts for becoming
1507 // disabled on permissions increase.
1508 bool previously_disabled =
1509 extension_prefs_->IsExtensionDisabled(extension->id());
1510 // Legacy disabled extensions do not have a disable reason. Infer that if
1511 // there was no permission increase, it was likely disabled by the user.
1512 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1513 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1514 disable_reasons |= Extension::DISABLE_USER_ACTION;
1516 // Extensions that came to us disabled from sync need a similar inference,
1517 // except based on the new version's permissions.
1518 if (previously_disabled &&
1519 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1520 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1521 extension_prefs_->ClearDisableReasons(extension->id());
1522 if (!is_privilege_increase)
1523 disable_reasons |= Extension::DISABLE_USER_ACTION;
1525 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1528 // Extension has changed permissions significantly. Disable it. A
1529 // notification should be sent by the caller. If the extension is already
1530 // disabled because it was installed remotely, don't add another disable
1531 // reason, but instead always set the "did escalate permissions" flag, to
1532 // ensure enabling it will always show a warning.
1533 if (disable_reasons == Extension::DISABLE_REMOTE_INSTALL) {
1534 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1535 } else if (is_privilege_increase) {
1536 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1537 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1538 RecordPermissionMessagesHistogram(extension,
1539 "Extensions.Permissions_AutoDisable2");
1541 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1542 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1544 if (disable_reasons != Extension::DISABLE_NONE) {
1545 extension_prefs_->AddDisableReason(
1547 static_cast<Extension::DisableReason>(disable_reasons));
1551 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1552 std::set<std::string> extension_ids;
1553 const ExtensionSet& extensions = registry_->enabled_extensions();
1554 for (ExtensionSet::const_iterator iter = extensions.begin();
1555 iter != extensions.end(); ++iter) {
1556 const Extension* extension = iter->get();
1557 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1558 extension_ids.insert(extension->id());
1561 // TODO(kalman): This is broken. ExtensionService is per-profile.
1562 // crash_keys::SetActiveExtensions is per-process. See
1563 // http://crbug.com/355029.
1564 crash_keys::SetActiveExtensions(extension_ids);
1567 void ExtensionService::OnExtensionInstalled(
1568 const Extension* extension,
1569 const syncer::StringOrdinal& page_ordinal,
1570 int install_flags) {
1571 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1573 const std::string& id = extension->id();
1574 bool initial_enable = ShouldEnableOnInstall(extension);
1575 std::string install_parameter;
1576 const extensions::PendingExtensionInfo* pending_extension_info =
1577 pending_extension_manager()->GetById(id);
1578 if (pending_extension_info) {
1579 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1580 pending_extension_manager()->Remove(id);
1582 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1583 << id << " of type " << extension->GetType()
1584 << " and update URL "
1585 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1586 << "; not installing";
1588 // Delete the extension directory since we're not going to
1590 if (!GetFileTaskRunner()->PostTask(
1592 base::Bind(&extensions::file_util::DeleteFile,
1600 install_parameter = pending_extension_info->install_parameter();
1601 pending_extension_manager()->Remove(id);
1603 // We explicitly want to re-enable an uninstalled external
1604 // extension; if we're here, that means the user is manually
1605 // installing the extension.
1606 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1607 initial_enable = true;
1611 // Unsupported requirements overrides the management policy.
1612 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1613 initial_enable = false;
1614 extension_prefs_->AddDisableReason(
1615 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1616 // If the extension was disabled because of unsupported requirements but
1617 // now supports all requirements after an update and there are not other
1618 // disable reasons, enable it.
1619 } else if (extension_prefs_->GetDisableReasons(id) ==
1620 Extension::DISABLE_UNSUPPORTED_REQUIREMENT) {
1621 initial_enable = true;
1622 extension_prefs_->ClearDisableReasons(id);
1625 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1626 // Installation of a blacklisted extension can happen from sync, policy,
1627 // etc, where to maintain consistency we need to install it, just never
1628 // load it (see AddExtension). Usually it should be the job of callers to
1629 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
1630 // showing the install dialogue).
1631 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1632 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1633 extension->location(),
1634 Manifest::NUM_LOCATIONS);
1637 if (!GetInstalledExtension(extension->id())) {
1638 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1639 extension->GetType(), 100);
1640 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1641 extension->location(), Manifest::NUM_LOCATIONS);
1642 RecordPermissionMessagesHistogram(extension,
1643 "Extensions.Permissions_Install2");
1645 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1646 extension->GetType(), 100);
1647 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1648 extension->location(), Manifest::NUM_LOCATIONS);
1650 // A fully installed app cannot be demoted to an ephemeral app.
1651 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1652 !extension_prefs_->IsEphemeralApp(id)) {
1653 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1657 const Extension::State initial_state =
1658 initial_enable ? Extension::ENABLED : Extension::DISABLED;
1659 if (ShouldDelayExtensionUpdate(
1661 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1662 extension_prefs_->SetDelayedInstallInfo(
1666 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1670 // Transfer ownership of |extension|.
1671 delayed_installs_.Insert(extension);
1673 // Notify observers that app update is available.
1674 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1675 OnAppUpdateAvailable(extension));
1679 extensions::SharedModuleService::ImportStatus status =
1680 shared_module_service_->SatisfyImports(extension);
1681 if (installs_delayed_for_gc_) {
1682 extension_prefs_->SetDelayedInstallInfo(
1686 extensions::ExtensionPrefs::DELAY_REASON_GC,
1689 delayed_installs_.Insert(extension);
1690 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1691 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1692 extension_prefs_->SetDelayedInstallInfo(
1696 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1699 delayed_installs_.Insert(extension);
1702 AddNewOrUpdatedExtension(extension,
1710 void ExtensionService::OnExtensionManagementSettingsChanged() {
1711 error_controller_->ShowErrorIfNeeded();
1713 // Revokes blocked permissions from active_permissions for all extensions.
1714 extensions::ExtensionManagement* settings =
1715 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1717 scoped_ptr<ExtensionSet> all_extensions(
1718 registry_->GenerateInstalledExtensionsSet());
1719 for (const auto& extension : *all_extensions.get()) {
1720 if (!settings->IsPermissionSetAllowed(
1722 extension->permissions_data()->active_permissions())) {
1723 extensions::PermissionsUpdater(profile()).RemovePermissions(
1725 settings->GetBlockedPermissions(extension.get()).get());
1729 CheckManagementPolicy();
1732 void ExtensionService::AddNewOrUpdatedExtension(
1733 const Extension* extension,
1734 Extension::State initial_state,
1736 const syncer::StringOrdinal& page_ordinal,
1737 const std::string& install_parameter) {
1738 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1739 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1740 extension_prefs_->OnExtensionInstalled(
1741 extension, initial_state, page_ordinal, install_flags, install_parameter);
1742 delayed_installs_.Remove(extension->id());
1743 if (InstallVerifier::NeedsVerification(*extension))
1744 system_->install_verifier()->VerifyExtension(extension->id());
1745 FinishInstallation(extension, was_ephemeral);
1748 void ExtensionService::MaybeFinishDelayedInstallation(
1749 const std::string& extension_id) {
1750 // Check if the extension already got installed.
1751 if (!delayed_installs_.Contains(extension_id))
1753 extensions::ExtensionPrefs::DelayReason reason =
1754 extension_prefs_->GetDelayedInstallReason(extension_id);
1756 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1757 // preferences files that will not have set this field but it was previously
1758 // only used for idle updates.
1759 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1760 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1761 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1764 const Extension* extension = delayed_installs_.GetByID(extension_id);
1765 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1766 extensions::SharedModuleService::ImportStatus status =
1767 shared_module_service_->SatisfyImports(extension);
1768 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1769 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1770 delayed_installs_.Remove(extension_id);
1771 // Make sure no version of the extension is actually installed, (i.e.,
1772 // that this delayed install was not an update).
1773 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1774 extension_prefs_->DeleteExtensionPrefs(extension_id);
1780 FinishDelayedInstallation(extension_id);
1783 void ExtensionService::FinishDelayedInstallation(
1784 const std::string& extension_id) {
1785 scoped_refptr<const Extension> extension(
1786 GetPendingExtensionUpdate(extension_id));
1787 CHECK(extension.get());
1788 delayed_installs_.Remove(extension_id);
1790 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1791 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1794 FinishInstallation(extension.get(), was_ephemeral);
1797 void ExtensionService::FinishInstallation(
1798 const Extension* extension, bool was_ephemeral) {
1799 const extensions::Extension* existing_extension =
1800 GetInstalledExtension(extension->id());
1801 bool is_update = false;
1802 std::string old_name;
1803 if (existing_extension) {
1805 old_name = existing_extension->name();
1807 bool from_ephemeral =
1808 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1809 extensions::InstalledExtensionInfo details(
1810 extension, is_update, from_ephemeral, old_name);
1811 content::NotificationService::current()->Notify(
1812 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1813 content::Source<Profile>(profile_),
1814 content::Details<const extensions::InstalledExtensionInfo>(&details));
1816 registry_->TriggerOnWillBeInstalled(
1817 extension, is_update, from_ephemeral, old_name);
1819 // Unpacked extensions default to allowing file access, but if that has been
1820 // overridden, don't reset the value.
1821 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1822 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1823 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1826 AddExtension(extension);
1828 // Notify observers that need to know when an installation is complete.
1829 registry_->TriggerOnInstalled(extension, is_update);
1831 // Check extensions that may have been delayed only because this shared module
1832 // was not available.
1833 if (SharedModuleInfo::IsSharedModule(extension))
1834 MaybeFinishDelayedInstallations();
1837 void ExtensionService::PromoteEphemeralApp(
1838 const extensions::Extension* extension, bool is_from_sync) {
1839 DCHECK(GetInstalledExtension(extension->id()) &&
1840 extension_prefs_->IsEphemeralApp(extension->id()));
1842 if (extension->RequiresSortOrdinal()) {
1843 extension_prefs_->app_sorting()->SetExtensionVisible(
1844 extension->id(), extension->ShouldDisplayInNewTabPage());
1846 if (!is_from_sync) {
1847 // Reset the sort ordinals of the app to ensure it is added to the default
1848 // position, like newly installed apps would.
1849 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
1852 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1853 extension->id(), syncer::StringOrdinal());
1856 // Remove the ephemeral flags from the preferences.
1857 extension_prefs_->OnEphemeralAppPromoted(extension->id());
1859 // Fire install-related events to allow observers to handle the promotion
1860 // of the ephemeral app.
1861 extensions::InstalledExtensionInfo details(
1863 true /* is update */,
1864 true /* from ephemeral */,
1865 extension->name() /* old name */);
1866 content::NotificationService::current()->Notify(
1867 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1868 content::Source<Profile>(profile_),
1869 content::Details<const extensions::InstalledExtensionInfo>(&details));
1871 registry_->TriggerOnWillBeInstalled(
1873 true /* is update */,
1874 true /* from ephemeral */,
1875 extension->name() /* old name */);
1877 if (registry_->enabled_extensions().Contains(extension->id())) {
1878 // If the app is already enabled and loaded, fire the load events to allow
1879 // observers to handle the promotion of the ephemeral app.
1880 content::NotificationService::current()->Notify(
1881 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1882 content::Source<Profile>(profile_),
1883 content::Details<const Extension>(extension));
1885 registry_->TriggerOnLoaded(extension);
1887 // Cached ephemeral apps may be updated and disabled due to permissions
1888 // increase. The app can be enabled (as long as no other disable reasons
1889 // exist) as the install was user-acknowledged.
1890 int disable_mask = Extension::DISABLE_NONE;
1892 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
1894 int other_disable_reasons =
1895 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
1896 if (!other_disable_reasons) {
1897 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
1898 GrantPermissionsAndEnableExtension(extension);
1900 EnableExtension(extension->id());
1904 registry_->TriggerOnInstalled(extension, true);
1906 if (!is_from_sync && extension_sync_service_)
1907 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1910 const Extension* ExtensionService::GetPendingExtensionUpdate(
1911 const std::string& id) const {
1912 return delayed_installs_.GetByID(id);
1915 void ExtensionService::RegisterContentSettings(
1916 HostContentSettingsMap* host_content_settings_map) {
1917 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1918 host_content_settings_map->RegisterProvider(
1919 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
1920 scoped_ptr<content_settings::ObservableProvider>(
1921 new content_settings::InternalExtensionProvider(this)));
1923 host_content_settings_map->RegisterProvider(
1924 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
1925 scoped_ptr<content_settings::ObservableProvider>(
1926 new content_settings::CustomExtensionProvider(
1927 extensions::ContentSettingsService::Get(
1928 profile_)->content_settings_store(),
1929 profile_->GetOriginalProfile() != profile_)));
1932 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
1933 // No need to check for duplicates; inserting a duplicate is a no-op.
1934 registry_->AddTerminated(make_scoped_refptr(extension));
1935 extensions_being_terminated_.erase(extension->id());
1936 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
1939 void ExtensionService::TerminateExtension(const std::string& extension_id) {
1940 const Extension* extension = GetInstalledExtension(extension_id);
1941 TrackTerminatedExtension(extension);
1944 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
1945 std::string lowercase_id = base::StringToLowerASCII(id);
1946 const Extension* extension =
1947 registry_->terminated_extensions().GetByID(lowercase_id);
1948 registry_->RemoveTerminated(lowercase_id);
1950 content::NotificationService::current()->Notify(
1951 extensions::NOTIFICATION_EXTENSION_REMOVED,
1952 content::Source<Profile>(profile_),
1953 content::Details<const Extension>(extension));
1957 const Extension* ExtensionService::GetInstalledExtension(
1958 const std::string& id) const {
1959 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
1962 bool ExtensionService::OnExternalExtensionFileFound(
1963 const std::string& id,
1964 const Version* version,
1965 const base::FilePath& path,
1966 Manifest::Location location,
1968 bool mark_acknowledged) {
1969 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1970 CHECK(crx_file::id_util::IdIsValid(id));
1971 if (extension_prefs_->IsExternalExtensionUninstalled(id))
1974 // Before even bothering to unpack, check and see if we already have this
1975 // version. This is important because these extensions are going to get
1976 // installed on every startup.
1977 const Extension* existing = GetExtensionById(id, true);
1980 // The default apps will have the location set as INTERNAL. Since older
1981 // default apps are installed as EXTERNAL, we override them. However, if the
1982 // app is already installed as internal, then do the version check.
1983 // TODO(grv) : Remove after Q1-2013.
1984 bool is_default_apps_migration =
1985 (location == Manifest::INTERNAL &&
1986 Manifest::IsExternalLocation(existing->location()));
1988 if (!is_default_apps_migration) {
1991 switch (existing->version()->CompareTo(*version)) {
1992 case -1: // existing version is older, we should upgrade
1994 case 0: // existing version is same, do nothing
1996 case 1: // existing version is newer, uh-oh
1997 LOG(WARNING) << "Found external version of extension " << id
1998 << "that is older than current version. Current version "
1999 << "is: " << existing->VersionString() << ". New "
2000 << "version is: " << version->GetString()
2001 << ". Keeping current version.";
2007 // If the extension is already pending, don't start an install.
2008 if (!pending_extension_manager()->AddFromExternalFile(
2009 id, location, *version, creation_flags, mark_acknowledged)) {
2013 // no client (silent install)
2014 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2015 installer->set_install_source(location);
2016 installer->set_expected_id(id);
2017 installer->set_expected_version(*version);
2018 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2019 installer->set_creation_flags(creation_flags);
2020 #if defined(OS_CHROMEOS)
2021 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2023 installer->InstallCrx(path);
2026 // Depending on the source, a new external extension might not need a user
2027 // notification on installation. For such extensions, mark them acknowledged
2028 // now to suppress the notification.
2029 if (mark_acknowledged)
2030 external_install_manager_->AcknowledgeExternalExtension(id);
2035 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2036 extensions::ExtensionHost* host) {
2037 OrphanedDevTools::iterator iter =
2038 orphaned_dev_tools_.find(host->extension_id());
2039 if (iter == orphaned_dev_tools_.end())
2042 iter->second->ConnectWebContents(host->host_contents());
2043 orphaned_dev_tools_.erase(iter);
2046 void ExtensionService::Observe(int type,
2047 const content::NotificationSource& source,
2048 const content::NotificationDetails& details) {
2050 case chrome::NOTIFICATION_APP_TERMINATING:
2051 // Shutdown has started. Don't start any more extension installs.
2052 // (We cannot use ExtensionService::Shutdown() for this because it
2053 // happens too late in browser teardown.)
2054 browser_terminating_ = true;
2056 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2058 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2062 extensions::ExtensionHost* host =
2063 content::Details<extensions::ExtensionHost>(details).ptr();
2065 // If the extension is already being terminated, there is nothing left to
2067 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2070 // Mark the extension as terminated and Unload it. We want it to
2071 // be in a consistent state: either fully working or not loaded
2072 // at all, but never half-crashed. We do it in a PostTask so
2073 // that other handlers of this notification will still have
2074 // access to the Extension and ExtensionHost.
2075 base::MessageLoop::current()->PostTask(
2078 &ExtensionService::TrackTerminatedExtension,
2080 host->extension()));
2083 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2084 content::RenderProcessHost* process =
2085 content::Source<content::RenderProcessHost>(source).ptr();
2086 Profile* host_profile =
2087 Profile::FromBrowserContext(process->GetBrowserContext());
2088 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2091 extensions::ProcessMap* process_map =
2092 extensions::ProcessMap::Get(profile_);
2093 if (process_map->Contains(process->GetID())) {
2094 // An extension process was terminated, this might have resulted in an
2095 // app or extension becoming idle.
2096 std::set<std::string> extension_ids =
2097 process_map->GetExtensionsInProcess(process->GetID());
2098 // In addition to the extensions listed in the process map, one of those
2099 // extensions could be referencing a shared module which is waiting for
2100 // idle to update. Check all imports of these extensions, too.
2101 std::set<std::string> import_ids;
2102 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2103 it != extension_ids.end();
2105 const Extension* extension = GetExtensionById(*it, true);
2108 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2109 SharedModuleInfo::GetImports(extension);
2110 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2111 for (import_it = imports.begin(); import_it != imports.end();
2113 import_ids.insert((*import_it).extension_id);
2116 extension_ids.insert(import_ids.begin(), import_ids.end());
2118 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2119 it != extension_ids.end(); ++it) {
2120 if (delayed_installs_.Contains(*it)) {
2121 base::MessageLoop::current()->PostDelayedTask(
2123 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2125 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2130 process_map->RemoveAllFromProcess(process->GetID());
2131 BrowserThread::PostTask(
2134 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2135 system_->info_map(),
2139 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2140 // Notify observers that chrome update is available.
2141 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2142 OnChromeUpdateAvailable());
2145 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2146 OnProfileDestructionStarted();
2151 NOTREACHED() << "Unexpected notification type.";
2155 bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) {
2156 // Extensions installed by policy can't be disabled. So even if a previous
2157 // installation disabled the extension, make sure it is now enabled.
2158 if (system_->management_policy()->MustRemainEnabled(extension, NULL))
2161 if (extension_prefs_->IsExtensionDisabled(extension->id()))
2164 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2165 // External extensions are initially disabled. We prompt the user before
2166 // enabling them. Hosted apps are excepted because they are not dangerous
2167 // (they need to be launched by the user anyway).
2168 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2169 Manifest::IsExternalLocation(extension->location()) &&
2170 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2178 bool ExtensionService::ShouldDelayExtensionUpdate(
2179 const std::string& extension_id,
2180 bool install_immediately) const {
2181 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2183 // If delayed updates are globally disabled, or just for this extension,
2185 if (!install_updates_when_idle_ || install_immediately)
2188 const Extension* old = GetInstalledExtension(extension_id);
2189 // If there is no old extension, this is not an update, so don't delay.
2193 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2194 // Delay installation if the extension listens for the onUpdateAvailable
2196 return system_->event_router()->ExtensionHasEventListener(
2197 extension_id, kOnUpdateAvailableEvent);
2199 // Delay installation if the extension is not idle.
2200 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2204 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2205 DCHECK(!installs_delayed_for_gc_);
2206 installs_delayed_for_gc_ = true;
2209 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2210 DCHECK(installs_delayed_for_gc_);
2211 installs_delayed_for_gc_ = false;
2212 MaybeFinishDelayedInstallations();
2215 void ExtensionService::MaybeFinishDelayedInstallations() {
2216 std::vector<std::string> to_be_installed;
2217 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2218 it != delayed_installs_.end();
2220 to_be_installed.push_back((*it)->id());
2222 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2223 it != to_be_installed.end();
2225 MaybeFinishDelayedInstallation(*it);
2229 void ExtensionService::OnBlacklistUpdated() {
2230 blacklist_->GetBlacklistedIDs(
2231 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2232 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2235 void ExtensionService::ManageBlacklist(
2236 const extensions::Blacklist::BlacklistStateMap& state_map) {
2237 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2239 std::set<std::string> blocked;
2240 ExtensionIdSet greylist;
2241 ExtensionIdSet unchanged;
2242 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2244 it != state_map.end();
2246 switch (it->second) {
2247 case extensions::NOT_BLACKLISTED:
2250 case extensions::BLACKLISTED_MALWARE:
2251 blocked.insert(it->first);
2254 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2255 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2256 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2257 greylist.insert(it->first);
2260 case extensions::BLACKLISTED_UNKNOWN:
2261 unchanged.insert(it->first);
2266 UpdateBlockedExtensions(blocked, unchanged);
2267 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2269 error_controller_->ShowErrorIfNeeded();
2273 void Partition(const ExtensionIdSet& before,
2274 const ExtensionIdSet& after,
2275 const ExtensionIdSet& unchanged,
2276 ExtensionIdSet* no_longer,
2277 ExtensionIdSet* not_yet) {
2278 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2279 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2280 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2284 void ExtensionService::UpdateBlockedExtensions(
2285 const ExtensionIdSet& blocked,
2286 const ExtensionIdSet& unchanged) {
2287 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2288 Partition(registry_->blacklisted_extensions().GetIDs(),
2290 &no_longer_blocked, ¬_yet_blocked);
2292 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2293 it != no_longer_blocked.end(); ++it) {
2294 scoped_refptr<const Extension> extension =
2295 registry_->blacklisted_extensions().GetByID(*it);
2296 if (!extension.get()) {
2297 NOTREACHED() << "Extension " << *it << " no longer blocked, "
2298 << "but it was never blocked.";
2301 registry_->RemoveBlacklisted(*it);
2302 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2303 AddExtension(extension.get());
2304 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2305 extension->location(),
2306 Manifest::NUM_LOCATIONS);
2309 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2310 it != not_yet_blocked.end(); ++it) {
2311 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2312 if (!extension.get()) {
2313 NOTREACHED() << "Extension " << *it << " needs to be "
2314 << "blacklisted, but it's not installed.";
2317 registry_->AddBlacklisted(extension);
2318 extension_prefs_->SetExtensionBlacklistState(
2319 extension->id(), extensions::BLACKLISTED_MALWARE);
2320 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2321 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2322 extension->location(), Manifest::NUM_LOCATIONS);
2326 // TODO(oleg): UMA logging
2327 void ExtensionService::UpdateGreylistedExtensions(
2328 const ExtensionIdSet& greylist,
2329 const ExtensionIdSet& unchanged,
2330 const extensions::Blacklist::BlacklistStateMap& state_map) {
2331 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2332 Partition(greylist_.GetIDs(),
2333 greylist, unchanged,
2334 &no_longer_greylisted, ¬_yet_greylisted);
2336 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2337 it != no_longer_greylisted.end(); ++it) {
2338 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2339 if (!extension.get()) {
2340 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2341 << "but it was not marked as greylisted.";
2345 greylist_.Remove(*it);
2346 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2347 extensions::NOT_BLACKLISTED);
2348 if (extension_prefs_->GetDisableReasons(extension->id()) &
2349 extensions::Extension::DISABLE_GREYLIST)
2350 EnableExtension(*it);
2353 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2354 it != not_yet_greylisted.end(); ++it) {
2355 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2356 if (!extension.get()) {
2357 NOTREACHED() << "Extension " << *it << " needs to be "
2358 << "disabled, but it's not installed.";
2361 greylist_.Insert(extension);
2362 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2363 state_map.find(*it)->second);
2364 if (registry_->enabled_extensions().Contains(extension->id()))
2365 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2369 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2370 update_observers_.AddObserver(observer);
2373 void ExtensionService::RemoveUpdateObserver(
2374 extensions::UpdateObserver* observer) {
2375 update_observers_.RemoveObserver(observer);
2378 // Used only by test code.
2379 void ExtensionService::UnloadAllExtensionsInternal() {
2380 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2382 registry_->ClearAll();
2383 system_->runtime_data()->ClearAll();
2385 // TODO(erikkay) should there be a notification for this? We can't use
2386 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2390 void ExtensionService::OnProfileDestructionStarted() {
2391 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2392 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2393 it != ids_to_unload.end();
2395 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);