app_list: Re-enable people search.
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
bloba93594708fc816d00a30ee1df19b28ffd2125a3f
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/extension_service.h"
7 #include <algorithm>
8 #include <iterator>
9 #include <set>
11 #include "base/command_line.h"
12 #include "base/metrics/histogram.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/content_settings/content_settings_internal_extension_provider.h"
22 #include "chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h"
23 #include "chrome/browser/extensions/api/content_settings/content_settings_service.h"
24 #include "chrome/browser/extensions/component_loader.h"
25 #include "chrome/browser/extensions/crx_installer.h"
26 #include "chrome/browser/extensions/data_deleter.h"
27 #include "chrome/browser/extensions/extension_action_storage_manager.h"
28 #include "chrome/browser/extensions/extension_assets_manager.h"
29 #include "chrome/browser/extensions/extension_disabled_ui.h"
30 #include "chrome/browser/extensions/extension_error_controller.h"
31 #include "chrome/browser/extensions/extension_special_storage_policy.h"
32 #include "chrome/browser/extensions/extension_sync_service.h"
33 #include "chrome/browser/extensions/extension_util.h"
34 #include "chrome/browser/extensions/external_install_manager.h"
35 #include "chrome/browser/extensions/external_provider_impl.h"
36 #include "chrome/browser/extensions/install_verifier.h"
37 #include "chrome/browser/extensions/installed_loader.h"
38 #include "chrome/browser/extensions/pending_extension_manager.h"
39 #include "chrome/browser/extensions/permissions_updater.h"
40 #include "chrome/browser/extensions/shared_module_service.h"
41 #include "chrome/browser/extensions/unpacked_installer.h"
42 #include "chrome/browser/extensions/updater/chrome_extension_downloader_factory.h"
43 #include "chrome/browser/extensions/updater/extension_updater.h"
44 #include "chrome/browser/google/google_brand.h"
45 #include "chrome/browser/profiles/profile.h"
46 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
47 #include "chrome/browser/ui/webui/favicon_source.h"
48 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
49 #include "chrome/browser/ui/webui/theme_source.h"
50 #include "chrome/common/chrome_switches.h"
51 #include "chrome/common/crash_keys.h"
52 #include "chrome/common/extensions/extension_constants.h"
53 #include "chrome/common/extensions/features/feature_channel.h"
54 #include "chrome/common/url_constants.h"
55 #include "components/content_settings/core/browser/host_content_settings_map.h"
56 #include "components/crx_file/id_util.h"
57 #include "components/startup_metric_utils/startup_metric_utils.h"
58 #include "content/public/browser/devtools_agent_host.h"
59 #include "content/public/browser/notification_service.h"
60 #include "content/public/browser/render_process_host.h"
61 #include "content/public/browser/storage_partition.h"
62 #include "extensions/browser/event_router.h"
63 #include "extensions/browser/extension_host.h"
64 #include "extensions/browser/extension_prefs.h"
65 #include "extensions/browser/extension_registry.h"
66 #include "extensions/browser/extension_system.h"
67 #include "extensions/browser/extensions_browser_client.h"
68 #include "extensions/browser/install_flag.h"
69 #include "extensions/browser/runtime_data.h"
70 #include "extensions/browser/uninstall_reason.h"
71 #include "extensions/browser/update_observer.h"
72 #include "extensions/browser/updater/extension_cache.h"
73 #include "extensions/browser/updater/extension_downloader.h"
74 #include "extensions/common/extension_messages.h"
75 #include "extensions/common/extension_urls.h"
76 #include "extensions/common/feature_switch.h"
77 #include "extensions/common/file_util.h"
78 #include "extensions/common/manifest_constants.h"
79 #include "extensions/common/manifest_handlers/background_info.h"
80 #include "extensions/common/manifest_url_handlers.h"
81 #include "extensions/common/one_shot_event.h"
82 #include "extensions/common/permissions/permission_message_provider.h"
83 #include "extensions/common/permissions/permissions_data.h"
85 #if defined(OS_CHROMEOS)
86 #include "chrome/browser/chromeos/extensions/install_limiter.h"
87 #include "storage/browser/fileapi/file_system_backend.h"
88 #include "storage/browser/fileapi/file_system_context.h"
89 #endif
91 using content::BrowserContext;
92 using content::BrowserThread;
93 using content::DevToolsAgentHost;
94 using extensions::CrxInstaller;
95 using extensions::Extension;
96 using extensions::ExtensionIdSet;
97 using extensions::ExtensionInfo;
98 using extensions::ExtensionRegistry;
99 using extensions::ExtensionSet;
100 using extensions::FeatureSwitch;
101 using extensions::InstallVerifier;
102 using extensions::ManagementPolicy;
103 using extensions::Manifest;
104 using extensions::PermissionMessage;
105 using extensions::PermissionMessages;
106 using extensions::PermissionSet;
107 using extensions::SharedModuleInfo;
108 using extensions::SharedModuleService;
109 using extensions::UnloadedExtensionInfo;
111 namespace errors = extensions::manifest_errors;
113 namespace {
115 // Wait this many seconds after an extensions becomes idle before updating it.
116 const int kUpdateIdleDelay = 5;
118 } // namespace
120 // ExtensionService.
122 void ExtensionService::CheckExternalUninstall(const std::string& id) {
123 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
125 // Check if the providers know about this extension.
126 extensions::ProviderCollection::const_iterator i;
127 for (i = external_extension_providers_.begin();
128 i != external_extension_providers_.end(); ++i) {
129 DCHECK(i->get()->IsReady());
130 if (i->get()->HasExtension(id))
131 return; // Yup, known extension, don't uninstall.
134 // We get the list of external extensions to check from preferences.
135 // It is possible that an extension has preferences but is not loaded.
136 // For example, an extension that requires experimental permissions
137 // will not be loaded if the experimental command line flag is not used.
138 // In this case, do not uninstall.
139 if (!GetInstalledExtension(id)) {
140 // We can't call UninstallExtension with an unloaded/invalid
141 // extension ID.
142 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
143 << "with id: " << id;
144 return;
146 UninstallExtension(id,
147 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
148 base::Bind(&base::DoNothing),
149 NULL);
152 void ExtensionService::SetFileTaskRunnerForTesting(
153 const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
154 file_task_runner_ = task_runner;
157 void ExtensionService::ClearProvidersForTesting() {
158 external_extension_providers_.clear();
161 void ExtensionService::AddProviderForTesting(
162 extensions::ExternalProviderInterface* test_provider) {
163 CHECK(test_provider);
164 external_extension_providers_.push_back(
165 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
168 void ExtensionService::BlacklistExtensionForTest(
169 const std::string& extension_id) {
170 ExtensionIdSet blacklisted;
171 ExtensionIdSet unchanged;
172 blacklisted.insert(extension_id);
173 UpdateBlacklistedExtensions(blacklisted, unchanged);
176 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
177 const std::string& id,
178 const std::string& install_parameter,
179 const GURL& update_url,
180 Manifest::Location location,
181 int creation_flags,
182 bool mark_acknowledged) {
183 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
184 CHECK(crx_file::id_util::IdIsValid(id));
186 if (Manifest::IsExternalLocation(location)) {
187 // All extensions that are not user specific can be cached.
188 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
189 ->AllowCaching(id);
192 const Extension* extension = GetExtensionById(id, true);
193 if (extension) {
194 // Already installed. Skip this install if the current location has
195 // higher priority than |location|.
196 Manifest::Location current = extension->location();
197 if (current == Manifest::GetHigherPriorityLocation(current, location))
198 return false;
199 // Otherwise, overwrite the current installation.
202 // Add |id| to the set of pending extensions. If it can not be added,
203 // then there is already a pending record from a higher-priority install
204 // source. In this case, signal that this extension will not be
205 // installed by returning false.
206 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
208 install_parameter,
209 update_url,
210 location,
211 creation_flags,
212 mark_acknowledged)) {
213 return false;
216 update_once_all_providers_are_ready_ = true;
217 return true;
220 // static
221 // This function is used to uninstall an extension via sync. The LOG statements
222 // within this function are used to inform the user if the uninstall cannot be
223 // done.
224 bool ExtensionService::UninstallExtensionHelper(
225 ExtensionService* extensions_service,
226 const std::string& extension_id,
227 extensions::UninstallReason reason) {
228 // We can't call UninstallExtension with an invalid extension ID.
229 if (!extensions_service->GetInstalledExtension(extension_id)) {
230 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
231 << "id: " << extension_id;
232 return false;
235 // The following call to UninstallExtension will not allow an uninstall of a
236 // policy-controlled extension.
237 base::string16 error;
238 if (!extensions_service->UninstallExtension(
239 extension_id, reason, base::Bind(&base::DoNothing), &error)) {
240 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
241 << ": " << error;
242 return false;
245 return true;
248 ExtensionService::ExtensionService(Profile* profile,
249 const base::CommandLine* command_line,
250 const base::FilePath& install_directory,
251 extensions::ExtensionPrefs* extension_prefs,
252 extensions::Blacklist* blacklist,
253 bool autoupdate_enabled,
254 bool extensions_enabled,
255 extensions::OneShotEvent* ready)
256 : extensions::Blacklist::Observer(blacklist),
257 profile_(profile),
258 system_(extensions::ExtensionSystem::Get(profile)),
259 extension_prefs_(extension_prefs),
260 blacklist_(blacklist),
261 extension_sync_service_(NULL),
262 registry_(extensions::ExtensionRegistry::Get(profile)),
263 pending_extension_manager_(profile),
264 install_directory_(install_directory),
265 extensions_enabled_(extensions_enabled),
266 show_extensions_prompts_(true),
267 install_updates_when_idle_(true),
268 ready_(ready),
269 update_once_all_providers_are_ready_(false),
270 browser_terminating_(false),
271 installs_delayed_for_gc_(false),
272 is_first_run_(false),
273 block_extensions_(false),
274 shared_module_service_(new extensions::SharedModuleService(profile_)) {
275 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
277 // Figure out if extension installation should be enabled.
278 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
279 *command_line, profile))
280 extensions_enabled_ = false;
282 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
283 content::NotificationService::AllBrowserContextsAndSources());
284 registrar_.Add(this,
285 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
286 content::NotificationService::AllBrowserContextsAndSources());
287 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
288 content::NotificationService::AllBrowserContextsAndSources());
289 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
290 content::NotificationService::AllBrowserContextsAndSources());
291 registrar_.Add(this,
292 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
293 content::Source<Profile>(profile_));
295 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
296 ->AddObserver(this);
298 // Set up the ExtensionUpdater
299 if (autoupdate_enabled) {
300 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
301 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
302 base::StringToInt(command_line->GetSwitchValueASCII(
303 switches::kExtensionsUpdateFrequency),
304 &update_frequency);
306 updater_.reset(new extensions::ExtensionUpdater(
307 this,
308 extension_prefs,
309 profile->GetPrefs(),
310 profile,
311 update_frequency,
312 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
313 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
314 profile)));
317 component_loader_.reset(
318 new extensions::ComponentLoader(this,
319 profile->GetPrefs(),
320 g_browser_process->local_state(),
321 profile));
323 if (extensions_enabled_) {
324 extensions::ExternalProviderImpl::CreateExternalProviders(
325 this, profile_, &external_extension_providers_);
328 // Set this as the ExtensionService for app sorting to ensure it causes syncs
329 // if required.
330 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
332 error_controller_.reset(
333 new extensions::ExtensionErrorController(profile_, is_first_run_));
334 external_install_manager_.reset(
335 new extensions::ExternalInstallManager(profile_, is_first_run_));
337 extension_action_storage_manager_.reset(
338 new extensions::ExtensionActionStorageManager(profile_));
340 // How long is the path to the Extensions directory?
341 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
342 install_directory_.value().length(), 0, 500, 100);
345 extensions::PendingExtensionManager*
346 ExtensionService::pending_extension_manager() {
347 return &pending_extension_manager_;
350 ExtensionService::~ExtensionService() {
351 // No need to unload extensions here because they are profile-scoped, and the
352 // profile is in the process of being deleted.
354 extensions::ProviderCollection::const_iterator i;
355 for (i = external_extension_providers_.begin();
356 i != external_extension_providers_.end(); ++i) {
357 extensions::ExternalProviderInterface* provider = i->get();
358 provider->ServiceShutdown();
362 void ExtensionService::Shutdown() {
363 extensions::ExtensionManagementFactory::GetInstance()
364 ->GetForBrowserContext(profile())
365 ->RemoveObserver(this);
366 system_->management_policy()->UnregisterProvider(
367 shared_module_policy_provider_.get());
370 const Extension* ExtensionService::GetExtensionById(
371 const std::string& id, bool include_disabled) const {
372 int include_mask = ExtensionRegistry::ENABLED;
373 if (include_disabled) {
374 // Include blacklisted and blocked extensions here because there are
375 // hundreds of callers of this function, and many might assume that this
376 // includes those that have been disabled due to blacklisting or blocking.
377 include_mask |= ExtensionRegistry::DISABLED |
378 ExtensionRegistry::BLACKLISTED | ExtensionRegistry::BLOCKED;
380 return registry_->GetExtensionById(id, include_mask);
383 void ExtensionService::Init() {
384 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
386 base::Time begin_time = base::Time::Now();
388 DCHECK(!is_ready()); // Can't redo init.
389 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
391 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
392 if (cmd_line->HasSwitch(switches::kInstallEphemeralAppFromWebstore)) {
393 // The sole purpose of this launch is to install a new extension from CWS
394 // and immediately terminate: loading already installed extensions is
395 // unnecessary and may interfere with the inline install dialog (e.g. if an
396 // extension listens to onStartup and opens a window).
397 SetReadyAndNotifyListeners();
398 } else {
399 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
400 component_loader_->LoadAll();
401 extensions::InstalledLoader(this).LoadAllExtensions();
403 // Attempt to re-enable extensions whose only disable reason is reloading.
404 std::vector<std::string> extensions_to_enable;
405 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
406 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
407 iter != disabled_extensions.end(); ++iter) {
408 const Extension* e = iter->get();
409 if (extension_prefs_->GetDisableReasons(e->id()) ==
410 Extension::DISABLE_RELOAD) {
411 extensions_to_enable.push_back(e->id());
414 for (std::vector<std::string>::iterator it = extensions_to_enable.begin();
415 it != extensions_to_enable.end(); ++it) {
416 EnableExtension(*it);
419 // Finish install (if possible) of extensions that were still delayed while
420 // the browser was shut down.
421 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
422 extension_prefs_->GetAllDelayedInstallInfo());
423 for (size_t i = 0; i < delayed_info->size(); ++i) {
424 ExtensionInfo* info = delayed_info->at(i).get();
425 scoped_refptr<const Extension> extension(NULL);
426 if (info->extension_manifest) {
427 std::string error;
428 extension = Extension::Create(
429 info->extension_path,
430 info->extension_location,
431 *info->extension_manifest,
432 extension_prefs_->GetDelayedInstallCreationFlags(
433 info->extension_id),
434 info->extension_id,
435 &error);
436 if (extension.get())
437 delayed_installs_.Insert(extension);
440 MaybeFinishDelayedInstallations();
442 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
443 extension_prefs_->GetAllDelayedInstallInfo());
444 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
445 delayed_info2->size() - delayed_info->size());
447 SetReadyAndNotifyListeners();
449 // TODO(erikkay) this should probably be deferred to a future point
450 // rather than running immediately at startup.
451 CheckForExternalUpdates();
453 LoadGreylistFromPrefs();
456 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
457 base::Time::Now() - begin_time);
460 void ExtensionService::LoadGreylistFromPrefs() {
461 scoped_ptr<ExtensionSet> all_extensions =
462 registry_->GenerateInstalledExtensionsSet();
464 for (ExtensionSet::const_iterator it = all_extensions->begin();
465 it != all_extensions->end(); ++it) {
466 extensions::BlacklistState state =
467 extension_prefs_->GetExtensionBlacklistState((*it)->id());
468 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
469 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
470 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
471 greylist_.Insert(*it);
475 bool ExtensionService::UpdateExtension(const std::string& id,
476 const base::FilePath& extension_path,
477 bool file_ownership_passed,
478 CrxInstaller** out_crx_installer) {
479 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
480 if (browser_terminating_) {
481 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
482 // Leak the temp file at extension_path. We don't want to add to the disk
483 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
484 // the file is in the OS temp directory which should be cleaned up for us.
485 return false;
488 const extensions::PendingExtensionInfo* pending_extension_info =
489 pending_extension_manager()->GetById(id);
491 const Extension* extension = GetInstalledExtension(id);
492 if (!pending_extension_info && !extension) {
493 LOG(WARNING) << "Will not update extension " << id
494 << " because it is not installed or pending";
495 // Delete extension_path since we're not creating a CrxInstaller
496 // that would do it for us.
497 if (!GetFileTaskRunner()->PostTask(
498 FROM_HERE,
499 base::Bind(
500 &extensions::file_util::DeleteFile, extension_path, false)))
501 NOTREACHED();
503 return false;
506 scoped_refptr<CrxInstaller> installer(
507 CrxInstaller::Create(this, scoped_ptr<ExtensionInstallPrompt>()));
508 installer->set_expected_id(id);
509 int creation_flags = Extension::NO_FLAGS;
510 if (pending_extension_info) {
511 installer->set_install_source(pending_extension_info->install_source());
512 installer->set_allow_silent_install(true);
513 if (pending_extension_info->remote_install())
514 installer->set_grant_permissions(false);
515 creation_flags = pending_extension_info->creation_flags();
516 if (pending_extension_info->mark_acknowledged())
517 external_install_manager_->AcknowledgeExternalExtension(id);
518 } else if (extension) {
519 installer->set_install_source(extension->location());
521 // If the extension was installed from or has migrated to the webstore, or
522 // its auto-update URL is from the webstore, treat it as a webstore install.
523 // Note that we ignore some older extensions with blank auto-update URLs
524 // because we are mostly concerned with restrictions on NaCl extensions,
525 // which are newer.
526 if ((extension && extension->from_webstore()) ||
527 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
528 (!extension && extension_urls::IsWebstoreUpdateUrl(
529 pending_extension_info->update_url()))) {
530 creation_flags |= Extension::FROM_WEBSTORE;
533 // Bookmark apps being updated is kind of a contradiction, but that's because
534 // we mark the default apps as bookmark apps, and they're hosted in the web
535 // store, thus they can get updated. See http://crbug.com/101605 for more
536 // details.
537 if (extension && extension->from_bookmark())
538 creation_flags |= Extension::FROM_BOOKMARK;
540 if (extension && extension->was_installed_by_default())
541 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
543 if (extension && extension->was_installed_by_oem())
544 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
546 if (extension && extension->was_installed_by_custodian())
547 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
549 if (extension) {
550 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
551 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
554 installer->set_creation_flags(creation_flags);
556 installer->set_delete_source(file_ownership_passed);
557 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
558 installer->InstallCrx(extension_path);
560 if (out_crx_installer)
561 *out_crx_installer = installer.get();
563 return true;
566 void ExtensionService::ReloadExtensionImpl(
567 // "transient" because the process of reloading may cause the reference
568 // to become invalid. Instead, use |extension_id|, a copy.
569 const std::string& transient_extension_id,
570 bool be_noisy) {
571 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
573 // If the extension is already reloading, don't reload again.
574 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
575 Extension::DISABLE_RELOAD) {
576 return;
579 // Ignore attempts to reload a blacklisted or blocked extension. Sometimes
580 // this can happen in a convoluted reload sequence triggered by the
581 // termination of a blacklisted or blocked extension and a naive attempt to
582 // reload it. For an example see http://crbug.com/373842.
583 if (registry_->blacklisted_extensions().Contains(transient_extension_id) ||
584 registry_->blocked_extensions().Contains(transient_extension_id)) {
585 return;
588 base::FilePath path;
590 std::string extension_id = transient_extension_id;
591 const Extension* transient_current_extension =
592 GetExtensionById(extension_id, false);
594 // Disable the extension if it's loaded. It might not be loaded if it crashed.
595 if (transient_current_extension) {
596 // If the extension has an inspector open for its background page, detach
597 // the inspector and hang onto a cookie for it, so that we can reattach
598 // later.
599 // TODO(yoz): this is not incognito-safe!
600 extensions::ProcessManager* manager =
601 extensions::ProcessManager::Get(profile_);
602 extensions::ExtensionHost* host =
603 manager->GetBackgroundHostForExtension(extension_id);
604 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
605 // Look for an open inspector for the background page.
606 scoped_refptr<DevToolsAgentHost> agent_host =
607 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
608 agent_host->DisconnectWebContents();
609 orphaned_dev_tools_[extension_id] = agent_host;
612 path = transient_current_extension->path();
613 // BeingUpgraded is set back to false when the extension is added.
614 system_->runtime_data()->SetBeingUpgraded(transient_current_extension->id(),
615 true);
616 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
617 reloading_extensions_.insert(extension_id);
618 } else {
619 std::map<std::string, base::FilePath>::const_iterator iter =
620 unloaded_extension_paths_.find(extension_id);
621 if (iter == unloaded_extension_paths_.end()) {
622 return;
624 path = unloaded_extension_paths_[extension_id];
627 transient_current_extension = NULL;
629 if (delayed_installs_.Contains(extension_id)) {
630 FinishDelayedInstallation(extension_id);
631 return;
634 // If we're reloading a component extension, use the component extension
635 // loader's reloader.
636 if (component_loader_->Exists(extension_id)) {
637 component_loader_->Reload(extension_id);
638 return;
641 // Check the installed extensions to see if what we're reloading was already
642 // installed.
643 scoped_ptr<ExtensionInfo> installed_extension(
644 extension_prefs_->GetInstalledExtensionInfo(extension_id));
645 if (installed_extension.get() &&
646 installed_extension->extension_manifest.get()) {
647 extensions::InstalledLoader(this).Load(*installed_extension, false);
648 } else {
649 // Otherwise, the extension is unpacked (location LOAD).
650 // We should always be able to remember the extension's path. If it's not in
651 // the map, someone failed to update |unloaded_extension_paths_|.
652 CHECK(!path.empty());
653 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
654 extensions::UnpackedInstaller::Create(this);
655 unpacked_installer->set_be_noisy_on_failure(be_noisy);
656 unpacked_installer->Load(path);
660 void ExtensionService::ReloadExtension(const std::string& extension_id) {
661 ReloadExtensionImpl(extension_id, true); // be_noisy
664 void ExtensionService::ReloadExtensionWithQuietFailure(
665 const std::string& extension_id) {
666 ReloadExtensionImpl(extension_id, false); // be_noisy
669 bool ExtensionService::UninstallExtension(
670 // "transient" because the process of uninstalling may cause the reference
671 // to become invalid. Instead, use |extenson->id()|.
672 const std::string& transient_extension_id,
673 extensions::UninstallReason reason,
674 const base::Closure& deletion_done_callback,
675 base::string16* error) {
676 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
678 scoped_refptr<const Extension> extension =
679 GetInstalledExtension(transient_extension_id);
681 // Callers should not send us nonexistent extensions.
682 CHECK(extension.get());
684 ManagementPolicy* by_policy = system_->management_policy();
685 // Policy change which triggers an uninstall will always set
686 // |external_uninstall| to true so this is the only way to uninstall
687 // managed extensions.
688 // Shared modules being uninstalled will also set |external_uninstall| to true
689 // so that we can guarantee users don't uninstall a shared module.
690 // (crbug.com/273300)
691 // TODO(rdevlin.cronin): This is probably not right. We should do something
692 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
693 // we don't do this.
694 bool external_uninstall =
695 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
696 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
697 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
698 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
699 (reason == extensions::UNINSTALL_REASON_SYNC &&
700 extension->was_installed_by_custodian());
701 if (!external_uninstall &&
702 (!by_policy->UserMayModifySettings(extension.get(), error) ||
703 by_policy->MustRemainInstalled(extension.get(), error))) {
704 content::NotificationService::current()->Notify(
705 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
706 content::Source<Profile>(profile_),
707 content::Details<const Extension>(extension.get()));
708 return false;
711 syncer::SyncChange sync_change;
712 // Don't sync the uninstall if we're going to reinstall the extension
713 // momentarily.
714 if (extension_sync_service_ &&
715 reason != extensions::UNINSTALL_REASON_REINSTALL) {
716 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
717 extension.get(), is_ready());
720 system_->install_verifier()->Remove(extension->id());
722 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
723 extension->GetType(), 100);
724 RecordPermissionMessagesHistogram(extension.get(),
725 "Extensions.Permissions_Uninstall2");
727 // Unload before doing more cleanup to ensure that nothing is hanging on to
728 // any of these resources.
729 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
731 // Tell the backend to start deleting installed extensions on the file thread.
732 if (!Manifest::IsUnpackedLocation(extension->location())) {
733 if (!GetFileTaskRunner()->PostTask(
734 FROM_HERE,
735 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
736 extension->id(),
737 profile_,
738 install_directory_,
739 extension->path())))
740 NOTREACHED();
743 extensions::DataDeleter::StartDeleting(
744 profile_, extension.get(), deletion_done_callback);
746 UntrackTerminatedExtension(extension->id());
748 // Notify interested parties that we've uninstalled this extension.
749 content::NotificationService::current()->Notify(
750 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
751 content::Source<Profile>(profile_),
752 content::Details<const Extension>(extension.get()));
753 ExtensionRegistry::Get(profile_)
754 ->TriggerOnUninstalled(extension.get(), reason);
756 if (sync_change.IsValid()) {
757 extension_sync_service_->ProcessSyncUninstallExtension(extension->id(),
758 sync_change);
761 delayed_installs_.Remove(extension->id());
763 extension_prefs_->OnExtensionUninstalled(
764 extension->id(), extension->location(), external_uninstall);
766 // Track the uninstallation.
767 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
769 return true;
772 // static
773 void ExtensionService::UninstallExtensionOnFileThread(
774 const std::string& id,
775 Profile* profile,
776 const base::FilePath& install_dir,
777 const base::FilePath& extension_path) {
778 extensions::ExtensionAssetsManager* assets_manager =
779 extensions::ExtensionAssetsManager::GetInstance();
780 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
783 bool ExtensionService::IsExtensionEnabled(
784 const std::string& extension_id) const {
785 if (registry_->enabled_extensions().Contains(extension_id) ||
786 registry_->terminated_extensions().Contains(extension_id)) {
787 return true;
790 if (registry_->disabled_extensions().Contains(extension_id) ||
791 registry_->blacklisted_extensions().Contains(extension_id) ||
792 registry_->blocked_extensions().Contains(extension_id)) {
793 return false;
796 // Blocked extensions aren't marked as such in prefs, thus if
797 // |block_extensions_| is true then CanBlockExtension() must be called with an
798 // Extension object. If the |extension_id| is not loaded, assume not enabled.
799 if (block_extensions_) {
800 const Extension* extension = GetInstalledExtension(extension_id);
801 if (!extension || CanBlockExtension(extension))
802 return false;
805 // If the extension hasn't been loaded yet, check the prefs for it. Assume
806 // enabled unless otherwise noted.
807 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
808 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
809 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
812 void ExtensionService::EnableExtension(const std::string& extension_id) {
813 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
815 if (IsExtensionEnabled(extension_id))
816 return;
817 const Extension* extension =
818 registry_->disabled_extensions().GetByID(extension_id);
820 ManagementPolicy* policy = system_->management_policy();
821 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
822 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
823 return;
826 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
827 extension_prefs_->ClearDisableReasons(extension_id);
829 // This can happen if sync enables an extension that is not
830 // installed yet.
831 if (!extension)
832 return;
834 // Move it over to the enabled list.
835 registry_->AddEnabled(make_scoped_refptr(extension));
836 registry_->RemoveDisabled(extension->id());
838 NotifyExtensionLoaded(extension);
840 // Notify listeners that the extension was enabled.
841 content::NotificationService::current()->Notify(
842 extensions::NOTIFICATION_EXTENSION_ENABLED,
843 content::Source<Profile>(profile_),
844 content::Details<const Extension>(extension));
846 if (extension_sync_service_)
847 extension_sync_service_->SyncEnableExtension(*extension);
850 void ExtensionService::DisableExtension(
851 const std::string& extension_id,
852 Extension::DisableReason disable_reason) {
853 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
855 // The extension may have been disabled already. Just add a disable reason.
856 if (!IsExtensionEnabled(extension_id)) {
857 extension_prefs_->AddDisableReason(extension_id, disable_reason);
858 return;
861 const Extension* extension = GetInstalledExtension(extension_id);
862 // |extension| can be NULL if sync disables an extension that is not
863 // installed yet.
864 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
865 // can be uninstalled by the browser if the user sets extension-specific
866 // preferences.
867 if (extension &&
868 disable_reason != Extension::DISABLE_RELOAD &&
869 disable_reason != Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY &&
870 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
871 extension->location() != Manifest::EXTERNAL_COMPONENT) {
872 return;
875 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
876 extension_prefs_->AddDisableReason(extension_id, disable_reason);
878 int include_mask =
879 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
880 extension = registry_->GetExtensionById(extension_id, include_mask);
881 if (!extension)
882 return;
884 // The extension is either enabled or terminated.
885 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
886 registry_->terminated_extensions().Contains(extension->id()));
888 // Move it over to the disabled list. Don't send a second unload notification
889 // for terminated extensions being disabled.
890 registry_->AddDisabled(make_scoped_refptr(extension));
891 if (registry_->enabled_extensions().Contains(extension->id())) {
892 registry_->RemoveEnabled(extension->id());
893 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
894 } else {
895 registry_->RemoveTerminated(extension->id());
898 if (extension_sync_service_)
899 extension_sync_service_->SyncDisableExtension(*extension);
902 void ExtensionService::DisableUserExtensions(
903 const std::vector<std::string>& except_ids) {
904 extensions::ManagementPolicy* management_policy =
905 system_->management_policy();
906 extensions::ExtensionList to_disable;
908 const ExtensionSet& enabled_set = registry_->enabled_extensions();
909 for (ExtensionSet::const_iterator extension = enabled_set.begin();
910 extension != enabled_set.end(); ++extension) {
911 if (management_policy->UserMayModifySettings(extension->get(), NULL))
912 to_disable.push_back(*extension);
914 const ExtensionSet& terminated_set = registry_->terminated_extensions();
915 for (ExtensionSet::const_iterator extension = terminated_set.begin();
916 extension != terminated_set.end(); ++extension) {
917 if (management_policy->UserMayModifySettings(extension->get(), NULL))
918 to_disable.push_back(*extension);
921 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
922 extension != to_disable.end(); ++extension) {
923 if ((*extension)->was_installed_by_default() &&
924 extension_urls::IsWebstoreUpdateUrl(
925 extensions::ManifestURL::GetUpdateURL(extension->get())))
926 continue;
927 const std::string& id = (*extension)->id();
928 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
929 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
933 // Extensions that are not locked, components or forced by policy should be
934 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
935 // extensions are now considered both blacklisted and locked.
936 void ExtensionService::BlockAllExtensions() {
937 if (block_extensions_)
938 return;
939 block_extensions_ = true;
941 // Blacklisted extensions are already unloaded, need not be blocked.
942 scoped_ptr<ExtensionSet> extensions =
943 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED |
944 ExtensionRegistry::DISABLED |
945 ExtensionRegistry::TERMINATED);
947 for (const scoped_refptr<const Extension>& extension : *extensions) {
948 const std::string& id = extension->id();
950 if (!CanBlockExtension(extension.get()))
951 continue;
953 registry_->RemoveEnabled(id);
954 registry_->RemoveDisabled(id);
955 registry_->RemoveTerminated(id);
957 registry_->AddBlocked(extension.get());
958 UnloadExtension(id, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL);
962 // All locked extensions should revert to being either enabled or disabled
963 // as appropriate.
964 void ExtensionService::UnblockAllExtensions() {
965 block_extensions_ = false;
966 scoped_ptr<ExtensionSet> to_unblock =
967 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED);
969 for (const scoped_refptr<const Extension>& extension : *to_unblock) {
970 registry_->RemoveBlocked(extension->id());
971 AddExtension(extension.get());
975 void ExtensionService::GrantPermissionsAndEnableExtension(
976 const Extension* extension) {
977 GrantPermissions(extension);
978 RecordPermissionMessagesHistogram(extension,
979 "Extensions.Permissions_ReEnable2");
980 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
981 EnableExtension(extension->id());
984 void ExtensionService::GrantPermissions(const Extension* extension) {
985 CHECK(extension);
986 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
989 // static
990 void ExtensionService::RecordPermissionMessagesHistogram(
991 const Extension* extension, const char* histogram) {
992 // Since this is called from multiple sources, and since the histogram macros
993 // use statics, we need to manually lookup the histogram ourselves.
994 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
995 histogram,
997 PermissionMessage::kEnumBoundary,
998 PermissionMessage::kEnumBoundary + 1,
999 base::HistogramBase::kUmaTargetedHistogramFlag);
1001 PermissionMessages permissions =
1002 extension->permissions_data()->GetPermissionMessages();
1003 if (permissions.empty()) {
1004 counter->Add(PermissionMessage::kNone);
1005 } else {
1006 for (PermissionMessages::iterator it = permissions.begin();
1007 it != permissions.end(); ++it)
1008 counter->Add(it->id());
1012 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1013 // The URLRequestContexts need to be first to know that the extension
1014 // was loaded, otherwise a race can arise where a renderer that is created
1015 // for the extension may try to load an extension URL with an extension id
1016 // that the request context doesn't yet know about. The profile is responsible
1017 // for ensuring its URLRequestContexts appropriately discover the loaded
1018 // extension.
1019 system_->RegisterExtensionWithRequestContexts(extension);
1021 // Tell renderers about the new extension, unless it's a theme (renderers
1022 // don't need to know about themes).
1023 if (!extension->is_theme()) {
1024 for (content::RenderProcessHost::iterator i(
1025 content::RenderProcessHost::AllHostsIterator());
1026 !i.IsAtEnd(); i.Advance()) {
1027 content::RenderProcessHost* host = i.GetCurrentValue();
1028 Profile* host_profile =
1029 Profile::FromBrowserContext(host->GetBrowserContext());
1030 if (host_profile->GetOriginalProfile() ==
1031 profile_->GetOriginalProfile()) {
1032 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1033 1, ExtensionMsg_Loaded_Params(extension));
1034 host->Send(
1035 new ExtensionMsg_Loaded(loaded_extensions));
1040 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1041 // extension.
1043 // NOTE: It is important that this happen after notifying the renderers about
1044 // the new extensions so that if we navigate to an extension URL in
1045 // ExtensionRegistryObserver::OnLoaded or
1046 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1047 // renderer is guaranteed to know about it.
1048 registry_->TriggerOnLoaded(extension);
1050 content::NotificationService::current()->Notify(
1051 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1052 content::Source<Profile>(profile_),
1053 content::Details<const Extension>(extension));
1055 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1056 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1057 profile_->GetExtensionSpecialStoragePolicy()->
1058 GrantRightsForExtension(extension, profile_);
1060 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1061 // work properly multi-profile. Besides which, it should be using
1062 // ExtensionRegistryObserver. See http://crbug.com/355029.
1063 UpdateActiveExtensionsInCrashReporter();
1065 const extensions::PermissionsData* permissions_data =
1066 extension->permissions_data();
1068 // If the extension has permission to load chrome://favicon/ resources we need
1069 // to make sure that the FaviconSource is registered with the
1070 // ChromeURLDataManager.
1071 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1072 FaviconSource* favicon_source = new FaviconSource(profile_,
1073 FaviconSource::FAVICON);
1074 content::URLDataSource::Add(profile_, favicon_source);
1077 // Same for chrome://theme/ resources.
1078 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1079 ThemeSource* theme_source = new ThemeSource(profile_);
1080 content::URLDataSource::Add(profile_, theme_source);
1083 // Same for chrome://thumb/ resources.
1084 if (permissions_data->HasHostPermission(
1085 GURL(chrome::kChromeUIThumbnailURL))) {
1086 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1087 content::URLDataSource::Add(profile_, thumbnail_source);
1091 void ExtensionService::NotifyExtensionUnloaded(
1092 const Extension* extension,
1093 UnloadedExtensionInfo::Reason reason) {
1094 UnloadedExtensionInfo details(extension, reason);
1096 registry_->TriggerOnUnloaded(extension, reason);
1098 content::NotificationService::current()->Notify(
1099 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1100 content::Source<Profile>(profile_),
1101 content::Details<UnloadedExtensionInfo>(&details));
1103 for (content::RenderProcessHost::iterator i(
1104 content::RenderProcessHost::AllHostsIterator());
1105 !i.IsAtEnd(); i.Advance()) {
1106 content::RenderProcessHost* host = i.GetCurrentValue();
1107 Profile* host_profile =
1108 Profile::FromBrowserContext(host->GetBrowserContext());
1109 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1110 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1113 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1115 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1116 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1117 profile_->GetExtensionSpecialStoragePolicy()->
1118 RevokeRightsForExtension(extension);
1120 #if defined(OS_CHROMEOS)
1121 // Revoke external file access for the extension from its file system context.
1122 // It is safe to access the extension's storage partition at this point. The
1123 // storage partition may get destroyed only after the extension gets unloaded.
1124 GURL site =
1125 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1126 storage::FileSystemContext* filesystem_context =
1127 BrowserContext::GetStoragePartitionForSite(profile_, site)
1128 ->GetFileSystemContext();
1129 if (filesystem_context && filesystem_context->external_backend()) {
1130 filesystem_context->external_backend()->
1131 RevokeAccessForExtension(extension->id());
1133 #endif
1135 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1136 // work properly multi-profile. Besides which, it should be using
1137 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1138 UpdateActiveExtensionsInCrashReporter();
1141 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1142 // Implemented in the .cc file to avoid adding a profile.h dependency to
1143 // extension_service.h.
1144 return profile_;
1147 bool ExtensionService::is_ready() {
1148 return ready_->is_signaled();
1151 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1152 if (file_task_runner_.get())
1153 return file_task_runner_.get();
1155 // We should be able to interrupt any part of extension install process during
1156 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1157 // will be ignored/deleted while we will block on started tasks.
1158 std::string token("ext_install-");
1159 token.append(profile_->GetPath().AsUTF8Unsafe());
1160 file_task_runner_ = BrowserThread::GetBlockingPool()->
1161 GetSequencedTaskRunnerWithShutdownBehavior(
1162 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1163 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1164 return file_task_runner_.get();
1167 void ExtensionService::CheckManagementPolicy() {
1168 std::vector<std::string> to_unload;
1169 std::map<std::string, Extension::DisableReason> to_disable;
1170 std::vector<std::string> to_enable;
1172 // Loop through the extensions list, finding extensions we need to unload or
1173 // disable.
1174 for (scoped_refptr<const Extension> extension :
1175 registry_->enabled_extensions()) {
1176 if (!system_->management_policy()->UserMayLoad(extension.get(), nullptr))
1177 to_unload.push_back(extension->id());
1178 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1179 if (system_->management_policy()->MustRemainDisabled(
1180 extension.get(), &disable_reason, nullptr))
1181 to_disable[extension->id()] = disable_reason;
1184 extensions::ExtensionManagement* management =
1185 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1187 // Loop through the disabled extension list, find extensions to re-enable
1188 // automatically. These extensions are exclusive from the |to_disable| and
1189 // |to_unload| lists constructed above, since disabled_extensions() and
1190 // enabled_extensions() are supposed to be mutually exclusive.
1191 for (scoped_refptr<const Extension> extension :
1192 registry_->disabled_extensions()) {
1193 // Find all disabled extensions disabled due to minimum version requirement,
1194 // but now satisfying it.
1195 if (management->CheckMinimumVersion(extension.get(), nullptr) &&
1196 extension_prefs_->HasDisableReason(
1197 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY)) {
1198 // Is DISABLE_UPDATE_REQUIRED_BY_POLICY the *only* reason?
1199 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1200 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1201 // We need to enable those disabled *only* due to minimum version
1202 // requirement.
1203 to_enable.push_back(extension->id());
1205 extension_prefs_->RemoveDisableReason(
1206 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1210 for (const std::string& id : to_unload)
1211 UnloadExtension(id, UnloadedExtensionInfo::REASON_DISABLE);
1213 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1214 to_disable.begin(); i != to_disable.end(); ++i)
1215 DisableExtension(i->first, i->second);
1217 // No extension is getting re-enabled here after disabling/unloading
1218 // because to_enable is mutually exclusive to to_disable + to_unload.
1219 for (const std::string& id : to_enable)
1220 EnableExtension(id);
1222 if (updater_.get()) {
1223 // Find all extensions disabled due to minimum version requirement from
1224 // policy (including the ones that got disabled just now), and check
1225 // for update.
1226 extensions::ExtensionUpdater::CheckParams to_recheck;
1227 for (scoped_refptr<const Extension> extension :
1228 registry_->disabled_extensions()) {
1229 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1230 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1231 // The minimum version check is the only thing holding this extension
1232 // back, so check if it can be updated to fix that.
1233 to_recheck.ids.push_back(extension->id());
1236 if (!to_recheck.ids.empty())
1237 updater_->CheckNow(to_recheck);
1241 void ExtensionService::CheckForUpdatesSoon() {
1242 // This can legitimately happen in unit tests.
1243 if (!updater_.get())
1244 return;
1246 if (AreAllExternalProvidersReady()) {
1247 updater_->CheckSoon();
1248 } else {
1249 // Sync can start updating before all the external providers are ready
1250 // during startup. Start the update as soon as those providers are ready,
1251 // but not before.
1252 update_once_all_providers_are_ready_ = true;
1256 // Some extensions will autoupdate themselves externally from Chrome. These
1257 // are typically part of some larger client application package. To support
1258 // these, the extension will register its location in the the preferences file
1259 // (and also, on Windows, in the registry) and this code will periodically
1260 // check that location for a .crx file, which it will then install locally if
1261 // a new version is available.
1262 // Errors are reported through ExtensionErrorReporter. Succcess is not
1263 // reported.
1264 void ExtensionService::CheckForExternalUpdates() {
1265 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1267 // Note that this installation is intentionally silent (since it didn't
1268 // go through the front-end). Extensions that are registered in this
1269 // way are effectively considered 'pre-bundled', and so implicitly
1270 // trusted. In general, if something has HKLM or filesystem access,
1271 // they could install an extension manually themselves anyway.
1273 // Ask each external extension provider to give us a call back for each
1274 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1275 extensions::ProviderCollection::const_iterator i;
1276 for (i = external_extension_providers_.begin();
1277 i != external_extension_providers_.end(); ++i) {
1278 extensions::ExternalProviderInterface* provider = i->get();
1279 provider->VisitRegisteredExtension();
1282 // Do any required work that we would have done after completion of all
1283 // providers.
1284 if (external_extension_providers_.empty())
1285 OnAllExternalProvidersReady();
1288 void ExtensionService::OnExternalProviderReady(
1289 const extensions::ExternalProviderInterface* provider) {
1290 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1291 CHECK(provider->IsReady());
1293 // An external provider has finished loading. We only take action
1294 // if all of them are finished. So we check them first.
1295 if (AreAllExternalProvidersReady())
1296 OnAllExternalProvidersReady();
1299 bool ExtensionService::AreAllExternalProvidersReady() const {
1300 extensions::ProviderCollection::const_iterator i;
1301 for (i = external_extension_providers_.begin();
1302 i != external_extension_providers_.end(); ++i) {
1303 if (!i->get()->IsReady())
1304 return false;
1306 return true;
1309 void ExtensionService::OnAllExternalProvidersReady() {
1310 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1311 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1312 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1314 // Install any pending extensions.
1315 if (update_once_all_providers_are_ready_ && updater()) {
1316 update_once_all_providers_are_ready_ = false;
1317 extensions::ExtensionUpdater::CheckParams params;
1318 params.callback = external_updates_finished_callback_;
1319 updater()->CheckNow(params);
1322 // Uninstall all the unclaimed extensions.
1323 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1324 extension_prefs_->GetInstalledExtensionsInfo());
1325 for (size_t i = 0; i < extensions_info->size(); ++i) {
1326 ExtensionInfo* info = extensions_info->at(i).get();
1327 if (Manifest::IsExternalLocation(info->extension_location))
1328 CheckExternalUninstall(info->extension_id);
1331 error_controller_->ShowErrorIfNeeded();
1333 external_install_manager_->UpdateExternalExtensionAlert();
1336 void ExtensionService::UnloadExtension(
1337 const std::string& extension_id,
1338 UnloadedExtensionInfo::Reason reason) {
1339 // Make sure the extension gets deleted after we return from this function.
1340 int include_mask =
1341 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1342 scoped_refptr<const Extension> extension(
1343 registry_->GetExtensionById(extension_id, include_mask));
1345 // This method can be called via PostTask, so the extension may have been
1346 // unloaded by the time this runs.
1347 if (!extension.get()) {
1348 // In case the extension may have crashed/uninstalled. Allow the profile to
1349 // clean up its RequestContexts.
1350 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1351 return;
1354 // Keep information about the extension so that we can reload it later
1355 // even if it's not permanently installed.
1356 unloaded_extension_paths_[extension->id()] = extension->path();
1358 // Clean up if the extension is meant to be enabled after a reload.
1359 reloading_extensions_.erase(extension->id());
1361 if (registry_->disabled_extensions().Contains(extension->id())) {
1362 registry_->RemoveDisabled(extension->id());
1363 // Make sure the profile cleans up its RequestContexts when an already
1364 // disabled extension is unloaded (since they are also tracking the disabled
1365 // extensions).
1366 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1367 // Don't send the unloaded notification. It was sent when the extension
1368 // was disabled.
1369 } else {
1370 // Remove the extension from the enabled list.
1371 registry_->RemoveEnabled(extension->id());
1372 NotifyExtensionUnloaded(extension.get(), reason);
1375 content::NotificationService::current()->Notify(
1376 extensions::NOTIFICATION_EXTENSION_REMOVED,
1377 content::Source<Profile>(profile_),
1378 content::Details<const Extension>(extension.get()));
1381 void ExtensionService::RemoveComponentExtension(
1382 const std::string& extension_id) {
1383 scoped_refptr<const Extension> extension(
1384 GetExtensionById(extension_id, false));
1385 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1386 if (extension.get()) {
1387 content::NotificationService::current()->Notify(
1388 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
1389 content::Source<Profile>(profile_),
1390 content::Details<const Extension>(extension.get()));
1391 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1392 extension.get(), extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT);
1396 void ExtensionService::UnloadAllExtensionsForTest() {
1397 UnloadAllExtensionsInternal();
1400 void ExtensionService::ReloadExtensionsForTest() {
1401 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1402 // warning about calling test code in production.
1403 UnloadAllExtensionsInternal();
1404 component_loader_->LoadAll();
1405 extensions::InstalledLoader(this).LoadAllExtensions();
1406 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1407 // times.
1410 void ExtensionService::SetReadyAndNotifyListeners() {
1411 ready_->Signal();
1412 content::NotificationService::current()->Notify(
1413 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1414 content::Source<Profile>(profile_),
1415 content::NotificationService::NoDetails());
1418 void ExtensionService::OnLoadedInstalledExtensions() {
1419 if (updater_)
1420 updater_->Start();
1422 OnBlacklistUpdated();
1425 void ExtensionService::AddExtension(const Extension* extension) {
1426 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1427 // default extension state to DISABLED when the --disable-extensions flag
1428 // is set (http://crbug.com/29067).
1429 if (!extensions_enabled() &&
1430 !extension->is_theme() &&
1431 extension->location() != Manifest::COMPONENT &&
1432 !Manifest::IsExternalLocation(extension->location())) {
1433 return;
1436 bool is_extension_upgrade = false;
1437 bool is_extension_installed = false;
1438 const Extension* old = GetInstalledExtension(extension->id());
1439 if (old) {
1440 is_extension_installed = true;
1441 int version_compare_result =
1442 extension->version()->CompareTo(*(old->version()));
1443 is_extension_upgrade = version_compare_result > 0;
1444 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1445 // that we aren't downgrading.
1446 if (!Manifest::IsUnpackedLocation(extension->location()))
1447 CHECK_GE(version_compare_result, 0);
1449 // If the extension was disabled for a reload, then enable it.
1450 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1452 // Set the upgraded bit; we consider reloads upgrades.
1453 system_->runtime_data()->SetBeingUpgraded(extension->id(),
1454 is_extension_upgrade || reloading);
1456 // The extension is now loaded, remove its data from unloaded extension map.
1457 unloaded_extension_paths_.erase(extension->id());
1459 // If a terminated extension is loaded, remove it from the terminated list.
1460 UntrackTerminatedExtension(extension->id());
1462 // Check if the extension's privileges have changed and mark the
1463 // extension disabled if necessary.
1464 CheckPermissionsIncrease(extension, is_extension_installed);
1466 if (is_extension_installed && !reloading) {
1467 // To upgrade an extension in place, unload the old one and then load the
1468 // new one. ReloadExtension disables the extension, which is sufficient.
1469 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1472 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1473 // Only prefs is checked for the blacklist. We rely on callers to check the
1474 // blacklist before calling into here, e.g. CrxInstaller checks before
1475 // installation then threads through the install and pending install flow
1476 // of this class, and we check when loading installed extensions.
1477 registry_->AddBlacklisted(extension);
1478 } else if (block_extensions_ && CanBlockExtension(extension)) {
1479 registry_->AddBlocked(extension);
1480 } else if (!reloading &&
1481 extension_prefs_->IsExtensionDisabled(extension->id())) {
1482 registry_->AddDisabled(extension);
1483 if (extension_sync_service_)
1484 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1485 content::NotificationService::current()->Notify(
1486 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1487 content::Source<Profile>(profile_),
1488 content::Details<const Extension>(extension));
1490 // Show the extension disabled error if a permissions increase or a remote
1491 // installation is the reason it was disabled, and no other reasons exist.
1492 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1493 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1494 Extension::DISABLE_REMOTE_INSTALL;
1495 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1496 extensions::AddExtensionDisabledError(
1497 this,
1498 extension,
1499 extension_prefs_->HasDisableReason(
1500 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1502 } else if (reloading) {
1503 // Replace the old extension with the new version.
1504 CHECK(!registry_->AddDisabled(extension));
1505 EnableExtension(extension->id());
1506 } else {
1507 // All apps that are displayed in the launcher are ordered by their ordinals
1508 // so we must ensure they have valid ordinals.
1509 if (extension->RequiresSortOrdinal()) {
1510 extension_prefs_->app_sorting()->SetExtensionVisible(
1511 extension->id(),
1512 extension->ShouldDisplayInNewTabPage() &&
1513 !extension_prefs_->IsEphemeralApp(extension->id()));
1514 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1515 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1516 extension->id(), syncer::StringOrdinal());
1520 registry_->AddEnabled(extension);
1521 if (extension_sync_service_)
1522 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1523 NotifyExtensionLoaded(extension);
1525 system_->runtime_data()->SetBeingUpgraded(extension->id(), false);
1528 void ExtensionService::AddComponentExtension(const Extension* extension) {
1529 const std::string old_version_string(
1530 extension_prefs_->GetVersionString(extension->id()));
1531 const Version old_version(old_version_string);
1533 VLOG(1) << "AddComponentExtension " << extension->name();
1534 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1535 VLOG(1) << "Component extension " << extension->name() << " ("
1536 << extension->id() << ") installing/upgrading from '"
1537 << old_version_string << "' to " << extension->version()->GetString();
1539 AddNewOrUpdatedExtension(extension,
1540 Extension::ENABLED,
1541 extensions::kInstallFlagNone,
1542 syncer::StringOrdinal(),
1543 std::string());
1544 return;
1547 AddExtension(extension);
1550 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1551 bool is_extension_installed) {
1552 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1554 // We keep track of all permissions the user has granted each extension.
1555 // This allows extensions to gracefully support backwards compatibility
1556 // by including unknown permissions in their manifests. When the user
1557 // installs the extension, only the recognized permissions are recorded.
1558 // When the unknown permissions become recognized (e.g., through browser
1559 // upgrade), we can prompt the user to accept these new permissions.
1560 // Extensions can also silently upgrade to less permissions, and then
1561 // silently upgrade to a version that adds these permissions back.
1563 // For example, pretend that Chrome 10 includes a permission "omnibox"
1564 // for an API that adds suggestions to the omnibox. An extension can
1565 // maintain backwards compatibility while still having "omnibox" in the
1566 // manifest. If a user installs the extension on Chrome 9, the browser
1567 // will record the permissions it recognized, not including "omnibox."
1568 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1569 // will disable the extension and prompt the user to approve the increase
1570 // in privileges. The extension could then release a new version that
1571 // removes the "omnibox" permission. When the user upgrades, Chrome will
1572 // still remember that "omnibox" had been granted, so that if the
1573 // extension once again includes "omnibox" in an upgrade, the extension
1574 // can upgrade without requiring this user's approval.
1575 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1577 bool auto_grant_permission =
1578 (!is_extension_installed && extension->was_installed_by_default()) ||
1579 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1580 // Silently grant all active permissions to default apps only on install.
1581 // After install they should behave like other apps.
1582 // Silently grant all active permissions to apps install in kiosk mode on both
1583 // install and update.
1584 if (auto_grant_permission)
1585 GrantPermissions(extension);
1587 bool is_privilege_increase = false;
1588 // We only need to compare the granted permissions to the current permissions
1589 // if the extension is not allowed to silently increase its permissions.
1590 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) &&
1591 !auto_grant_permission) {
1592 // Add all the recognized permissions if the granted permissions list
1593 // hasn't been initialized yet.
1594 scoped_refptr<PermissionSet> granted_permissions =
1595 extension_prefs_->GetGrantedPermissions(extension->id());
1596 CHECK(granted_permissions.get());
1598 // Here, we check if an extension's privileges have increased in a manner
1599 // that requires the user's approval. This could occur because the browser
1600 // upgraded and recognized additional privileges, or an extension upgrades
1601 // to a version that requires additional privileges.
1602 is_privilege_increase =
1603 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1604 granted_permissions.get(),
1605 extension->permissions_data()->active_permissions().get(),
1606 extension->GetType());
1609 if (is_extension_installed) {
1610 // If the extension was already disabled, suppress any alerts for becoming
1611 // disabled on permissions increase.
1612 bool previously_disabled =
1613 extension_prefs_->IsExtensionDisabled(extension->id());
1614 // Legacy disabled extensions do not have a disable reason. Infer that if
1615 // there was no permission increase, it was likely disabled by the user.
1616 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1617 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1618 disable_reasons |= Extension::DISABLE_USER_ACTION;
1620 // Extensions that came to us disabled from sync need a similar inference,
1621 // except based on the new version's permissions.
1622 if (previously_disabled &&
1623 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1624 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1625 extension_prefs_->ClearDisableReasons(extension->id());
1626 if (!is_privilege_increase)
1627 disable_reasons |= Extension::DISABLE_USER_ACTION;
1629 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1632 // Extension has changed permissions significantly. Disable it. A
1633 // notification should be sent by the caller. If the extension is already
1634 // disabled because it was installed remotely, don't add another disable
1635 // reason, but instead always set the "did escalate permissions" flag, to
1636 // ensure enabling it will always show a warning.
1637 if (disable_reasons == Extension::DISABLE_REMOTE_INSTALL) {
1638 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1639 } else if (is_privilege_increase) {
1640 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1641 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1642 RecordPermissionMessagesHistogram(extension,
1643 "Extensions.Permissions_AutoDisable2");
1645 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1646 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1648 if (disable_reasons != Extension::DISABLE_NONE) {
1649 extension_prefs_->AddDisableReason(
1650 extension->id(),
1651 static_cast<Extension::DisableReason>(disable_reasons));
1655 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1656 std::set<std::string> extension_ids;
1657 const ExtensionSet& extensions = registry_->enabled_extensions();
1658 for (ExtensionSet::const_iterator iter = extensions.begin();
1659 iter != extensions.end(); ++iter) {
1660 const Extension* extension = iter->get();
1661 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1662 extension_ids.insert(extension->id());
1665 // TODO(kalman): This is broken. ExtensionService is per-profile.
1666 // crash_keys::SetActiveExtensions is per-process. See
1667 // http://crbug.com/355029.
1668 crash_keys::SetActiveExtensions(extension_ids);
1671 void ExtensionService::OnExtensionInstalled(
1672 const Extension* extension,
1673 const syncer::StringOrdinal& page_ordinal,
1674 int install_flags) {
1675 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1677 const std::string& id = extension->id();
1678 int disable_reasons = GetDisableReasonsOnInstalled(extension);
1679 std::string install_parameter;
1680 const extensions::PendingExtensionInfo* pending_extension_info =
1681 pending_extension_manager()->GetById(id);
1682 if (pending_extension_info) {
1683 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1684 pending_extension_manager()->Remove(id);
1686 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1687 << id << " of type " << extension->GetType()
1688 << " and update URL "
1689 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1690 << "; not installing";
1692 // Delete the extension directory since we're not going to
1693 // load it.
1694 if (!GetFileTaskRunner()->PostTask(
1695 FROM_HERE,
1696 base::Bind(&extensions::file_util::DeleteFile,
1697 extension->path(),
1698 true))) {
1699 NOTREACHED();
1701 return;
1704 install_parameter = pending_extension_info->install_parameter();
1705 pending_extension_manager()->Remove(id);
1706 } else {
1707 // We explicitly want to re-enable an uninstalled external
1708 // extension; if we're here, that means the user is manually
1709 // installing the extension.
1710 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1711 disable_reasons = Extension::DISABLE_NONE;
1715 // Unsupported requirements overrides the management policy.
1716 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1717 disable_reasons |= Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1718 } else {
1719 // Requirement is supported now, remove the corresponding disable reason
1720 // instead.
1721 extension_prefs_->RemoveDisableReason(
1722 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1723 disable_reasons &= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1726 // Check if the extension was disabled because of the minimum version
1727 // requirements from enterprise policy, and satisfies it now.
1728 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1729 ->CheckMinimumVersion(extension, nullptr)) {
1730 // And remove the corresponding disable reason.
1731 extension_prefs_->RemoveDisableReason(
1732 id, Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1733 disable_reasons &= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY;
1736 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1737 // Installation of a blacklisted extension can happen from sync, policy,
1738 // etc, where to maintain consistency we need to install it, just never
1739 // load it (see AddExtension). Usually it should be the job of callers to
1740 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
1741 // showing the install dialogue).
1742 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1743 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1744 extension->location(),
1745 Manifest::NUM_LOCATIONS);
1748 if (!GetInstalledExtension(extension->id())) {
1749 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1750 extension->GetType(), 100);
1751 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1752 extension->location(), Manifest::NUM_LOCATIONS);
1753 RecordPermissionMessagesHistogram(extension,
1754 "Extensions.Permissions_Install2");
1755 } else {
1756 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1757 extension->GetType(), 100);
1758 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1759 extension->location(), Manifest::NUM_LOCATIONS);
1761 // A fully installed app cannot be demoted to an ephemeral app.
1762 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1763 !extension_prefs_->IsEphemeralApp(id)) {
1764 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1768 if (disable_reasons)
1769 extension_prefs_->AddDisableReasons(id, disable_reasons);
1771 const Extension::State initial_state =
1772 disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED
1773 : Extension::DISABLED;
1775 if (ShouldDelayExtensionUpdate(
1777 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1778 extension_prefs_->SetDelayedInstallInfo(
1779 extension,
1780 initial_state,
1781 install_flags,
1782 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1783 page_ordinal,
1784 install_parameter);
1786 // Transfer ownership of |extension|.
1787 delayed_installs_.Insert(extension);
1789 // Notify observers that app update is available.
1790 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1791 OnAppUpdateAvailable(extension));
1792 return;
1795 extensions::SharedModuleService::ImportStatus status =
1796 shared_module_service_->SatisfyImports(extension);
1797 if (installs_delayed_for_gc_) {
1798 extension_prefs_->SetDelayedInstallInfo(
1799 extension,
1800 initial_state,
1801 install_flags,
1802 extensions::ExtensionPrefs::DELAY_REASON_GC,
1803 page_ordinal,
1804 install_parameter);
1805 delayed_installs_.Insert(extension);
1806 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1807 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1808 extension_prefs_->SetDelayedInstallInfo(
1809 extension,
1810 initial_state,
1811 install_flags,
1812 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1813 page_ordinal,
1814 install_parameter);
1815 delayed_installs_.Insert(extension);
1817 } else {
1818 AddNewOrUpdatedExtension(extension,
1819 initial_state,
1820 install_flags,
1821 page_ordinal,
1822 install_parameter);
1826 void ExtensionService::OnExtensionManagementSettingsChanged() {
1827 error_controller_->ShowErrorIfNeeded();
1829 // Revokes blocked permissions from active_permissions for all extensions.
1830 extensions::ExtensionManagement* settings =
1831 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1832 CHECK(settings);
1833 scoped_ptr<ExtensionSet> all_extensions(
1834 registry_->GenerateInstalledExtensionsSet());
1835 for (const auto& extension : *all_extensions.get()) {
1836 if (!settings->IsPermissionSetAllowed(
1837 extension.get(),
1838 extension->permissions_data()->active_permissions())) {
1839 extensions::PermissionsUpdater(profile()).RemovePermissions(
1840 extension.get(),
1841 settings->GetBlockedPermissions(extension.get()).get());
1845 CheckManagementPolicy();
1848 void ExtensionService::AddNewOrUpdatedExtension(
1849 const Extension* extension,
1850 Extension::State initial_state,
1851 int install_flags,
1852 const syncer::StringOrdinal& page_ordinal,
1853 const std::string& install_parameter) {
1854 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1855 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1856 extension_prefs_->OnExtensionInstalled(
1857 extension, initial_state, page_ordinal, install_flags, install_parameter);
1858 delayed_installs_.Remove(extension->id());
1859 if (InstallVerifier::NeedsVerification(*extension))
1860 system_->install_verifier()->VerifyExtension(extension->id());
1861 FinishInstallation(extension, was_ephemeral);
1864 void ExtensionService::MaybeFinishDelayedInstallation(
1865 const std::string& extension_id) {
1866 // Check if the extension already got installed.
1867 if (!delayed_installs_.Contains(extension_id))
1868 return;
1869 extensions::ExtensionPrefs::DelayReason reason =
1870 extension_prefs_->GetDelayedInstallReason(extension_id);
1872 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1873 // preferences files that will not have set this field but it was previously
1874 // only used for idle updates.
1875 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1876 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1877 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1878 return;
1880 const Extension* extension = delayed_installs_.GetByID(extension_id);
1881 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1882 extensions::SharedModuleService::ImportStatus status =
1883 shared_module_service_->SatisfyImports(extension);
1884 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1885 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1886 delayed_installs_.Remove(extension_id);
1887 // Make sure no version of the extension is actually installed, (i.e.,
1888 // that this delayed install was not an update).
1889 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1890 extension_prefs_->DeleteExtensionPrefs(extension_id);
1892 return;
1896 FinishDelayedInstallation(extension_id);
1899 void ExtensionService::FinishDelayedInstallation(
1900 const std::string& extension_id) {
1901 scoped_refptr<const Extension> extension(
1902 GetPendingExtensionUpdate(extension_id));
1903 CHECK(extension.get());
1904 delayed_installs_.Remove(extension_id);
1906 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1907 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1908 NOTREACHED();
1910 FinishInstallation(extension.get(), was_ephemeral);
1913 void ExtensionService::FinishInstallation(
1914 const Extension* extension, bool was_ephemeral) {
1915 const extensions::Extension* existing_extension =
1916 GetInstalledExtension(extension->id());
1917 bool is_update = false;
1918 std::string old_name;
1919 if (existing_extension) {
1920 is_update = true;
1921 old_name = existing_extension->name();
1923 bool from_ephemeral =
1924 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1925 extensions::InstalledExtensionInfo details(
1926 extension, is_update, from_ephemeral, old_name);
1927 content::NotificationService::current()->Notify(
1928 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1929 content::Source<Profile>(profile_),
1930 content::Details<const extensions::InstalledExtensionInfo>(&details));
1932 registry_->TriggerOnWillBeInstalled(
1933 extension, is_update, from_ephemeral, old_name);
1935 // Unpacked extensions default to allowing file access, but if that has been
1936 // overridden, don't reset the value.
1937 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1938 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1939 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1942 AddExtension(extension);
1944 // Notify observers that need to know when an installation is complete.
1945 registry_->TriggerOnInstalled(extension, is_update);
1947 // Check extensions that may have been delayed only because this shared module
1948 // was not available.
1949 if (SharedModuleInfo::IsSharedModule(extension))
1950 MaybeFinishDelayedInstallations();
1953 void ExtensionService::PromoteEphemeralApp(
1954 const extensions::Extension* extension, bool is_from_sync) {
1955 DCHECK(GetInstalledExtension(extension->id()) &&
1956 extension_prefs_->IsEphemeralApp(extension->id()));
1958 if (extension->RequiresSortOrdinal()) {
1959 extension_prefs_->app_sorting()->SetExtensionVisible(
1960 extension->id(), extension->ShouldDisplayInNewTabPage());
1962 if (!is_from_sync) {
1963 // Reset the sort ordinals of the app to ensure it is added to the default
1964 // position, like newly installed apps would.
1965 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
1968 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1969 extension->id(), syncer::StringOrdinal());
1972 // Remove the ephemeral flags from the preferences.
1973 extension_prefs_->OnEphemeralAppPromoted(extension->id());
1975 // Fire install-related events to allow observers to handle the promotion
1976 // of the ephemeral app.
1977 extensions::InstalledExtensionInfo details(
1978 extension,
1979 true /* is update */,
1980 true /* from ephemeral */,
1981 extension->name() /* old name */);
1982 content::NotificationService::current()->Notify(
1983 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1984 content::Source<Profile>(profile_),
1985 content::Details<const extensions::InstalledExtensionInfo>(&details));
1987 registry_->TriggerOnWillBeInstalled(
1988 extension,
1989 true /* is update */,
1990 true /* from ephemeral */,
1991 extension->name() /* old name */);
1993 if (registry_->enabled_extensions().Contains(extension->id())) {
1994 // If the app is already enabled and loaded, fire the load events to allow
1995 // observers to handle the promotion of the ephemeral app.
1996 content::NotificationService::current()->Notify(
1997 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1998 content::Source<Profile>(profile_),
1999 content::Details<const Extension>(extension));
2001 registry_->TriggerOnLoaded(extension);
2002 } else {
2003 // Cached ephemeral apps may be updated and disabled due to permissions
2004 // increase. The app can be enabled (as long as no other disable reasons
2005 // exist) as the install was user-acknowledged.
2006 int disable_mask = Extension::DISABLE_NONE;
2007 if (!is_from_sync)
2008 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
2010 int other_disable_reasons =
2011 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
2012 if (!other_disable_reasons) {
2013 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
2014 GrantPermissionsAndEnableExtension(extension);
2015 else
2016 EnableExtension(extension->id());
2020 registry_->TriggerOnInstalled(extension, true);
2022 if (!is_from_sync && extension_sync_service_)
2023 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
2026 const Extension* ExtensionService::GetPendingExtensionUpdate(
2027 const std::string& id) const {
2028 return delayed_installs_.GetByID(id);
2031 void ExtensionService::RegisterContentSettings(
2032 HostContentSettingsMap* host_content_settings_map) {
2033 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2034 host_content_settings_map->RegisterProvider(
2035 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
2036 scoped_ptr<content_settings::ObservableProvider>(
2037 new content_settings::InternalExtensionProvider(profile_)));
2039 host_content_settings_map->RegisterProvider(
2040 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
2041 scoped_ptr<content_settings::ObservableProvider>(
2042 new content_settings::CustomExtensionProvider(
2043 extensions::ContentSettingsService::Get(
2044 profile_)->content_settings_store(),
2045 profile_->GetOriginalProfile() != profile_)));
2048 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
2049 // No need to check for duplicates; inserting a duplicate is a no-op.
2050 registry_->AddTerminated(make_scoped_refptr(extension));
2051 extensions_being_terminated_.erase(extension->id());
2052 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2055 void ExtensionService::TerminateExtension(const std::string& extension_id) {
2056 const Extension* extension = GetInstalledExtension(extension_id);
2057 TrackTerminatedExtension(extension);
2060 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2061 std::string lowercase_id = base::StringToLowerASCII(id);
2062 const Extension* extension =
2063 registry_->terminated_extensions().GetByID(lowercase_id);
2064 registry_->RemoveTerminated(lowercase_id);
2065 if (extension) {
2066 content::NotificationService::current()->Notify(
2067 extensions::NOTIFICATION_EXTENSION_REMOVED,
2068 content::Source<Profile>(profile_),
2069 content::Details<const Extension>(extension));
2073 const Extension* ExtensionService::GetInstalledExtension(
2074 const std::string& id) const {
2075 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2078 bool ExtensionService::OnExternalExtensionFileFound(
2079 const std::string& id,
2080 const Version* version,
2081 const base::FilePath& path,
2082 Manifest::Location location,
2083 int creation_flags,
2084 bool mark_acknowledged) {
2085 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2086 CHECK(crx_file::id_util::IdIsValid(id));
2087 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2088 return false;
2090 // Before even bothering to unpack, check and see if we already have this
2091 // version. This is important because these extensions are going to get
2092 // installed on every startup.
2093 const Extension* existing = GetExtensionById(id, true);
2095 if (existing) {
2096 // The default apps will have the location set as INTERNAL. Since older
2097 // default apps are installed as EXTERNAL, we override them. However, if the
2098 // app is already installed as internal, then do the version check.
2099 // TODO(grv) : Remove after Q1-2013.
2100 bool is_default_apps_migration =
2101 (location == Manifest::INTERNAL &&
2102 Manifest::IsExternalLocation(existing->location()));
2104 if (!is_default_apps_migration) {
2105 DCHECK(version);
2107 switch (existing->version()->CompareTo(*version)) {
2108 case -1: // existing version is older, we should upgrade
2109 break;
2110 case 0: // existing version is same, do nothing
2111 return false;
2112 case 1: // existing version is newer, uh-oh
2113 LOG(WARNING) << "Found external version of extension " << id
2114 << "that is older than current version. Current version "
2115 << "is: " << existing->VersionString() << ". New "
2116 << "version is: " << version->GetString()
2117 << ". Keeping current version.";
2118 return false;
2123 // If the extension is already pending, don't start an install.
2124 if (!pending_extension_manager()->AddFromExternalFile(
2125 id, location, *version, creation_flags, mark_acknowledged)) {
2126 return false;
2129 // no client (silent install)
2130 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2131 installer->set_install_source(location);
2132 installer->set_expected_id(id);
2133 installer->set_expected_version(*version);
2134 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2135 installer->set_creation_flags(creation_flags);
2136 #if defined(OS_CHROMEOS)
2137 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2138 #else
2139 installer->InstallCrx(path);
2140 #endif
2142 // Depending on the source, a new external extension might not need a user
2143 // notification on installation. For such extensions, mark them acknowledged
2144 // now to suppress the notification.
2145 if (mark_acknowledged)
2146 external_install_manager_->AcknowledgeExternalExtension(id);
2148 return true;
2151 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2152 extensions::ExtensionHost* host) {
2153 OrphanedDevTools::iterator iter =
2154 orphaned_dev_tools_.find(host->extension_id());
2155 if (iter == orphaned_dev_tools_.end())
2156 return;
2158 iter->second->ConnectWebContents(host->host_contents());
2159 orphaned_dev_tools_.erase(iter);
2162 void ExtensionService::Observe(int type,
2163 const content::NotificationSource& source,
2164 const content::NotificationDetails& details) {
2165 switch (type) {
2166 case chrome::NOTIFICATION_APP_TERMINATING:
2167 // Shutdown has started. Don't start any more extension installs.
2168 // (We cannot use ExtensionService::Shutdown() for this because it
2169 // happens too late in browser teardown.)
2170 browser_terminating_ = true;
2171 break;
2172 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2173 if (profile_ !=
2174 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2175 break;
2178 extensions::ExtensionHost* host =
2179 content::Details<extensions::ExtensionHost>(details).ptr();
2181 // If the extension is already being terminated, there is nothing left to
2182 // do.
2183 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2184 break;
2186 // Mark the extension as terminated and Unload it. We want it to
2187 // be in a consistent state: either fully working or not loaded
2188 // at all, but never half-crashed. We do it in a PostTask so
2189 // that other handlers of this notification will still have
2190 // access to the Extension and ExtensionHost.
2191 base::MessageLoop::current()->PostTask(
2192 FROM_HERE,
2193 base::Bind(
2194 &ExtensionService::TrackTerminatedExtension,
2195 AsWeakPtr(),
2196 host->extension()));
2197 break;
2199 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2200 content::RenderProcessHost* process =
2201 content::Source<content::RenderProcessHost>(source).ptr();
2202 Profile* host_profile =
2203 Profile::FromBrowserContext(process->GetBrowserContext());
2204 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2205 break;
2207 extensions::ProcessMap* process_map =
2208 extensions::ProcessMap::Get(profile_);
2209 if (process_map->Contains(process->GetID())) {
2210 // An extension process was terminated, this might have resulted in an
2211 // app or extension becoming idle.
2212 std::set<std::string> extension_ids =
2213 process_map->GetExtensionsInProcess(process->GetID());
2214 // In addition to the extensions listed in the process map, one of those
2215 // extensions could be referencing a shared module which is waiting for
2216 // idle to update. Check all imports of these extensions, too.
2217 std::set<std::string> import_ids;
2218 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2219 it != extension_ids.end();
2220 ++it) {
2221 const Extension* extension = GetExtensionById(*it, true);
2222 if (!extension)
2223 continue;
2224 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2225 SharedModuleInfo::GetImports(extension);
2226 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2227 for (import_it = imports.begin(); import_it != imports.end();
2228 import_it++) {
2229 import_ids.insert((*import_it).extension_id);
2232 extension_ids.insert(import_ids.begin(), import_ids.end());
2234 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2235 it != extension_ids.end(); ++it) {
2236 if (delayed_installs_.Contains(*it)) {
2237 base::MessageLoop::current()->PostDelayedTask(
2238 FROM_HERE,
2239 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2240 AsWeakPtr(), *it),
2241 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2246 process_map->RemoveAllFromProcess(process->GetID());
2247 BrowserThread::PostTask(
2248 BrowserThread::IO,
2249 FROM_HERE,
2250 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2251 system_->info_map(),
2252 process->GetID()));
2253 break;
2255 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2256 // Notify observers that chrome update is available.
2257 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2258 OnChromeUpdateAvailable());
2259 break;
2261 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2262 OnProfileDestructionStarted();
2263 break;
2266 default:
2267 NOTREACHED() << "Unexpected notification type.";
2271 int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
2272 Extension::DisableReason disable_reason;
2273 // Extensions disabled by management policy should always be disabled, even
2274 // if it's force-installed.
2275 if (system_->management_policy()->MustRemainDisabled(
2276 extension, &disable_reason, nullptr)) {
2277 // A specified reason is required to disable the extension.
2278 DCHECK(disable_reason != Extension::DISABLE_NONE);
2279 return disable_reason;
2282 // Extensions installed by policy can't be disabled. So even if a previous
2283 // installation disabled the extension, make sure it is now enabled.
2284 if (system_->management_policy()->MustRemainEnabled(extension, nullptr))
2285 return Extension::DISABLE_NONE;
2287 // An already disabled extension should inherit the disable reasons and
2288 // remain disabled.
2289 if (extension_prefs_->IsExtensionDisabled(extension->id())) {
2290 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2291 // If an extension was disabled without specified reason, presume it's
2292 // disabled by user.
2293 return disable_reasons == Extension::DISABLE_NONE
2294 ? Extension::DISABLE_USER_ACTION
2295 : disable_reasons;
2298 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2299 // External extensions are initially disabled. We prompt the user before
2300 // enabling them. Hosted apps are excepted because they are not dangerous
2301 // (they need to be launched by the user anyway).
2302 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2303 Manifest::IsExternalLocation(extension->location()) &&
2304 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2305 return Extension::DISABLE_EXTERNAL_EXTENSION;
2309 return Extension::DISABLE_NONE;
2312 // Helper method to determine if an extension can be blocked.
2313 bool ExtensionService::CanBlockExtension(const Extension* extension) const {
2314 DCHECK(extension);
2315 return extension->location() != Manifest::COMPONENT &&
2316 extension->location() != Manifest::EXTERNAL_COMPONENT &&
2317 !system_->management_policy()->MustRemainEnabled(extension, NULL);
2320 bool ExtensionService::ShouldDelayExtensionUpdate(
2321 const std::string& extension_id,
2322 bool install_immediately) const {
2323 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2325 // If delayed updates are globally disabled, or just for this extension,
2326 // don't delay.
2327 if (!install_updates_when_idle_ || install_immediately)
2328 return false;
2330 const Extension* old = GetInstalledExtension(extension_id);
2331 // If there is no old extension, this is not an update, so don't delay.
2332 if (!old)
2333 return false;
2335 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2336 // Delay installation if the extension listens for the onUpdateAvailable
2337 // event.
2338 return system_->event_router()->ExtensionHasEventListener(
2339 extension_id, kOnUpdateAvailableEvent);
2340 } else {
2341 // Delay installation if the extension is not idle.
2342 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2346 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2347 DCHECK(!installs_delayed_for_gc_);
2348 installs_delayed_for_gc_ = true;
2351 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2352 DCHECK(installs_delayed_for_gc_);
2353 installs_delayed_for_gc_ = false;
2354 MaybeFinishDelayedInstallations();
2357 void ExtensionService::MaybeFinishDelayedInstallations() {
2358 std::vector<std::string> to_be_installed;
2359 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2360 it != delayed_installs_.end();
2361 ++it) {
2362 to_be_installed.push_back((*it)->id());
2364 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2365 it != to_be_installed.end();
2366 ++it) {
2367 MaybeFinishDelayedInstallation(*it);
2371 void ExtensionService::OnBlacklistUpdated() {
2372 blacklist_->GetBlacklistedIDs(
2373 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2374 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2377 void ExtensionService::ManageBlacklist(
2378 const extensions::Blacklist::BlacklistStateMap& state_map) {
2379 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2381 std::set<std::string> blacklisted;
2382 ExtensionIdSet greylist;
2383 ExtensionIdSet unchanged;
2384 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2385 state_map.begin();
2386 it != state_map.end();
2387 ++it) {
2388 switch (it->second) {
2389 case extensions::NOT_BLACKLISTED:
2390 break;
2392 case extensions::BLACKLISTED_MALWARE:
2393 blacklisted.insert(it->first);
2394 break;
2396 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2397 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2398 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2399 greylist.insert(it->first);
2400 break;
2402 case extensions::BLACKLISTED_UNKNOWN:
2403 unchanged.insert(it->first);
2404 break;
2408 UpdateBlacklistedExtensions(blacklisted, unchanged);
2409 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2411 error_controller_->ShowErrorIfNeeded();
2414 namespace {
2415 void Partition(const ExtensionIdSet& before,
2416 const ExtensionIdSet& after,
2417 const ExtensionIdSet& unchanged,
2418 ExtensionIdSet* no_longer,
2419 ExtensionIdSet* not_yet) {
2420 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2421 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2422 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2424 } // namespace
2426 void ExtensionService::UpdateBlacklistedExtensions(
2427 const ExtensionIdSet& blacklisted,
2428 const ExtensionIdSet& unchanged) {
2429 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2430 Partition(registry_->blacklisted_extensions().GetIDs(), blacklisted,
2431 unchanged, &no_longer_blocked, &not_yet_blocked);
2433 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2434 it != no_longer_blocked.end(); ++it) {
2435 scoped_refptr<const Extension> extension =
2436 registry_->blacklisted_extensions().GetByID(*it);
2437 if (!extension.get()) {
2438 NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
2439 << "but it was never blacklisted.";
2440 continue;
2442 registry_->RemoveBlacklisted(*it);
2443 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2444 AddExtension(extension.get());
2445 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2446 extension->location(),
2447 Manifest::NUM_LOCATIONS);
2450 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2451 it != not_yet_blocked.end(); ++it) {
2452 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2453 if (!extension.get()) {
2454 NOTREACHED() << "Extension " << *it << " needs to be "
2455 << "blacklisted, but it's not installed.";
2456 continue;
2458 registry_->AddBlacklisted(extension);
2459 extension_prefs_->SetExtensionBlacklistState(
2460 extension->id(), extensions::BLACKLISTED_MALWARE);
2461 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2462 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2463 extension->location(), Manifest::NUM_LOCATIONS);
2467 // TODO(oleg): UMA logging
2468 void ExtensionService::UpdateGreylistedExtensions(
2469 const ExtensionIdSet& greylist,
2470 const ExtensionIdSet& unchanged,
2471 const extensions::Blacklist::BlacklistStateMap& state_map) {
2472 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2473 Partition(greylist_.GetIDs(),
2474 greylist, unchanged,
2475 &no_longer_greylisted, &not_yet_greylisted);
2477 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2478 it != no_longer_greylisted.end(); ++it) {
2479 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2480 if (!extension.get()) {
2481 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2482 << "but it was not marked as greylisted.";
2483 continue;
2486 greylist_.Remove(*it);
2487 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2488 extensions::NOT_BLACKLISTED);
2489 if (extension_prefs_->GetDisableReasons(extension->id()) &
2490 extensions::Extension::DISABLE_GREYLIST)
2491 EnableExtension(*it);
2494 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2495 it != not_yet_greylisted.end(); ++it) {
2496 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2497 if (!extension.get()) {
2498 NOTREACHED() << "Extension " << *it << " needs to be "
2499 << "disabled, but it's not installed.";
2500 continue;
2502 greylist_.Insert(extension);
2503 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2504 state_map.find(*it)->second);
2505 if (registry_->enabled_extensions().Contains(extension->id()))
2506 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2510 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2511 update_observers_.AddObserver(observer);
2514 void ExtensionService::RemoveUpdateObserver(
2515 extensions::UpdateObserver* observer) {
2516 update_observers_.RemoveObserver(observer);
2519 // Used only by test code.
2520 void ExtensionService::UnloadAllExtensionsInternal() {
2521 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2523 registry_->ClearAll();
2524 system_->runtime_data()->ClearAll();
2526 // TODO(erikkay) should there be a notification for this? We can't use
2527 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2528 // or uninstalled.
2531 void ExtensionService::OnProfileDestructionStarted() {
2532 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2533 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2534 it != ids_to_unload.end();
2535 ++it) {
2536 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);