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/values.h"
28 #include "base/version.h"
29 #include "chrome/browser/browser_process.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
32 #include "chrome/browser/extensions/api/storage/settings_frontend.h"
33 #include "chrome/browser/extensions/component_loader.h"
34 #include "chrome/browser/extensions/crx_installer.h"
35 #include "chrome/browser/extensions/data_deleter.h"
36 #include "chrome/browser/extensions/extension_disabled_ui.h"
37 #include "chrome/browser/extensions/extension_error_reporter.h"
38 #include "chrome/browser/extensions/extension_error_ui.h"
39 #include "chrome/browser/extensions/extension_host.h"
40 #include "chrome/browser/extensions/extension_install_ui.h"
41 #include "chrome/browser/extensions/extension_special_storage_policy.h"
42 #include "chrome/browser/extensions/extension_sync_service.h"
43 #include "chrome/browser/extensions/extension_system.h"
44 #include "chrome/browser/extensions/extension_util.h"
45 #include "chrome/browser/extensions/external_install_ui.h"
46 #include "chrome/browser/extensions/external_provider_impl.h"
47 #include "chrome/browser/extensions/install_verifier.h"
48 #include "chrome/browser/extensions/installed_loader.h"
49 #include "chrome/browser/extensions/permissions_updater.h"
50 #include "chrome/browser/extensions/unpacked_installer.h"
51 #include "chrome/browser/extensions/updater/extension_cache.h"
52 #include "chrome/browser/extensions/updater/extension_updater.h"
53 #include "chrome/browser/profiles/profile.h"
54 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
55 #include "chrome/browser/ui/webui/favicon_source.h"
56 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
57 #include "chrome/browser/ui/webui/theme_source.h"
58 #include "chrome/common/chrome_switches.h"
59 #include "chrome/common/crash_keys.h"
60 #include "chrome/common/extensions/extension_constants.h"
61 #include "chrome/common/extensions/extension_file_util.h"
62 #include "chrome/common/extensions/extension_messages.h"
63 #include "chrome/common/extensions/features/feature_channel.h"
64 #include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
65 #include "chrome/common/extensions/manifest_url_handler.h"
66 #include "chrome/common/pref_names.h"
67 #include "chrome/common/url_constants.h"
68 #include "components/startup_metric_utils/startup_metric_utils.h"
69 #include "content/public/browser/browser_thread.h"
70 #include "content/public/browser/devtools_agent_host.h"
71 #include "content/public/browser/notification_service.h"
72 #include "content/public/browser/notification_types.h"
73 #include "content/public/browser/render_process_host.h"
74 #include "content/public/browser/site_instance.h"
75 #include "content/public/browser/storage_partition.h"
76 #include "content/public/browser/url_data_source.h"
77 #include "extensions/browser/app_sorting.h"
78 #include "extensions/browser/event_router.h"
79 #include "extensions/browser/extension_registry.h"
80 #include "extensions/browser/extensions_browser_client.h"
81 #include "extensions/browser/external_provider_interface.h"
82 #include "extensions/browser/management_policy.h"
83 #include "extensions/browser/pending_extension_manager.h"
84 #include "extensions/browser/pref_names.h"
85 #include "extensions/browser/process_manager.h"
86 #include "extensions/browser/process_map.h"
87 #include "extensions/browser/runtime_data.h"
88 #include "extensions/browser/update_observer.h"
89 #include "extensions/common/constants.h"
90 #include "extensions/common/error_utils.h"
91 #include "extensions/common/extension.h"
92 #include "extensions/common/extensions_client.h"
93 #include "extensions/common/feature_switch.h"
94 #include "extensions/common/manifest.h"
95 #include "extensions/common/manifest_constants.h"
96 #include "extensions/common/manifest_handlers/background_info.h"
97 #include "extensions/common/manifest_handlers/incognito_info.h"
98 #include "extensions/common/manifest_handlers/shared_module_info.h"
99 #include "extensions/common/permissions/permission_message_provider.h"
100 #include "extensions/common/permissions/permissions_data.h"
101 #include "grit/generated_resources.h"
102 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
103 #include "ui/base/webui/web_ui_util.h"
104 #include "url/gurl.h"
105 #include "webkit/browser/database/database_tracker.h"
106 #include "webkit/browser/database/database_util.h"
108 #if defined(OS_CHROMEOS)
109 #include "chrome/browser/chromeos/extensions/install_limiter.h"
110 #include "webkit/browser/fileapi/file_system_backend.h"
111 #include "webkit/browser/fileapi/file_system_context.h"
114 using content::BrowserContext;
115 using content::BrowserThread;
116 using content::DevToolsAgentHost;
117 using extensions::CrxInstaller;
118 using extensions::Extension;
119 using extensions::ExtensionIdSet;
120 using extensions::ExtensionInfo;
121 using extensions::ExtensionRegistry;
122 using extensions::ExtensionSet;
123 using extensions::FeatureSwitch;
124 using extensions::InstallVerifier;
125 using extensions::ManagementPolicy;
126 using extensions::Manifest;
127 using extensions::PermissionMessage;
128 using extensions::PermissionMessages;
129 using extensions::PermissionSet;
130 using extensions::SharedModuleInfo;
131 using extensions::UnloadedExtensionInfo;
133 namespace errors = extensions::manifest_errors;
137 // Histogram values for logging events related to externally installed
139 enum ExternalExtensionEvent {
140 EXTERNAL_EXTENSION_INSTALLED = 0,
141 EXTERNAL_EXTENSION_IGNORED,
142 EXTERNAL_EXTENSION_REENABLED,
143 EXTERNAL_EXTENSION_UNINSTALLED,
144 EXTERNAL_EXTENSION_BUCKET_BOUNDARY,
147 // Prompt the user this many times before considering an extension acknowledged.
148 static const int kMaxExtensionAcknowledgePromptCount = 3;
150 // Wait this many seconds after an extensions becomes idle before updating it.
151 static const int kUpdateIdleDelay = 5;
153 // Wait this many seconds before trying to garbage collect extensions again.
154 static const int kGarbageCollectRetryDelay = 30;
156 // Wait this many seconds after startup to see if there are any extensions
157 // which can be garbage collected.
158 static const int kGarbageCollectStartupDelay = 30;
160 static bool IsSharedModule(const Extension* extension) {
161 return SharedModuleInfo::IsSharedModule(extension);
164 static bool IsCWSSharedModule(const Extension* extension) {
165 return extension->from_webstore() && IsSharedModule(extension);
168 class SharedModuleProvider : public extensions::ManagementPolicy::Provider {
170 SharedModuleProvider() {}
171 virtual ~SharedModuleProvider() {}
173 virtual std::string GetDebugPolicyProviderName() const OVERRIDE {
174 return "SharedModuleProvider";
177 virtual bool UserMayModifySettings(const Extension* extension,
178 base::string16* error) const OVERRIDE {
179 return !IsCWSSharedModule(extension);
182 virtual bool MustRemainEnabled(const Extension* extension,
183 base::string16* error) const OVERRIDE {
184 return IsCWSSharedModule(extension);
188 DISALLOW_COPY_AND_ASSIGN(SharedModuleProvider);
196 void ExtensionService::CheckExternalUninstall(const std::string& id) {
197 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
199 // Check if the providers know about this extension.
200 extensions::ProviderCollection::const_iterator i;
201 for (i = external_extension_providers_.begin();
202 i != external_extension_providers_.end(); ++i) {
203 DCHECK(i->get()->IsReady());
204 if (i->get()->HasExtension(id))
205 return; // Yup, known extension, don't uninstall.
208 // We get the list of external extensions to check from preferences.
209 // It is possible that an extension has preferences but is not loaded.
210 // For example, an extension that requires experimental permissions
211 // will not be loaded if the experimental command line flag is not used.
212 // In this case, do not uninstall.
213 if (!GetInstalledExtension(id)) {
214 // We can't call UninstallExtension with an unloaded/invalid
216 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
217 << "with id: " << id;
220 UninstallExtension(id, true, NULL);
223 void ExtensionService::SetFileTaskRunnerForTesting(
224 base::SequencedTaskRunner* task_runner) {
225 file_task_runner_ = task_runner;
228 void ExtensionService::ClearProvidersForTesting() {
229 external_extension_providers_.clear();
232 void ExtensionService::AddProviderForTesting(
233 extensions::ExternalProviderInterface* test_provider) {
234 CHECK(test_provider);
235 external_extension_providers_.push_back(
236 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
239 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
240 const std::string& id,
241 const GURL& update_url,
242 Manifest::Location location,
244 bool mark_acknowledged) {
245 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
246 CHECK(Extension::IdIsValid(id));
248 if (Manifest::IsExternalLocation(location)) {
249 // All extensions that are not user specific can be cached.
250 extensions::ExtensionCache::GetInstance()->AllowCaching(id);
253 const Extension* extension = GetExtensionById(id, true);
255 // Already installed. Skip this install if the current location has
256 // higher priority than |location|.
257 Manifest::Location current = extension->location();
258 if (current == Manifest::GetHigherPriorityLocation(current, location))
260 // Otherwise, overwrite the current installation.
263 // Add |id| to the set of pending extensions. If it can not be added,
264 // then there is already a pending record from a higher-priority install
265 // source. In this case, signal that this extension will not be
266 // installed by returning false.
267 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
268 id, update_url, location, creation_flags, mark_acknowledged)) {
272 update_once_all_providers_are_ready_ = true;
276 const Extension* ExtensionService::GetInstalledExtensionByUrl(
277 const GURL& url) const {
278 return registry_->enabled_extensions().GetExtensionOrAppByURL(url);
281 const Extension* ExtensionService::GetInstalledApp(const GURL& url) const {
282 const Extension* extension = GetInstalledExtensionByUrl(url);
283 return (extension && extension->is_app()) ? extension : NULL;
286 bool ExtensionService::IsInstalledApp(const GURL& url) const {
287 return !!GetInstalledApp(url);
291 // This function is used to implement the command-line switch
292 // --uninstall-extension, and to uninstall an extension via sync. The LOG
293 // statements within this function are used to inform the user if the uninstall
295 bool ExtensionService::UninstallExtensionHelper(
296 ExtensionService* extensions_service,
297 const std::string& extension_id) {
298 // We can't call UninstallExtension with an invalid extension ID.
299 if (!extensions_service->GetInstalledExtension(extension_id)) {
300 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
301 << "id: " << extension_id;
305 // The following call to UninstallExtension will not allow an uninstall of a
306 // policy-controlled extension.
307 base::string16 error;
308 if (!extensions_service->UninstallExtension(extension_id, false, &error)) {
309 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
317 ExtensionService::ExtensionService(Profile* profile,
318 const CommandLine* command_line,
319 const base::FilePath& install_directory,
320 extensions::ExtensionPrefs* extension_prefs,
321 extensions::Blacklist* blacklist,
322 bool autoupdate_enabled,
323 bool extensions_enabled,
324 extensions::OneShotEvent* ready)
325 : extensions::Blacklist::Observer(blacklist),
327 system_(extensions::ExtensionSystem::Get(profile)),
328 extension_prefs_(extension_prefs),
329 blacklist_(blacklist),
330 settings_frontend_(extensions::SettingsFrontend::Create(profile)),
331 extension_sync_service_(NULL),
332 registry_(extensions::ExtensionRegistry::Get(profile)),
333 pending_extension_manager_(*this),
334 install_directory_(install_directory),
335 extensions_enabled_(extensions_enabled),
336 show_extensions_prompts_(true),
337 install_updates_when_idle_(true),
339 update_once_all_providers_are_ready_(false),
340 browser_terminating_(false),
341 installs_delayed_for_gc_(false),
342 is_first_run_(false) {
343 #if defined(OS_CHROMEOS)
344 disable_garbage_collection_ = false;
346 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
348 // Figure out if extension installation should be enabled.
349 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
350 *command_line, profile))
351 extensions_enabled_ = false;
353 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
354 content::NotificationService::AllBrowserContextsAndSources());
355 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
356 content::NotificationService::AllBrowserContextsAndSources());
357 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
358 content::NotificationService::AllBrowserContextsAndSources());
359 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
360 content::NotificationService::AllBrowserContextsAndSources());
361 pref_change_registrar_.Init(profile->GetPrefs());
362 base::Closure callback =
363 base::Bind(&ExtensionService::OnExtensionInstallPrefChanged,
364 base::Unretained(this));
365 pref_change_registrar_.Add(extensions::pref_names::kInstallAllowList,
367 pref_change_registrar_.Add(extensions::pref_names::kInstallDenyList,
369 pref_change_registrar_.Add(extensions::pref_names::kAllowedTypes, callback);
371 // Set up the ExtensionUpdater
372 if (autoupdate_enabled) {
373 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
374 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
375 base::StringToInt(command_line->GetSwitchValueASCII(
376 switches::kExtensionsUpdateFrequency),
379 updater_.reset(new extensions::ExtensionUpdater(
385 extensions::ExtensionCache::GetInstance()));
388 component_loader_.reset(
389 new extensions::ComponentLoader(this,
391 g_browser_process->local_state(),
394 if (extensions_enabled_) {
395 extensions::ExternalProviderImpl::CreateExternalProviders(
396 this, profile_, &external_extension_providers_);
399 // Set this as the ExtensionService for app sorting to ensure it causes syncs
401 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
403 #if defined(ENABLE_EXTENSIONS)
404 extension_action_storage_manager_.reset(
405 new extensions::ExtensionActionStorageManager(profile_));
408 shared_module_policy_provider_.reset(new SharedModuleProvider);
410 // How long is the path to the Extensions directory?
411 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
412 install_directory_.value().length(), 0, 500, 100);
415 const ExtensionSet* ExtensionService::extensions() const {
416 return ®istry_->enabled_extensions();
419 const ExtensionSet* ExtensionService::disabled_extensions() const {
420 return ®istry_->disabled_extensions();
423 const ExtensionSet* ExtensionService::delayed_installs() const {
424 return &delayed_installs_;
427 scoped_ptr<ExtensionSet>
428 ExtensionService::GenerateInstalledExtensionsSet() const {
429 scoped_ptr<ExtensionSet> installed_extensions(new ExtensionSet());
430 installed_extensions->InsertAll(registry_->enabled_extensions());
431 installed_extensions->InsertAll(registry_->disabled_extensions());
432 installed_extensions->InsertAll(registry_->terminated_extensions());
433 installed_extensions->InsertAll(registry_->blacklisted_extensions());
434 return installed_extensions.Pass();
437 extensions::PendingExtensionManager*
438 ExtensionService::pending_extension_manager() {
439 return &pending_extension_manager_;
442 ExtensionService::~ExtensionService() {
443 // No need to unload extensions here because they are profile-scoped, and the
444 // profile is in the process of being deleted.
446 extensions::ProviderCollection::const_iterator i;
447 for (i = external_extension_providers_.begin();
448 i != external_extension_providers_.end(); ++i) {
449 extensions::ExternalProviderInterface* provider = i->get();
450 provider->ServiceShutdown();
454 void ExtensionService::Shutdown() {
455 system_->management_policy()->UnregisterProvider(
456 shared_module_policy_provider_.get());
459 const Extension* ExtensionService::GetExtensionById(
460 const std::string& id, bool include_disabled) const {
461 int include_mask = ExtensionRegistry::ENABLED;
462 if (include_disabled) {
463 // Include blacklisted extensions here because there are hundreds of
464 // callers of this function, and many might assume that this includes those
465 // that have been disabled due to blacklisting.
466 include_mask |= ExtensionRegistry::DISABLED |
467 ExtensionRegistry::BLACKLISTED;
469 return registry_->GetExtensionById(id, include_mask);
472 GURL ExtensionService::GetSiteForExtensionId(const std::string& extension_id) {
473 return content::SiteInstance::GetSiteForURL(
475 Extension::GetBaseURLFromExtensionId(extension_id));
478 void ExtensionService::Init() {
479 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
481 base::Time begin_time = base::Time::Now();
483 DCHECK(!is_ready()); // Can't redo init.
484 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
486 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
487 if (cmd_line->HasSwitch(switches::kInstallFromWebstore) ||
488 cmd_line->HasSwitch(switches::kLimitedInstallFromWebstore)) {
489 // The sole purpose of this launch is to install a new extension from CWS
490 // and immediately terminate: loading already installed extensions is
491 // unnecessary and may interfere with the inline install dialog (e.g. if an
492 // extension listens to onStartup and opens a window).
493 SetReadyAndNotifyListeners();
495 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
496 component_loader_->LoadAll();
497 extensions::InstalledLoader(this).LoadAllExtensions();
499 ReconcileKnownDisabled();
501 // Attempt to re-enable extensions whose only disable reason is reloading.
502 std::vector<std::string> extensions_to_enable;
503 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
504 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
505 iter != disabled_extensions.end(); ++iter) {
506 const Extension* e = iter->get();
507 if (extension_prefs_->GetDisableReasons(e->id()) ==
508 Extension::DISABLE_RELOAD) {
509 extensions_to_enable.push_back(e->id());
512 for (std::vector<std::string>::iterator it = extensions_to_enable.begin();
513 it != extensions_to_enable.end(); ++it) {
514 EnableExtension(*it);
517 // Finish install (if possible) of extensions that were still delayed while
518 // the browser was shut down.
519 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
520 extension_prefs_->GetAllDelayedInstallInfo());
521 for (size_t i = 0; i < delayed_info->size(); ++i) {
522 ExtensionInfo* info = delayed_info->at(i).get();
523 scoped_refptr<const Extension> extension(NULL);
524 if (info->extension_manifest) {
526 extension = Extension::Create(
527 info->extension_path,
528 info->extension_location,
529 *info->extension_manifest,
530 extension_prefs_->GetDelayedInstallCreationFlags(
535 delayed_installs_.Insert(extension);
538 MaybeFinishDelayedInstallations();
540 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
541 extension_prefs_->GetAllDelayedInstallInfo());
542 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
543 delayed_info2->size() - delayed_info->size());
545 SetReadyAndNotifyListeners();
547 // TODO(erikkay) this should probably be deferred to a future point
548 // rather than running immediately at startup.
549 CheckForExternalUpdates();
551 InstallVerifier* verifier =
552 extensions::ExtensionSystem::Get(profile_)->install_verifier();
553 if (verifier->NeedsBootstrap())
554 VerifyAllExtensions();
555 base::MessageLoop::current()->PostDelayedTask(
557 base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
558 base::TimeDelta::FromSeconds(kGarbageCollectStartupDelay));
560 if (extension_prefs_->NeedsStorageGarbageCollection()) {
561 GarbageCollectIsolatedStorage();
562 extension_prefs_->SetNeedsStorageGarbageCollection(false);
564 system_->management_policy()->RegisterProvider(
565 shared_module_policy_provider_.get());
567 LoadGreylistFromPrefs();
570 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
571 base::Time::Now() - begin_time);
574 void ExtensionService::LoadGreylistFromPrefs() {
575 scoped_ptr<ExtensionSet> all_extensions = GenerateInstalledExtensionsSet();
577 for (ExtensionSet::const_iterator it = all_extensions->begin();
578 it != all_extensions->end(); ++it) {
579 extensions::BlacklistState state =
580 extension_prefs_->GetExtensionBlacklistState((*it)->id());
581 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
582 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
583 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
584 greylist_.Insert(*it);
588 void ExtensionService::VerifyAllExtensions() {
589 ExtensionIdSet to_add;
590 scoped_ptr<ExtensionSet> all_extensions = GenerateInstalledExtensionsSet();
592 for (ExtensionSet::const_iterator i = all_extensions->begin();
593 i != all_extensions->end(); ++i) {
594 const Extension& extension = **i;
596 if (InstallVerifier::NeedsVerification(extension))
597 to_add.insert(extension.id());
599 extensions::ExtensionSystem::Get(profile_)->install_verifier()->AddMany(
600 to_add, base::Bind(&ExtensionService::FinishVerifyAllExtensions,
604 void ExtensionService::FinishVerifyAllExtensions(bool success) {
606 // Check to see if any currently unverified extensions became verified.
607 InstallVerifier* verifier =
608 extensions::ExtensionSystem::Get(profile_)->install_verifier();
609 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
610 for (ExtensionSet::const_iterator i = disabled_extensions.begin();
611 i != disabled_extensions.end(); ++i) {
612 const Extension& extension = **i;
613 int disable_reasons = extension_prefs_->GetDisableReasons(extension.id());
614 if (disable_reasons & Extension::DISABLE_NOT_VERIFIED &&
615 !verifier->MustRemainDisabled(&extension, NULL, NULL)) {
616 extension_prefs_->RemoveDisableReason(extension.id(),
617 Extension::DISABLE_NOT_VERIFIED);
618 // Notify interested observers (eg the extensions settings page) by
619 // sending an UNLOADED notification.
621 // TODO(asargent) - this is a slight hack because it's already
622 // disabled; the right solution might be to add a separate listener
623 // interface for DisableReason's changing. http://crbug.com/328916
624 UnloadedExtensionInfo details(&extension,
625 UnloadedExtensionInfo::REASON_DISABLE);
626 content::NotificationService::current()->Notify(
627 chrome::NOTIFICATION_EXTENSION_UNLOADED,
628 content::Source<Profile>(profile_),
629 content::Details<UnloadedExtensionInfo>(&details));
632 // Might disable some extensions.
633 CheckManagementPolicy();
637 bool ExtensionService::UpdateExtension(const std::string& id,
638 const base::FilePath& extension_path,
639 bool file_ownership_passed,
640 const GURL& download_url,
641 CrxInstaller** out_crx_installer) {
642 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
643 if (browser_terminating_) {
644 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
645 // Leak the temp file at extension_path. We don't want to add to the disk
646 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
647 // the file is in the OS temp directory which should be cleaned up for us.
651 const extensions::PendingExtensionInfo* pending_extension_info =
652 pending_extension_manager()->GetById(id);
654 const Extension* extension = GetInstalledExtension(id);
655 if (!pending_extension_info && !extension) {
656 LOG(WARNING) << "Will not update extension " << id
657 << " because it is not installed or pending";
658 // Delete extension_path since we're not creating a CrxInstaller
659 // that would do it for us.
660 if (!GetFileTaskRunner()->PostTask(
663 &extension_file_util::DeleteFile, extension_path, false)))
669 // We want a silent install only for non-pending extensions and
670 // pending extensions that have install_silently set.
671 scoped_ptr<ExtensionInstallPrompt> client;
672 if (pending_extension_info && !pending_extension_info->install_silently())
673 client.reset(ExtensionInstallUI::CreateInstallPromptWithProfile(profile_));
675 scoped_refptr<CrxInstaller> installer(
676 CrxInstaller::Create(this, client.Pass()));
677 installer->set_expected_id(id);
678 int creation_flags = Extension::NO_FLAGS;
679 if (pending_extension_info) {
680 installer->set_install_source(pending_extension_info->install_source());
681 if (pending_extension_info->install_silently())
682 installer->set_allow_silent_install(true);
683 creation_flags = pending_extension_info->creation_flags();
684 if (pending_extension_info->mark_acknowledged())
685 AcknowledgeExternalExtension(id);
686 } else if (extension) {
687 installer->set_install_source(extension->location());
689 // If the extension was installed from or has migrated to the webstore, or
690 // its auto-update URL is from the webstore, treat it as a webstore install.
691 // Note that we ignore some older extensions with blank auto-update URLs
692 // because we are mostly concerned with restrictions on NaCl extensions,
694 if ((extension && extension->from_webstore()) ||
695 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
696 (!extension && extension_urls::IsWebstoreUpdateUrl(
697 pending_extension_info->update_url()))) {
698 creation_flags |= Extension::FROM_WEBSTORE;
701 // Bookmark apps being updated is kind of a contradiction, but that's because
702 // we mark the default apps as bookmark apps, and they're hosted in the web
703 // store, thus they can get updated. See http://crbug.com/101605 for more
705 if (extension && extension->from_bookmark())
706 creation_flags |= Extension::FROM_BOOKMARK;
708 if (extension && extension->was_installed_by_default())
709 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
711 if (extension && extension->is_ephemeral())
712 creation_flags |= Extension::IS_EPHEMERAL;
714 installer->set_creation_flags(creation_flags);
716 installer->set_delete_source(file_ownership_passed);
717 installer->set_download_url(download_url);
718 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
719 installer->InstallCrx(extension_path);
721 if (out_crx_installer)
722 *out_crx_installer = installer.get();
727 void ExtensionService::ReloadExtension(const std::string extension_id) {
728 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
730 // If the extension is already reloading, don't reload again.
731 if (extension_prefs_->GetDisableReasons(extension_id) &
732 Extension::DISABLE_RELOAD) {
737 const Extension* current_extension = GetExtensionById(extension_id, false);
739 // Disable the extension if it's loaded. It might not be loaded if it crashed.
740 if (current_extension) {
741 // If the extension has an inspector open for its background page, detach
742 // the inspector and hang onto a cookie for it, so that we can reattach
744 // TODO(yoz): this is not incognito-safe!
745 extensions::ProcessManager* manager = system_->process_manager();
746 extensions::ExtensionHost* host =
747 manager->GetBackgroundHostForExtension(extension_id);
748 if (host && DevToolsAgentHost::HasFor(host->render_view_host())) {
749 // Look for an open inspector for the background page.
750 scoped_refptr<DevToolsAgentHost> agent_host =
751 DevToolsAgentHost::GetOrCreateFor(host->render_view_host());
752 agent_host->DisconnectRenderViewHost();
753 orphaned_dev_tools_[extension_id] = agent_host;
756 path = current_extension->path();
757 // BeingUpgraded is set back to false when the extension is added.
758 system_->runtime_data()->SetBeingUpgraded(current_extension, true);
759 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
760 reloading_extensions_.insert(extension_id);
762 path = unloaded_extension_paths_[extension_id];
765 if (delayed_installs_.Contains(extension_id)) {
766 FinishDelayedInstallation(extension_id);
770 // If we're reloading a component extension, use the component extension
771 // loader's reloader.
772 if (component_loader_->Exists(extension_id)) {
773 SetBeingReloaded(extension_id, true);
774 component_loader_->Reload(extension_id);
775 SetBeingReloaded(extension_id, false);
779 // Check the installed extensions to see if what we're reloading was already
781 SetBeingReloaded(extension_id, true);
782 scoped_ptr<ExtensionInfo> installed_extension(
783 extension_prefs_->GetInstalledExtensionInfo(extension_id));
784 if (installed_extension.get() &&
785 installed_extension->extension_manifest.get()) {
786 extensions::InstalledLoader(this).Load(*installed_extension, false);
788 // Otherwise, the extension is unpacked (location LOAD).
789 // We should always be able to remember the extension's path. If it's not in
790 // the map, someone failed to update |unloaded_extension_paths_|.
791 CHECK(!path.empty());
792 extensions::UnpackedInstaller::Create(this)->Load(path);
794 // When reloading is done, mark this extension as done reloading.
795 SetBeingReloaded(extension_id, false);
798 bool ExtensionService::UninstallExtension(
799 std::string extension_id,
800 bool external_uninstall,
801 base::string16* error) {
802 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
804 scoped_refptr<const Extension> extension(GetInstalledExtension(extension_id));
806 // Callers should not send us nonexistent extensions.
807 CHECK(extension.get());
809 // Policy change which triggers an uninstall will always set
810 // |external_uninstall| to true so this is the only way to uninstall
811 // managed extensions.
812 if (!external_uninstall &&
813 !system_->management_policy()->UserMayModifySettings(
814 extension.get(), error)) {
815 content::NotificationService::current()->Notify(
816 chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
817 content::Source<Profile>(profile_),
818 content::Details<const Extension>(extension.get()));
822 syncer::SyncChange sync_change;
823 if (extension_sync_service_) {
824 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
825 extension.get(), is_ready());
828 extensions::ExtensionSystem::Get(profile_)->install_verifier()->Remove(
831 if (IsUnacknowledgedExternalExtension(extension.get())) {
832 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
833 EXTERNAL_EXTENSION_UNINSTALLED,
834 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
835 if (extensions::ManifestURL::UpdatesFromGallery(extension.get())) {
836 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
837 EXTERNAL_EXTENSION_UNINSTALLED,
838 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
840 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
841 EXTERNAL_EXTENSION_UNINSTALLED,
842 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
845 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
846 extension->GetType(), 100);
847 RecordPermissionMessagesHistogram(extension.get(),
848 "Extensions.Permissions_Uninstall");
850 // Unload before doing more cleanup to ensure that nothing is hanging on to
851 // any of these resources.
852 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
854 // Tell the backend to start deleting installed extensions on the file thread.
855 if (!Manifest::IsUnpackedLocation(extension->location())) {
856 if (!GetFileTaskRunner()->PostTask(
859 &extension_file_util::UninstallExtension,
865 extensions::DataDeleter::StartDeleting(profile_, extension.get());
867 UntrackTerminatedExtension(extension_id);
869 // Notify interested parties that we've uninstalled this extension.
870 content::NotificationService::current()->Notify(
871 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
872 content::Source<Profile>(profile_),
873 content::Details<const Extension>(extension.get()));
875 if (extension_sync_service_) {
876 extension_sync_service_->ProcessSyncUninstallExtension(extension_id,
880 delayed_installs_.Remove(extension_id);
882 PruneSharedModulesOnUninstall(extension.get());
884 extension_prefs_->OnExtensionUninstalled(extension_id, extension->location(),
887 // Track the uninstallation.
888 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
893 bool ExtensionService::IsExtensionEnabled(
894 const std::string& extension_id) const {
895 if (registry_->enabled_extensions().Contains(extension_id) ||
896 registry_->terminated_extensions().Contains(extension_id)) {
900 if (registry_->disabled_extensions().Contains(extension_id) ||
901 registry_->blacklisted_extensions().Contains(extension_id)) {
905 // If the extension hasn't been loaded yet, check the prefs for it. Assume
906 // enabled unless otherwise noted.
907 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
908 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
911 bool ExtensionService::IsExternalExtensionUninstalled(
912 const std::string& extension_id) const {
913 return extension_prefs_->IsExternalExtensionUninstalled(extension_id);
916 void ExtensionService::EnableExtension(const std::string& extension_id) {
917 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
919 if (IsExtensionEnabled(extension_id))
921 const Extension* extension =
922 registry_->disabled_extensions().GetByID(extension_id);
924 ManagementPolicy* policy = system_->management_policy();
925 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
926 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
930 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
931 extension_prefs_->ClearDisableReasons(extension_id);
933 // This can happen if sync enables an extension that is not
938 if (IsUnacknowledgedExternalExtension(extension)) {
939 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
940 EXTERNAL_EXTENSION_REENABLED,
941 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
942 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
943 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
944 EXTERNAL_EXTENSION_REENABLED,
945 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
947 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
948 EXTERNAL_EXTENSION_REENABLED,
949 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
951 AcknowledgeExternalExtension(extension->id());
954 // Move it over to the enabled list.
955 registry_->AddEnabled(make_scoped_refptr(extension));
956 registry_->RemoveDisabled(extension->id());
958 NotifyExtensionLoaded(extension);
960 // Notify listeners that the extension was enabled.
961 content::NotificationService::current()->Notify(
962 chrome::NOTIFICATION_EXTENSION_ENABLED,
963 content::Source<Profile>(profile_),
964 content::Details<const Extension>(extension));
966 if (extension_sync_service_)
967 extension_sync_service_->SyncEnableExtension(*extension);
970 void ExtensionService::DisableExtension(
971 const std::string& extension_id,
972 Extension::DisableReason disable_reason) {
973 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
975 // The extension may have been disabled already.
976 if (!IsExtensionEnabled(extension_id))
979 const Extension* extension = GetInstalledExtension(extension_id);
980 // |extension| can be NULL if sync disables an extension that is not
983 disable_reason != Extension::DISABLE_RELOAD &&
984 !system_->management_policy()->UserMayModifySettings(extension, NULL)) {
988 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
989 extension_prefs_->AddDisableReason(extension_id, disable_reason);
992 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
993 extension = registry_->GetExtensionById(extension_id, include_mask);
997 // The extension is either enabled or terminated.
998 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
999 registry_->terminated_extensions().Contains(extension->id()));
1001 // Move it over to the disabled list. Don't send a second unload notification
1002 // for terminated extensions being disabled.
1003 registry_->AddDisabled(make_scoped_refptr(extension));
1004 if (registry_->enabled_extensions().Contains(extension->id())) {
1005 registry_->RemoveEnabled(extension->id());
1006 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
1008 registry_->RemoveTerminated(extension->id());
1011 if (extension_sync_service_)
1012 extension_sync_service_->SyncDisableExtension(*extension);
1015 void ExtensionService::DisableUserExtensions(
1016 const std::vector<std::string>& except_ids) {
1017 extensions::ManagementPolicy* management_policy =
1018 system_->management_policy();
1019 extensions::ExtensionList to_disable;
1021 const ExtensionSet& enabled_set = registry_->enabled_extensions();
1022 for (ExtensionSet::const_iterator extension = enabled_set.begin();
1023 extension != enabled_set.end(); ++extension) {
1024 if (management_policy->UserMayModifySettings(extension->get(), NULL))
1025 to_disable.push_back(*extension);
1027 const ExtensionSet& terminated_set = registry_->terminated_extensions();
1028 for (ExtensionSet::const_iterator extension = terminated_set.begin();
1029 extension != terminated_set.end(); ++extension) {
1030 if (management_policy->UserMayModifySettings(extension->get(), NULL))
1031 to_disable.push_back(*extension);
1034 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
1035 extension != to_disable.end(); ++extension) {
1036 if ((*extension)->was_installed_by_default() &&
1037 extension_urls::IsWebstoreUpdateUrl(
1038 extensions::ManifestURL::GetUpdateURL(*extension)))
1040 const std::string& id = (*extension)->id();
1041 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
1042 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
1046 void ExtensionService::GrantPermissionsAndEnableExtension(
1047 const Extension* extension) {
1048 GrantPermissions(extension);
1049 RecordPermissionMessagesHistogram(
1050 extension, "Extensions.Permissions_ReEnable");
1051 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
1052 EnableExtension(extension->id());
1055 void ExtensionService::GrantPermissions(const Extension* extension) {
1057 extensions::PermissionsUpdater perms_updater(profile());
1058 perms_updater.GrantActivePermissions(extension);
1062 void ExtensionService::RecordPermissionMessagesHistogram(
1063 const Extension* extension, const char* histogram) {
1064 // Since this is called from multiple sources, and since the histogram macros
1065 // use statics, we need to manually lookup the histogram ourselves.
1066 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
1069 PermissionMessage::kEnumBoundary,
1070 PermissionMessage::kEnumBoundary + 1,
1071 base::HistogramBase::kUmaTargetedHistogramFlag);
1073 PermissionMessages permissions =
1074 extensions::PermissionsData::GetPermissionMessages(extension);
1075 if (permissions.empty()) {
1076 counter->Add(PermissionMessage::kNone);
1078 for (PermissionMessages::iterator it = permissions.begin();
1079 it != permissions.end(); ++it)
1080 counter->Add(it->id());
1084 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1085 // The ChromeURLRequestContexts need to be first to know that the extension
1086 // was loaded, otherwise a race can arise where a renderer that is created
1087 // for the extension may try to load an extension URL with an extension id
1088 // that the request context doesn't yet know about. The profile is responsible
1089 // for ensuring its URLRequestContexts appropriately discover the loaded
1091 system_->RegisterExtensionWithRequestContexts(extension);
1093 // Tell renderers about the new extension, unless it's a theme (renderers
1094 // don't need to know about themes).
1095 if (!extension->is_theme()) {
1096 for (content::RenderProcessHost::iterator i(
1097 content::RenderProcessHost::AllHostsIterator());
1098 !i.IsAtEnd(); i.Advance()) {
1099 content::RenderProcessHost* host = i.GetCurrentValue();
1100 Profile* host_profile =
1101 Profile::FromBrowserContext(host->GetBrowserContext());
1102 if (host_profile->GetOriginalProfile() ==
1103 profile_->GetOriginalProfile()) {
1104 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1105 1, ExtensionMsg_Loaded_Params(extension));
1107 new ExtensionMsg_Loaded(loaded_extensions));
1112 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1115 // NOTE: It is important that this happen after notifying the renderers about
1116 // the new extensions so that if we navigate to an extension URL in
1117 // NOTIFICATION_EXTENSION_LOADED, the renderer is guaranteed to know about it.
1118 content::NotificationService::current()->Notify(
1119 chrome::NOTIFICATION_EXTENSION_LOADED,
1120 content::Source<Profile>(profile_),
1121 content::Details<const Extension>(extension));
1123 // Tell a random-ass collection of other subsystems about the new extension.
1124 // TODO(aa): What should we do with all this goop? Can it move into the
1125 // relevant objects via EXTENSION_LOADED?
1127 profile_->GetExtensionSpecialStoragePolicy()->
1128 GrantRightsForExtension(extension);
1130 UpdateActiveExtensionsInCrashReporter();
1132 // If the extension has permission to load chrome://favicon/ resources we need
1133 // to make sure that the FaviconSource is registered with the
1134 // ChromeURLDataManager.
1135 if (extensions::PermissionsData::HasHostPermission(
1136 extension, GURL(chrome::kChromeUIFaviconURL))) {
1137 FaviconSource* favicon_source = new FaviconSource(profile_,
1138 FaviconSource::FAVICON);
1139 content::URLDataSource::Add(profile_, favicon_source);
1142 #if !defined(OS_ANDROID)
1143 // Same for chrome://theme/ resources.
1144 if (extensions::PermissionsData::HasHostPermission(
1145 extension, GURL(chrome::kChromeUIThemeURL))) {
1146 ThemeSource* theme_source = new ThemeSource(profile_);
1147 content::URLDataSource::Add(profile_, theme_source);
1151 // Same for chrome://thumb/ resources.
1152 if (extensions::PermissionsData::HasHostPermission(
1153 extension, GURL(chrome::kChromeUIThumbnailURL))) {
1154 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1155 content::URLDataSource::Add(profile_, thumbnail_source);
1159 void ExtensionService::NotifyExtensionUnloaded(
1160 const Extension* extension,
1161 UnloadedExtensionInfo::Reason reason) {
1162 registry_->TriggerOnUnloaded(extension);
1164 UnloadedExtensionInfo details(extension, reason);
1165 content::NotificationService::current()->Notify(
1166 chrome::NOTIFICATION_EXTENSION_UNLOADED,
1167 content::Source<Profile>(profile_),
1168 content::Details<UnloadedExtensionInfo>(&details));
1170 for (content::RenderProcessHost::iterator i(
1171 content::RenderProcessHost::AllHostsIterator());
1172 !i.IsAtEnd(); i.Advance()) {
1173 content::RenderProcessHost* host = i.GetCurrentValue();
1174 Profile* host_profile =
1175 Profile::FromBrowserContext(host->GetBrowserContext());
1176 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1177 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1180 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1181 profile_->GetExtensionSpecialStoragePolicy()->
1182 RevokeRightsForExtension(extension);
1184 #if defined(OS_CHROMEOS)
1185 // Revoke external file access for the extension from its file system context.
1186 // It is safe to access the extension's storage partition at this point. The
1187 // storage partition may get destroyed only after the extension gets unloaded.
1188 GURL site = extensions::ExtensionSystem::Get(profile_)->extension_service()->
1189 GetSiteForExtensionId(extension->id());
1190 fileapi::FileSystemContext* filesystem_context =
1191 BrowserContext::GetStoragePartitionForSite(profile_, site)->
1192 GetFileSystemContext();
1193 if (filesystem_context && filesystem_context->external_backend()) {
1194 filesystem_context->external_backend()->
1195 RevokeAccessForExtension(extension->id());
1199 UpdateActiveExtensionsInCrashReporter();
1202 Profile* ExtensionService::profile() {
1206 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1207 // Implemented in the .cc file to avoid adding a profile.h dependency to
1208 // extension_service.h.
1212 extensions::ExtensionPrefs* ExtensionService::extension_prefs() {
1213 return extension_prefs_;
1216 const extensions::ExtensionPrefs* ExtensionService::extension_prefs() const {
1217 return extension_prefs_;
1220 extensions::SettingsFrontend* ExtensionService::settings_frontend() {
1221 return settings_frontend_.get();
1224 extensions::ContentSettingsStore* ExtensionService::GetContentSettingsStore() {
1225 return extension_prefs()->content_settings_store();
1228 bool ExtensionService::is_ready() {
1229 return ready_->is_signaled();
1232 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1233 if (file_task_runner_.get())
1234 return file_task_runner_.get();
1236 // We should be able to interrupt any part of extension install process during
1237 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1238 // will be ignored/deleted while we will block on started tasks.
1239 std::string token("ext_install-");
1240 token.append(profile_->GetPath().AsUTF8Unsafe());
1241 file_task_runner_ = BrowserThread::GetBlockingPool()->
1242 GetSequencedTaskRunnerWithShutdownBehavior(
1243 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1244 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1245 return file_task_runner_.get();
1248 extensions::ExtensionUpdater* ExtensionService::updater() {
1249 return updater_.get();
1252 void ExtensionService::CheckManagementPolicy() {
1253 std::vector<std::string> to_unload;
1254 std::map<std::string, Extension::DisableReason> to_disable;
1256 // Loop through the extensions list, finding extensions we need to unload or
1258 const ExtensionSet& extensions = registry_->enabled_extensions();
1259 for (ExtensionSet::const_iterator iter = extensions.begin();
1260 iter != extensions.end(); ++iter) {
1261 const Extension* extension = (iter->get());
1262 if (!system_->management_policy()->UserMayLoad(extension, NULL))
1263 to_unload.push_back(extension->id());
1264 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1265 if (system_->management_policy()->MustRemainDisabled(
1266 extension, &disable_reason, NULL))
1267 to_disable[extension->id()] = disable_reason;
1270 for (size_t i = 0; i < to_unload.size(); ++i)
1271 UnloadExtension(to_unload[i], UnloadedExtensionInfo::REASON_DISABLE);
1273 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1274 to_disable.begin(); i != to_disable.end(); ++i)
1275 DisableExtension(i->first, i->second);
1278 void ExtensionService::CheckForUpdatesSoon() {
1280 if (AreAllExternalProvidersReady()) {
1281 updater()->CheckSoon();
1283 // Sync can start updating before all the external providers are ready
1284 // during startup. Start the update as soon as those providers are ready,
1286 update_once_all_providers_are_ready_ = true;
1289 LOG(WARNING) << "CheckForUpdatesSoon() called with auto-update turned off";
1293 void ExtensionService::OnExtensionMoved(
1294 const std::string& moved_extension_id,
1295 const std::string& predecessor_extension_id,
1296 const std::string& successor_extension_id) {
1297 extension_prefs_->app_sorting()->OnExtensionMoved(
1299 predecessor_extension_id,
1300 successor_extension_id);
1302 const Extension* extension = GetInstalledExtension(moved_extension_id);
1303 if (extension_sync_service_ && extension) {
1304 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1308 // Some extensions will autoupdate themselves externally from Chrome. These
1309 // are typically part of some larger client application package. To support
1310 // these, the extension will register its location in the the preferences file
1311 // (and also, on Windows, in the registry) and this code will periodically
1312 // check that location for a .crx file, which it will then install locally if
1313 // a new version is available.
1314 // Errors are reported through ExtensionErrorReporter. Succcess is not
1316 void ExtensionService::CheckForExternalUpdates() {
1317 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1319 // Note that this installation is intentionally silent (since it didn't
1320 // go through the front-end). Extensions that are registered in this
1321 // way are effectively considered 'pre-bundled', and so implicitly
1322 // trusted. In general, if something has HKLM or filesystem access,
1323 // they could install an extension manually themselves anyway.
1325 // Ask each external extension provider to give us a call back for each
1326 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1327 extensions::ProviderCollection::const_iterator i;
1328 for (i = external_extension_providers_.begin();
1329 i != external_extension_providers_.end(); ++i) {
1330 extensions::ExternalProviderInterface* provider = i->get();
1331 provider->VisitRegisteredExtension();
1334 // Do any required work that we would have done after completion of all
1336 if (external_extension_providers_.empty()) {
1337 OnAllExternalProvidersReady();
1341 void ExtensionService::OnExternalProviderReady(
1342 const extensions::ExternalProviderInterface* provider) {
1343 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1344 CHECK(provider->IsReady());
1346 // An external provider has finished loading. We only take action
1347 // if all of them are finished. So we check them first.
1348 if (AreAllExternalProvidersReady())
1349 OnAllExternalProvidersReady();
1352 bool ExtensionService::AreAllExternalProvidersReady() const {
1353 extensions::ProviderCollection::const_iterator i;
1354 for (i = external_extension_providers_.begin();
1355 i != external_extension_providers_.end(); ++i) {
1356 if (!i->get()->IsReady())
1362 void ExtensionService::OnAllExternalProvidersReady() {
1363 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1364 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1365 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1367 // Install any pending extensions.
1368 if (update_once_all_providers_are_ready_ && updater()) {
1369 update_once_all_providers_are_ready_ = false;
1370 extensions::ExtensionUpdater::CheckParams params;
1371 params.callback = external_updates_finished_callback_;
1372 updater()->CheckNow(params);
1375 // Uninstall all the unclaimed extensions.
1376 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1377 extension_prefs_->GetInstalledExtensionsInfo());
1378 for (size_t i = 0; i < extensions_info->size(); ++i) {
1379 ExtensionInfo* info = extensions_info->at(i).get();
1380 if (Manifest::IsExternalLocation(info->extension_location))
1381 CheckExternalUninstall(info->extension_id);
1383 IdentifyAlertableExtensions();
1386 void ExtensionService::IdentifyAlertableExtensions() {
1387 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1389 // Build up the lists of extensions that require acknowledgment. If this is
1390 // the first time, grandfather extensions that would have caused
1392 extension_error_ui_.reset(ExtensionErrorUI::Create(this));
1394 bool did_show_alert = false;
1395 if (PopulateExtensionErrorUI(extension_error_ui_.get())) {
1396 if (!is_first_run_) {
1397 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1398 did_show_alert = extension_error_ui_->ShowErrorInBubbleView();
1400 // First run. Just acknowledge all the extensions, silently, by
1401 // shortcutting the display of the UI and going straight to the
1402 // callback for pressing the Accept button.
1403 HandleExtensionAlertAccept();
1407 UpdateExternalExtensionAlert();
1409 if (!did_show_alert)
1410 extension_error_ui_.reset();
1413 bool ExtensionService::PopulateExtensionErrorUI(
1414 ExtensionErrorUI* extension_error_ui) {
1415 bool needs_alert = false;
1417 // Extensions that are blacklisted.
1418 const ExtensionSet& blacklisted_set = registry_->blacklisted_extensions();
1419 for (ExtensionSet::const_iterator it = blacklisted_set.begin();
1420 it != blacklisted_set.end(); ++it) {
1421 std::string id = (*it)->id();
1422 if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(id)) {
1423 extension_error_ui->AddBlacklistedExtension(id);
1428 const ExtensionSet& enabled_set = registry_->enabled_extensions();
1429 for (ExtensionSet::const_iterator iter = enabled_set.begin();
1430 iter != enabled_set.end(); ++iter) {
1431 const Extension* e = iter->get();
1433 // Skip for extensions that have pending updates. They will be checked again
1434 // once the pending update is finished.
1435 if (pending_extension_manager()->IsIdPending(e->id()))
1438 // Extensions disabled by policy. Note: this no longer includes blacklisted
1439 // extensions, though we still show the same UI.
1440 if (!system_->management_policy()->UserMayLoad(e, NULL)) {
1441 if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(e->id())) {
1442 extension_error_ui->AddBlacklistedExtension(e->id());
1451 void ExtensionService::HandleExtensionAlertClosed() {
1452 const ExtensionIdSet* extension_ids =
1453 extension_error_ui_->get_blacklisted_extension_ids();
1454 for (ExtensionIdSet::const_iterator iter = extension_ids->begin();
1455 iter != extension_ids->end(); ++iter) {
1456 extension_prefs_->AcknowledgeBlacklistedExtension(*iter);
1458 extension_error_ui_.reset();
1461 void ExtensionService::HandleExtensionAlertAccept() {
1462 extension_error_ui_->Close();
1465 void ExtensionService::AcknowledgeExternalExtension(const std::string& id) {
1466 extension_prefs_->AcknowledgeExternalExtension(id);
1467 UpdateExternalExtensionAlert();
1470 bool ExtensionService::IsUnacknowledgedExternalExtension(
1471 const Extension* extension) {
1472 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1475 return (Manifest::IsExternalLocation(extension->location()) &&
1476 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id()) &&
1477 !(extension_prefs_->GetDisableReasons(extension->id()) &
1478 Extension::DISABLE_SIDELOAD_WIPEOUT));
1481 void ExtensionService::ReconcileKnownDisabled() {
1482 ExtensionIdSet known_disabled_ids;
1483 if (!extension_prefs_->GetKnownDisabled(&known_disabled_ids)) {
1484 extension_prefs_->SetKnownDisabled(
1485 registry_->disabled_extensions().GetIDs());
1486 UMA_HISTOGRAM_BOOLEAN("Extensions.KnownDisabledInitialized", true);
1490 // Both |known_disabled_ids| and |extensions| are ordered (by definition
1491 // of std::map and std::set). Iterate forward over both sets in parallel
1492 // to find matching IDs and disable the corresponding extensions.
1493 const ExtensionSet& enabled_set = registry_->enabled_extensions();
1494 ExtensionSet::const_iterator extensions_it = enabled_set.begin();
1495 ExtensionIdSet::const_iterator known_disabled_ids_it =
1496 known_disabled_ids.begin();
1497 int known_disabled_count = 0;
1498 while (extensions_it != enabled_set.end() &&
1499 known_disabled_ids_it != known_disabled_ids.end()) {
1500 const std::string& extension_id = extensions_it->get()->id();
1501 const int comparison = extension_id.compare(*known_disabled_ids_it);
1502 if (comparison < 0) {
1504 } else if (comparison > 0) {
1505 ++known_disabled_ids_it;
1507 ++known_disabled_count;
1508 // Advance |extensions_it| immediately as it will be invalidated upon
1509 // disabling the extension it points to.
1511 ++known_disabled_ids_it;
1512 DisableExtension(extension_id, Extension::DISABLE_KNOWN_DISABLED);
1515 UMA_HISTOGRAM_COUNTS_100("Extensions.KnownDisabledReDisabled",
1516 known_disabled_count);
1518 // Update the list of known disabled to reflect every change to
1519 // |disabled_extensions_| from this point forward.
1520 registry_->SetDisabledModificationCallback(
1521 base::Bind(&extensions::ExtensionPrefs::SetKnownDisabled,
1522 base::Unretained(extension_prefs_)));
1525 void ExtensionService::HandleExtensionAlertDetails() {
1526 extension_error_ui_->ShowExtensions();
1527 // ShowExtensions may cause the error UI to close synchronously, e.g. if it
1528 // causes a navigation.
1529 if (extension_error_ui_)
1530 extension_error_ui_->Close();
1533 void ExtensionService::UpdateExternalExtensionAlert() {
1534 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1537 const Extension* extension = NULL;
1538 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
1539 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
1540 iter != disabled_extensions.end(); ++iter) {
1541 const Extension* e = iter->get();
1542 if (IsUnacknowledgedExternalExtension(e)) {
1549 if (!extensions::HasExternalInstallError(this)) {
1550 if (extension_prefs_->IncrementAcknowledgePromptCount(extension->id()) >
1551 kMaxExtensionAcknowledgePromptCount) {
1552 // Stop prompting for this extension, and check if there's another
1553 // one that needs prompting.
1554 extension_prefs_->AcknowledgeExternalExtension(extension->id());
1555 UpdateExternalExtensionAlert();
1556 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
1557 EXTERNAL_EXTENSION_IGNORED,
1558 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1559 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
1560 UMA_HISTOGRAM_ENUMERATION(
1561 "Extensions.ExternalExtensionEventWebstore",
1562 EXTERNAL_EXTENSION_IGNORED,
1563 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1565 UMA_HISTOGRAM_ENUMERATION(
1566 "Extensions.ExternalExtensionEventNonWebstore",
1567 EXTERNAL_EXTENSION_IGNORED,
1568 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1573 extension_prefs_->SetExternalInstallFirstRun(extension->id());
1574 // first_run is true if the extension was installed during a first run
1575 // (even if it's post-first run now).
1576 bool first_run = extension_prefs_->IsExternalInstallFirstRun(
1578 extensions::AddExternalInstallError(this, extension, first_run);
1581 extensions::RemoveExternalInstallError(this);
1585 void ExtensionService::UnloadExtension(
1586 const std::string& extension_id,
1587 UnloadedExtensionInfo::Reason reason) {
1588 // Make sure the extension gets deleted after we return from this function.
1590 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1591 scoped_refptr<const Extension> extension(
1592 registry_->GetExtensionById(extension_id, include_mask));
1594 // This method can be called via PostTask, so the extension may have been
1595 // unloaded by the time this runs.
1596 if (!extension.get()) {
1597 // In case the extension may have crashed/uninstalled. Allow the profile to
1598 // clean up its RequestContexts.
1599 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1603 // Keep information about the extension so that we can reload it later
1604 // even if it's not permanently installed.
1605 unloaded_extension_paths_[extension->id()] = extension->path();
1607 // Clean up if the extension is meant to be enabled after a reload.
1608 reloading_extensions_.erase(extension->id());
1610 if (registry_->disabled_extensions().Contains(extension->id())) {
1611 registry_->RemoveDisabled(extension->id());
1612 // Make sure the profile cleans up its RequestContexts when an already
1613 // disabled extension is unloaded (since they are also tracking the disabled
1615 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1616 // Don't send the unloaded notification. It was sent when the extension
1619 // Remove the extension from the enabled list.
1620 registry_->RemoveEnabled(extension->id());
1621 NotifyExtensionUnloaded(extension.get(), reason);
1624 content::NotificationService::current()->Notify(
1625 chrome::NOTIFICATION_EXTENSION_REMOVED,
1626 content::Source<Profile>(profile_),
1627 content::Details<const Extension>(extension.get()));
1630 void ExtensionService::RemoveComponentExtension(
1631 const std::string& extension_id) {
1632 scoped_refptr<const Extension> extension(
1633 GetExtensionById(extension_id, false));
1634 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1635 content::NotificationService::current()->Notify(
1636 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
1637 content::Source<Profile>(profile_),
1638 content::Details<const Extension>(extension.get()));
1641 void ExtensionService::UnloadAllExtensionsForTest() {
1642 UnloadAllExtensionsInternal();
1645 void ExtensionService::ReloadExtensionsForTest() {
1646 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1647 // warning about calling test code in production.
1648 UnloadAllExtensionsInternal();
1649 component_loader_->LoadAll();
1650 extensions::InstalledLoader(this).LoadAllExtensions();
1651 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1655 void ExtensionService::GarbageCollectExtensions() {
1656 #if defined(OS_CHROMEOS)
1657 if (disable_garbage_collection_)
1661 if (extension_prefs_->pref_service()->ReadOnly())
1664 bool clean_temp_dir = true;
1666 if (pending_extension_manager()->HasPendingExtensions()) {
1667 // Don't garbage collect temp dir while there are pending installations,
1668 // which may be using the temporary installation directory. Try to garbage
1669 // collect again later.
1670 clean_temp_dir = false;
1671 base::MessageLoop::current()->PostDelayedTask(
1673 base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
1674 base::TimeDelta::FromSeconds(kGarbageCollectRetryDelay));
1677 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> info(
1678 extension_prefs_->GetInstalledExtensionsInfo());
1680 std::multimap<std::string, base::FilePath> extension_paths;
1681 for (size_t i = 0; i < info->size(); ++i)
1682 extension_paths.insert(std::make_pair(info->at(i)->extension_id,
1683 info->at(i)->extension_path));
1685 info = extension_prefs_->GetAllDelayedInstallInfo();
1686 for (size_t i = 0; i < info->size(); ++i)
1687 extension_paths.insert(std::make_pair(info->at(i)->extension_id,
1688 info->at(i)->extension_path));
1690 if (!GetFileTaskRunner()->PostTask(
1693 &extension_file_util::GarbageCollectExtensions,
1701 void ExtensionService::SetReadyAndNotifyListeners() {
1703 content::NotificationService::current()->Notify(
1704 chrome::NOTIFICATION_EXTENSIONS_READY,
1705 content::Source<Profile>(profile_),
1706 content::NotificationService::NoDetails());
1709 void ExtensionService::OnLoadedInstalledExtensions() {
1713 OnBlacklistUpdated();
1716 void ExtensionService::AddExtension(const Extension* extension) {
1717 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1718 // default extension state to DISABLED when the --disable-extensions flag
1719 // is set (http://crbug.com/29067).
1720 if (!extensions_enabled() &&
1721 !extension->is_theme() &&
1722 extension->location() != Manifest::COMPONENT &&
1723 !Manifest::IsExternalLocation(extension->location())) {
1727 bool is_extension_upgrade = false;
1728 bool is_extension_installed = false;
1729 const Extension* old = GetInstalledExtension(extension->id());
1731 is_extension_installed = true;
1732 int version_compare_result =
1733 extension->version()->CompareTo(*(old->version()));
1734 is_extension_upgrade = version_compare_result > 0;
1735 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1736 // that we aren't downgrading.
1737 if (!Manifest::IsUnpackedLocation(extension->location()))
1738 CHECK_GE(version_compare_result, 0);
1740 system_->runtime_data()->SetBeingUpgraded(extension, is_extension_upgrade);
1742 // The extension is now loaded, remove its data from unloaded extension map.
1743 unloaded_extension_paths_.erase(extension->id());
1745 // If a terminated extension is loaded, remove it from the terminated list.
1746 UntrackTerminatedExtension(extension->id());
1748 // If the extension was disabled for a reload, then enable it.
1749 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1751 // Check if the extension's privileges have changed and mark the
1752 // extension disabled if necessary.
1753 CheckPermissionsIncrease(extension, is_extension_installed);
1755 if (is_extension_installed && !reloading) {
1756 // To upgrade an extension in place, unload the old one and then load the
1757 // new one. ReloadExtension disables the extension, which is sufficient.
1758 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1761 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1762 // Only prefs is checked for the blacklist. We rely on callers to check the
1763 // blacklist before calling into here, e.g. CrxInstaller checks before
1764 // installation then threads through the install and pending install flow
1765 // of this class, and we check when loading installed extensions.
1766 registry_->AddBlacklisted(extension);
1767 } else if (!reloading &&
1768 extension_prefs_->IsExtensionDisabled(extension->id())) {
1769 registry_->AddDisabled(extension);
1770 if (extension_sync_service_)
1771 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1772 content::NotificationService::current()->Notify(
1773 chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1774 content::Source<Profile>(profile_),
1775 content::Details<const Extension>(extension));
1777 // Show the extension disabled error if a permissions increase was the
1778 // only reason it was disabled.
1779 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1780 Extension::DISABLE_PERMISSIONS_INCREASE) {
1781 extensions::AddExtensionDisabledError(this, extension);
1783 } else if (reloading) {
1784 // Replace the old extension with the new version.
1785 CHECK(!registry_->AddDisabled(extension));
1786 EnableExtension(extension->id());
1788 // All apps that are displayed in the launcher are ordered by their ordinals
1789 // so we must ensure they have valid ordinals.
1790 if (extension->RequiresSortOrdinal()) {
1791 if (!extension->ShouldDisplayInNewTabPage()) {
1792 extension_prefs_->app_sorting()->MarkExtensionAsHidden(extension->id());
1794 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1795 extension->id(), syncer::StringOrdinal());
1798 registry_->AddEnabled(extension);
1799 if (extension_sync_service_)
1800 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1801 NotifyExtensionLoaded(extension);
1803 system_->runtime_data()->SetBeingUpgraded(extension, false);
1806 void ExtensionService::AddComponentExtension(const Extension* extension) {
1807 const std::string old_version_string(
1808 extension_prefs_->GetVersionString(extension->id()));
1809 const Version old_version(old_version_string);
1811 VLOG(1) << "AddComponentExtension " << extension->name();
1812 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1813 VLOG(1) << "Component extension " << extension->name() << " ("
1814 << extension->id() << ") installing/upgrading from '"
1815 << old_version_string << "' to " << extension->version()->GetString();
1817 AddNewOrUpdatedExtension(extension,
1818 Extension::ENABLED_COMPONENT,
1819 extensions::NOT_BLACKLISTED,
1820 syncer::StringOrdinal());
1824 AddExtension(extension);
1827 void ExtensionService::UpdateActivePermissions(const Extension* extension) {
1828 // If the extension has used the optional permissions API, it will have a
1829 // custom set of active permissions defined in the extension prefs. Here,
1830 // we update the extension's active permissions based on the prefs.
1831 scoped_refptr<PermissionSet> active_permissions =
1832 extension_prefs()->GetActivePermissions(extension->id());
1834 if (active_permissions.get()) {
1835 // We restrict the active permissions to be within the bounds defined in the
1836 // extension's manifest.
1837 // a) active permissions must be a subset of optional + default permissions
1838 // b) active permissions must contains all default permissions
1839 scoped_refptr<PermissionSet> total_permissions =
1840 PermissionSet::CreateUnion(
1841 extensions::PermissionsData::GetRequiredPermissions(extension),
1842 extensions::PermissionsData::GetOptionalPermissions(extension));
1844 // Make sure the active permissions contain no more than optional + default.
1845 scoped_refptr<PermissionSet> adjusted_active =
1846 PermissionSet::CreateIntersection(
1847 total_permissions.get(), active_permissions.get());
1849 // Make sure the active permissions contain the default permissions.
1850 adjusted_active = PermissionSet::CreateUnion(
1851 extensions::PermissionsData::GetRequiredPermissions(extension),
1852 adjusted_active.get());
1854 extensions::PermissionsUpdater perms_updater(profile());
1855 perms_updater.UpdateActivePermissions(extension, adjusted_active.get());
1859 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1860 bool is_extension_installed) {
1861 UpdateActivePermissions(extension);
1863 // We keep track of all permissions the user has granted each extension.
1864 // This allows extensions to gracefully support backwards compatibility
1865 // by including unknown permissions in their manifests. When the user
1866 // installs the extension, only the recognized permissions are recorded.
1867 // When the unknown permissions become recognized (e.g., through browser
1868 // upgrade), we can prompt the user to accept these new permissions.
1869 // Extensions can also silently upgrade to less permissions, and then
1870 // silently upgrade to a version that adds these permissions back.
1872 // For example, pretend that Chrome 10 includes a permission "omnibox"
1873 // for an API that adds suggestions to the omnibox. An extension can
1874 // maintain backwards compatibility while still having "omnibox" in the
1875 // manifest. If a user installs the extension on Chrome 9, the browser
1876 // will record the permissions it recognized, not including "omnibox."
1877 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1878 // will disable the extension and prompt the user to approve the increase
1879 // in privileges. The extension could then release a new version that
1880 // removes the "omnibox" permission. When the user upgrades, Chrome will
1881 // still remember that "omnibox" had been granted, so that if the
1882 // extension once again includes "omnibox" in an upgrade, the extension
1883 // can upgrade without requiring this user's approval.
1884 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1886 bool auto_grant_permission =
1887 (!is_extension_installed && extension->was_installed_by_default()) ||
1888 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1889 // Silently grant all active permissions to default apps only on install.
1890 // After install they should behave like other apps.
1891 // Silently grant all active permissions to apps install in kiosk mode on both
1892 // install and update.
1893 if (auto_grant_permission)
1894 GrantPermissions(extension);
1896 bool is_privilege_increase = false;
1897 // We only need to compare the granted permissions to the current permissions
1898 // if the extension is not allowed to silently increase its permissions.
1899 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) &&
1900 !auto_grant_permission) {
1901 // Add all the recognized permissions if the granted permissions list
1902 // hasn't been initialized yet.
1903 scoped_refptr<PermissionSet> granted_permissions =
1904 extension_prefs_->GetGrantedPermissions(extension->id());
1905 CHECK(granted_permissions.get());
1907 // Here, we check if an extension's privileges have increased in a manner
1908 // that requires the user's approval. This could occur because the browser
1909 // upgraded and recognized additional privileges, or an extension upgrades
1910 // to a version that requires additional privileges.
1911 is_privilege_increase =
1912 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1913 granted_permissions,
1914 extension->GetActivePermissions().get(),
1915 extension->GetType());
1918 if (is_extension_installed) {
1919 // If the extension was already disabled, suppress any alerts for becoming
1920 // disabled on permissions increase.
1921 bool previously_disabled =
1922 extension_prefs_->IsExtensionDisabled(extension->id());
1923 // Legacy disabled extensions do not have a disable reason. Infer that if
1924 // there was no permission increase, it was likely disabled by the user.
1925 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1926 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1927 disable_reasons |= Extension::DISABLE_USER_ACTION;
1929 // Extensions that came to us disabled from sync need a similar inference,
1930 // except based on the new version's permissions.
1931 if (previously_disabled &&
1932 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1933 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1934 extension_prefs_->ClearDisableReasons(extension->id());
1935 if (!is_privilege_increase)
1936 disable_reasons |= Extension::DISABLE_USER_ACTION;
1938 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1941 // Extension has changed permissions significantly. Disable it. A
1942 // notification should be sent by the caller.
1943 if (is_privilege_increase) {
1944 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1945 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1946 RecordPermissionMessagesHistogram(
1947 extension, "Extensions.Permissions_AutoDisable");
1949 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1950 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1952 if (disable_reasons != Extension::DISABLE_NONE) {
1953 extension_prefs_->AddDisableReason(
1955 static_cast<Extension::DisableReason>(disable_reasons));
1959 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1960 std::set<std::string> extension_ids;
1961 const ExtensionSet& extensions = registry_->enabled_extensions();
1962 for (ExtensionSet::const_iterator iter = extensions.begin();
1963 iter != extensions.end(); ++iter) {
1964 const Extension* extension = iter->get();
1965 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1966 extension_ids.insert(extension->id());
1969 crash_keys::SetActiveExtensions(extension_ids);
1972 ExtensionService::ImportStatus ExtensionService::CheckImports(
1973 const extensions::Extension* extension,
1974 std::list<SharedModuleInfo::ImportInfo>* missing_modules,
1975 std::list<SharedModuleInfo::ImportInfo>* outdated_modules) {
1977 DCHECK(missing_modules && missing_modules->empty());
1978 DCHECK(outdated_modules && outdated_modules->empty());
1979 ImportStatus status = IMPORT_STATUS_OK;
1980 if (SharedModuleInfo::ImportsModules(extension)) {
1981 const std::vector<SharedModuleInfo::ImportInfo>& imports =
1982 SharedModuleInfo::GetImports(extension);
1983 std::vector<SharedModuleInfo::ImportInfo>::const_iterator i;
1984 for (i = imports.begin(); i != imports.end(); ++i) {
1985 Version version_required(i->minimum_version);
1986 const Extension* imported_module =
1987 GetExtensionById(i->extension_id, true);
1988 if (!imported_module) {
1989 if (extension->from_webstore()) {
1990 status = IMPORT_STATUS_UNSATISFIED;
1991 missing_modules->push_back(*i);
1993 return IMPORT_STATUS_UNRECOVERABLE;
1995 } else if (!SharedModuleInfo::IsSharedModule(imported_module)) {
1996 return IMPORT_STATUS_UNRECOVERABLE;
1997 } else if (version_required.IsValid() &&
1998 imported_module->version()->CompareTo(version_required) < 0) {
1999 if (imported_module->from_webstore()) {
2000 outdated_modules->push_back(*i);
2001 status = IMPORT_STATUS_UNSATISFIED;
2003 return IMPORT_STATUS_UNRECOVERABLE;
2011 ExtensionService::ImportStatus ExtensionService::SatisfyImports(
2012 const Extension* extension) {
2013 std::list<SharedModuleInfo::ImportInfo> noinstalled;
2014 std::list<SharedModuleInfo::ImportInfo> outdated;
2015 ImportStatus status = CheckImports(extension, &noinstalled, &outdated);
2016 if (status == IMPORT_STATUS_UNRECOVERABLE)
2018 if (status == IMPORT_STATUS_UNSATISFIED) {
2019 std::list<SharedModuleInfo::ImportInfo>::const_iterator iter;
2020 for (iter = noinstalled.begin(); iter != noinstalled.end(); ++iter) {
2021 pending_extension_manager()->AddFromExtensionImport(
2023 extension_urls::GetWebstoreUpdateUrl(),
2026 CheckForUpdatesSoon();
2031 scoped_ptr<const ExtensionSet>
2032 ExtensionService::GetDependentExtensions(const Extension* extension) {
2033 scoped_ptr<ExtensionSet> dependents(new ExtensionSet());
2034 scoped_ptr<ExtensionSet> set_to_check(new ExtensionSet());
2035 if (SharedModuleInfo::IsSharedModule(extension)) {
2036 set_to_check->InsertAll(registry_->disabled_extensions());
2037 set_to_check->InsertAll(delayed_installs_);
2038 set_to_check->InsertAll(registry_->enabled_extensions());
2039 for (ExtensionSet::const_iterator iter = set_to_check->begin();
2040 iter != set_to_check->end(); ++iter) {
2041 if (SharedModuleInfo::ImportsExtensionById(iter->get(),
2043 dependents->Insert(*iter);
2047 return dependents.PassAs<const ExtensionSet>();
2050 void ExtensionService::PruneSharedModulesOnUninstall(
2051 const Extension* extension) {
2052 if (SharedModuleInfo::ImportsModules(extension)) {
2053 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2054 SharedModuleInfo::GetImports(extension);
2055 std::vector<SharedModuleInfo::ImportInfo>::const_iterator i;
2056 for (i = imports.begin(); i != imports.end(); ++i) {
2057 const Extension* imported_module =
2058 GetExtensionById(i->extension_id, true);
2059 if (imported_module && imported_module->from_webstore()) {
2060 scoped_ptr<const ExtensionSet> dependents =
2061 GetDependentExtensions(imported_module);
2062 if (dependents->size() == 0) {
2063 UninstallExtension(i->extension_id, true, NULL);
2070 void ExtensionService::OnExtensionInstalled(
2071 const Extension* extension,
2072 const syncer::StringOrdinal& page_ordinal,
2073 bool has_requirement_errors,
2074 extensions::BlacklistState blacklist_state,
2075 bool wait_for_idle) {
2076 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2078 const std::string& id = extension->id();
2079 bool initial_enable = ShouldEnableOnInstall(extension);
2080 const extensions::PendingExtensionInfo* pending_extension_info = NULL;
2081 if ((pending_extension_info = pending_extension_manager()->GetById(id))) {
2082 if (!pending_extension_info->ShouldAllowInstall(extension)) {
2083 pending_extension_manager()->Remove(id);
2085 LOG(WARNING) << "ShouldAllowInstall() returned false for "
2086 << id << " of type " << extension->GetType()
2087 << " and update URL "
2088 << extensions::ManifestURL::GetUpdateURL(extension).spec()
2089 << "; not installing";
2091 // Delete the extension directory since we're not going to
2093 if (!GetFileTaskRunner()->PostTask(
2095 base::Bind(&extension_file_util::DeleteFile,
2096 extension->path(), true))) {
2102 pending_extension_manager()->Remove(id);
2104 // We explicitly want to re-enable an uninstalled external
2105 // extension; if we're here, that means the user is manually
2106 // installing the extension.
2107 if (IsExternalExtensionUninstalled(id)) {
2108 initial_enable = true;
2112 // Unsupported requirements overrides the management policy.
2113 if (has_requirement_errors) {
2114 initial_enable = false;
2115 extension_prefs_->AddDisableReason(
2116 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
2117 // If the extension was disabled because of unsupported requirements but
2118 // now supports all requirements after an update and there are not other
2119 // disable reasons, enable it.
2120 } else if (extension_prefs_->GetDisableReasons(id) ==
2121 Extension::DISABLE_UNSUPPORTED_REQUIREMENT) {
2122 initial_enable = true;
2123 extension_prefs_->ClearDisableReasons(id);
2126 if (blacklist_state == extensions::BLACKLISTED_MALWARE) {
2127 // Installation of a blacklisted extension can happen from sync, policy,
2128 // etc, where to maintain consistency we need to install it, just never
2129 // load it (see AddExtension). Usually it should be the job of callers to
2130 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
2131 // showing the install dialogue).
2132 extension_prefs()->AcknowledgeBlacklistedExtension(id);
2133 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
2134 extension->location(),
2135 Manifest::NUM_LOCATIONS);
2138 if (!GetInstalledExtension(extension->id())) {
2139 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
2140 extension->GetType(), 100);
2141 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
2142 extension->location(), Manifest::NUM_LOCATIONS);
2143 RecordPermissionMessagesHistogram(
2144 extension, "Extensions.Permissions_Install");
2146 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
2147 extension->GetType(), 100);
2148 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
2149 extension->location(), Manifest::NUM_LOCATIONS);
2152 // Certain extension locations are specific enough that we can
2153 // auto-acknowledge any extension that came from one of them.
2154 if (Manifest::IsPolicyLocation(extension->location()))
2155 AcknowledgeExternalExtension(extension->id());
2156 const Extension::State initial_state =
2157 initial_enable ? Extension::ENABLED : Extension::DISABLED;
2158 const bool blacklisted_for_malware =
2159 blacklist_state == extensions::BLACKLISTED_MALWARE;
2160 if (ShouldDelayExtensionUpdate(id, wait_for_idle)) {
2161 extension_prefs_->SetDelayedInstallInfo(
2164 blacklisted_for_malware,
2165 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
2168 // Transfer ownership of |extension|.
2169 delayed_installs_.Insert(extension);
2171 // Notify observers that app update is available.
2172 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2173 OnAppUpdateAvailable(extension));
2177 ImportStatus status = SatisfyImports(extension);
2178 if (installs_delayed_for_gc()) {
2179 extension_prefs_->SetDelayedInstallInfo(
2182 blacklisted_for_malware,
2183 extensions::ExtensionPrefs::DELAY_REASON_GC,
2185 delayed_installs_.Insert(extension);
2186 } else if (status != IMPORT_STATUS_OK) {
2187 if (status == IMPORT_STATUS_UNSATISFIED) {
2188 extension_prefs_->SetDelayedInstallInfo(
2191 blacklisted_for_malware,
2192 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
2194 delayed_installs_.Insert(extension);
2197 AddNewOrUpdatedExtension(extension,
2204 void ExtensionService::AddNewOrUpdatedExtension(
2205 const Extension* extension,
2206 Extension::State initial_state,
2207 extensions::BlacklistState blacklist_state,
2208 const syncer::StringOrdinal& page_ordinal) {
2209 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2210 const bool blacklisted_for_malware =
2211 blacklist_state == extensions::BLACKLISTED_MALWARE;
2212 extension_prefs_->OnExtensionInstalled(extension,
2214 blacklisted_for_malware,
2216 delayed_installs_.Remove(extension->id());
2217 if (InstallVerifier::NeedsVerification(*extension)) {
2218 extensions::ExtensionSystem::Get(profile_)->install_verifier()->Add(
2219 extension->id(), InstallVerifier::AddResultCallback());
2221 FinishInstallation(extension);
2224 void ExtensionService::MaybeFinishDelayedInstallation(
2225 const std::string& extension_id) {
2226 // Check if the extension already got installed.
2227 if (!delayed_installs_.Contains(extension_id))
2229 extensions::ExtensionPrefs::DelayReason reason =
2230 extension_prefs_->GetDelayedInstallReason(extension_id);
2232 // Check if the extension is idle. DELAY_REASON_NONE is used for older
2233 // preferences files that will not have set this field but it was previously
2234 // only used for idle updates.
2235 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
2236 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
2237 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
2240 const Extension* extension = delayed_installs_.GetByID(extension_id);
2241 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
2242 ImportStatus status = SatisfyImports(extension);
2243 if (status != IMPORT_STATUS_OK) {
2244 if (status == IMPORT_STATUS_UNRECOVERABLE) {
2245 delayed_installs_.Remove(extension_id);
2246 // Make sure no version of the extension is actually installed, (i.e.,
2247 // that this delayed install was not an update).
2248 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
2249 extension_prefs_->DeleteExtensionPrefs(extension_id);
2255 FinishDelayedInstallation(extension_id);
2258 void ExtensionService::FinishDelayedInstallation(
2259 const std::string& extension_id) {
2260 scoped_refptr<const Extension> extension(
2261 GetPendingExtensionUpdate(extension_id));
2262 CHECK(extension.get());
2263 delayed_installs_.Remove(extension_id);
2265 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
2268 FinishInstallation(extension.get());
2271 void ExtensionService::FinishInstallation(const Extension* extension) {
2272 const extensions::Extension* existing_extension =
2273 GetInstalledExtension(extension->id());
2274 bool is_update = false;
2275 std::string old_name;
2276 if (existing_extension) {
2278 old_name = existing_extension->name();
2280 extensions::InstalledExtensionInfo details(extension, is_update, old_name);
2281 content::NotificationService::current()->Notify(
2282 chrome::NOTIFICATION_EXTENSION_INSTALLED,
2283 content::Source<Profile>(profile_),
2284 content::Details<const extensions::InstalledExtensionInfo>(&details));
2286 bool unacknowledged_external = IsUnacknowledgedExternalExtension(extension);
2288 // Unpacked extensions default to allowing file access, but if that has been
2289 // overridden, don't reset the value.
2290 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
2291 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
2292 extension_prefs_->SetAllowFileAccess(extension->id(), true);
2295 AddExtension(extension);
2297 // If this is a new external extension that was disabled, alert the user
2298 // so he can reenable it. We do this last so that it has already been
2299 // added to our list of extensions.
2300 if (unacknowledged_external && !is_update) {
2301 UpdateExternalExtensionAlert();
2302 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
2303 EXTERNAL_EXTENSION_INSTALLED,
2304 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
2305 if (extensions::ManifestURL::UpdatesFromGallery(extension)) {
2306 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
2307 EXTERNAL_EXTENSION_INSTALLED,
2308 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
2310 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
2311 EXTERNAL_EXTENSION_INSTALLED,
2312 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
2316 // Check extensions that may have been delayed only because this shared module
2317 // was not available.
2318 if (SharedModuleInfo::IsSharedModule(extension)) {
2319 MaybeFinishDelayedInstallations();
2323 const Extension* ExtensionService::GetPendingExtensionUpdate(
2324 const std::string& id) const {
2325 return delayed_installs_.GetByID(id);
2328 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
2329 // No need to check for duplicates; inserting a duplicate is a no-op.
2330 registry_->AddTerminated(make_scoped_refptr(extension));
2331 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2334 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2335 std::string lowercase_id = StringToLowerASCII(id);
2336 const Extension* extension =
2337 registry_->terminated_extensions().GetByID(lowercase_id);
2338 registry_->RemoveTerminated(lowercase_id);
2340 content::NotificationService::current()->Notify(
2341 chrome::NOTIFICATION_EXTENSION_REMOVED,
2342 content::Source<Profile>(profile_),
2343 content::Details<const Extension>(extension));
2347 const Extension* ExtensionService::GetTerminatedExtension(
2348 const std::string& id) const {
2349 return registry_->GetExtensionById(id, ExtensionRegistry::TERMINATED);
2352 const Extension* ExtensionService::GetInstalledExtension(
2353 const std::string& id) const {
2354 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2357 bool ExtensionService::ExtensionBindingsAllowed(const GURL& url) {
2358 // Allow bindings for all packaged extensions and component hosted apps.
2359 const Extension* extension =
2360 registry_->enabled_extensions().GetExtensionOrAppByURL(url);
2361 return extension && (!extension->is_hosted_app() ||
2362 extension->location() == Manifest::COMPONENT);
2365 bool ExtensionService::ShouldBlockUrlInBrowserTab(GURL* url) {
2366 const Extension* extension =
2367 registry_->enabled_extensions().GetExtensionOrAppByURL(*url);
2368 if (extension && extension->is_platform_app()) {
2369 *url = GURL(chrome::kExtensionInvalidRequestURL);
2376 bool ExtensionService::OnExternalExtensionFileFound(
2377 const std::string& id,
2378 const Version* version,
2379 const base::FilePath& path,
2380 Manifest::Location location,
2382 bool mark_acknowledged) {
2383 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2384 CHECK(Extension::IdIsValid(id));
2385 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2388 // Before even bothering to unpack, check and see if we already have this
2389 // version. This is important because these extensions are going to get
2390 // installed on every startup.
2391 const Extension* existing = GetExtensionById(id, true);
2394 // The default apps will have the location set as INTERNAL. Since older
2395 // default apps are installed as EXTERNAL, we override them. However, if the
2396 // app is already installed as internal, then do the version check.
2397 // TODO(grv) : Remove after Q1-2013.
2398 bool is_default_apps_migration =
2399 (location == Manifest::INTERNAL &&
2400 Manifest::IsExternalLocation(existing->location()));
2402 if (!is_default_apps_migration) {
2405 switch (existing->version()->CompareTo(*version)) {
2406 case -1: // existing version is older, we should upgrade
2408 case 0: // existing version is same, do nothing
2410 case 1: // existing version is newer, uh-oh
2411 LOG(WARNING) << "Found external version of extension " << id
2412 << "that is older than current version. Current version "
2413 << "is: " << existing->VersionString() << ". New "
2414 << "version is: " << version->GetString()
2415 << ". Keeping current version.";
2421 // If the extension is already pending, don't start an install.
2422 if (!pending_extension_manager()->AddFromExternalFile(
2423 id, location, *version, creation_flags, mark_acknowledged)) {
2427 // no client (silent install)
2428 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2429 installer->set_install_source(location);
2430 installer->set_expected_id(id);
2431 installer->set_expected_version(*version);
2432 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2433 installer->set_creation_flags(creation_flags);
2434 #if defined(OS_CHROMEOS)
2435 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2437 installer->InstallCrx(path);
2440 // Depending on the source, a new external extension might not need a user
2441 // notification on installation. For such extensions, mark them acknowledged
2442 // now to suppress the notification.
2443 if (mark_acknowledged)
2444 AcknowledgeExternalExtension(id);
2449 scoped_ptr<base::DictionaryValue> ExtensionService::GetExtensionInfo(
2450 const std::string& extension_id) const {
2451 scoped_ptr<base::DictionaryValue> dictionary(new base::DictionaryValue);
2452 const extensions::Extension* extension =
2453 registry_->enabled_extensions().GetByID(extension_id);
2455 GURL icon = extensions::ExtensionIconSource::GetIconURL(
2456 extension, extension_misc::EXTENSION_ICON_SMALLISH,
2457 ExtensionIconSet::MATCH_BIGGER, false, NULL);
2458 dictionary->SetString("id", extension_id);
2459 dictionary->SetString("name", extension->name());
2460 dictionary->SetString("icon", icon.spec());
2462 return dictionary.Pass();
2465 void ExtensionService::ReportExtensionLoadError(
2466 const base::FilePath& extension_path,
2467 const std::string &error,
2469 content::NotificationService::current()->Notify(
2470 chrome::NOTIFICATION_EXTENSION_LOAD_ERROR,
2471 content::Source<Profile>(profile_),
2472 content::Details<const std::string>(&error));
2474 std::string path_str = base::UTF16ToUTF8(extension_path.LossyDisplayName());
2475 base::string16 message = base::UTF8ToUTF16(base::StringPrintf(
2476 "Could not load extension from '%s'. %s",
2477 path_str.c_str(), error.c_str()));
2478 ExtensionErrorReporter::GetInstance()->ReportError(message, be_noisy);
2481 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2482 extensions::ExtensionHost* host) {
2483 OrphanedDevTools::iterator iter =
2484 orphaned_dev_tools_.find(host->extension_id());
2485 if (iter == orphaned_dev_tools_.end())
2488 iter->second->ConnectRenderViewHost(host->render_view_host());
2489 orphaned_dev_tools_.erase(iter);
2492 void ExtensionService::Observe(int type,
2493 const content::NotificationSource& source,
2494 const content::NotificationDetails& details) {
2496 case chrome::NOTIFICATION_APP_TERMINATING:
2497 // Shutdown has started. Don't start any more extension installs.
2498 // (We cannot use ExtensionService::Shutdown() for this because it
2499 // happens too late in browser teardown.)
2500 browser_terminating_ = true;
2502 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2504 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2508 extensions::ExtensionHost* host =
2509 content::Details<extensions::ExtensionHost>(details).ptr();
2511 // Mark the extension as terminated and Unload it. We want it to
2512 // be in a consistent state: either fully working or not loaded
2513 // at all, but never half-crashed. We do it in a PostTask so
2514 // that other handlers of this notification will still have
2515 // access to the Extension and ExtensionHost.
2516 base::MessageLoop::current()->PostTask(
2519 &ExtensionService::TrackTerminatedExtension,
2521 host->extension()));
2524 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2525 content::RenderProcessHost* process =
2526 content::Source<content::RenderProcessHost>(source).ptr();
2527 Profile* host_profile =
2528 Profile::FromBrowserContext(process->GetBrowserContext());
2529 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2532 extensions::ProcessMap* process_map =
2533 extensions::ProcessMap::Get(profile_);
2534 if (process_map->Contains(process->GetID())) {
2535 // An extension process was terminated, this might have resulted in an
2536 // app or extension becoming idle.
2537 std::set<std::string> extension_ids =
2538 process_map->GetExtensionsInProcess(process->GetID());
2539 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2540 it != extension_ids.end(); ++it) {
2541 if (delayed_installs_.Contains(*it)) {
2542 base::MessageLoop::current()->PostDelayedTask(
2544 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2546 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2551 process_map->RemoveAllFromProcess(process->GetID());
2552 BrowserThread::PostTask(
2555 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2556 system_->info_map(),
2560 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2561 // Notify observers that chrome update is available.
2562 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2563 OnChromeUpdateAvailable());
2568 NOTREACHED() << "Unexpected notification type.";
2572 void ExtensionService::OnExtensionInstallPrefChanged() {
2573 IdentifyAlertableExtensions();
2574 CheckManagementPolicy();
2577 bool ExtensionService::HasApps() const {
2578 return !GetAppIds().empty();
2581 ExtensionIdSet ExtensionService::GetAppIds() const {
2582 ExtensionIdSet result;
2583 const ExtensionSet& extensions = registry_->enabled_extensions();
2584 for (ExtensionSet::const_iterator it = extensions.begin();
2585 it != extensions.end(); ++it) {
2586 if ((*it)->is_app() && (*it)->location() != Manifest::COMPONENT)
2587 result.insert((*it)->id());
2593 bool ExtensionService::IsBeingReloaded(
2594 const std::string& extension_id) const {
2595 return ContainsKey(extensions_being_reloaded_, extension_id);
2598 void ExtensionService::SetBeingReloaded(const std::string& extension_id,
2599 bool isBeingReloaded) {
2600 if (isBeingReloaded)
2601 extensions_being_reloaded_.insert(extension_id);
2603 extensions_being_reloaded_.erase(extension_id);
2606 bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) {
2607 // Extensions installed by policy can't be disabled. So even if a previous
2608 // installation disabled the extension, make sure it is now enabled.
2609 if (system_->management_policy()->MustRemainEnabled(extension, NULL))
2612 if (extension_prefs_->IsExtensionDisabled(extension->id()))
2615 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2616 // External extensions are initially disabled. We prompt the user before
2617 // enabling them. Hosted apps are excepted because they are not dangerous
2618 // (they need to be launched by the user anyway).
2619 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2620 Manifest::IsExternalLocation(extension->location()) &&
2621 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2629 bool ExtensionService::ShouldDelayExtensionUpdate(
2630 const std::string& extension_id,
2631 bool wait_for_idle) const {
2632 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2634 // If delayed updates are globally disabled, or just for this extension,
2636 if (!install_updates_when_idle_ || !wait_for_idle)
2639 const Extension* old = GetInstalledExtension(extension_id);
2640 // If there is no old extension, this is not an update, so don't delay.
2644 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2645 // Delay installation if the extension listens for the onUpdateAvailable
2647 return system_->event_router()->ExtensionHasEventListener(
2648 extension_id, kOnUpdateAvailableEvent);
2650 // Delay installation if the extension is not idle.
2651 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2655 void ExtensionService::GarbageCollectIsolatedStorage() {
2656 scoped_ptr<base::hash_set<base::FilePath> > active_paths(
2657 new base::hash_set<base::FilePath>());
2658 const ExtensionSet& extensions = registry_->enabled_extensions();
2659 for (ExtensionSet::const_iterator it = extensions.begin();
2660 it != extensions.end(); ++it) {
2661 if (extensions::AppIsolationInfo::HasIsolatedStorage(it->get())) {
2662 active_paths->insert(BrowserContext::GetStoragePartitionForSite(
2663 profile_, GetSiteForExtensionId((*it)->id()))->GetPath());
2667 DCHECK(!installs_delayed_for_gc());
2668 set_installs_delayed_for_gc(true);
2669 BrowserContext::GarbageCollectStoragePartitions(
2670 profile_, active_paths.Pass(),
2671 base::Bind(&ExtensionService::OnGarbageCollectIsolatedStorageFinished,
2675 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2676 set_installs_delayed_for_gc(false);
2677 MaybeFinishDelayedInstallations();
2680 void ExtensionService::MaybeFinishDelayedInstallations() {
2681 std::vector<std::string> to_be_installed;
2682 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2683 it != delayed_installs_.end();
2685 to_be_installed.push_back((*it)->id());
2687 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2688 it != to_be_installed.end();
2690 MaybeFinishDelayedInstallation(*it);
2694 void ExtensionService::OnBlacklistUpdated() {
2695 blacklist_->GetBlacklistedIDs(
2696 GenerateInstalledExtensionsSet()->GetIDs(),
2697 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2700 void ExtensionService::ManageBlacklist(
2701 const extensions::Blacklist::BlacklistStateMap& state_map) {
2702 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2704 std::set<std::string> blocked;
2705 ExtensionIdSet greylist;
2706 ExtensionIdSet unchanged;
2707 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2709 it != state_map.end();
2711 switch (it->second) {
2712 case extensions::NOT_BLACKLISTED:
2715 case extensions::BLACKLISTED_MALWARE:
2716 blocked.insert(it->first);
2719 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2720 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2721 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2722 greylist.insert(it->first);
2725 case extensions::BLACKLISTED_UNKNOWN:
2726 unchanged.insert(it->first);
2731 UpdateBlockedExtensions(blocked, unchanged);
2732 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2734 IdentifyAlertableExtensions();
2738 void Partition(const ExtensionIdSet& before,
2739 const ExtensionIdSet& after,
2740 const ExtensionIdSet& unchanged,
2741 ExtensionIdSet* no_longer,
2742 ExtensionIdSet* not_yet) {
2743 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2744 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2745 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2749 void ExtensionService::UpdateBlockedExtensions(
2750 const ExtensionIdSet& blocked,
2751 const ExtensionIdSet& unchanged) {
2752 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2753 Partition(registry_->blacklisted_extensions().GetIDs(),
2755 &no_longer_blocked, ¬_yet_blocked);
2757 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2758 it != no_longer_blocked.end(); ++it) {
2759 scoped_refptr<const Extension> extension =
2760 registry_->blacklisted_extensions().GetByID(*it);
2761 if (!extension.get()) {
2762 NOTREACHED() << "Extension " << *it << " no longer blocked, "
2763 << "but it was never blocked.";
2766 registry_->RemoveBlacklisted(*it);
2767 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2768 AddExtension(extension.get());
2769 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2770 extension->location(),
2771 Manifest::NUM_LOCATIONS);
2774 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2775 it != not_yet_blocked.end(); ++it) {
2776 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2777 if (!extension.get()) {
2778 NOTREACHED() << "Extension " << *it << " needs to be "
2779 << "blacklisted, but it's not installed.";
2782 registry_->AddBlacklisted(extension);
2783 extension_prefs_->SetExtensionBlacklistState(
2784 extension->id(), extensions::BLACKLISTED_MALWARE);
2785 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2786 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2787 extension->location(), Manifest::NUM_LOCATIONS);
2791 // TODO(oleg): UMA logging
2792 void ExtensionService::UpdateGreylistedExtensions(
2793 const ExtensionIdSet& greylist,
2794 const ExtensionIdSet& unchanged,
2795 const extensions::Blacklist::BlacklistStateMap& state_map) {
2796 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2797 Partition(greylist_.GetIDs(),
2798 greylist, unchanged,
2799 &no_longer_greylisted, ¬_yet_greylisted);
2801 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2802 it != no_longer_greylisted.end(); ++it) {
2803 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2804 if (!extension.get()) {
2805 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2806 << "but it was not marked as greylisted.";
2810 greylist_.Remove(*it);
2811 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2812 extensions::NOT_BLACKLISTED);
2813 if (extension_prefs_->GetDisableReasons(extension->id()) &
2814 extensions::Extension::DISABLE_GREYLIST)
2815 EnableExtension(*it);
2818 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2819 it != not_yet_greylisted.end(); ++it) {
2820 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2821 if (!extension.get()) {
2822 NOTREACHED() << "Extension " << *it << " needs to be "
2823 << "disabled, but it's not installed.";
2826 greylist_.Insert(extension);
2827 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2828 state_map.find(*it)->second);
2829 if (registry_->enabled_extensions().Contains(extension->id()))
2830 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2834 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2835 update_observers_.AddObserver(observer);
2838 void ExtensionService::RemoveUpdateObserver(
2839 extensions::UpdateObserver* observer) {
2840 update_observers_.RemoveObserver(observer);
2843 // Used only by test code.
2844 void ExtensionService::UnloadAllExtensionsInternal() {
2845 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2847 registry_->ClearAll();
2848 system_->runtime_data()->ClearAll();
2850 // TODO(erikkay) should there be a notification for this? We can't use
2851 // EXTENSION_UNLOADED since that implies that the extension has been disabled