ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blob3708493cb3b45db6b09a9ac4b75290f1f201157b
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/extension_service.h"
7 #include <algorithm>
8 #include <iterator>
9 #include <set>
11 #include "base/command_line.h"
12 #include "base/metrics/histogram.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "base/time/time.h"
19 #include "base/trace_event/trace_event.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/content_settings/content_settings_internal_extension_provider.h"
23 #include "chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h"
24 #include "chrome/browser/extensions/api/content_settings/content_settings_service.h"
25 #include "chrome/browser/extensions/app_data_migrator.h"
26 #include "chrome/browser/extensions/component_loader.h"
27 #include "chrome/browser/extensions/crx_installer.h"
28 #include "chrome/browser/extensions/data_deleter.h"
29 #include "chrome/browser/extensions/extension_action_storage_manager.h"
30 #include "chrome/browser/extensions/extension_assets_manager.h"
31 #include "chrome/browser/extensions/extension_disabled_ui.h"
32 #include "chrome/browser/extensions/extension_error_controller.h"
33 #include "chrome/browser/extensions/extension_special_storage_policy.h"
34 #include "chrome/browser/extensions/extension_sync_service.h"
35 #include "chrome/browser/extensions/extension_util.h"
36 #include "chrome/browser/extensions/external_install_manager.h"
37 #include "chrome/browser/extensions/external_provider_impl.h"
38 #include "chrome/browser/extensions/install_verifier.h"
39 #include "chrome/browser/extensions/installed_loader.h"
40 #include "chrome/browser/extensions/pending_extension_manager.h"
41 #include "chrome/browser/extensions/permissions_updater.h"
42 #include "chrome/browser/extensions/shared_module_service.h"
43 #include "chrome/browser/extensions/unpacked_installer.h"
44 #include "chrome/browser/extensions/updater/chrome_extension_downloader_factory.h"
45 #include "chrome/browser/extensions/updater/extension_updater.h"
46 #include "chrome/browser/google/google_brand.h"
47 #include "chrome/browser/profiles/profile.h"
48 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
49 #include "chrome/browser/ui/webui/favicon_source.h"
50 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
51 #include "chrome/browser/ui/webui/theme_source.h"
52 #include "chrome/common/chrome_switches.h"
53 #include "chrome/common/crash_keys.h"
54 #include "chrome/common/extensions/extension_constants.h"
55 #include "chrome/common/extensions/features/feature_channel.h"
56 #include "chrome/common/url_constants.h"
57 #include "components/content_settings/core/browser/host_content_settings_map.h"
58 #include "components/crx_file/id_util.h"
59 #include "components/startup_metric_utils/startup_metric_utils.h"
60 #include "content/public/browser/devtools_agent_host.h"
61 #include "content/public/browser/notification_service.h"
62 #include "content/public/browser/render_process_host.h"
63 #include "content/public/browser/storage_partition.h"
64 #include "extensions/browser/event_router.h"
65 #include "extensions/browser/extension_host.h"
66 #include "extensions/browser/extension_prefs.h"
67 #include "extensions/browser/extension_registry.h"
68 #include "extensions/browser/extension_system.h"
69 #include "extensions/browser/extensions_browser_client.h"
70 #include "extensions/browser/install_flag.h"
71 #include "extensions/browser/runtime_data.h"
72 #include "extensions/browser/uninstall_reason.h"
73 #include "extensions/browser/update_observer.h"
74 #include "extensions/browser/updater/extension_cache.h"
75 #include "extensions/browser/updater/extension_downloader.h"
76 #include "extensions/common/extension_messages.h"
77 #include "extensions/common/extension_urls.h"
78 #include "extensions/common/feature_switch.h"
79 #include "extensions/common/file_util.h"
80 #include "extensions/common/manifest_constants.h"
81 #include "extensions/common/manifest_handlers/background_info.h"
82 #include "extensions/common/manifest_url_handlers.h"
83 #include "extensions/common/one_shot_event.h"
84 #include "extensions/common/permissions/permission_message_provider.h"
85 #include "extensions/common/permissions/permissions_data.h"
87 #if defined(OS_CHROMEOS)
88 #include "chrome/browser/chromeos/extensions/install_limiter.h"
89 #include "storage/browser/fileapi/file_system_backend.h"
90 #include "storage/browser/fileapi/file_system_context.h"
91 #endif
93 using content::BrowserContext;
94 using content::BrowserThread;
95 using content::DevToolsAgentHost;
96 using extensions::CrxInstaller;
97 using extensions::Extension;
98 using extensions::ExtensionIdSet;
99 using extensions::ExtensionInfo;
100 using extensions::ExtensionRegistry;
101 using extensions::ExtensionSet;
102 using extensions::FeatureSwitch;
103 using extensions::InstallVerifier;
104 using extensions::ManagementPolicy;
105 using extensions::Manifest;
106 using extensions::PermissionMessage;
107 using extensions::PermissionMessages;
108 using extensions::PermissionSet;
109 using extensions::SharedModuleInfo;
110 using extensions::SharedModuleService;
111 using extensions::UnloadedExtensionInfo;
113 namespace errors = extensions::manifest_errors;
115 namespace {
117 // Wait this many seconds after an extensions becomes idle before updating it.
118 const int kUpdateIdleDelay = 5;
120 } // namespace
122 // ExtensionService.
124 void ExtensionService::CheckExternalUninstall(const std::string& id) {
125 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
127 // Check if the providers know about this extension.
128 extensions::ProviderCollection::const_iterator i;
129 for (i = external_extension_providers_.begin();
130 i != external_extension_providers_.end(); ++i) {
131 DCHECK(i->get()->IsReady());
132 if (i->get()->HasExtension(id))
133 return; // Yup, known extension, don't uninstall.
136 // We get the list of external extensions to check from preferences.
137 // It is possible that an extension has preferences but is not loaded.
138 // For example, an extension that requires experimental permissions
139 // will not be loaded if the experimental command line flag is not used.
140 // In this case, do not uninstall.
141 if (!GetInstalledExtension(id)) {
142 // We can't call UninstallExtension with an unloaded/invalid
143 // extension ID.
144 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
145 << "with id: " << id;
146 return;
148 UninstallExtension(id,
149 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
150 base::Bind(&base::DoNothing),
151 NULL);
154 void ExtensionService::SetFileTaskRunnerForTesting(
155 const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
156 file_task_runner_ = task_runner;
159 void ExtensionService::ClearProvidersForTesting() {
160 external_extension_providers_.clear();
163 void ExtensionService::AddProviderForTesting(
164 extensions::ExternalProviderInterface* test_provider) {
165 CHECK(test_provider);
166 external_extension_providers_.push_back(
167 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
170 void ExtensionService::BlacklistExtensionForTest(
171 const std::string& extension_id) {
172 ExtensionIdSet blacklisted;
173 ExtensionIdSet unchanged;
174 blacklisted.insert(extension_id);
175 UpdateBlacklistedExtensions(blacklisted, unchanged);
178 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
179 const std::string& id,
180 const std::string& install_parameter,
181 const GURL& update_url,
182 Manifest::Location location,
183 int creation_flags,
184 bool mark_acknowledged) {
185 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
186 CHECK(crx_file::id_util::IdIsValid(id));
188 if (Manifest::IsExternalLocation(location)) {
189 // All extensions that are not user specific can be cached.
190 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
191 ->AllowCaching(id);
194 const Extension* extension = GetExtensionById(id, true);
195 if (extension) {
196 // Already installed. Skip this install if the current location has
197 // higher priority than |location|.
198 Manifest::Location current = extension->location();
199 if (current == Manifest::GetHigherPriorityLocation(current, location))
200 return false;
201 // Otherwise, overwrite the current installation.
204 // Add |id| to the set of pending extensions. If it can not be added,
205 // then there is already a pending record from a higher-priority install
206 // source. In this case, signal that this extension will not be
207 // installed by returning false.
208 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
210 install_parameter,
211 update_url,
212 location,
213 creation_flags,
214 mark_acknowledged)) {
215 return false;
218 update_once_all_providers_are_ready_ = true;
219 return true;
222 // static
223 // This function is used to uninstall an extension via sync. The LOG statements
224 // within this function are used to inform the user if the uninstall cannot be
225 // done.
226 bool ExtensionService::UninstallExtensionHelper(
227 ExtensionService* extensions_service,
228 const std::string& extension_id,
229 extensions::UninstallReason reason) {
230 // We can't call UninstallExtension with an invalid extension ID.
231 if (!extensions_service->GetInstalledExtension(extension_id)) {
232 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
233 << "id: " << extension_id;
234 return false;
237 // The following call to UninstallExtension will not allow an uninstall of a
238 // policy-controlled extension.
239 base::string16 error;
240 if (!extensions_service->UninstallExtension(
241 extension_id, reason, base::Bind(&base::DoNothing), &error)) {
242 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
243 << ": " << error;
244 return false;
247 return true;
250 ExtensionService::ExtensionService(Profile* profile,
251 const base::CommandLine* command_line,
252 const base::FilePath& install_directory,
253 extensions::ExtensionPrefs* extension_prefs,
254 extensions::Blacklist* blacklist,
255 bool autoupdate_enabled,
256 bool extensions_enabled,
257 extensions::OneShotEvent* ready)
258 : extensions::Blacklist::Observer(blacklist),
259 profile_(profile),
260 system_(extensions::ExtensionSystem::Get(profile)),
261 extension_prefs_(extension_prefs),
262 blacklist_(blacklist),
263 extension_sync_service_(NULL),
264 registry_(extensions::ExtensionRegistry::Get(profile)),
265 pending_extension_manager_(profile),
266 install_directory_(install_directory),
267 extensions_enabled_(extensions_enabled),
268 show_extensions_prompts_(true),
269 install_updates_when_idle_(true),
270 ready_(ready),
271 update_once_all_providers_are_ready_(false),
272 browser_terminating_(false),
273 installs_delayed_for_gc_(false),
274 is_first_run_(false),
275 block_extensions_(false),
276 shared_module_service_(new extensions::SharedModuleService(profile_)),
277 app_data_migrator_(new extensions::AppDataMigrator(profile_, registry_)) {
278 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
280 // Figure out if extension installation should be enabled.
281 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
282 *command_line, profile))
283 extensions_enabled_ = false;
285 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
286 content::NotificationService::AllBrowserContextsAndSources());
287 registrar_.Add(this,
288 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
289 content::NotificationService::AllBrowserContextsAndSources());
290 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
291 content::NotificationService::AllBrowserContextsAndSources());
292 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
293 content::NotificationService::AllBrowserContextsAndSources());
294 registrar_.Add(this,
295 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
296 content::Source<Profile>(profile_));
298 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
299 ->AddObserver(this);
301 // Set up the ExtensionUpdater
302 if (autoupdate_enabled) {
303 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
304 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
305 base::StringToInt(command_line->GetSwitchValueASCII(
306 switches::kExtensionsUpdateFrequency),
307 &update_frequency);
309 updater_.reset(new extensions::ExtensionUpdater(
310 this,
311 extension_prefs,
312 profile->GetPrefs(),
313 profile,
314 update_frequency,
315 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
316 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
317 profile)));
320 component_loader_.reset(
321 new extensions::ComponentLoader(this,
322 profile->GetPrefs(),
323 g_browser_process->local_state(),
324 profile));
326 if (extensions_enabled_) {
327 extensions::ExternalProviderImpl::CreateExternalProviders(
328 this, profile_, &external_extension_providers_);
331 // Set this as the ExtensionService for app sorting to ensure it causes syncs
332 // if required.
333 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
335 error_controller_.reset(
336 new extensions::ExtensionErrorController(profile_, is_first_run_));
337 external_install_manager_.reset(
338 new extensions::ExternalInstallManager(profile_, is_first_run_));
340 extension_action_storage_manager_.reset(
341 new extensions::ExtensionActionStorageManager(profile_));
343 // How long is the path to the Extensions directory?
344 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
345 install_directory_.value().length(), 0, 500, 100);
348 extensions::PendingExtensionManager*
349 ExtensionService::pending_extension_manager() {
350 return &pending_extension_manager_;
353 ExtensionService::~ExtensionService() {
354 // No need to unload extensions here because they are profile-scoped, and the
355 // profile is in the process of being deleted.
357 extensions::ProviderCollection::const_iterator i;
358 for (i = external_extension_providers_.begin();
359 i != external_extension_providers_.end(); ++i) {
360 extensions::ExternalProviderInterface* provider = i->get();
361 provider->ServiceShutdown();
365 void ExtensionService::Shutdown() {
366 extensions::ExtensionManagementFactory::GetInstance()
367 ->GetForBrowserContext(profile())
368 ->RemoveObserver(this);
369 system_->management_policy()->UnregisterProvider(
370 shared_module_policy_provider_.get());
373 const Extension* ExtensionService::GetExtensionById(
374 const std::string& id, bool include_disabled) const {
375 int include_mask = ExtensionRegistry::ENABLED;
376 if (include_disabled) {
377 // Include blacklisted and blocked extensions here because there are
378 // hundreds of callers of this function, and many might assume that this
379 // includes those that have been disabled due to blacklisting or blocking.
380 include_mask |= ExtensionRegistry::DISABLED |
381 ExtensionRegistry::BLACKLISTED | ExtensionRegistry::BLOCKED;
383 return registry_->GetExtensionById(id, include_mask);
386 void ExtensionService::Init() {
387 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
388 TRACE_EVENT0("browser,startup", "ExtensionService::Init");
389 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.ExtensionServiceInitTime");
391 DCHECK(!is_ready()); // Can't redo init.
392 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
394 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
395 if (cmd_line->HasSwitch(switches::kInstallEphemeralAppFromWebstore)) {
396 // The sole purpose of this launch is to install a new extension from CWS
397 // and immediately terminate: loading already installed extensions is
398 // unnecessary and may interfere with the inline install dialog (e.g. if an
399 // extension listens to onStartup and opens a window).
400 SetReadyAndNotifyListeners();
401 } else {
402 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
403 component_loader_->LoadAll();
404 extensions::InstalledLoader(this).LoadAllExtensions();
406 EnabledReloadableExtensions();
407 MaybeFinishShutdownDelayed();
408 SetReadyAndNotifyListeners();
410 // TODO(erikkay): this should probably be deferred to a future point
411 // rather than running immediately at startup.
412 CheckForExternalUpdates();
414 LoadGreylistFromPrefs();
418 void ExtensionService::EnabledReloadableExtensions() {
419 TRACE_EVENT0("browser,startup",
420 "ExtensionService::EnabledReloadableExtensions");
422 std::vector<std::string> extensions_to_enable;
423 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
424 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
425 iter != disabled_extensions.end(); ++iter) {
426 const Extension* e = iter->get();
427 if (extension_prefs_->GetDisableReasons(e->id()) ==
428 Extension::DISABLE_RELOAD) {
429 extensions_to_enable.push_back(e->id());
432 for (const std::string& extension : extensions_to_enable) {
433 EnableExtension(extension);
437 void ExtensionService::MaybeFinishShutdownDelayed() {
438 TRACE_EVENT0("browser,startup",
439 "ExtensionService::MaybeFinishShutdownDelayed");
441 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
442 extension_prefs_->GetAllDelayedInstallInfo());
443 for (size_t i = 0; i < delayed_info->size(); ++i) {
444 ExtensionInfo* info = delayed_info->at(i).get();
445 scoped_refptr<const Extension> extension(NULL);
446 if (info->extension_manifest) {
447 std::string error;
448 extension = Extension::Create(
449 info->extension_path, info->extension_location,
450 *info->extension_manifest,
451 extension_prefs_->GetDelayedInstallCreationFlags(info->extension_id),
452 info->extension_id, &error);
453 if (extension.get())
454 delayed_installs_.Insert(extension);
457 MaybeFinishDelayedInstallations();
458 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
459 extension_prefs_->GetAllDelayedInstallInfo());
460 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
461 delayed_info2->size() - delayed_info->size());
464 void ExtensionService::LoadGreylistFromPrefs() {
465 TRACE_EVENT0("browser,startup", "ExtensionService::LoadGreylistFromPrefs");
467 scoped_ptr<ExtensionSet> all_extensions =
468 registry_->GenerateInstalledExtensionsSet();
470 for (ExtensionSet::const_iterator it = all_extensions->begin();
471 it != all_extensions->end(); ++it) {
472 extensions::BlacklistState state =
473 extension_prefs_->GetExtensionBlacklistState((*it)->id());
474 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
475 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
476 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
477 greylist_.Insert(*it);
481 bool ExtensionService::UpdateExtension(const extensions::CRXFileInfo& file,
482 bool file_ownership_passed,
483 CrxInstaller** out_crx_installer) {
484 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
485 if (browser_terminating_) {
486 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
487 // Leak the temp file at extension_path. We don't want to add to the disk
488 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
489 // the file is in the OS temp directory which should be cleaned up for us.
490 return false;
493 const std::string& id = file.extension_id;
495 const extensions::PendingExtensionInfo* pending_extension_info =
496 pending_extension_manager()->GetById(id);
498 const Extension* extension = GetInstalledExtension(id);
499 if (!pending_extension_info && !extension) {
500 LOG(WARNING) << "Will not update extension " << id
501 << " because it is not installed or pending";
502 // Delete extension_path since we're not creating a CrxInstaller
503 // that would do it for us.
504 if (!GetFileTaskRunner()->PostTask(
505 FROM_HERE,
506 base::Bind(&extensions::file_util::DeleteFile, file.path, false)))
507 NOTREACHED();
509 return false;
512 scoped_refptr<CrxInstaller> installer(
513 CrxInstaller::Create(this, scoped_ptr<ExtensionInstallPrompt>()));
514 installer->set_expected_id(id);
515 installer->set_expected_hash(file.expected_hash);
516 int creation_flags = Extension::NO_FLAGS;
517 if (pending_extension_info) {
518 installer->set_install_source(pending_extension_info->install_source());
519 installer->set_allow_silent_install(true);
520 if (pending_extension_info->remote_install())
521 installer->set_grant_permissions(false);
522 creation_flags = pending_extension_info->creation_flags();
523 if (pending_extension_info->mark_acknowledged())
524 external_install_manager_->AcknowledgeExternalExtension(id);
525 } else if (extension) {
526 installer->set_install_source(extension->location());
528 // If the extension was installed from or has migrated to the webstore, or
529 // its auto-update URL is from the webstore, treat it as a webstore install.
530 // Note that we ignore some older extensions with blank auto-update URLs
531 // because we are mostly concerned with restrictions on NaCl extensions,
532 // which are newer.
533 if ((extension && extension->from_webstore()) ||
534 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
535 (!extension && extension_urls::IsWebstoreUpdateUrl(
536 pending_extension_info->update_url()))) {
537 creation_flags |= Extension::FROM_WEBSTORE;
540 // Bookmark apps being updated is kind of a contradiction, but that's because
541 // we mark the default apps as bookmark apps, and they're hosted in the web
542 // store, thus they can get updated. See http://crbug.com/101605 for more
543 // details.
544 if (extension && extension->from_bookmark())
545 creation_flags |= Extension::FROM_BOOKMARK;
547 if (extension && extension->was_installed_by_default())
548 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
550 if (extension && extension->was_installed_by_oem())
551 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
553 if (extension && extension->was_installed_by_custodian())
554 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
556 if (extension) {
557 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
558 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
561 installer->set_creation_flags(creation_flags);
563 installer->set_delete_source(file_ownership_passed);
564 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
565 installer->InstallCrxFile(file);
567 if (out_crx_installer)
568 *out_crx_installer = installer.get();
570 return true;
573 void ExtensionService::ReloadExtensionImpl(
574 // "transient" because the process of reloading may cause the reference
575 // to become invalid. Instead, use |extension_id|, a copy.
576 const std::string& transient_extension_id,
577 bool be_noisy) {
578 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
580 // If the extension is already reloading, don't reload again.
581 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
582 Extension::DISABLE_RELOAD) {
583 return;
586 // Ignore attempts to reload a blacklisted or blocked extension. Sometimes
587 // this can happen in a convoluted reload sequence triggered by the
588 // termination of a blacklisted or blocked extension and a naive attempt to
589 // reload it. For an example see http://crbug.com/373842.
590 if (registry_->blacklisted_extensions().Contains(transient_extension_id) ||
591 registry_->blocked_extensions().Contains(transient_extension_id)) {
592 return;
595 base::FilePath path;
597 std::string extension_id = transient_extension_id;
598 const Extension* transient_current_extension =
599 GetExtensionById(extension_id, false);
601 // Disable the extension if it's loaded. It might not be loaded if it crashed.
602 if (transient_current_extension) {
603 // If the extension has an inspector open for its background page, detach
604 // the inspector and hang onto a cookie for it, so that we can reattach
605 // later.
606 // TODO(yoz): this is not incognito-safe!
607 extensions::ProcessManager* manager =
608 extensions::ProcessManager::Get(profile_);
609 extensions::ExtensionHost* host =
610 manager->GetBackgroundHostForExtension(extension_id);
611 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
612 // Look for an open inspector for the background page.
613 scoped_refptr<DevToolsAgentHost> agent_host =
614 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
615 agent_host->DisconnectWebContents();
616 orphaned_dev_tools_[extension_id] = agent_host;
619 path = transient_current_extension->path();
620 // BeingUpgraded is set back to false when the extension is added.
621 system_->runtime_data()->SetBeingUpgraded(transient_current_extension->id(),
622 true);
623 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
624 reloading_extensions_.insert(extension_id);
625 } else {
626 std::map<std::string, base::FilePath>::const_iterator iter =
627 unloaded_extension_paths_.find(extension_id);
628 if (iter == unloaded_extension_paths_.end()) {
629 return;
631 path = unloaded_extension_paths_[extension_id];
634 transient_current_extension = NULL;
636 if (delayed_installs_.Contains(extension_id)) {
637 FinishDelayedInstallation(extension_id);
638 return;
641 // If we're reloading a component extension, use the component extension
642 // loader's reloader.
643 if (component_loader_->Exists(extension_id)) {
644 component_loader_->Reload(extension_id);
645 return;
648 // Check the installed extensions to see if what we're reloading was already
649 // installed.
650 scoped_ptr<ExtensionInfo> installed_extension(
651 extension_prefs_->GetInstalledExtensionInfo(extension_id));
652 if (installed_extension.get() &&
653 installed_extension->extension_manifest.get()) {
654 extensions::InstalledLoader(this).Load(*installed_extension, false);
655 } else {
656 // Otherwise, the extension is unpacked (location LOAD).
657 // We should always be able to remember the extension's path. If it's not in
658 // the map, someone failed to update |unloaded_extension_paths_|.
659 CHECK(!path.empty());
660 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
661 extensions::UnpackedInstaller::Create(this);
662 unpacked_installer->set_be_noisy_on_failure(be_noisy);
663 unpacked_installer->Load(path);
667 void ExtensionService::ReloadExtension(const std::string& extension_id) {
668 ReloadExtensionImpl(extension_id, true); // be_noisy
671 void ExtensionService::ReloadExtensionWithQuietFailure(
672 const std::string& extension_id) {
673 ReloadExtensionImpl(extension_id, false); // be_noisy
676 bool ExtensionService::UninstallExtension(
677 // "transient" because the process of uninstalling may cause the reference
678 // to become invalid. Instead, use |extenson->id()|.
679 const std::string& transient_extension_id,
680 extensions::UninstallReason reason,
681 const base::Closure& deletion_done_callback,
682 base::string16* error) {
683 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
685 scoped_refptr<const Extension> extension =
686 GetInstalledExtension(transient_extension_id);
688 // Callers should not send us nonexistent extensions.
689 CHECK(extension.get());
691 ManagementPolicy* by_policy = system_->management_policy();
692 // Policy change which triggers an uninstall will always set
693 // |external_uninstall| to true so this is the only way to uninstall
694 // managed extensions.
695 // Shared modules being uninstalled will also set |external_uninstall| to true
696 // so that we can guarantee users don't uninstall a shared module.
697 // (crbug.com/273300)
698 // TODO(rdevlin.cronin): This is probably not right. We should do something
699 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
700 // we don't do this.
701 bool external_uninstall =
702 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
703 (reason == extensions::UNINSTALL_REASON_COMPONENT_REMOVED) ||
704 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
705 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
706 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
707 (reason == extensions::UNINSTALL_REASON_SYNC &&
708 extension->was_installed_by_custodian());
709 if (!external_uninstall &&
710 (!by_policy->UserMayModifySettings(extension.get(), error) ||
711 by_policy->MustRemainInstalled(extension.get(), error))) {
712 content::NotificationService::current()->Notify(
713 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
714 content::Source<Profile>(profile_),
715 content::Details<const Extension>(extension.get()));
716 return false;
719 syncer::SyncChange sync_change;
720 // Don't sync the uninstall if we're going to reinstall the extension
721 // momentarily.
722 if (extension_sync_service_ &&
723 reason != extensions::UNINSTALL_REASON_REINSTALL) {
724 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
725 extension.get(), is_ready());
728 system_->install_verifier()->Remove(extension->id());
730 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
731 extension->GetType(), 100);
732 RecordPermissionMessagesHistogram(extension.get(),
733 "Extensions.Permissions_Uninstall2");
735 // Unload before doing more cleanup to ensure that nothing is hanging on to
736 // any of these resources.
737 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
739 // Tell the backend to start deleting installed extensions on the file thread.
740 if (!Manifest::IsUnpackedLocation(extension->location())) {
741 if (!GetFileTaskRunner()->PostTask(
742 FROM_HERE,
743 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
744 extension->id(),
745 profile_,
746 install_directory_,
747 extension->path())))
748 NOTREACHED();
751 extensions::DataDeleter::StartDeleting(
752 profile_, extension.get(), deletion_done_callback);
754 UntrackTerminatedExtension(extension->id());
756 // Notify interested parties that we've uninstalled this extension.
757 content::NotificationService::current()->Notify(
758 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
759 content::Source<Profile>(profile_),
760 content::Details<const Extension>(extension.get()));
761 ExtensionRegistry::Get(profile_)
762 ->TriggerOnUninstalled(extension.get(), reason);
764 if (sync_change.IsValid()) {
765 extension_sync_service_->ProcessSyncUninstallExtension(extension->id(),
766 sync_change);
769 delayed_installs_.Remove(extension->id());
771 extension_prefs_->OnExtensionUninstalled(
772 extension->id(), extension->location(), external_uninstall);
774 // Track the uninstallation.
775 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
777 return true;
780 // static
781 void ExtensionService::UninstallExtensionOnFileThread(
782 const std::string& id,
783 Profile* profile,
784 const base::FilePath& install_dir,
785 const base::FilePath& extension_path) {
786 extensions::ExtensionAssetsManager* assets_manager =
787 extensions::ExtensionAssetsManager::GetInstance();
788 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
791 bool ExtensionService::IsExtensionEnabled(
792 const std::string& extension_id) const {
793 if (registry_->enabled_extensions().Contains(extension_id) ||
794 registry_->terminated_extensions().Contains(extension_id)) {
795 return true;
798 if (registry_->disabled_extensions().Contains(extension_id) ||
799 registry_->blacklisted_extensions().Contains(extension_id) ||
800 registry_->blocked_extensions().Contains(extension_id)) {
801 return false;
804 // Blocked extensions aren't marked as such in prefs, thus if
805 // |block_extensions_| is true then CanBlockExtension() must be called with an
806 // Extension object. If the |extension_id| is not loaded, assume not enabled.
807 if (block_extensions_) {
808 const Extension* extension = GetInstalledExtension(extension_id);
809 if (!extension || CanBlockExtension(extension))
810 return false;
813 // If the extension hasn't been loaded yet, check the prefs for it. Assume
814 // enabled unless otherwise noted.
815 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
816 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
817 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
820 void ExtensionService::EnableExtension(const std::string& extension_id) {
821 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
823 if (IsExtensionEnabled(extension_id))
824 return;
825 const Extension* extension =
826 registry_->disabled_extensions().GetByID(extension_id);
828 ManagementPolicy* policy = system_->management_policy();
829 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
830 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
831 return;
834 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
835 extension_prefs_->ClearDisableReasons(extension_id);
837 // This can happen if sync enables an extension that is not
838 // installed yet.
839 if (!extension)
840 return;
842 // Move it over to the enabled list.
843 registry_->AddEnabled(make_scoped_refptr(extension));
844 registry_->RemoveDisabled(extension->id());
846 NotifyExtensionLoaded(extension);
848 // Notify listeners that the extension was enabled.
849 content::NotificationService::current()->Notify(
850 extensions::NOTIFICATION_EXTENSION_ENABLED,
851 content::Source<Profile>(profile_),
852 content::Details<const Extension>(extension));
854 if (extension_sync_service_)
855 extension_sync_service_->SyncEnableExtension(*extension);
858 void ExtensionService::DisableExtension(
859 const std::string& extension_id,
860 Extension::DisableReason disable_reason) {
861 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
863 // The extension may have been disabled already. Just add a disable reason.
864 if (!IsExtensionEnabled(extension_id)) {
865 extension_prefs_->AddDisableReason(extension_id, disable_reason);
866 return;
869 const Extension* extension = GetInstalledExtension(extension_id);
870 // |extension| can be NULL if sync disables an extension that is not
871 // installed yet.
872 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
873 // can be uninstalled by the browser if the user sets extension-specific
874 // preferences.
875 if (extension &&
876 disable_reason != Extension::DISABLE_RELOAD &&
877 disable_reason != Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY &&
878 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
879 extension->location() != Manifest::EXTERNAL_COMPONENT) {
880 return;
883 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
884 extension_prefs_->AddDisableReason(extension_id, disable_reason);
886 int include_mask =
887 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
888 extension = registry_->GetExtensionById(extension_id, include_mask);
889 if (!extension)
890 return;
892 // The extension is either enabled or terminated.
893 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
894 registry_->terminated_extensions().Contains(extension->id()));
896 // Move it over to the disabled list. Don't send a second unload notification
897 // for terminated extensions being disabled.
898 registry_->AddDisabled(make_scoped_refptr(extension));
899 if (registry_->enabled_extensions().Contains(extension->id())) {
900 registry_->RemoveEnabled(extension->id());
901 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
902 } else {
903 registry_->RemoveTerminated(extension->id());
906 if (extension_sync_service_)
907 extension_sync_service_->SyncDisableExtension(*extension);
910 void ExtensionService::DisableUserExtensions(
911 const std::vector<std::string>& except_ids) {
912 extensions::ManagementPolicy* management_policy =
913 system_->management_policy();
914 extensions::ExtensionList to_disable;
916 const ExtensionSet& enabled_set = registry_->enabled_extensions();
917 for (ExtensionSet::const_iterator extension = enabled_set.begin();
918 extension != enabled_set.end(); ++extension) {
919 if (management_policy->UserMayModifySettings(extension->get(), NULL))
920 to_disable.push_back(*extension);
922 const ExtensionSet& terminated_set = registry_->terminated_extensions();
923 for (ExtensionSet::const_iterator extension = terminated_set.begin();
924 extension != terminated_set.end(); ++extension) {
925 if (management_policy->UserMayModifySettings(extension->get(), NULL))
926 to_disable.push_back(*extension);
929 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
930 extension != to_disable.end(); ++extension) {
931 if ((*extension)->was_installed_by_default() &&
932 extension_urls::IsWebstoreUpdateUrl(
933 extensions::ManifestURL::GetUpdateURL(extension->get())))
934 continue;
935 const std::string& id = (*extension)->id();
936 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
937 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
941 // Extensions that are not locked, components or forced by policy should be
942 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
943 // extensions are now considered both blacklisted and locked.
944 void ExtensionService::BlockAllExtensions() {
945 if (block_extensions_)
946 return;
947 block_extensions_ = true;
949 // Blacklisted extensions are already unloaded, need not be blocked.
950 scoped_ptr<ExtensionSet> extensions =
951 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED |
952 ExtensionRegistry::DISABLED |
953 ExtensionRegistry::TERMINATED);
955 for (const scoped_refptr<const Extension>& extension : *extensions) {
956 const std::string& id = extension->id();
958 if (!CanBlockExtension(extension.get()))
959 continue;
961 registry_->RemoveEnabled(id);
962 registry_->RemoveDisabled(id);
963 registry_->RemoveTerminated(id);
965 registry_->AddBlocked(extension.get());
966 UnloadExtension(id, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL);
970 // All locked extensions should revert to being either enabled or disabled
971 // as appropriate.
972 void ExtensionService::UnblockAllExtensions() {
973 block_extensions_ = false;
974 scoped_ptr<ExtensionSet> to_unblock =
975 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED);
977 for (const scoped_refptr<const Extension>& extension : *to_unblock) {
978 registry_->RemoveBlocked(extension->id());
979 AddExtension(extension.get());
983 void ExtensionService::GrantPermissionsAndEnableExtension(
984 const Extension* extension) {
985 GrantPermissions(extension);
986 RecordPermissionMessagesHistogram(extension,
987 "Extensions.Permissions_ReEnable2");
988 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
989 EnableExtension(extension->id());
992 void ExtensionService::GrantPermissions(const Extension* extension) {
993 CHECK(extension);
994 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
997 // static
998 void ExtensionService::RecordPermissionMessagesHistogram(
999 const Extension* extension, const char* histogram) {
1000 // Since this is called from multiple sources, and since the histogram macros
1001 // use statics, we need to manually lookup the histogram ourselves.
1002 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
1003 histogram,
1005 PermissionMessage::kEnumBoundary,
1006 PermissionMessage::kEnumBoundary + 1,
1007 base::HistogramBase::kUmaTargetedHistogramFlag);
1009 PermissionMessages permissions =
1010 extension->permissions_data()->GetPermissionMessages();
1011 if (permissions.empty()) {
1012 counter->Add(PermissionMessage::kNone);
1013 } else {
1014 for (PermissionMessages::iterator it = permissions.begin();
1015 it != permissions.end(); ++it)
1016 counter->Add(it->id());
1020 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1021 // The URLRequestContexts need to be first to know that the extension
1022 // was loaded, otherwise a race can arise where a renderer that is created
1023 // for the extension may try to load an extension URL with an extension id
1024 // that the request context doesn't yet know about. The profile is responsible
1025 // for ensuring its URLRequestContexts appropriately discover the loaded
1026 // extension.
1027 system_->RegisterExtensionWithRequestContexts(extension);
1029 // Tell renderers about the new extension, unless it's a theme (renderers
1030 // don't need to know about themes).
1031 if (!extension->is_theme()) {
1032 for (content::RenderProcessHost::iterator i(
1033 content::RenderProcessHost::AllHostsIterator());
1034 !i.IsAtEnd(); i.Advance()) {
1035 content::RenderProcessHost* host = i.GetCurrentValue();
1036 Profile* host_profile =
1037 Profile::FromBrowserContext(host->GetBrowserContext());
1038 if (host_profile->GetOriginalProfile() ==
1039 profile_->GetOriginalProfile()) {
1040 // We don't need to include tab permisisons here, since the extension
1041 // was just loaded.
1042 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1043 1, ExtensionMsg_Loaded_Params(extension,
1044 false /* no tab permissions */));
1045 host->Send(
1046 new ExtensionMsg_Loaded(loaded_extensions));
1051 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1052 // extension.
1054 // NOTE: It is important that this happen after notifying the renderers about
1055 // the new extensions so that if we navigate to an extension URL in
1056 // ExtensionRegistryObserver::OnLoaded or
1057 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1058 // renderer is guaranteed to know about it.
1059 registry_->TriggerOnLoaded(extension);
1061 content::NotificationService::current()->Notify(
1062 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1063 content::Source<Profile>(profile_),
1064 content::Details<const Extension>(extension));
1066 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1067 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1068 profile_->GetExtensionSpecialStoragePolicy()->
1069 GrantRightsForExtension(extension, profile_);
1071 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1072 // work properly multi-profile. Besides which, it should be using
1073 // ExtensionRegistryObserver. See http://crbug.com/355029.
1074 UpdateActiveExtensionsInCrashReporter();
1076 const extensions::PermissionsData* permissions_data =
1077 extension->permissions_data();
1079 // If the extension has permission to load chrome://favicon/ resources we need
1080 // to make sure that the FaviconSource is registered with the
1081 // ChromeURLDataManager.
1082 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1083 FaviconSource* favicon_source = new FaviconSource(profile_,
1084 FaviconSource::FAVICON);
1085 content::URLDataSource::Add(profile_, favicon_source);
1088 // Same for chrome://theme/ resources.
1089 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1090 ThemeSource* theme_source = new ThemeSource(profile_);
1091 content::URLDataSource::Add(profile_, theme_source);
1094 // Same for chrome://thumb/ resources.
1095 if (permissions_data->HasHostPermission(
1096 GURL(chrome::kChromeUIThumbnailURL))) {
1097 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1098 content::URLDataSource::Add(profile_, thumbnail_source);
1102 void ExtensionService::NotifyExtensionUnloaded(
1103 const Extension* extension,
1104 UnloadedExtensionInfo::Reason reason) {
1105 UnloadedExtensionInfo details(extension, reason);
1107 registry_->TriggerOnUnloaded(extension, reason);
1109 content::NotificationService::current()->Notify(
1110 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1111 content::Source<Profile>(profile_),
1112 content::Details<UnloadedExtensionInfo>(&details));
1114 for (content::RenderProcessHost::iterator i(
1115 content::RenderProcessHost::AllHostsIterator());
1116 !i.IsAtEnd(); i.Advance()) {
1117 content::RenderProcessHost* host = i.GetCurrentValue();
1118 Profile* host_profile =
1119 Profile::FromBrowserContext(host->GetBrowserContext());
1120 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1121 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1124 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1126 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1127 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1128 profile_->GetExtensionSpecialStoragePolicy()->
1129 RevokeRightsForExtension(extension);
1131 #if defined(OS_CHROMEOS)
1132 // Revoke external file access for the extension from its file system context.
1133 // It is safe to access the extension's storage partition at this point. The
1134 // storage partition may get destroyed only after the extension gets unloaded.
1135 GURL site =
1136 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1137 storage::FileSystemContext* filesystem_context =
1138 BrowserContext::GetStoragePartitionForSite(profile_, site)
1139 ->GetFileSystemContext();
1140 if (filesystem_context && filesystem_context->external_backend()) {
1141 filesystem_context->external_backend()->
1142 RevokeAccessForExtension(extension->id());
1144 #endif
1146 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1147 // work properly multi-profile. Besides which, it should be using
1148 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1149 UpdateActiveExtensionsInCrashReporter();
1152 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1153 // Implemented in the .cc file to avoid adding a profile.h dependency to
1154 // extension_service.h.
1155 return profile_;
1158 bool ExtensionService::is_ready() {
1159 return ready_->is_signaled();
1162 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1163 if (file_task_runner_.get())
1164 return file_task_runner_.get();
1166 // We should be able to interrupt any part of extension install process during
1167 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1168 // will be ignored/deleted while we will block on started tasks.
1169 std::string token("ext_install-");
1170 token.append(profile_->GetPath().AsUTF8Unsafe());
1171 file_task_runner_ = BrowserThread::GetBlockingPool()->
1172 GetSequencedTaskRunnerWithShutdownBehavior(
1173 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1174 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1175 return file_task_runner_.get();
1178 void ExtensionService::CheckManagementPolicy() {
1179 std::vector<std::string> to_unload;
1180 std::map<std::string, Extension::DisableReason> to_disable;
1181 std::vector<std::string> to_enable;
1183 // Loop through the extensions list, finding extensions we need to unload or
1184 // disable.
1185 for (scoped_refptr<const Extension> extension :
1186 registry_->enabled_extensions()) {
1187 if (!system_->management_policy()->UserMayLoad(extension.get(), nullptr))
1188 to_unload.push_back(extension->id());
1189 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1190 if (system_->management_policy()->MustRemainDisabled(
1191 extension.get(), &disable_reason, nullptr))
1192 to_disable[extension->id()] = disable_reason;
1195 extensions::ExtensionManagement* management =
1196 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1198 // Loop through the disabled extension list, find extensions to re-enable
1199 // automatically. These extensions are exclusive from the |to_disable| and
1200 // |to_unload| lists constructed above, since disabled_extensions() and
1201 // enabled_extensions() are supposed to be mutually exclusive.
1202 for (scoped_refptr<const Extension> extension :
1203 registry_->disabled_extensions()) {
1204 // Find all disabled extensions disabled due to minimum version requirement,
1205 // but now satisfying it.
1206 if (management->CheckMinimumVersion(extension.get(), nullptr) &&
1207 extension_prefs_->HasDisableReason(
1208 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY)) {
1209 // Is DISABLE_UPDATE_REQUIRED_BY_POLICY the *only* reason?
1210 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1211 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1212 // We need to enable those disabled *only* due to minimum version
1213 // requirement.
1214 to_enable.push_back(extension->id());
1216 extension_prefs_->RemoveDisableReason(
1217 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1221 for (const std::string& id : to_unload)
1222 UnloadExtension(id, UnloadedExtensionInfo::REASON_DISABLE);
1224 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1225 to_disable.begin(); i != to_disable.end(); ++i)
1226 DisableExtension(i->first, i->second);
1228 // No extension is getting re-enabled here after disabling/unloading
1229 // because to_enable is mutually exclusive to to_disable + to_unload.
1230 for (const std::string& id : to_enable)
1231 EnableExtension(id);
1233 if (updater_.get()) {
1234 // Find all extensions disabled due to minimum version requirement from
1235 // policy (including the ones that got disabled just now), and check
1236 // for update.
1237 extensions::ExtensionUpdater::CheckParams to_recheck;
1238 for (scoped_refptr<const Extension> extension :
1239 registry_->disabled_extensions()) {
1240 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1241 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1242 // The minimum version check is the only thing holding this extension
1243 // back, so check if it can be updated to fix that.
1244 to_recheck.ids.push_back(extension->id());
1247 if (!to_recheck.ids.empty())
1248 updater_->CheckNow(to_recheck);
1252 void ExtensionService::CheckForUpdatesSoon() {
1253 // This can legitimately happen in unit tests.
1254 if (!updater_.get())
1255 return;
1257 if (AreAllExternalProvidersReady()) {
1258 updater_->CheckSoon();
1259 } else {
1260 // Sync can start updating before all the external providers are ready
1261 // during startup. Start the update as soon as those providers are ready,
1262 // but not before.
1263 update_once_all_providers_are_ready_ = true;
1267 // Some extensions will autoupdate themselves externally from Chrome. These
1268 // are typically part of some larger client application package. To support
1269 // these, the extension will register its location in the preferences file
1270 // (and also, on Windows, in the registry) and this code will periodically
1271 // check that location for a .crx file, which it will then install locally if
1272 // a new version is available.
1273 // Errors are reported through ExtensionErrorReporter. Success is not
1274 // reported.
1275 void ExtensionService::CheckForExternalUpdates() {
1276 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1277 TRACE_EVENT0("browser,startup", "ExtensionService::CheckForExternalUpdates");
1278 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.CheckForExternalUpdatesTime");
1280 // Note that this installation is intentionally silent (since it didn't
1281 // go through the front-end). Extensions that are registered in this
1282 // way are effectively considered 'pre-bundled', and so implicitly
1283 // trusted. In general, if something has HKLM or filesystem access,
1284 // they could install an extension manually themselves anyway.
1286 // Ask each external extension provider to give us a call back for each
1287 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1288 extensions::ProviderCollection::const_iterator i;
1289 for (i = external_extension_providers_.begin();
1290 i != external_extension_providers_.end(); ++i) {
1291 extensions::ExternalProviderInterface* provider = i->get();
1292 provider->VisitRegisteredExtension();
1295 // Do any required work that we would have done after completion of all
1296 // providers.
1297 if (external_extension_providers_.empty())
1298 OnAllExternalProvidersReady();
1301 void ExtensionService::OnExternalProviderReady(
1302 const extensions::ExternalProviderInterface* provider) {
1303 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1304 CHECK(provider->IsReady());
1306 // An external provider has finished loading. We only take action
1307 // if all of them are finished. So we check them first.
1308 if (AreAllExternalProvidersReady())
1309 OnAllExternalProvidersReady();
1312 bool ExtensionService::AreAllExternalProvidersReady() const {
1313 extensions::ProviderCollection::const_iterator i;
1314 for (i = external_extension_providers_.begin();
1315 i != external_extension_providers_.end(); ++i) {
1316 if (!i->get()->IsReady())
1317 return false;
1319 return true;
1322 void ExtensionService::OnAllExternalProvidersReady() {
1323 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1324 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1325 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1327 // Install any pending extensions.
1328 if (update_once_all_providers_are_ready_ && updater()) {
1329 update_once_all_providers_are_ready_ = false;
1330 extensions::ExtensionUpdater::CheckParams params;
1331 params.callback = external_updates_finished_callback_;
1332 updater()->CheckNow(params);
1335 // Uninstall all the unclaimed extensions.
1336 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1337 extension_prefs_->GetInstalledExtensionsInfo());
1338 for (size_t i = 0; i < extensions_info->size(); ++i) {
1339 ExtensionInfo* info = extensions_info->at(i).get();
1340 if (Manifest::IsExternalLocation(info->extension_location))
1341 CheckExternalUninstall(info->extension_id);
1344 error_controller_->ShowErrorIfNeeded();
1346 external_install_manager_->UpdateExternalExtensionAlert();
1349 void ExtensionService::UnloadExtension(
1350 const std::string& extension_id,
1351 UnloadedExtensionInfo::Reason reason) {
1352 // Make sure the extension gets deleted after we return from this function.
1353 int include_mask =
1354 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1355 scoped_refptr<const Extension> extension(
1356 registry_->GetExtensionById(extension_id, include_mask));
1358 // This method can be called via PostTask, so the extension may have been
1359 // unloaded by the time this runs.
1360 if (!extension.get()) {
1361 // In case the extension may have crashed/uninstalled. Allow the profile to
1362 // clean up its RequestContexts.
1363 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1364 return;
1367 // Keep information about the extension so that we can reload it later
1368 // even if it's not permanently installed.
1369 unloaded_extension_paths_[extension->id()] = extension->path();
1371 // Clean up if the extension is meant to be enabled after a reload.
1372 reloading_extensions_.erase(extension->id());
1374 if (registry_->disabled_extensions().Contains(extension->id())) {
1375 registry_->RemoveDisabled(extension->id());
1376 // Make sure the profile cleans up its RequestContexts when an already
1377 // disabled extension is unloaded (since they are also tracking the disabled
1378 // extensions).
1379 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1380 // Don't send the unloaded notification. It was sent when the extension
1381 // was disabled.
1382 } else {
1383 // Remove the extension from the enabled list.
1384 registry_->RemoveEnabled(extension->id());
1385 NotifyExtensionUnloaded(extension.get(), reason);
1388 content::NotificationService::current()->Notify(
1389 extensions::NOTIFICATION_EXTENSION_REMOVED,
1390 content::Source<Profile>(profile_),
1391 content::Details<const Extension>(extension.get()));
1394 void ExtensionService::RemoveComponentExtension(
1395 const std::string& extension_id) {
1396 scoped_refptr<const Extension> extension(
1397 GetExtensionById(extension_id, false));
1398 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1399 if (extension.get()) {
1400 content::NotificationService::current()->Notify(
1401 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
1402 content::Source<Profile>(profile_),
1403 content::Details<const Extension>(extension.get()));
1404 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1405 extension.get(), extensions::UNINSTALL_REASON_COMPONENT_REMOVED);
1409 void ExtensionService::UnloadAllExtensionsForTest() {
1410 UnloadAllExtensionsInternal();
1413 void ExtensionService::ReloadExtensionsForTest() {
1414 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1415 // warning about calling test code in production.
1416 UnloadAllExtensionsInternal();
1417 component_loader_->LoadAll();
1418 extensions::InstalledLoader(this).LoadAllExtensions();
1419 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1420 // times.
1423 void ExtensionService::SetReadyAndNotifyListeners() {
1424 TRACE_EVENT0("browser,startup",
1425 "ExtensionService::SetReadyAndNotifyListeners");
1426 SCOPED_UMA_HISTOGRAM_TIMER(
1427 "Extensions.ExtensionServiceNotifyReadyListenersTime");
1429 ready_->Signal();
1430 content::NotificationService::current()->Notify(
1431 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1432 content::Source<Profile>(profile_),
1433 content::NotificationService::NoDetails());
1436 void ExtensionService::OnLoadedInstalledExtensions() {
1437 if (updater_)
1438 updater_->Start();
1440 OnBlacklistUpdated();
1443 void ExtensionService::AddExtension(const Extension* extension) {
1444 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1445 // default extension state to DISABLED when the --disable-extensions flag
1446 // is set (http://crbug.com/29067).
1447 if (!extensions_enabled() &&
1448 !extension->is_theme() &&
1449 extension->location() != Manifest::COMPONENT &&
1450 !Manifest::IsExternalLocation(extension->location())) {
1451 return;
1454 bool is_extension_upgrade = false;
1455 bool is_extension_installed = false;
1456 const Extension* old = GetInstalledExtension(extension->id());
1457 if (old) {
1458 is_extension_installed = true;
1459 int version_compare_result =
1460 extension->version()->CompareTo(*(old->version()));
1461 is_extension_upgrade = version_compare_result > 0;
1462 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1463 // that we aren't downgrading.
1464 if (!Manifest::IsUnpackedLocation(extension->location()))
1465 CHECK_GE(version_compare_result, 0);
1467 // If the extension was disabled for a reload, then enable it.
1468 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1470 // Set the upgraded bit; we consider reloads upgrades.
1471 system_->runtime_data()->SetBeingUpgraded(extension->id(),
1472 is_extension_upgrade || reloading);
1474 // The extension is now loaded, remove its data from unloaded extension map.
1475 unloaded_extension_paths_.erase(extension->id());
1477 // If a terminated extension is loaded, remove it from the terminated list.
1478 UntrackTerminatedExtension(extension->id());
1480 // Check if the extension's privileges have changed and mark the
1481 // extension disabled if necessary.
1482 CheckPermissionsIncrease(extension, is_extension_installed);
1484 if (is_extension_installed && !reloading) {
1485 // To upgrade an extension in place, unload the old one and then load the
1486 // new one. ReloadExtension disables the extension, which is sufficient.
1487 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1490 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1491 // Only prefs is checked for the blacklist. We rely on callers to check the
1492 // blacklist before calling into here, e.g. CrxInstaller checks before
1493 // installation then threads through the install and pending install flow
1494 // of this class, and we check when loading installed extensions.
1495 registry_->AddBlacklisted(extension);
1496 } else if (block_extensions_ && CanBlockExtension(extension)) {
1497 registry_->AddBlocked(extension);
1498 } else if (!reloading &&
1499 extension_prefs_->IsExtensionDisabled(extension->id())) {
1500 registry_->AddDisabled(extension);
1501 if (extension_sync_service_)
1502 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1503 content::NotificationService::current()->Notify(
1504 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1505 content::Source<Profile>(profile_),
1506 content::Details<const Extension>(extension));
1508 // Show the extension disabled error if a permissions increase or a remote
1509 // installation is the reason it was disabled, and no other reasons exist.
1510 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1511 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1512 Extension::DISABLE_REMOTE_INSTALL;
1513 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1514 extensions::AddExtensionDisabledError(
1515 this,
1516 extension,
1517 extension_prefs_->HasDisableReason(
1518 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1520 } else if (reloading) {
1521 // Replace the old extension with the new version.
1522 CHECK(!registry_->AddDisabled(extension));
1523 EnableExtension(extension->id());
1524 } else {
1525 // All apps that are displayed in the launcher are ordered by their ordinals
1526 // so we must ensure they have valid ordinals.
1527 if (extension->RequiresSortOrdinal()) {
1528 extension_prefs_->app_sorting()->SetExtensionVisible(
1529 extension->id(),
1530 extension->ShouldDisplayInNewTabPage() &&
1531 !extension_prefs_->IsEphemeralApp(extension->id()));
1532 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1533 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1534 extension->id(), syncer::StringOrdinal());
1538 registry_->AddEnabled(extension);
1539 if (extension_sync_service_)
1540 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1541 NotifyExtensionLoaded(extension);
1543 system_->runtime_data()->SetBeingUpgraded(extension->id(), false);
1546 void ExtensionService::AddComponentExtension(const Extension* extension) {
1547 const std::string old_version_string(
1548 extension_prefs_->GetVersionString(extension->id()));
1549 const Version old_version(old_version_string);
1551 VLOG(1) << "AddComponentExtension " << extension->name();
1552 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1553 VLOG(1) << "Component extension " << extension->name() << " ("
1554 << extension->id() << ") installing/upgrading from '"
1555 << old_version_string << "' to " << extension->version()->GetString();
1557 AddNewOrUpdatedExtension(extension,
1558 Extension::ENABLED,
1559 extensions::kInstallFlagNone,
1560 syncer::StringOrdinal(),
1561 std::string());
1562 return;
1565 AddExtension(extension);
1568 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1569 bool is_extension_installed) {
1570 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1572 // We keep track of all permissions the user has granted each extension.
1573 // This allows extensions to gracefully support backwards compatibility
1574 // by including unknown permissions in their manifests. When the user
1575 // installs the extension, only the recognized permissions are recorded.
1576 // When the unknown permissions become recognized (e.g., through browser
1577 // upgrade), we can prompt the user to accept these new permissions.
1578 // Extensions can also silently upgrade to less permissions, and then
1579 // silently upgrade to a version that adds these permissions back.
1581 // For example, pretend that Chrome 10 includes a permission "omnibox"
1582 // for an API that adds suggestions to the omnibox. An extension can
1583 // maintain backwards compatibility while still having "omnibox" in the
1584 // manifest. If a user installs the extension on Chrome 9, the browser
1585 // will record the permissions it recognized, not including "omnibox."
1586 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1587 // will disable the extension and prompt the user to approve the increase
1588 // in privileges. The extension could then release a new version that
1589 // removes the "omnibox" permission. When the user upgrades, Chrome will
1590 // still remember that "omnibox" had been granted, so that if the
1591 // extension once again includes "omnibox" in an upgrade, the extension
1592 // can upgrade without requiring this user's approval.
1593 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1595 // Silently grant all active permissions to default apps and apps installed
1596 // in kiosk mode.
1597 bool auto_grant_permission =
1598 extension->was_installed_by_default() ||
1599 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1600 if (auto_grant_permission)
1601 GrantPermissions(extension);
1603 bool is_privilege_increase = false;
1604 // We only need to compare the granted permissions to the current permissions
1605 // if the extension has not been auto-granted its permissions above and is
1606 // installed internally.
1607 if (extension->location() == Manifest::INTERNAL && !auto_grant_permission) {
1608 // Add all the recognized permissions if the granted permissions list
1609 // hasn't been initialized yet.
1610 scoped_refptr<PermissionSet> granted_permissions =
1611 extension_prefs_->GetGrantedPermissions(extension->id());
1612 CHECK(granted_permissions.get());
1614 // Here, we check if an extension's privileges have increased in a manner
1615 // that requires the user's approval. This could occur because the browser
1616 // upgraded and recognized additional privileges, or an extension upgrades
1617 // to a version that requires additional privileges.
1618 is_privilege_increase =
1619 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1620 granted_permissions.get(),
1621 extension->permissions_data()->active_permissions().get(),
1622 extension->GetType());
1625 if (is_extension_installed) {
1626 // If the extension was already disabled, suppress any alerts for becoming
1627 // disabled on permissions increase.
1628 bool previously_disabled =
1629 extension_prefs_->IsExtensionDisabled(extension->id());
1630 // Legacy disabled extensions do not have a disable reason. Infer that if
1631 // there was no permission increase, it was likely disabled by the user.
1632 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1633 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1634 disable_reasons |= Extension::DISABLE_USER_ACTION;
1636 // Extensions that came to us disabled from sync need a similar inference,
1637 // except based on the new version's permissions.
1638 if (previously_disabled &&
1639 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1640 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1641 extension_prefs_->ClearDisableReasons(extension->id());
1642 if (!is_privilege_increase)
1643 disable_reasons |= Extension::DISABLE_USER_ACTION;
1645 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1648 // Extension has changed permissions significantly. Disable it. A
1649 // notification should be sent by the caller. If the extension is already
1650 // disabled because it was installed remotely, don't add another disable
1651 // reason, but instead always set the "did escalate permissions" flag, to
1652 // ensure enabling it will always show a warning.
1653 if (disable_reasons == Extension::DISABLE_REMOTE_INSTALL) {
1654 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1655 } else if (is_privilege_increase) {
1656 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1657 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1658 RecordPermissionMessagesHistogram(extension,
1659 "Extensions.Permissions_AutoDisable2");
1661 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1662 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1664 if (disable_reasons != Extension::DISABLE_NONE) {
1665 extension_prefs_->AddDisableReason(
1666 extension->id(),
1667 static_cast<Extension::DisableReason>(disable_reasons));
1671 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1672 std::set<std::string> extension_ids;
1673 const ExtensionSet& extensions = registry_->enabled_extensions();
1674 for (ExtensionSet::const_iterator iter = extensions.begin();
1675 iter != extensions.end(); ++iter) {
1676 const Extension* extension = iter->get();
1677 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1678 extension_ids.insert(extension->id());
1681 // TODO(kalman): This is broken. ExtensionService is per-profile.
1682 // crash_keys::SetActiveExtensions is per-process. See
1683 // http://crbug.com/355029.
1684 crash_keys::SetActiveExtensions(extension_ids);
1687 void ExtensionService::OnExtensionInstalled(
1688 const Extension* extension,
1689 const syncer::StringOrdinal& page_ordinal,
1690 int install_flags) {
1691 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1693 const std::string& id = extension->id();
1694 int disable_reasons = GetDisableReasonsOnInstalled(extension);
1695 std::string install_parameter;
1696 const extensions::PendingExtensionInfo* pending_extension_info =
1697 pending_extension_manager()->GetById(id);
1698 if (pending_extension_info) {
1699 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1700 pending_extension_manager()->Remove(id);
1702 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1703 << id << " of type " << extension->GetType()
1704 << " and update URL "
1705 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1706 << "; not installing";
1708 // Delete the extension directory since we're not going to
1709 // load it.
1710 if (!GetFileTaskRunner()->PostTask(
1711 FROM_HERE,
1712 base::Bind(&extensions::file_util::DeleteFile,
1713 extension->path(),
1714 true))) {
1715 NOTREACHED();
1717 return;
1720 install_parameter = pending_extension_info->install_parameter();
1721 pending_extension_manager()->Remove(id);
1722 } else {
1723 // We explicitly want to re-enable an uninstalled external
1724 // extension; if we're here, that means the user is manually
1725 // installing the extension.
1726 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1727 disable_reasons = Extension::DISABLE_NONE;
1731 // Unsupported requirements overrides the management policy.
1732 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1733 disable_reasons |= Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1734 } else {
1735 // Requirement is supported now, remove the corresponding disable reason
1736 // instead.
1737 extension_prefs_->RemoveDisableReason(
1738 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1739 disable_reasons &= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1742 // Check if the extension was disabled because of the minimum version
1743 // requirements from enterprise policy, and satisfies it now.
1744 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1745 ->CheckMinimumVersion(extension, nullptr)) {
1746 // And remove the corresponding disable reason.
1747 extension_prefs_->RemoveDisableReason(
1748 id, Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1749 disable_reasons &= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY;
1752 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1753 // Installation of a blacklisted extension can happen from sync, policy,
1754 // etc, where to maintain consistency we need to install it, just never
1755 // load it (see AddExtension). Usually it should be the job of callers to
1756 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
1757 // showing the install dialogue).
1758 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1759 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1760 extension->location(),
1761 Manifest::NUM_LOCATIONS);
1764 if (!GetInstalledExtension(extension->id())) {
1765 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1766 extension->GetType(), 100);
1767 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1768 extension->location(), Manifest::NUM_LOCATIONS);
1769 RecordPermissionMessagesHistogram(extension,
1770 "Extensions.Permissions_Install2");
1771 } else {
1772 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1773 extension->GetType(), 100);
1774 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1775 extension->location(), Manifest::NUM_LOCATIONS);
1777 // A fully installed app cannot be demoted to an ephemeral app.
1778 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1779 !extension_prefs_->IsEphemeralApp(id)) {
1780 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1784 if (disable_reasons)
1785 extension_prefs_->AddDisableReasons(id, disable_reasons);
1787 const Extension::State initial_state =
1788 disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED
1789 : Extension::DISABLED;
1791 if (ShouldDelayExtensionUpdate(
1793 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1794 extension_prefs_->SetDelayedInstallInfo(
1795 extension,
1796 initial_state,
1797 install_flags,
1798 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1799 page_ordinal,
1800 install_parameter);
1802 // Transfer ownership of |extension|.
1803 delayed_installs_.Insert(extension);
1805 // Notify observers that app update is available.
1806 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1807 OnAppUpdateAvailable(extension));
1808 return;
1811 extensions::SharedModuleService::ImportStatus status =
1812 shared_module_service_->SatisfyImports(extension);
1813 if (installs_delayed_for_gc_) {
1814 extension_prefs_->SetDelayedInstallInfo(
1815 extension,
1816 initial_state,
1817 install_flags,
1818 extensions::ExtensionPrefs::DELAY_REASON_GC,
1819 page_ordinal,
1820 install_parameter);
1821 delayed_installs_.Insert(extension);
1822 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1823 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1824 extension_prefs_->SetDelayedInstallInfo(
1825 extension,
1826 initial_state,
1827 install_flags,
1828 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1829 page_ordinal,
1830 install_parameter);
1831 delayed_installs_.Insert(extension);
1833 } else {
1834 AddNewOrUpdatedExtension(extension,
1835 initial_state,
1836 install_flags,
1837 page_ordinal,
1838 install_parameter);
1842 void ExtensionService::OnExtensionManagementSettingsChanged() {
1843 error_controller_->ShowErrorIfNeeded();
1845 // Revokes blocked permissions from active_permissions for all extensions.
1846 extensions::ExtensionManagement* settings =
1847 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1848 CHECK(settings);
1849 scoped_ptr<ExtensionSet> all_extensions(
1850 registry_->GenerateInstalledExtensionsSet());
1851 for (const auto& extension : *all_extensions.get()) {
1852 if (!settings->IsPermissionSetAllowed(
1853 extension.get(),
1854 extension->permissions_data()->active_permissions())) {
1855 extensions::PermissionsUpdater(profile()).RemovePermissions(
1856 extension.get(),
1857 settings->GetBlockedPermissions(extension.get()).get());
1861 CheckManagementPolicy();
1864 void ExtensionService::AddNewOrUpdatedExtension(
1865 const Extension* extension,
1866 Extension::State initial_state,
1867 int install_flags,
1868 const syncer::StringOrdinal& page_ordinal,
1869 const std::string& install_parameter) {
1870 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1871 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1872 extension_prefs_->OnExtensionInstalled(
1873 extension, initial_state, page_ordinal, install_flags, install_parameter);
1874 delayed_installs_.Remove(extension->id());
1875 if (InstallVerifier::NeedsVerification(*extension))
1876 system_->install_verifier()->VerifyExtension(extension->id());
1878 const Extension* old = GetInstalledExtension(extension->id());
1879 if (extensions::AppDataMigrator::NeedsMigration(old, extension)) {
1880 app_data_migrator_->DoMigrationAndReply(
1881 old, extension,
1882 base::Bind(&ExtensionService::FinishInstallation, AsWeakPtr(),
1883 make_scoped_refptr(extension), was_ephemeral));
1884 return;
1887 FinishInstallation(extension, was_ephemeral);
1890 void ExtensionService::MaybeFinishDelayedInstallation(
1891 const std::string& extension_id) {
1892 // Check if the extension already got installed.
1893 if (!delayed_installs_.Contains(extension_id))
1894 return;
1895 extensions::ExtensionPrefs::DelayReason reason =
1896 extension_prefs_->GetDelayedInstallReason(extension_id);
1898 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1899 // preferences files that will not have set this field but it was previously
1900 // only used for idle updates.
1901 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1902 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1903 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1904 return;
1906 const Extension* extension = delayed_installs_.GetByID(extension_id);
1907 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1908 extensions::SharedModuleService::ImportStatus status =
1909 shared_module_service_->SatisfyImports(extension);
1910 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1911 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1912 delayed_installs_.Remove(extension_id);
1913 // Make sure no version of the extension is actually installed, (i.e.,
1914 // that this delayed install was not an update).
1915 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1916 extension_prefs_->DeleteExtensionPrefs(extension_id);
1918 return;
1922 FinishDelayedInstallation(extension_id);
1925 void ExtensionService::FinishDelayedInstallation(
1926 const std::string& extension_id) {
1927 scoped_refptr<const Extension> extension(
1928 GetPendingExtensionUpdate(extension_id));
1929 CHECK(extension.get());
1930 delayed_installs_.Remove(extension_id);
1932 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1933 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1934 NOTREACHED();
1936 FinishInstallation(extension.get(), was_ephemeral);
1939 void ExtensionService::FinishInstallation(
1940 const Extension* extension, bool was_ephemeral) {
1941 const extensions::Extension* existing_extension =
1942 GetInstalledExtension(extension->id());
1943 bool is_update = false;
1944 std::string old_name;
1945 if (existing_extension) {
1946 is_update = true;
1947 old_name = existing_extension->name();
1949 bool from_ephemeral =
1950 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1951 extensions::InstalledExtensionInfo details(
1952 extension, is_update, from_ephemeral, old_name);
1953 content::NotificationService::current()->Notify(
1954 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1955 content::Source<Profile>(profile_),
1956 content::Details<const extensions::InstalledExtensionInfo>(&details));
1958 registry_->TriggerOnWillBeInstalled(
1959 extension, is_update, from_ephemeral, old_name);
1961 // Unpacked extensions default to allowing file access, but if that has been
1962 // overridden, don't reset the value.
1963 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1964 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1965 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1968 AddExtension(extension);
1970 // Notify observers that need to know when an installation is complete.
1971 registry_->TriggerOnInstalled(extension, is_update);
1973 // Check extensions that may have been delayed only because this shared module
1974 // was not available.
1975 if (SharedModuleInfo::IsSharedModule(extension))
1976 MaybeFinishDelayedInstallations();
1979 void ExtensionService::PromoteEphemeralApp(
1980 const extensions::Extension* extension, bool is_from_sync) {
1981 DCHECK(GetInstalledExtension(extension->id()) &&
1982 extension_prefs_->IsEphemeralApp(extension->id()));
1984 if (extension->RequiresSortOrdinal()) {
1985 extension_prefs_->app_sorting()->SetExtensionVisible(
1986 extension->id(), extension->ShouldDisplayInNewTabPage());
1988 if (!is_from_sync) {
1989 // Reset the sort ordinals of the app to ensure it is added to the default
1990 // position, like newly installed apps would.
1991 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
1994 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1995 extension->id(), syncer::StringOrdinal());
1998 // Remove the ephemeral flags from the preferences.
1999 extension_prefs_->OnEphemeralAppPromoted(extension->id());
2001 // Fire install-related events to allow observers to handle the promotion
2002 // of the ephemeral app.
2003 extensions::InstalledExtensionInfo details(
2004 extension,
2005 true /* is update */,
2006 true /* from ephemeral */,
2007 extension->name() /* old name */);
2008 content::NotificationService::current()->Notify(
2009 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2010 content::Source<Profile>(profile_),
2011 content::Details<const extensions::InstalledExtensionInfo>(&details));
2013 registry_->TriggerOnWillBeInstalled(
2014 extension,
2015 true /* is update */,
2016 true /* from ephemeral */,
2017 extension->name() /* old name */);
2019 if (registry_->enabled_extensions().Contains(extension->id())) {
2020 // If the app is already enabled and loaded, fire the load events to allow
2021 // observers to handle the promotion of the ephemeral app.
2022 content::NotificationService::current()->Notify(
2023 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
2024 content::Source<Profile>(profile_),
2025 content::Details<const Extension>(extension));
2027 registry_->TriggerOnLoaded(extension);
2028 } else {
2029 // Cached ephemeral apps may be updated and disabled due to permissions
2030 // increase. The app can be enabled (as long as no other disable reasons
2031 // exist) as the install was user-acknowledged.
2032 int disable_mask = Extension::DISABLE_NONE;
2033 if (!is_from_sync)
2034 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
2036 int other_disable_reasons =
2037 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
2038 if (!other_disable_reasons) {
2039 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
2040 GrantPermissionsAndEnableExtension(extension);
2041 else
2042 EnableExtension(extension->id());
2046 registry_->TriggerOnInstalled(extension, true);
2048 if (!is_from_sync && extension_sync_service_)
2049 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
2052 const Extension* ExtensionService::GetPendingExtensionUpdate(
2053 const std::string& id) const {
2054 return delayed_installs_.GetByID(id);
2057 void ExtensionService::RegisterContentSettings(
2058 HostContentSettingsMap* host_content_settings_map) {
2059 TRACE_EVENT0("browser,startup", "ExtensionService::RegisterContentSettings");
2060 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2061 host_content_settings_map->RegisterProvider(
2062 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
2063 scoped_ptr<content_settings::ObservableProvider>(
2064 new content_settings::InternalExtensionProvider(profile_)));
2066 host_content_settings_map->RegisterProvider(
2067 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
2068 scoped_ptr<content_settings::ObservableProvider>(
2069 new content_settings::CustomExtensionProvider(
2070 extensions::ContentSettingsService::Get(
2071 profile_)->content_settings_store(),
2072 profile_->GetOriginalProfile() != profile_)));
2075 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
2076 // No need to check for duplicates; inserting a duplicate is a no-op.
2077 registry_->AddTerminated(make_scoped_refptr(extension));
2078 extensions_being_terminated_.erase(extension->id());
2079 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2082 void ExtensionService::TerminateExtension(const std::string& extension_id) {
2083 const Extension* extension = GetInstalledExtension(extension_id);
2084 TrackTerminatedExtension(extension);
2087 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2088 std::string lowercase_id = base::StringToLowerASCII(id);
2089 const Extension* extension =
2090 registry_->terminated_extensions().GetByID(lowercase_id);
2091 registry_->RemoveTerminated(lowercase_id);
2092 if (extension) {
2093 content::NotificationService::current()->Notify(
2094 extensions::NOTIFICATION_EXTENSION_REMOVED,
2095 content::Source<Profile>(profile_),
2096 content::Details<const Extension>(extension));
2100 const Extension* ExtensionService::GetInstalledExtension(
2101 const std::string& id) const {
2102 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2105 bool ExtensionService::OnExternalExtensionFileFound(
2106 const std::string& id,
2107 const Version* version,
2108 const base::FilePath& path,
2109 Manifest::Location location,
2110 int creation_flags,
2111 bool mark_acknowledged) {
2112 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2113 CHECK(crx_file::id_util::IdIsValid(id));
2114 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2115 return false;
2117 // Before even bothering to unpack, check and see if we already have this
2118 // version. This is important because these extensions are going to get
2119 // installed on every startup.
2120 const Extension* existing = GetExtensionById(id, true);
2122 if (existing) {
2123 // The default apps will have the location set as INTERNAL. Since older
2124 // default apps are installed as EXTERNAL, we override them. However, if the
2125 // app is already installed as internal, then do the version check.
2126 // TODO(grv) : Remove after Q1-2013.
2127 bool is_default_apps_migration =
2128 (location == Manifest::INTERNAL &&
2129 Manifest::IsExternalLocation(existing->location()));
2131 if (!is_default_apps_migration) {
2132 DCHECK(version);
2134 switch (existing->version()->CompareTo(*version)) {
2135 case -1: // existing version is older, we should upgrade
2136 break;
2137 case 0: // existing version is same, do nothing
2138 return false;
2139 case 1: // existing version is newer, uh-oh
2140 LOG(WARNING) << "Found external version of extension " << id
2141 << "that is older than current version. Current version "
2142 << "is: " << existing->VersionString() << ". New "
2143 << "version is: " << version->GetString()
2144 << ". Keeping current version.";
2145 return false;
2150 // If the extension is already pending, don't start an install.
2151 if (!pending_extension_manager()->AddFromExternalFile(
2152 id, location, *version, creation_flags, mark_acknowledged)) {
2153 return false;
2156 // no client (silent install)
2157 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2158 installer->set_install_source(location);
2159 installer->set_expected_id(id);
2160 installer->set_expected_version(*version);
2161 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2162 installer->set_creation_flags(creation_flags);
2163 #if defined(OS_CHROMEOS)
2164 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2165 #else
2166 installer->InstallCrx(path);
2167 #endif
2169 // Depending on the source, a new external extension might not need a user
2170 // notification on installation. For such extensions, mark them acknowledged
2171 // now to suppress the notification.
2172 if (mark_acknowledged)
2173 external_install_manager_->AcknowledgeExternalExtension(id);
2175 return true;
2178 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2179 extensions::ExtensionHost* host) {
2180 OrphanedDevTools::iterator iter =
2181 orphaned_dev_tools_.find(host->extension_id());
2182 if (iter == orphaned_dev_tools_.end())
2183 return;
2185 iter->second->ConnectWebContents(host->host_contents());
2186 orphaned_dev_tools_.erase(iter);
2189 void ExtensionService::Observe(int type,
2190 const content::NotificationSource& source,
2191 const content::NotificationDetails& details) {
2192 switch (type) {
2193 case chrome::NOTIFICATION_APP_TERMINATING:
2194 // Shutdown has started. Don't start any more extension installs.
2195 // (We cannot use ExtensionService::Shutdown() for this because it
2196 // happens too late in browser teardown.)
2197 browser_terminating_ = true;
2198 break;
2199 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2200 if (profile_ !=
2201 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2202 break;
2205 extensions::ExtensionHost* host =
2206 content::Details<extensions::ExtensionHost>(details).ptr();
2208 // If the extension is already being terminated, there is nothing left to
2209 // do.
2210 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2211 break;
2213 // Mark the extension as terminated and Unload it. We want it to
2214 // be in a consistent state: either fully working or not loaded
2215 // at all, but never half-crashed. We do it in a PostTask so
2216 // that other handlers of this notification will still have
2217 // access to the Extension and ExtensionHost.
2218 base::MessageLoop::current()->PostTask(
2219 FROM_HERE,
2220 base::Bind(
2221 &ExtensionService::TrackTerminatedExtension,
2222 AsWeakPtr(),
2223 host->extension()));
2224 break;
2226 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2227 content::RenderProcessHost* process =
2228 content::Source<content::RenderProcessHost>(source).ptr();
2229 Profile* host_profile =
2230 Profile::FromBrowserContext(process->GetBrowserContext());
2231 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2232 break;
2234 extensions::ProcessMap* process_map =
2235 extensions::ProcessMap::Get(profile_);
2236 if (process_map->Contains(process->GetID())) {
2237 // An extension process was terminated, this might have resulted in an
2238 // app or extension becoming idle.
2239 std::set<std::string> extension_ids =
2240 process_map->GetExtensionsInProcess(process->GetID());
2241 // In addition to the extensions listed in the process map, one of those
2242 // extensions could be referencing a shared module which is waiting for
2243 // idle to update. Check all imports of these extensions, too.
2244 std::set<std::string> import_ids;
2245 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2246 it != extension_ids.end();
2247 ++it) {
2248 const Extension* extension = GetExtensionById(*it, true);
2249 if (!extension)
2250 continue;
2251 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2252 SharedModuleInfo::GetImports(extension);
2253 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2254 for (import_it = imports.begin(); import_it != imports.end();
2255 import_it++) {
2256 import_ids.insert((*import_it).extension_id);
2259 extension_ids.insert(import_ids.begin(), import_ids.end());
2261 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2262 it != extension_ids.end(); ++it) {
2263 if (delayed_installs_.Contains(*it)) {
2264 base::MessageLoop::current()->PostDelayedTask(
2265 FROM_HERE,
2266 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2267 AsWeakPtr(), *it),
2268 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2273 process_map->RemoveAllFromProcess(process->GetID());
2274 BrowserThread::PostTask(
2275 BrowserThread::IO,
2276 FROM_HERE,
2277 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2278 system_->info_map(),
2279 process->GetID()));
2280 break;
2282 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2283 // Notify observers that chrome update is available.
2284 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2285 OnChromeUpdateAvailable());
2286 break;
2288 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2289 OnProfileDestructionStarted();
2290 break;
2293 default:
2294 NOTREACHED() << "Unexpected notification type.";
2298 int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
2299 Extension::DisableReason disable_reason;
2300 // Extensions disabled by management policy should always be disabled, even
2301 // if it's force-installed.
2302 if (system_->management_policy()->MustRemainDisabled(
2303 extension, &disable_reason, nullptr)) {
2304 // A specified reason is required to disable the extension.
2305 DCHECK(disable_reason != Extension::DISABLE_NONE);
2306 return disable_reason;
2309 // Extensions installed by policy can't be disabled. So even if a previous
2310 // installation disabled the extension, make sure it is now enabled.
2311 if (system_->management_policy()->MustRemainEnabled(extension, nullptr))
2312 return Extension::DISABLE_NONE;
2314 // An already disabled extension should inherit the disable reasons and
2315 // remain disabled.
2316 if (extension_prefs_->IsExtensionDisabled(extension->id())) {
2317 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2318 // If an extension was disabled without specified reason, presume it's
2319 // disabled by user.
2320 return disable_reasons == Extension::DISABLE_NONE
2321 ? Extension::DISABLE_USER_ACTION
2322 : disable_reasons;
2325 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2326 // External extensions are initially disabled. We prompt the user before
2327 // enabling them. Hosted apps are excepted because they are not dangerous
2328 // (they need to be launched by the user anyway).
2329 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2330 Manifest::IsExternalLocation(extension->location()) &&
2331 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2332 return Extension::DISABLE_EXTERNAL_EXTENSION;
2336 return Extension::DISABLE_NONE;
2339 // Helper method to determine if an extension can be blocked.
2340 bool ExtensionService::CanBlockExtension(const Extension* extension) const {
2341 DCHECK(extension);
2342 return extension->location() != Manifest::COMPONENT &&
2343 extension->location() != Manifest::EXTERNAL_COMPONENT &&
2344 !system_->management_policy()->MustRemainEnabled(extension, NULL);
2347 bool ExtensionService::ShouldDelayExtensionUpdate(
2348 const std::string& extension_id,
2349 bool install_immediately) const {
2350 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2352 // If delayed updates are globally disabled, or just for this extension,
2353 // don't delay.
2354 if (!install_updates_when_idle_ || install_immediately)
2355 return false;
2357 const Extension* old = GetInstalledExtension(extension_id);
2358 // If there is no old extension, this is not an update, so don't delay.
2359 if (!old)
2360 return false;
2362 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2363 // Delay installation if the extension listens for the onUpdateAvailable
2364 // event.
2365 return system_->event_router()->ExtensionHasEventListener(
2366 extension_id, kOnUpdateAvailableEvent);
2367 } else {
2368 // Delay installation if the extension is not idle.
2369 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2373 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2374 DCHECK(!installs_delayed_for_gc_);
2375 installs_delayed_for_gc_ = true;
2378 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2379 DCHECK(installs_delayed_for_gc_);
2380 installs_delayed_for_gc_ = false;
2381 MaybeFinishDelayedInstallations();
2384 void ExtensionService::MaybeFinishDelayedInstallations() {
2385 std::vector<std::string> to_be_installed;
2386 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2387 it != delayed_installs_.end();
2388 ++it) {
2389 to_be_installed.push_back((*it)->id());
2391 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2392 it != to_be_installed.end();
2393 ++it) {
2394 MaybeFinishDelayedInstallation(*it);
2398 void ExtensionService::OnBlacklistUpdated() {
2399 blacklist_->GetBlacklistedIDs(
2400 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2401 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2404 void ExtensionService::ManageBlacklist(
2405 const extensions::Blacklist::BlacklistStateMap& state_map) {
2406 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2408 std::set<std::string> blacklisted;
2409 ExtensionIdSet greylist;
2410 ExtensionIdSet unchanged;
2411 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2412 state_map.begin();
2413 it != state_map.end();
2414 ++it) {
2415 switch (it->second) {
2416 case extensions::NOT_BLACKLISTED:
2417 break;
2419 case extensions::BLACKLISTED_MALWARE:
2420 blacklisted.insert(it->first);
2421 break;
2423 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2424 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2425 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2426 greylist.insert(it->first);
2427 break;
2429 case extensions::BLACKLISTED_UNKNOWN:
2430 unchanged.insert(it->first);
2431 break;
2435 UpdateBlacklistedExtensions(blacklisted, unchanged);
2436 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2438 error_controller_->ShowErrorIfNeeded();
2441 namespace {
2442 void Partition(const ExtensionIdSet& before,
2443 const ExtensionIdSet& after,
2444 const ExtensionIdSet& unchanged,
2445 ExtensionIdSet* no_longer,
2446 ExtensionIdSet* not_yet) {
2447 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2448 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2449 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2451 } // namespace
2453 void ExtensionService::UpdateBlacklistedExtensions(
2454 const ExtensionIdSet& blacklisted,
2455 const ExtensionIdSet& unchanged) {
2456 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2457 Partition(registry_->blacklisted_extensions().GetIDs(), blacklisted,
2458 unchanged, &no_longer_blocked, &not_yet_blocked);
2460 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2461 it != no_longer_blocked.end(); ++it) {
2462 scoped_refptr<const Extension> extension =
2463 registry_->blacklisted_extensions().GetByID(*it);
2464 if (!extension.get()) {
2465 NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
2466 << "but it was never blacklisted.";
2467 continue;
2469 registry_->RemoveBlacklisted(*it);
2470 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2471 AddExtension(extension.get());
2472 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2473 extension->location(),
2474 Manifest::NUM_LOCATIONS);
2477 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2478 it != not_yet_blocked.end(); ++it) {
2479 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2480 if (!extension.get()) {
2481 NOTREACHED() << "Extension " << *it << " needs to be "
2482 << "blacklisted, but it's not installed.";
2483 continue;
2485 registry_->AddBlacklisted(extension);
2486 extension_prefs_->SetExtensionBlacklistState(
2487 extension->id(), extensions::BLACKLISTED_MALWARE);
2488 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2489 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2490 extension->location(), Manifest::NUM_LOCATIONS);
2494 // TODO(oleg): UMA logging
2495 void ExtensionService::UpdateGreylistedExtensions(
2496 const ExtensionIdSet& greylist,
2497 const ExtensionIdSet& unchanged,
2498 const extensions::Blacklist::BlacklistStateMap& state_map) {
2499 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2500 Partition(greylist_.GetIDs(),
2501 greylist, unchanged,
2502 &no_longer_greylisted, &not_yet_greylisted);
2504 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2505 it != no_longer_greylisted.end(); ++it) {
2506 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2507 if (!extension.get()) {
2508 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2509 << "but it was not marked as greylisted.";
2510 continue;
2513 greylist_.Remove(*it);
2514 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2515 extensions::NOT_BLACKLISTED);
2516 if (extension_prefs_->GetDisableReasons(extension->id()) &
2517 extensions::Extension::DISABLE_GREYLIST)
2518 EnableExtension(*it);
2521 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2522 it != not_yet_greylisted.end(); ++it) {
2523 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2524 if (!extension.get()) {
2525 NOTREACHED() << "Extension " << *it << " needs to be "
2526 << "disabled, but it's not installed.";
2527 continue;
2529 greylist_.Insert(extension);
2530 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2531 state_map.find(*it)->second);
2532 if (registry_->enabled_extensions().Contains(extension->id()))
2533 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2537 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2538 update_observers_.AddObserver(observer);
2541 void ExtensionService::RemoveUpdateObserver(
2542 extensions::UpdateObserver* observer) {
2543 update_observers_.RemoveObserver(observer);
2546 // Used only by test code.
2547 void ExtensionService::UnloadAllExtensionsInternal() {
2548 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2550 registry_->ClearAll();
2551 system_->runtime_data()->ClearAll();
2553 // TODO(erikkay) should there be a notification for this? We can't use
2554 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2555 // or uninstalled.
2558 void ExtensionService::OnProfileDestructionStarted() {
2559 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2560 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2561 it != ids_to_unload.end();
2562 ++it) {
2563 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);