Elim cr-checkbox
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blob0f976b895a63e7df8336d64cf586129c66670b83
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/location.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/profiler/scoped_profile.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/threading/sequenced_worker_pool.h"
21 #include "base/threading/thread_restrictions.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/trace_event.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/content_settings/content_settings_internal_extension_provider.h"
27 #include "chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h"
28 #include "chrome/browser/extensions/api/content_settings/content_settings_service.h"
29 #include "chrome/browser/extensions/app_data_migrator.h"
30 #include "chrome/browser/extensions/component_loader.h"
31 #include "chrome/browser/extensions/crx_installer.h"
32 #include "chrome/browser/extensions/data_deleter.h"
33 #include "chrome/browser/extensions/extension_action_storage_manager.h"
34 #include "chrome/browser/extensions/extension_assets_manager.h"
35 #include "chrome/browser/extensions/extension_disabled_ui.h"
36 #include "chrome/browser/extensions/extension_error_controller.h"
37 #include "chrome/browser/extensions/extension_special_storage_policy.h"
38 #include "chrome/browser/extensions/extension_sync_service.h"
39 #include "chrome/browser/extensions/extension_util.h"
40 #include "chrome/browser/extensions/external_install_manager.h"
41 #include "chrome/browser/extensions/external_provider_impl.h"
42 #include "chrome/browser/extensions/install_verifier.h"
43 #include "chrome/browser/extensions/installed_loader.h"
44 #include "chrome/browser/extensions/pending_extension_manager.h"
45 #include "chrome/browser/extensions/permissions_updater.h"
46 #include "chrome/browser/extensions/shared_module_service.h"
47 #include "chrome/browser/extensions/unpacked_installer.h"
48 #include "chrome/browser/extensions/updater/chrome_extension_downloader_factory.h"
49 #include "chrome/browser/extensions/updater/extension_updater.h"
50 #include "chrome/browser/google/google_brand.h"
51 #include "chrome/browser/profiles/profile.h"
52 #include "chrome/browser/search/thumbnail_source.h"
53 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
54 #include "chrome/browser/ui/webui/favicon_source.h"
55 #include "chrome/browser/ui/webui/theme_source.h"
56 #include "chrome/common/chrome_switches.h"
57 #include "chrome/common/crash_keys.h"
58 #include "chrome/common/extensions/extension_constants.h"
59 #include "chrome/common/extensions/features/feature_channel.h"
60 #include "chrome/common/url_constants.h"
61 #include "components/content_settings/core/browser/host_content_settings_map.h"
62 #include "components/crx_file/id_util.h"
63 #include "components/startup_metric_utils/startup_metric_utils.h"
64 #include "content/public/browser/devtools_agent_host.h"
65 #include "content/public/browser/notification_service.h"
66 #include "content/public/browser/render_process_host.h"
67 #include "content/public/browser/storage_partition.h"
68 #include "extensions/browser/app_sorting.h"
69 #include "extensions/browser/event_router.h"
70 #include "extensions/browser/extension_host.h"
71 #include "extensions/browser/extension_prefs.h"
72 #include "extensions/browser/extension_registry.h"
73 #include "extensions/browser/extension_system.h"
74 #include "extensions/browser/extensions_browser_client.h"
75 #include "extensions/browser/install_flag.h"
76 #include "extensions/browser/runtime_data.h"
77 #include "extensions/browser/uninstall_reason.h"
78 #include "extensions/browser/update_observer.h"
79 #include "extensions/browser/updater/extension_cache.h"
80 #include "extensions/browser/updater/extension_downloader.h"
81 #include "extensions/common/extension_messages.h"
82 #include "extensions/common/extension_urls.h"
83 #include "extensions/common/feature_switch.h"
84 #include "extensions/common/file_util.h"
85 #include "extensions/common/manifest_constants.h"
86 #include "extensions/common/manifest_handlers/background_info.h"
87 #include "extensions/common/manifest_url_handlers.h"
88 #include "extensions/common/one_shot_event.h"
89 #include "extensions/common/permissions/api_permission.h"
90 #include "extensions/common/permissions/permission_message_provider.h"
91 #include "extensions/common/permissions/permissions_data.h"
93 #if defined(ENABLE_SUPERVISED_USERS)
94 #include "chrome/browser/supervised_user/supervised_user_service.h"
95 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
96 #endif
98 #if defined(OS_CHROMEOS)
99 #include "chrome/browser/chromeos/extensions/install_limiter.h"
100 #include "storage/browser/fileapi/file_system_backend.h"
101 #include "storage/browser/fileapi/file_system_context.h"
102 #endif
104 using content::BrowserContext;
105 using content::BrowserThread;
106 using content::DevToolsAgentHost;
107 using extensions::APIPermission;
108 using extensions::CrxInstaller;
109 using extensions::Extension;
110 using extensions::ExtensionIdSet;
111 using extensions::ExtensionInfo;
112 using extensions::ExtensionRegistry;
113 using extensions::ExtensionSet;
114 using extensions::FeatureSwitch;
115 using extensions::InstallVerifier;
116 using extensions::ManagementPolicy;
117 using extensions::Manifest;
118 using extensions::PermissionID;
119 using extensions::PermissionIDSet;
120 using extensions::PermissionSet;
121 using extensions::SharedModuleInfo;
122 using extensions::SharedModuleService;
123 using extensions::UnloadedExtensionInfo;
125 namespace {
127 // Wait this many seconds after an extensions becomes idle before updating it.
128 const int kUpdateIdleDelay = 5;
130 #if defined(ENABLE_SUPERVISED_USERS)
131 // Callback for SupervisedUserService::AddExtensionUpdateRequest.
132 void ExtensionUpdateRequestSent(const std::string& id, bool success) {
133 LOG_IF(WARNING, !success) << "Failed sending update request for " << id;
135 #endif
137 } // namespace
139 // ExtensionService.
141 void ExtensionService::CheckExternalUninstall(const std::string& id) {
142 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
144 // Check if the providers know about this extension.
145 extensions::ProviderCollection::const_iterator i;
146 for (i = external_extension_providers_.begin();
147 i != external_extension_providers_.end(); ++i) {
148 DCHECK(i->get()->IsReady());
149 if (i->get()->HasExtension(id))
150 return; // Yup, known extension, don't uninstall.
153 // We get the list of external extensions to check from preferences.
154 // It is possible that an extension has preferences but is not loaded.
155 // For example, an extension that requires experimental permissions
156 // will not be loaded if the experimental command line flag is not used.
157 // In this case, do not uninstall.
158 if (!GetInstalledExtension(id)) {
159 // We can't call UninstallExtension with an unloaded/invalid
160 // extension ID.
161 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
162 << "with id: " << id;
163 return;
165 UninstallExtension(id,
166 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
167 base::Bind(&base::DoNothing),
168 NULL);
171 void ExtensionService::SetFileTaskRunnerForTesting(
172 const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
173 file_task_runner_ = task_runner;
176 void ExtensionService::ClearProvidersForTesting() {
177 external_extension_providers_.clear();
180 void ExtensionService::AddProviderForTesting(
181 extensions::ExternalProviderInterface* test_provider) {
182 CHECK(test_provider);
183 external_extension_providers_.push_back(
184 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
187 void ExtensionService::BlacklistExtensionForTest(
188 const std::string& extension_id) {
189 ExtensionIdSet blacklisted;
190 ExtensionIdSet unchanged;
191 blacklisted.insert(extension_id);
192 UpdateBlacklistedExtensions(blacklisted, unchanged);
195 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
196 const std::string& id,
197 const std::string& install_parameter,
198 const GURL& update_url,
199 Manifest::Location location,
200 int creation_flags,
201 bool mark_acknowledged) {
202 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
203 CHECK(crx_file::id_util::IdIsValid(id));
205 if (Manifest::IsExternalLocation(location)) {
206 // All extensions that are not user specific can be cached.
207 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
208 ->AllowCaching(id);
211 const Extension* extension = GetExtensionById(id, true);
212 if (extension) {
213 // Already installed. Skip this install if the current location has
214 // higher priority than |location|.
215 Manifest::Location current = extension->location();
216 if (current == Manifest::GetHigherPriorityLocation(current, location))
217 return false;
218 // Otherwise, overwrite the current installation.
221 // Add |id| to the set of pending extensions. If it can not be added,
222 // then there is already a pending record from a higher-priority install
223 // source. In this case, signal that this extension will not be
224 // installed by returning false.
225 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
227 install_parameter,
228 update_url,
229 location,
230 creation_flags,
231 mark_acknowledged)) {
232 return false;
235 update_once_all_providers_are_ready_ = true;
236 return true;
239 // static
240 // This function is used to uninstall an extension via sync. The LOG statements
241 // within this function are used to inform the user if the uninstall cannot be
242 // done.
243 bool ExtensionService::UninstallExtensionHelper(
244 ExtensionService* extensions_service,
245 const std::string& extension_id,
246 extensions::UninstallReason reason) {
247 // We can't call UninstallExtension with an invalid extension ID.
248 if (!extensions_service->GetInstalledExtension(extension_id)) {
249 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
250 << "id: " << extension_id;
251 return false;
254 // The following call to UninstallExtension will not allow an uninstall of a
255 // policy-controlled extension.
256 base::string16 error;
257 if (!extensions_service->UninstallExtension(
258 extension_id, reason, base::Bind(&base::DoNothing), &error)) {
259 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
260 << ": " << error;
261 return false;
264 return true;
267 ExtensionService::ExtensionService(Profile* profile,
268 const base::CommandLine* command_line,
269 const base::FilePath& install_directory,
270 extensions::ExtensionPrefs* extension_prefs,
271 extensions::Blacklist* blacklist,
272 bool autoupdate_enabled,
273 bool extensions_enabled,
274 extensions::OneShotEvent* ready)
275 : extensions::Blacklist::Observer(blacklist),
276 profile_(profile),
277 system_(extensions::ExtensionSystem::Get(profile)),
278 extension_prefs_(extension_prefs),
279 blacklist_(blacklist),
280 registry_(extensions::ExtensionRegistry::Get(profile)),
281 pending_extension_manager_(profile),
282 install_directory_(install_directory),
283 extensions_enabled_(extensions_enabled),
284 show_extensions_prompts_(true),
285 install_updates_when_idle_(true),
286 ready_(ready),
287 update_once_all_providers_are_ready_(false),
288 browser_terminating_(false),
289 installs_delayed_for_gc_(false),
290 is_first_run_(false),
291 block_extensions_(false),
292 shared_module_service_(new extensions::SharedModuleService(profile_)),
293 app_data_migrator_(new extensions::AppDataMigrator(profile_, registry_)) {
294 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
295 TRACE_EVENT0("browser,startup", "ExtensionService::ExtensionService::ctor");
297 // Figure out if extension installation should be enabled.
298 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
299 *command_line, profile))
300 extensions_enabled_ = false;
302 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
303 content::NotificationService::AllBrowserContextsAndSources());
304 registrar_.Add(this,
305 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
306 content::NotificationService::AllBrowserContextsAndSources());
307 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
308 content::NotificationService::AllBrowserContextsAndSources());
309 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
310 content::NotificationService::AllBrowserContextsAndSources());
311 registrar_.Add(this,
312 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
313 content::Source<Profile>(profile_));
315 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
316 ->AddObserver(this);
318 // Set up the ExtensionUpdater.
319 if (autoupdate_enabled) {
320 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
321 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
322 base::StringToInt(command_line->GetSwitchValueASCII(
323 switches::kExtensionsUpdateFrequency),
324 &update_frequency);
326 updater_.reset(new extensions::ExtensionUpdater(
327 this,
328 extension_prefs,
329 profile->GetPrefs(),
330 profile,
331 update_frequency,
332 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
333 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
334 profile)));
337 component_loader_.reset(
338 new extensions::ComponentLoader(this,
339 profile->GetPrefs(),
340 g_browser_process->local_state(),
341 profile));
343 if (extensions_enabled_) {
344 extensions::ExternalProviderImpl::CreateExternalProviders(
345 this, profile_, &external_extension_providers_);
348 // Set this as the ExtensionService for app sorting to ensure it causes syncs
349 // if required.
350 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
352 error_controller_.reset(
353 new extensions::ExtensionErrorController(profile_, is_first_run_));
354 external_install_manager_.reset(
355 new extensions::ExternalInstallManager(profile_, is_first_run_));
357 extension_action_storage_manager_.reset(
358 new extensions::ExtensionActionStorageManager(profile_));
360 // How long is the path to the Extensions directory?
361 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
362 install_directory_.value().length(), 0, 500, 100);
365 extensions::PendingExtensionManager*
366 ExtensionService::pending_extension_manager() {
367 return &pending_extension_manager_;
370 ExtensionService::~ExtensionService() {
371 // No need to unload extensions here because they are profile-scoped, and the
372 // profile is in the process of being deleted.
374 extensions::ProviderCollection::const_iterator i;
375 for (i = external_extension_providers_.begin();
376 i != external_extension_providers_.end(); ++i) {
377 extensions::ExternalProviderInterface* provider = i->get();
378 provider->ServiceShutdown();
382 void ExtensionService::Shutdown() {
383 extensions::ExtensionManagementFactory::GetInstance()
384 ->GetForBrowserContext(profile())
385 ->RemoveObserver(this);
386 system_->management_policy()->UnregisterProvider(
387 shared_module_policy_provider_.get());
390 const Extension* ExtensionService::GetExtensionById(
391 const std::string& id, bool include_disabled) const {
392 int include_mask = ExtensionRegistry::ENABLED;
393 if (include_disabled) {
394 // Include blacklisted and blocked extensions here because there are
395 // hundreds of callers of this function, and many might assume that this
396 // includes those that have been disabled due to blacklisting or blocking.
397 include_mask |= ExtensionRegistry::DISABLED |
398 ExtensionRegistry::BLACKLISTED | ExtensionRegistry::BLOCKED;
400 return registry_->GetExtensionById(id, include_mask);
403 void ExtensionService::Init() {
404 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
405 TRACE_EVENT0("browser,startup", "ExtensionService::Init");
406 TRACK_SCOPED_REGION("Startup", "ExtensionService::Init");
407 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.ExtensionServiceInitTime");
409 DCHECK(!is_ready()); // Can't redo init.
410 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
412 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
413 component_loader_->LoadAll();
414 extensions::InstalledLoader(this).LoadAllExtensions();
416 EnabledReloadableExtensions();
417 MaybeFinishShutdownDelayed();
418 SetReadyAndNotifyListeners();
420 // TODO(erikkay): this should probably be deferred to a future point
421 // rather than running immediately at startup.
422 CheckForExternalUpdates();
424 LoadGreylistFromPrefs();
427 void ExtensionService::EnabledReloadableExtensions() {
428 TRACE_EVENT0("browser,startup",
429 "ExtensionService::EnabledReloadableExtensions");
431 std::vector<std::string> extensions_to_enable;
432 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
433 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
434 iter != disabled_extensions.end(); ++iter) {
435 const Extension* e = iter->get();
436 if (extension_prefs_->GetDisableReasons(e->id()) ==
437 Extension::DISABLE_RELOAD) {
438 extensions_to_enable.push_back(e->id());
441 for (const std::string& extension : extensions_to_enable) {
442 EnableExtension(extension);
446 void ExtensionService::MaybeFinishShutdownDelayed() {
447 TRACE_EVENT0("browser,startup",
448 "ExtensionService::MaybeFinishShutdownDelayed");
450 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
451 extension_prefs_->GetAllDelayedInstallInfo());
452 for (size_t i = 0; i < delayed_info->size(); ++i) {
453 ExtensionInfo* info = delayed_info->at(i).get();
454 scoped_refptr<const Extension> extension(NULL);
455 if (info->extension_manifest) {
456 std::string error;
457 extension = Extension::Create(
458 info->extension_path, info->extension_location,
459 *info->extension_manifest,
460 extension_prefs_->GetDelayedInstallCreationFlags(info->extension_id),
461 info->extension_id, &error);
462 if (extension.get())
463 delayed_installs_.Insert(extension);
466 MaybeFinishDelayedInstallations();
467 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
468 extension_prefs_->GetAllDelayedInstallInfo());
469 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
470 delayed_info2->size() - delayed_info->size());
473 void ExtensionService::LoadGreylistFromPrefs() {
474 TRACE_EVENT0("browser,startup", "ExtensionService::LoadGreylistFromPrefs");
476 scoped_ptr<ExtensionSet> all_extensions =
477 registry_->GenerateInstalledExtensionsSet();
479 for (ExtensionSet::const_iterator it = all_extensions->begin();
480 it != all_extensions->end(); ++it) {
481 extensions::BlacklistState state =
482 extension_prefs_->GetExtensionBlacklistState((*it)->id());
483 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
484 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
485 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
486 greylist_.Insert(*it);
490 bool ExtensionService::UpdateExtension(const extensions::CRXFileInfo& file,
491 bool file_ownership_passed,
492 CrxInstaller** out_crx_installer) {
493 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
494 if (browser_terminating_) {
495 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
496 // Leak the temp file at extension_path. We don't want to add to the disk
497 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
498 // the file is in the OS temp directory which should be cleaned up for us.
499 return false;
502 const std::string& id = file.extension_id;
504 const extensions::PendingExtensionInfo* pending_extension_info =
505 pending_extension_manager()->GetById(id);
507 const Extension* extension = GetInstalledExtension(id);
508 if (!pending_extension_info && !extension) {
509 LOG(WARNING) << "Will not update extension " << id
510 << " because it is not installed or pending";
511 // Delete extension_path since we're not creating a CrxInstaller
512 // that would do it for us.
513 if (!GetFileTaskRunner()->PostTask(
514 FROM_HERE,
515 base::Bind(&extensions::file_util::DeleteFile, file.path, false)))
516 NOTREACHED();
518 return false;
521 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
522 installer->set_expected_id(id);
523 installer->set_expected_hash(file.expected_hash);
524 int creation_flags = Extension::NO_FLAGS;
525 if (pending_extension_info) {
526 installer->set_install_source(pending_extension_info->install_source());
527 installer->set_allow_silent_install(true);
528 // If the extension came in disabled due to a permission increase, then
529 // don't grant it all the permissions. crbug.com/484214
530 bool has_permissions_increase =
531 extensions::ExtensionPrefs::Get(profile_)->HasDisableReason(
532 id, Extension::DISABLE_PERMISSIONS_INCREASE);
533 const base::Version& expected_version = pending_extension_info->version();
534 if (has_permissions_increase ||
535 pending_extension_info->remote_install() ||
536 !expected_version.IsValid()) {
537 installer->set_grant_permissions(false);
538 } else {
539 installer->set_expected_version(expected_version,
540 false /* fail_install_if_unexpected */);
542 creation_flags = pending_extension_info->creation_flags();
543 if (pending_extension_info->mark_acknowledged())
544 external_install_manager_->AcknowledgeExternalExtension(id);
545 } else if (extension) {
546 installer->set_install_source(extension->location());
548 // If the extension was installed from or has migrated to the webstore, or
549 // its auto-update URL is from the webstore, treat it as a webstore install.
550 // Note that we ignore some older extensions with blank auto-update URLs
551 // because we are mostly concerned with restrictions on NaCl extensions,
552 // which are newer.
553 if ((extension && extension->from_webstore()) ||
554 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
555 (!extension && extension_urls::IsWebstoreUpdateUrl(
556 pending_extension_info->update_url()))) {
557 creation_flags |= Extension::FROM_WEBSTORE;
560 // Bookmark apps being updated is kind of a contradiction, but that's because
561 // we mark the default apps as bookmark apps, and they're hosted in the web
562 // store, thus they can get updated. See http://crbug.com/101605 for more
563 // details.
564 if (extension && extension->from_bookmark())
565 creation_flags |= Extension::FROM_BOOKMARK;
567 if (extension && extension->was_installed_by_default())
568 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
570 if (extension && extension->was_installed_by_oem())
571 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
573 if (extension && extension->was_installed_by_custodian())
574 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
576 if (extension) {
577 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
578 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
581 installer->set_creation_flags(creation_flags);
583 installer->set_delete_source(file_ownership_passed);
584 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
585 installer->InstallCrxFile(file);
587 if (out_crx_installer)
588 *out_crx_installer = installer.get();
590 return true;
593 void ExtensionService::ReloadExtensionImpl(
594 // "transient" because the process of reloading may cause the reference
595 // to become invalid. Instead, use |extension_id|, a copy.
596 const std::string& transient_extension_id,
597 bool be_noisy) {
598 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
600 // If the extension is already reloading, don't reload again.
601 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
602 Extension::DISABLE_RELOAD) {
603 return;
606 // Ignore attempts to reload a blacklisted or blocked extension. Sometimes
607 // this can happen in a convoluted reload sequence triggered by the
608 // termination of a blacklisted or blocked extension and a naive attempt to
609 // reload it. For an example see http://crbug.com/373842.
610 if (registry_->blacklisted_extensions().Contains(transient_extension_id) ||
611 registry_->blocked_extensions().Contains(transient_extension_id)) {
612 return;
615 base::FilePath path;
617 std::string extension_id = transient_extension_id;
618 const Extension* transient_current_extension =
619 GetExtensionById(extension_id, false);
621 // Disable the extension if it's loaded. It might not be loaded if it crashed.
622 if (transient_current_extension) {
623 // If the extension has an inspector open for its background page, detach
624 // the inspector and hang onto a cookie for it, so that we can reattach
625 // later.
626 // TODO(yoz): this is not incognito-safe!
627 extensions::ProcessManager* manager =
628 extensions::ProcessManager::Get(profile_);
629 extensions::ExtensionHost* host =
630 manager->GetBackgroundHostForExtension(extension_id);
631 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
632 // Look for an open inspector for the background page.
633 scoped_refptr<DevToolsAgentHost> agent_host =
634 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
635 agent_host->DisconnectWebContents();
636 orphaned_dev_tools_[extension_id] = agent_host;
639 path = transient_current_extension->path();
640 // BeingUpgraded is set back to false when the extension is added.
641 system_->runtime_data()->SetBeingUpgraded(transient_current_extension->id(),
642 true);
643 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
644 reloading_extensions_.insert(extension_id);
645 } else {
646 std::map<std::string, base::FilePath>::const_iterator iter =
647 unloaded_extension_paths_.find(extension_id);
648 if (iter == unloaded_extension_paths_.end()) {
649 return;
651 path = unloaded_extension_paths_[extension_id];
654 transient_current_extension = NULL;
656 if (delayed_installs_.Contains(extension_id)) {
657 FinishDelayedInstallation(extension_id);
658 return;
661 // If we're reloading a component extension, use the component extension
662 // loader's reloader.
663 if (component_loader_->Exists(extension_id)) {
664 component_loader_->Reload(extension_id);
665 return;
668 // Check the installed extensions to see if what we're reloading was already
669 // installed.
670 scoped_ptr<ExtensionInfo> installed_extension(
671 extension_prefs_->GetInstalledExtensionInfo(extension_id));
672 if (installed_extension.get() &&
673 installed_extension->extension_manifest.get()) {
674 extensions::InstalledLoader(this).Load(*installed_extension, false);
675 } else {
676 // Otherwise, the extension is unpacked (location LOAD).
677 // We should always be able to remember the extension's path. If it's not in
678 // the map, someone failed to update |unloaded_extension_paths_|.
679 CHECK(!path.empty());
680 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
681 extensions::UnpackedInstaller::Create(this);
682 unpacked_installer->set_be_noisy_on_failure(be_noisy);
683 unpacked_installer->Load(path);
687 void ExtensionService::ReloadExtension(const std::string& extension_id) {
688 ReloadExtensionImpl(extension_id, true); // be_noisy
691 void ExtensionService::ReloadExtensionWithQuietFailure(
692 const std::string& extension_id) {
693 ReloadExtensionImpl(extension_id, false); // be_noisy
696 bool ExtensionService::UninstallExtension(
697 // "transient" because the process of uninstalling may cause the reference
698 // to become invalid. Instead, use |extenson->id()|.
699 const std::string& transient_extension_id,
700 extensions::UninstallReason reason,
701 const base::Closure& deletion_done_callback,
702 base::string16* error) {
703 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
705 scoped_refptr<const Extension> extension =
706 GetInstalledExtension(transient_extension_id);
708 // Callers should not send us nonexistent extensions.
709 CHECK(extension.get());
711 ManagementPolicy* by_policy = system_->management_policy();
712 // Policy change which triggers an uninstall will always set
713 // |external_uninstall| to true so this is the only way to uninstall
714 // managed extensions.
715 // Shared modules being uninstalled will also set |external_uninstall| to true
716 // so that we can guarantee users don't uninstall a shared module.
717 // (crbug.com/273300)
718 // TODO(rdevlin.cronin): This is probably not right. We should do something
719 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
720 // we don't do this.
721 bool external_uninstall =
722 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
723 (reason == extensions::UNINSTALL_REASON_COMPONENT_REMOVED) ||
724 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
725 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
726 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
727 (reason == extensions::UNINSTALL_REASON_SYNC &&
728 extension->was_installed_by_custodian());
729 if (!external_uninstall &&
730 (!by_policy->UserMayModifySettings(extension.get(), error) ||
731 by_policy->MustRemainInstalled(extension.get(), error))) {
732 content::NotificationService::current()->Notify(
733 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
734 content::Source<Profile>(profile_),
735 content::Details<const Extension>(extension.get()));
736 return false;
739 InstallVerifier::Get(GetBrowserContext())->Remove(extension->id());
741 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
742 extension->GetType(), 100);
743 RecordPermissionMessagesHistogram(extension.get(), "Uninstall");
745 // Unload before doing more cleanup to ensure that nothing is hanging on to
746 // any of these resources.
747 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
749 // Tell the backend to start deleting installed extensions on the file thread.
750 if (!Manifest::IsUnpackedLocation(extension->location())) {
751 if (!GetFileTaskRunner()->PostTask(
752 FROM_HERE,
753 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
754 extension->id(),
755 profile_,
756 install_directory_,
757 extension->path())))
758 NOTREACHED();
761 extensions::DataDeleter::StartDeleting(
762 profile_, extension.get(), deletion_done_callback);
764 UntrackTerminatedExtension(extension->id());
766 // Notify interested parties that we've uninstalled this extension.
767 ExtensionRegistry::Get(profile_)
768 ->TriggerOnUninstalled(extension.get(), reason);
770 delayed_installs_.Remove(extension->id());
772 extension_prefs_->OnExtensionUninstalled(
773 extension->id(), extension->location(), external_uninstall);
775 // Track the uninstallation.
776 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
778 return true;
781 // static
782 void ExtensionService::UninstallExtensionOnFileThread(
783 const std::string& id,
784 Profile* profile,
785 const base::FilePath& install_dir,
786 const base::FilePath& extension_path) {
787 extensions::ExtensionAssetsManager* assets_manager =
788 extensions::ExtensionAssetsManager::GetInstance();
789 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
792 bool ExtensionService::IsExtensionEnabled(
793 const std::string& extension_id) const {
794 if (registry_->enabled_extensions().Contains(extension_id) ||
795 registry_->terminated_extensions().Contains(extension_id)) {
796 return true;
799 if (registry_->disabled_extensions().Contains(extension_id) ||
800 registry_->blacklisted_extensions().Contains(extension_id) ||
801 registry_->blocked_extensions().Contains(extension_id)) {
802 return false;
805 // Blocked extensions aren't marked as such in prefs, thus if
806 // |block_extensions_| is true then CanBlockExtension() must be called with an
807 // Extension object. If the |extension_id| is not loaded, assume not enabled.
808 if (block_extensions_) {
809 const Extension* extension = GetInstalledExtension(extension_id);
810 if (!extension || CanBlockExtension(extension))
811 return false;
814 // If the extension hasn't been loaded yet, check the prefs for it. Assume
815 // enabled unless otherwise noted.
816 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
817 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
818 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
821 void ExtensionService::EnableExtension(const std::string& extension_id) {
822 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
824 if (IsExtensionEnabled(extension_id))
825 return;
826 const Extension* extension =
827 registry_->disabled_extensions().GetByID(extension_id);
829 ManagementPolicy* policy = system_->management_policy();
830 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
831 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
832 return;
835 extension_prefs_->SetExtensionEnabled(extension_id);
837 // This can happen if sync enables an extension that is not installed yet.
838 if (!extension)
839 return;
841 // Move it over to the enabled list.
842 registry_->AddEnabled(make_scoped_refptr(extension));
843 registry_->RemoveDisabled(extension->id());
845 NotifyExtensionLoaded(extension);
847 // Notify listeners that the extension was enabled.
848 content::NotificationService::current()->Notify(
849 extensions::NOTIFICATION_EXTENSION_ENABLED,
850 content::Source<Profile>(profile_),
851 content::Details<const Extension>(extension));
854 void ExtensionService::DisableExtension(const std::string& extension_id,
855 int disable_reasons) {
856 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
858 // The extension may have been disabled already. Just add the disable reasons.
859 if (!IsExtensionEnabled(extension_id)) {
860 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
861 return;
864 const Extension* extension = GetInstalledExtension(extension_id);
865 // |extension| can be NULL if sync disables an extension that is not
866 // installed yet.
867 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
868 // can be uninstalled by the browser if the user sets extension-specific
869 // preferences.
870 if (extension &&
871 !(disable_reasons & Extension::DISABLE_RELOAD) &&
872 !(disable_reasons & Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) &&
873 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
874 extension->location() != Manifest::EXTERNAL_COMPONENT) {
875 return;
878 extension_prefs_->SetExtensionDisabled(extension_id, disable_reasons);
880 int include_mask =
881 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
882 extension = registry_->GetExtensionById(extension_id, include_mask);
883 if (!extension)
884 return;
886 // The extension is either enabled or terminated.
887 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
888 registry_->terminated_extensions().Contains(extension->id()));
890 // Move it over to the disabled list. Don't send a second unload notification
891 // for terminated extensions being disabled.
892 registry_->AddDisabled(make_scoped_refptr(extension));
893 if (registry_->enabled_extensions().Contains(extension->id())) {
894 registry_->RemoveEnabled(extension->id());
895 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
896 } else {
897 registry_->RemoveTerminated(extension->id());
901 void ExtensionService::DisableUserExtensions(
902 const std::vector<std::string>& except_ids) {
903 extensions::ManagementPolicy* management_policy =
904 system_->management_policy();
905 extensions::ExtensionList to_disable;
907 const ExtensionSet& enabled_set = registry_->enabled_extensions();
908 for (ExtensionSet::const_iterator extension = enabled_set.begin();
909 extension != enabled_set.end(); ++extension) {
910 if (management_policy->UserMayModifySettings(extension->get(), NULL))
911 to_disable.push_back(*extension);
913 const ExtensionSet& terminated_set = registry_->terminated_extensions();
914 for (ExtensionSet::const_iterator extension = terminated_set.begin();
915 extension != terminated_set.end(); ++extension) {
916 if (management_policy->UserMayModifySettings(extension->get(), NULL))
917 to_disable.push_back(*extension);
920 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
921 extension != to_disable.end(); ++extension) {
922 if ((*extension)->was_installed_by_default() &&
923 extension_urls::IsWebstoreUpdateUrl(
924 extensions::ManifestURL::GetUpdateURL(extension->get())))
925 continue;
926 const std::string& id = (*extension)->id();
927 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
928 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
932 // Extensions that are not locked, components or forced by policy should be
933 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
934 // extensions are now considered both blacklisted and locked.
935 void ExtensionService::BlockAllExtensions() {
936 if (block_extensions_)
937 return;
938 block_extensions_ = true;
940 // Blacklisted extensions are already unloaded, need not be blocked.
941 scoped_ptr<ExtensionSet> extensions =
942 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED |
943 ExtensionRegistry::DISABLED |
944 ExtensionRegistry::TERMINATED);
946 for (const scoped_refptr<const Extension>& extension : *extensions) {
947 const std::string& id = extension->id();
949 if (!CanBlockExtension(extension.get()))
950 continue;
952 registry_->RemoveEnabled(id);
953 registry_->RemoveDisabled(id);
954 registry_->RemoveTerminated(id);
956 registry_->AddBlocked(extension.get());
957 UnloadExtension(id, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL);
961 // All locked extensions should revert to being either enabled or disabled
962 // as appropriate.
963 void ExtensionService::UnblockAllExtensions() {
964 block_extensions_ = false;
965 scoped_ptr<ExtensionSet> to_unblock =
966 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED);
968 for (const scoped_refptr<const Extension>& extension : *to_unblock) {
969 registry_->RemoveBlocked(extension->id());
970 AddExtension(extension.get());
974 void ExtensionService::GrantPermissionsAndEnableExtension(
975 const Extension* extension) {
976 GrantPermissions(extension);
977 RecordPermissionMessagesHistogram(extension, "ReEnable");
978 EnableExtension(extension->id());
981 void ExtensionService::GrantPermissions(const Extension* extension) {
982 CHECK(extension);
983 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
986 // static
987 void ExtensionService::RecordPermissionMessagesHistogram(
988 const Extension* extension, const char* histogram) {
989 // Since this is called from multiple sources, and since the histogram macros
990 // use statics, we need to manually lookup the histogram ourselves.
991 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
992 base::StringPrintf("Extensions.Permissions_%s3", histogram),
994 APIPermission::kEnumBoundary,
995 APIPermission::kEnumBoundary + 1,
996 base::HistogramBase::kUmaTargetedHistogramFlag);
998 base::HistogramBase* counter_has_any = base::BooleanHistogram::FactoryGet(
999 base::StringPrintf("Extensions.HasPermissions_%s3", histogram),
1000 base::HistogramBase::kUmaTargetedHistogramFlag);
1002 PermissionIDSet permissions =
1003 extensions::PermissionMessageProvider::Get()->GetAllPermissionIDs(
1004 extension->permissions_data()->active_permissions().get(),
1005 extension->GetType());
1006 counter_has_any->AddBoolean(!permissions.empty());
1007 for (const PermissionID& id : permissions)
1008 counter->Add(id.id());
1011 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1012 // The URLRequestContexts need to be first to know that the extension
1013 // was loaded, otherwise a race can arise where a renderer that is created
1014 // for the extension may try to load an extension URL with an extension id
1015 // that the request context doesn't yet know about. The profile is responsible
1016 // for ensuring its URLRequestContexts appropriately discover the loaded
1017 // extension.
1018 system_->RegisterExtensionWithRequestContexts(
1019 extension,
1020 base::Bind(&ExtensionService::OnExtensionRegisteredWithRequestContexts,
1021 AsWeakPtr(), make_scoped_refptr(extension)));
1023 // Tell renderers about the new extension, unless it's a theme (renderers
1024 // don't need to know about themes).
1025 if (!extension->is_theme()) {
1026 for (content::RenderProcessHost::iterator i(
1027 content::RenderProcessHost::AllHostsIterator());
1028 !i.IsAtEnd(); i.Advance()) {
1029 content::RenderProcessHost* host = i.GetCurrentValue();
1030 Profile* host_profile =
1031 Profile::FromBrowserContext(host->GetBrowserContext());
1032 if (host_profile->GetOriginalProfile() ==
1033 profile_->GetOriginalProfile()) {
1034 // We don't need to include tab permisisons here, since the extension
1035 // was just loaded.
1036 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1037 1, ExtensionMsg_Loaded_Params(extension,
1038 false /* no tab permissions */));
1039 host->Send(
1040 new ExtensionMsg_Loaded(loaded_extensions));
1045 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1046 // extension.
1048 // NOTE: It is important that this happen after notifying the renderers about
1049 // the new extensions so that if we navigate to an extension URL in
1050 // ExtensionRegistryObserver::OnLoaded or
1051 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1052 // renderer is guaranteed to know about it.
1053 registry_->TriggerOnLoaded(extension);
1055 content::NotificationService::current()->Notify(
1056 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1057 content::Source<Profile>(profile_),
1058 content::Details<const Extension>(extension));
1060 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1061 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1062 profile_->GetExtensionSpecialStoragePolicy()->
1063 GrantRightsForExtension(extension, profile_);
1065 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1066 // work properly multi-profile. Besides which, it should be using
1067 // ExtensionRegistryObserver. See http://crbug.com/355029.
1068 UpdateActiveExtensionsInCrashReporter();
1070 const extensions::PermissionsData* permissions_data =
1071 extension->permissions_data();
1073 // If the extension has permission to load chrome://favicon/ resources we need
1074 // to make sure that the FaviconSource is registered with the
1075 // ChromeURLDataManager.
1076 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1077 FaviconSource* favicon_source = new FaviconSource(profile_,
1078 FaviconSource::FAVICON);
1079 content::URLDataSource::Add(profile_, favicon_source);
1082 // Same for chrome://theme/ resources.
1083 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1084 ThemeSource* theme_source = new ThemeSource(profile_);
1085 content::URLDataSource::Add(profile_, theme_source);
1088 // Same for chrome://thumb/ resources.
1089 if (permissions_data->HasHostPermission(
1090 GURL(chrome::kChromeUIThumbnailURL))) {
1091 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1092 content::URLDataSource::Add(profile_, thumbnail_source);
1096 void ExtensionService::OnExtensionRegisteredWithRequestContexts(
1097 scoped_refptr<const extensions::Extension> extension) {
1098 registry_->AddReady(extension);
1099 if (registry_->enabled_extensions().Contains(extension->id()))
1100 registry_->TriggerOnReady(extension.get());
1103 void ExtensionService::NotifyExtensionUnloaded(
1104 const Extension* extension,
1105 UnloadedExtensionInfo::Reason reason) {
1106 UnloadedExtensionInfo details(extension, reason);
1108 registry_->TriggerOnUnloaded(extension, reason);
1110 content::NotificationService::current()->Notify(
1111 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1112 content::Source<Profile>(profile_),
1113 content::Details<UnloadedExtensionInfo>(&details));
1115 for (content::RenderProcessHost::iterator i(
1116 content::RenderProcessHost::AllHostsIterator());
1117 !i.IsAtEnd(); i.Advance()) {
1118 content::RenderProcessHost* host = i.GetCurrentValue();
1119 Profile* host_profile =
1120 Profile::FromBrowserContext(host->GetBrowserContext());
1121 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1122 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1125 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1127 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1128 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1129 profile_->GetExtensionSpecialStoragePolicy()->
1130 RevokeRightsForExtension(extension);
1132 #if defined(OS_CHROMEOS)
1133 // Revoke external file access for the extension from its file system context.
1134 // It is safe to access the extension's storage partition at this point. The
1135 // storage partition may get destroyed only after the extension gets unloaded.
1136 GURL site =
1137 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1138 storage::FileSystemContext* filesystem_context =
1139 BrowserContext::GetStoragePartitionForSite(profile_, site)
1140 ->GetFileSystemContext();
1141 if (filesystem_context && filesystem_context->external_backend()) {
1142 filesystem_context->external_backend()->
1143 RevokeAccessForExtension(extension->id());
1145 #endif
1147 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1148 // work properly multi-profile. Besides which, it should be using
1149 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1150 UpdateActiveExtensionsInCrashReporter();
1153 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1154 // Implemented in the .cc file to avoid adding a profile.h dependency to
1155 // extension_service.h.
1156 return profile_;
1159 bool ExtensionService::is_ready() {
1160 return ready_->is_signaled();
1163 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1164 if (file_task_runner_.get())
1165 return file_task_runner_.get();
1167 // We should be able to interrupt any part of extension install process during
1168 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1169 // will be ignored/deleted while we will block on started tasks.
1170 std::string token("ext_install-");
1171 token.append(profile_->GetPath().AsUTF8Unsafe());
1172 file_task_runner_ = BrowserThread::GetBlockingPool()->
1173 GetSequencedTaskRunnerWithShutdownBehavior(
1174 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1175 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1176 return file_task_runner_.get();
1179 void ExtensionService::CheckManagementPolicy() {
1180 std::vector<std::string> to_unload;
1181 std::map<std::string, Extension::DisableReason> to_disable;
1182 std::vector<std::string> to_enable;
1184 // Loop through the extensions list, finding extensions we need to unload or
1185 // disable.
1186 for (scoped_refptr<const Extension> extension :
1187 registry_->enabled_extensions()) {
1188 if (!system_->management_policy()->UserMayLoad(extension.get(), nullptr))
1189 to_unload.push_back(extension->id());
1190 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1191 if (system_->management_policy()->MustRemainDisabled(
1192 extension.get(), &disable_reason, nullptr))
1193 to_disable[extension->id()] = disable_reason;
1196 extensions::ExtensionManagement* management =
1197 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1199 // Loop through the disabled extension list, find extensions to re-enable
1200 // automatically. These extensions are exclusive from the |to_disable| and
1201 // |to_unload| lists constructed above, since disabled_extensions() and
1202 // enabled_extensions() are supposed to be mutually exclusive.
1203 for (scoped_refptr<const Extension> extension :
1204 registry_->disabled_extensions()) {
1205 // Find all disabled extensions disabled due to minimum version requirement,
1206 // but now satisfying it.
1207 if (management->CheckMinimumVersion(extension.get(), nullptr) &&
1208 extension_prefs_->HasDisableReason(
1209 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY)) {
1210 // Is DISABLE_UPDATE_REQUIRED_BY_POLICY the *only* reason?
1211 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1212 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1213 // We need to enable those disabled *only* due to minimum version
1214 // requirement.
1215 to_enable.push_back(extension->id());
1217 extension_prefs_->RemoveDisableReason(
1218 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1222 for (const std::string& id : to_unload)
1223 UnloadExtension(id, UnloadedExtensionInfo::REASON_DISABLE);
1225 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1226 to_disable.begin(); i != to_disable.end(); ++i)
1227 DisableExtension(i->first, i->second);
1229 // No extension is getting re-enabled here after disabling/unloading
1230 // because to_enable is mutually exclusive to to_disable + to_unload.
1231 for (const std::string& id : to_enable)
1232 EnableExtension(id);
1234 if (updater_.get()) {
1235 // Find all extensions disabled due to minimum version requirement from
1236 // policy (including the ones that got disabled just now), and check
1237 // for update.
1238 extensions::ExtensionUpdater::CheckParams to_recheck;
1239 for (scoped_refptr<const Extension> extension :
1240 registry_->disabled_extensions()) {
1241 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1242 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1243 // The minimum version check is the only thing holding this extension
1244 // back, so check if it can be updated to fix that.
1245 to_recheck.ids.push_back(extension->id());
1248 if (!to_recheck.ids.empty())
1249 updater_->CheckNow(to_recheck);
1253 void ExtensionService::CheckForUpdatesSoon() {
1254 // This can legitimately happen in unit tests.
1255 if (!updater_.get())
1256 return;
1258 if (AreAllExternalProvidersReady()) {
1259 updater_->CheckSoon();
1260 } else {
1261 // Sync can start updating before all the external providers are ready
1262 // during startup. Start the update as soon as those providers are ready,
1263 // but not before.
1264 update_once_all_providers_are_ready_ = true;
1268 // Some extensions will autoupdate themselves externally from Chrome. These
1269 // are typically part of some larger client application package. To support
1270 // these, the extension will register its location in the preferences file
1271 // (and also, on Windows, in the registry) and this code will periodically
1272 // check that location for a .crx file, which it will then install locally if
1273 // a new version is available.
1274 // Errors are reported through ExtensionErrorReporter. Success is not
1275 // reported.
1276 void ExtensionService::CheckForExternalUpdates() {
1277 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1278 TRACE_EVENT0("browser,startup", "ExtensionService::CheckForExternalUpdates");
1279 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.CheckForExternalUpdatesTime");
1281 // Note that this installation is intentionally silent (since it didn't
1282 // go through the front-end). Extensions that are registered in this
1283 // way are effectively considered 'pre-bundled', and so implicitly
1284 // trusted. In general, if something has HKLM or filesystem access,
1285 // they could install an extension manually themselves anyway.
1287 // Ask each external extension provider to give us a call back for each
1288 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1289 extensions::ProviderCollection::const_iterator i;
1290 for (i = external_extension_providers_.begin();
1291 i != external_extension_providers_.end(); ++i) {
1292 extensions::ExternalProviderInterface* provider = i->get();
1293 provider->VisitRegisteredExtension();
1296 // Do any required work that we would have done after completion of all
1297 // providers.
1298 if (external_extension_providers_.empty())
1299 OnAllExternalProvidersReady();
1302 void ExtensionService::OnExternalProviderReady(
1303 const extensions::ExternalProviderInterface* provider) {
1304 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1305 CHECK(provider->IsReady());
1307 // An external provider has finished loading. We only take action
1308 // if all of them are finished. So we check them first.
1309 if (AreAllExternalProvidersReady())
1310 OnAllExternalProvidersReady();
1313 bool ExtensionService::AreAllExternalProvidersReady() const {
1314 extensions::ProviderCollection::const_iterator i;
1315 for (i = external_extension_providers_.begin();
1316 i != external_extension_providers_.end(); ++i) {
1317 if (!i->get()->IsReady())
1318 return false;
1320 return true;
1323 void ExtensionService::OnAllExternalProvidersReady() {
1324 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1325 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1326 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1328 // Install any pending extensions.
1329 if (update_once_all_providers_are_ready_ && updater()) {
1330 update_once_all_providers_are_ready_ = false;
1331 extensions::ExtensionUpdater::CheckParams params;
1332 params.callback = external_updates_finished_callback_;
1333 updater()->CheckNow(params);
1336 // Uninstall all the unclaimed extensions.
1337 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1338 extension_prefs_->GetInstalledExtensionsInfo());
1339 for (size_t i = 0; i < extensions_info->size(); ++i) {
1340 ExtensionInfo* info = extensions_info->at(i).get();
1341 if (Manifest::IsExternalLocation(info->extension_location))
1342 CheckExternalUninstall(info->extension_id);
1345 error_controller_->ShowErrorIfNeeded();
1347 external_install_manager_->UpdateExternalExtensionAlert();
1350 void ExtensionService::UnloadExtension(
1351 const std::string& extension_id,
1352 UnloadedExtensionInfo::Reason reason) {
1353 // Make sure the extension gets deleted after we return from this function.
1354 int include_mask =
1355 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1356 scoped_refptr<const Extension> extension(
1357 registry_->GetExtensionById(extension_id, include_mask));
1359 // This method can be called via PostTask, so the extension may have been
1360 // unloaded by the time this runs.
1361 if (!extension.get()) {
1362 // In case the extension may have crashed/uninstalled. Allow the profile to
1363 // clean up its RequestContexts.
1364 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1365 return;
1368 // Keep information about the extension so that we can reload it later
1369 // even if it's not permanently installed.
1370 unloaded_extension_paths_[extension->id()] = extension->path();
1372 // Clean up if the extension is meant to be enabled after a reload.
1373 reloading_extensions_.erase(extension->id());
1375 if (registry_->disabled_extensions().Contains(extension->id())) {
1376 registry_->RemoveDisabled(extension->id());
1377 // Make sure the profile cleans up its RequestContexts when an already
1378 // disabled extension is unloaded (since they are also tracking the disabled
1379 // extensions).
1380 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1381 // Don't send the unloaded notification. It was sent when the extension
1382 // was disabled.
1383 } else {
1384 // Remove the extension from the enabled list.
1385 registry_->RemoveEnabled(extension->id());
1386 NotifyExtensionUnloaded(extension.get(), reason);
1389 content::NotificationService::current()->Notify(
1390 extensions::NOTIFICATION_EXTENSION_REMOVED,
1391 content::Source<Profile>(profile_),
1392 content::Details<const Extension>(extension.get()));
1395 void ExtensionService::RemoveComponentExtension(
1396 const std::string& extension_id) {
1397 scoped_refptr<const Extension> extension(
1398 GetExtensionById(extension_id, false));
1399 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1400 if (extension.get()) {
1401 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1402 extension.get(), extensions::UNINSTALL_REASON_COMPONENT_REMOVED);
1406 void ExtensionService::UnloadAllExtensionsForTest() {
1407 UnloadAllExtensionsInternal();
1410 void ExtensionService::ReloadExtensionsForTest() {
1411 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1412 // warning about calling test code in production.
1413 UnloadAllExtensionsInternal();
1414 component_loader_->LoadAll();
1415 extensions::InstalledLoader(this).LoadAllExtensions();
1416 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1417 // times.
1420 void ExtensionService::SetReadyAndNotifyListeners() {
1421 TRACE_EVENT0("browser,startup",
1422 "ExtensionService::SetReadyAndNotifyListeners");
1423 TRACK_SCOPED_REGION(
1424 "Startup", "ExtensionService::SetReadyAndNotifyListeners");
1425 SCOPED_UMA_HISTOGRAM_TIMER(
1426 "Extensions.ExtensionServiceNotifyReadyListenersTime");
1428 ready_->Signal();
1429 content::NotificationService::current()->Notify(
1430 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1431 content::Source<Profile>(profile_),
1432 content::NotificationService::NoDetails());
1435 void ExtensionService::OnLoadedInstalledExtensions() {
1436 if (updater_)
1437 updater_->Start();
1439 OnBlacklistUpdated();
1442 void ExtensionService::AddExtension(const Extension* extension) {
1443 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1444 // default extension state to DISABLED when the --disable-extensions flag
1445 // is set (http://crbug.com/29067).
1446 if (!extensions_enabled() &&
1447 !extension->is_theme() &&
1448 extension->location() != Manifest::COMPONENT &&
1449 !Manifest::IsExternalLocation(extension->location())) {
1450 return;
1453 bool is_extension_upgrade = false;
1454 bool is_extension_installed = false;
1455 const Extension* old = GetInstalledExtension(extension->id());
1456 if (old) {
1457 is_extension_installed = true;
1458 int version_compare_result =
1459 extension->version()->CompareTo(*(old->version()));
1460 is_extension_upgrade = version_compare_result > 0;
1461 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1462 // that we aren't downgrading.
1463 if (!Manifest::IsUnpackedLocation(extension->location()))
1464 CHECK_GE(version_compare_result, 0);
1466 // If the extension was disabled for a reload, then enable it.
1467 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1469 // Set the upgraded bit; we consider reloads upgrades.
1470 system_->runtime_data()->SetBeingUpgraded(extension->id(),
1471 is_extension_upgrade || reloading);
1473 // The extension is now loaded, remove its data from unloaded extension map.
1474 unloaded_extension_paths_.erase(extension->id());
1476 // If a terminated extension is loaded, remove it from the terminated list.
1477 UntrackTerminatedExtension(extension->id());
1479 // Check if the extension's privileges have changed and mark the
1480 // extension disabled if necessary.
1481 CheckPermissionsIncrease(extension, is_extension_installed);
1483 if (is_extension_installed && !reloading) {
1484 // To upgrade an extension in place, unload the old one and then load the
1485 // new one. ReloadExtension disables the extension, which is sufficient.
1486 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1489 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1490 // Only prefs is checked for the blacklist. We rely on callers to check the
1491 // blacklist before calling into here, e.g. CrxInstaller checks before
1492 // installation then threads through the install and pending install flow
1493 // of this class, and we check when loading installed extensions.
1494 registry_->AddBlacklisted(extension);
1495 } else if (block_extensions_ && CanBlockExtension(extension)) {
1496 registry_->AddBlocked(extension);
1497 } else if (!reloading &&
1498 extension_prefs_->IsExtensionDisabled(extension->id())) {
1499 registry_->AddDisabled(extension);
1500 content::NotificationService::current()->Notify(
1501 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1502 content::Source<Profile>(profile_),
1503 content::Details<const Extension>(extension));
1505 // Show the extension disabled error if a permissions increase or a remote
1506 // installation is the reason it was disabled, and no other reasons exist.
1507 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1508 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1509 Extension::DISABLE_REMOTE_INSTALL;
1510 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1511 extensions::AddExtensionDisabledError(
1512 this,
1513 extension,
1514 extension_prefs_->HasDisableReason(
1515 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1517 } else if (reloading) {
1518 // Replace the old extension with the new version.
1519 CHECK(!registry_->AddDisabled(extension));
1520 EnableExtension(extension->id());
1521 } else {
1522 // All apps that are displayed in the launcher are ordered by their ordinals
1523 // so we must ensure they have valid ordinals.
1524 if (extension->RequiresSortOrdinal()) {
1525 extension_prefs_->app_sorting()->SetExtensionVisible(
1526 extension->id(),
1527 extension->ShouldDisplayInNewTabPage() &&
1528 !extension_prefs_->IsEphemeralApp(extension->id()));
1529 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1530 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1531 extension->id(), syncer::StringOrdinal());
1535 registry_->AddEnabled(extension);
1536 NotifyExtensionLoaded(extension);
1538 system_->runtime_data()->SetBeingUpgraded(extension->id(), false);
1541 void ExtensionService::AddComponentExtension(const Extension* extension) {
1542 const std::string old_version_string(
1543 extension_prefs_->GetVersionString(extension->id()));
1544 const Version old_version(old_version_string);
1546 VLOG(1) << "AddComponentExtension " << extension->name();
1547 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1548 VLOG(1) << "Component extension " << extension->name() << " ("
1549 << extension->id() << ") installing/upgrading from '"
1550 << old_version_string << "' to " << extension->version()->GetString();
1552 AddNewOrUpdatedExtension(extension,
1553 Extension::ENABLED,
1554 extensions::kInstallFlagNone,
1555 syncer::StringOrdinal(),
1556 std::string());
1557 return;
1560 AddExtension(extension);
1563 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1564 bool is_extension_installed) {
1565 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1567 // We keep track of all permissions the user has granted each extension.
1568 // This allows extensions to gracefully support backwards compatibility
1569 // by including unknown permissions in their manifests. When the user
1570 // installs the extension, only the recognized permissions are recorded.
1571 // When the unknown permissions become recognized (e.g., through browser
1572 // upgrade), we can prompt the user to accept these new permissions.
1573 // Extensions can also silently upgrade to less permissions, and then
1574 // silently upgrade to a version that adds these permissions back.
1576 // For example, pretend that Chrome 10 includes a permission "omnibox"
1577 // for an API that adds suggestions to the omnibox. An extension can
1578 // maintain backwards compatibility while still having "omnibox" in the
1579 // manifest. If a user installs the extension on Chrome 9, the browser
1580 // will record the permissions it recognized, not including "omnibox."
1581 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1582 // will disable the extension and prompt the user to approve the increase
1583 // in privileges. The extension could then release a new version that
1584 // removes the "omnibox" permission. When the user upgrades, Chrome will
1585 // still remember that "omnibox" had been granted, so that if the
1586 // extension once again includes "omnibox" in an upgrade, the extension
1587 // can upgrade without requiring this user's approval.
1588 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1590 // Silently grant all active permissions to default apps and apps installed
1591 // in kiosk mode.
1592 bool auto_grant_permission =
1593 extension->was_installed_by_default() ||
1594 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1595 if (auto_grant_permission)
1596 GrantPermissions(extension);
1598 bool is_privilege_increase = false;
1599 // We only need to compare the granted permissions to the current permissions
1600 // if the extension has not been auto-granted its permissions above and is
1601 // installed internally.
1602 if (extension->location() == Manifest::INTERNAL && !auto_grant_permission) {
1603 // Add all the recognized permissions if the granted permissions list
1604 // hasn't been initialized yet.
1605 scoped_refptr<const PermissionSet> granted_permissions =
1606 extension_prefs_->GetGrantedPermissions(extension->id());
1607 CHECK(granted_permissions.get());
1609 // Here, we check if an extension's privileges have increased in a manner
1610 // that requires the user's approval. This could occur because the browser
1611 // upgraded and recognized additional privileges, or an extension upgrades
1612 // to a version that requires additional privileges.
1613 is_privilege_increase =
1614 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1615 granted_permissions.get(),
1616 extension->permissions_data()->active_permissions().get(),
1617 extension->GetType());
1620 if (is_extension_installed) {
1621 // If the extension was already disabled, suppress any alerts for becoming
1622 // disabled on permissions increase.
1623 bool previously_disabled =
1624 extension_prefs_->IsExtensionDisabled(extension->id());
1625 // Legacy disabled extensions do not have a disable reason. Infer that it
1626 // was likely disabled by the user.
1627 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE)
1628 disable_reasons |= Extension::DISABLE_USER_ACTION;
1630 // Extensions that came to us disabled from sync need a similar inference,
1631 // except based on the new version's permissions.
1632 if (previously_disabled &&
1633 (disable_reasons & Extension::DISABLE_UNKNOWN_FROM_SYNC)) {
1634 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1635 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1636 extension_prefs_->RemoveDisableReason(
1637 extension->id(), Extension::DISABLE_UNKNOWN_FROM_SYNC);
1638 // If there was no privilege increase, it was likely disabled by the user.
1639 if (!is_privilege_increase)
1640 disable_reasons |= Extension::DISABLE_USER_ACTION;
1644 // Extension has changed permissions significantly. Disable it. A
1645 // notification should be sent by the caller. If the extension is already
1646 // disabled because it was installed remotely, don't add another disable
1647 // reason.
1648 if (is_privilege_increase &&
1649 !(disable_reasons & Extension::DISABLE_REMOTE_INSTALL)) {
1650 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1651 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
1652 RecordPermissionMessagesHistogram(extension, "AutoDisable");
1654 #if defined(ENABLE_SUPERVISED_USERS)
1655 // If a custodian-installed extension is disabled for a supervised user due
1656 // to a permissions increase, send a request to the custodian if the
1657 // supervised user themselves can't re-enable the extension.
1658 if (extensions::util::IsExtensionSupervised(extension, profile_) &&
1659 extensions::util::NeedCustodianApprovalForPermissionIncrease()) {
1660 SupervisedUserService* supervised_user_service =
1661 SupervisedUserServiceFactory::GetForProfile(profile_);
1662 supervised_user_service->AddExtensionUpdateRequest(
1663 extension->id(), *extension->version(),
1664 base::Bind(ExtensionUpdateRequestSent, extension->id()));
1666 #endif
1668 if (disable_reasons != Extension::DISABLE_NONE)
1669 extension_prefs_->SetExtensionDisabled(extension->id(), disable_reasons);
1672 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1673 std::set<std::string> extension_ids;
1674 const ExtensionSet& extensions = registry_->enabled_extensions();
1675 for (ExtensionSet::const_iterator iter = extensions.begin();
1676 iter != extensions.end(); ++iter) {
1677 const Extension* extension = iter->get();
1678 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1679 extension_ids.insert(extension->id());
1682 // TODO(kalman): This is broken. ExtensionService is per-profile.
1683 // crash_keys::SetActiveExtensions is per-process. See
1684 // http://crbug.com/355029.
1685 crash_keys::SetActiveExtensions(extension_ids);
1688 void ExtensionService::OnExtensionInstalled(
1689 const Extension* extension,
1690 const syncer::StringOrdinal& page_ordinal,
1691 int install_flags) {
1692 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1694 const std::string& id = extension->id();
1695 int disable_reasons = GetDisableReasonsOnInstalled(extension);
1696 std::string install_parameter;
1697 const extensions::PendingExtensionInfo* pending_extension_info =
1698 pending_extension_manager()->GetById(id);
1699 if (pending_extension_info) {
1700 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1701 pending_extension_manager()->Remove(id);
1703 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1704 << id << " of type " << extension->GetType()
1705 << " and update URL "
1706 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1707 << "; not installing";
1709 // Delete the extension directory since we're not going to
1710 // load it.
1711 if (!GetFileTaskRunner()->PostTask(
1712 FROM_HERE,
1713 base::Bind(&extensions::file_util::DeleteFile,
1714 extension->path(),
1715 true))) {
1716 NOTREACHED();
1718 return;
1721 install_parameter = pending_extension_info->install_parameter();
1722 pending_extension_manager()->Remove(id);
1723 } else {
1724 // We explicitly want to re-enable an uninstalled external
1725 // extension; if we're here, that means the user is manually
1726 // installing the extension.
1727 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1728 disable_reasons = Extension::DISABLE_NONE;
1732 // Unsupported requirements overrides the management policy.
1733 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1734 disable_reasons |= Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1735 } else {
1736 // Requirement is supported now, remove the corresponding disable reason
1737 // instead.
1738 disable_reasons &= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1741 // Check if the extension was disabled because of the minimum version
1742 // requirements from enterprise policy, and satisfies it now.
1743 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1744 ->CheckMinimumVersion(extension, nullptr)) {
1745 // And remove the corresponding disable reason.
1746 disable_reasons &= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY;
1749 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1750 // Installation of a blacklisted extension can happen from sync, policy,
1751 // etc, where to maintain consistency we need to install it, just never
1752 // load it (see AddExtension). Usually it should be the job of callers to
1753 // intercept blacklisted extensions earlier (e.g. CrxInstaller, before even
1754 // showing the install dialogue).
1755 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1756 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1757 extension->location(),
1758 Manifest::NUM_LOCATIONS);
1761 if (!GetInstalledExtension(extension->id())) {
1762 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1763 extension->GetType(), 100);
1764 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1765 extension->location(), Manifest::NUM_LOCATIONS);
1766 RecordPermissionMessagesHistogram(extension, "Install");
1767 } else {
1768 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1769 extension->GetType(), 100);
1770 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1771 extension->location(), Manifest::NUM_LOCATIONS);
1773 // A fully installed app cannot be demoted to an ephemeral app.
1774 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1775 !extension_prefs_->IsEphemeralApp(id)) {
1776 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1780 const Extension::State initial_state =
1781 disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED
1782 : Extension::DISABLED;
1783 if (initial_state == Extension::ENABLED)
1784 extension_prefs_->SetExtensionEnabled(id);
1785 else
1786 extension_prefs_->SetExtensionDisabled(id, disable_reasons);
1788 if (ShouldDelayExtensionUpdate(
1790 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1791 extension_prefs_->SetDelayedInstallInfo(
1792 extension,
1793 initial_state,
1794 install_flags,
1795 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1796 page_ordinal,
1797 install_parameter);
1799 // Transfer ownership of |extension|.
1800 delayed_installs_.Insert(extension);
1802 // Notify observers that app update is available.
1803 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1804 OnAppUpdateAvailable(extension));
1805 return;
1808 extensions::SharedModuleService::ImportStatus status =
1809 shared_module_service_->SatisfyImports(extension);
1810 if (installs_delayed_for_gc_) {
1811 extension_prefs_->SetDelayedInstallInfo(
1812 extension,
1813 initial_state,
1814 install_flags,
1815 extensions::ExtensionPrefs::DELAY_REASON_GC,
1816 page_ordinal,
1817 install_parameter);
1818 delayed_installs_.Insert(extension);
1819 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1820 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1821 extension_prefs_->SetDelayedInstallInfo(
1822 extension,
1823 initial_state,
1824 install_flags,
1825 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1826 page_ordinal,
1827 install_parameter);
1828 delayed_installs_.Insert(extension);
1830 } else {
1831 AddNewOrUpdatedExtension(extension,
1832 initial_state,
1833 install_flags,
1834 page_ordinal,
1835 install_parameter);
1839 void ExtensionService::OnExtensionManagementSettingsChanged() {
1840 error_controller_->ShowErrorIfNeeded();
1842 // Revokes blocked permissions from active_permissions for all extensions.
1843 extensions::ExtensionManagement* settings =
1844 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1845 CHECK(settings);
1846 scoped_ptr<ExtensionSet> all_extensions(
1847 registry_->GenerateInstalledExtensionsSet());
1848 for (const auto& extension : *all_extensions.get()) {
1849 if (!settings->IsPermissionSetAllowed(
1850 extension.get(),
1851 extension->permissions_data()->active_permissions())) {
1852 extensions::PermissionsUpdater(profile()).RemovePermissionsUnsafe(
1853 extension.get(),
1854 settings->GetBlockedPermissions(extension.get()).get());
1858 CheckManagementPolicy();
1861 void ExtensionService::AddNewOrUpdatedExtension(
1862 const Extension* extension,
1863 Extension::State initial_state,
1864 int install_flags,
1865 const syncer::StringOrdinal& page_ordinal,
1866 const std::string& install_parameter) {
1867 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1868 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1869 extension_prefs_->OnExtensionInstalled(
1870 extension, initial_state, page_ordinal, install_flags, install_parameter);
1871 delayed_installs_.Remove(extension->id());
1872 if (InstallVerifier::NeedsVerification(*extension))
1873 InstallVerifier::Get(GetBrowserContext())->VerifyExtension(extension->id());
1875 const Extension* old = GetInstalledExtension(extension->id());
1876 if (extensions::AppDataMigrator::NeedsMigration(old, extension)) {
1877 app_data_migrator_->DoMigrationAndReply(
1878 old, extension,
1879 base::Bind(&ExtensionService::FinishInstallation, AsWeakPtr(),
1880 make_scoped_refptr(extension), was_ephemeral));
1881 return;
1884 FinishInstallation(extension, was_ephemeral);
1887 void ExtensionService::MaybeFinishDelayedInstallation(
1888 const std::string& extension_id) {
1889 // Check if the extension already got installed.
1890 if (!delayed_installs_.Contains(extension_id))
1891 return;
1892 extensions::ExtensionPrefs::DelayReason reason =
1893 extension_prefs_->GetDelayedInstallReason(extension_id);
1895 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1896 // preferences files that will not have set this field but it was previously
1897 // only used for idle updates.
1898 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1899 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1900 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1901 return;
1903 const Extension* extension = delayed_installs_.GetByID(extension_id);
1904 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1905 extensions::SharedModuleService::ImportStatus status =
1906 shared_module_service_->SatisfyImports(extension);
1907 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1908 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1909 delayed_installs_.Remove(extension_id);
1910 // Make sure no version of the extension is actually installed, (i.e.,
1911 // that this delayed install was not an update).
1912 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1913 extension_prefs_->DeleteExtensionPrefs(extension_id);
1915 return;
1919 FinishDelayedInstallation(extension_id);
1922 void ExtensionService::FinishDelayedInstallation(
1923 const std::string& extension_id) {
1924 scoped_refptr<const Extension> extension(
1925 GetPendingExtensionUpdate(extension_id));
1926 CHECK(extension.get());
1927 delayed_installs_.Remove(extension_id);
1929 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1930 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1931 NOTREACHED();
1933 FinishInstallation(extension.get(), was_ephemeral);
1936 void ExtensionService::FinishInstallation(
1937 const Extension* extension, bool was_ephemeral) {
1938 const extensions::Extension* existing_extension =
1939 GetInstalledExtension(extension->id());
1940 bool is_update = false;
1941 std::string old_name;
1942 if (existing_extension) {
1943 is_update = true;
1944 old_name = existing_extension->name();
1946 bool from_ephemeral =
1947 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1948 extensions::InstalledExtensionInfo details(
1949 extension, is_update, from_ephemeral, old_name);
1950 content::NotificationService::current()->Notify(
1951 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1952 content::Source<Profile>(profile_),
1953 content::Details<const extensions::InstalledExtensionInfo>(&details));
1955 registry_->TriggerOnWillBeInstalled(
1956 extension, is_update, from_ephemeral, old_name);
1958 // Unpacked extensions default to allowing file access, but if that has been
1959 // overridden, don't reset the value.
1960 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1961 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1962 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1965 AddExtension(extension);
1967 // Notify observers that need to know when an installation is complete.
1968 registry_->TriggerOnInstalled(extension, is_update);
1970 // Check extensions that may have been delayed only because this shared module
1971 // was not available.
1972 if (SharedModuleInfo::IsSharedModule(extension))
1973 MaybeFinishDelayedInstallations();
1976 void ExtensionService::PromoteEphemeralApp(
1977 const extensions::Extension* extension, bool is_from_sync) {
1978 DCHECK(GetInstalledExtension(extension->id()) &&
1979 extension_prefs_->IsEphemeralApp(extension->id()));
1981 if (extension->RequiresSortOrdinal()) {
1982 extension_prefs_->app_sorting()->SetExtensionVisible(
1983 extension->id(), extension->ShouldDisplayInNewTabPage());
1985 if (!is_from_sync) {
1986 // Reset the sort ordinals of the app to ensure it is added to the default
1987 // position, like newly installed apps would.
1988 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
1991 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1992 extension->id(), syncer::StringOrdinal());
1995 // Remove the ephemeral flags from the preferences.
1996 extension_prefs_->OnEphemeralAppPromoted(extension->id());
1998 // Fire install-related events to allow observers to handle the promotion
1999 // of the ephemeral app.
2000 extensions::InstalledExtensionInfo details(
2001 extension,
2002 true /* is update */,
2003 true /* from ephemeral */,
2004 extension->name() /* old name */);
2005 content::NotificationService::current()->Notify(
2006 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2007 content::Source<Profile>(profile_),
2008 content::Details<const extensions::InstalledExtensionInfo>(&details));
2010 registry_->TriggerOnWillBeInstalled(
2011 extension,
2012 true /* is update */,
2013 true /* from ephemeral */,
2014 extension->name() /* old name */);
2016 if (registry_->enabled_extensions().Contains(extension->id())) {
2017 // If the app is already enabled and loaded, fire the load events to allow
2018 // observers to handle the promotion of the ephemeral app.
2019 content::NotificationService::current()->Notify(
2020 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
2021 content::Source<Profile>(profile_),
2022 content::Details<const Extension>(extension));
2024 registry_->TriggerOnLoaded(extension);
2025 } else {
2026 // Cached ephemeral apps may be updated and disabled due to permissions
2027 // increase. The app can be enabled (as long as no other disable reasons
2028 // exist) as the install was user-acknowledged.
2029 int disable_mask = Extension::DISABLE_NONE;
2030 if (!is_from_sync)
2031 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
2033 int other_disable_reasons =
2034 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
2035 if (!other_disable_reasons) {
2036 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
2037 GrantPermissionsAndEnableExtension(extension);
2038 else
2039 EnableExtension(extension->id());
2043 registry_->TriggerOnInstalled(extension, true);
2045 if (!is_from_sync) {
2046 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(
2047 *extension);
2051 const Extension* ExtensionService::GetPendingExtensionUpdate(
2052 const std::string& id) const {
2053 return delayed_installs_.GetByID(id);
2056 void ExtensionService::RegisterContentSettings(
2057 HostContentSettingsMap* host_content_settings_map) {
2058 TRACE_EVENT0("browser,startup", "ExtensionService::RegisterContentSettings");
2059 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2060 host_content_settings_map->RegisterProvider(
2061 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
2062 scoped_ptr<content_settings::ObservableProvider>(
2063 new content_settings::InternalExtensionProvider(profile_)));
2065 host_content_settings_map->RegisterProvider(
2066 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
2067 scoped_ptr<content_settings::ObservableProvider>(
2068 new content_settings::CustomExtensionProvider(
2069 extensions::ContentSettingsService::Get(
2070 profile_)->content_settings_store(),
2071 profile_->GetOriginalProfile() != profile_)));
2074 void ExtensionService::TrackTerminatedExtension(
2075 const std::string& extension_id) {
2076 extensions_being_terminated_.erase(extension_id);
2078 const Extension* extension = GetInstalledExtension(extension_id);
2079 if (!extension) {
2080 return;
2083 // No need to check for duplicates; inserting a duplicate is a no-op.
2084 registry_->AddTerminated(make_scoped_refptr(extension));
2085 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2088 void ExtensionService::TerminateExtension(const std::string& extension_id) {
2089 TrackTerminatedExtension(extension_id);
2092 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2093 std::string lowercase_id = base::ToLowerASCII(id);
2094 const Extension* extension =
2095 registry_->terminated_extensions().GetByID(lowercase_id);
2096 registry_->RemoveTerminated(lowercase_id);
2097 if (extension) {
2098 content::NotificationService::current()->Notify(
2099 extensions::NOTIFICATION_EXTENSION_REMOVED,
2100 content::Source<Profile>(profile_),
2101 content::Details<const Extension>(extension));
2105 const Extension* ExtensionService::GetInstalledExtension(
2106 const std::string& id) const {
2107 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2110 bool ExtensionService::OnExternalExtensionFileFound(
2111 const std::string& id,
2112 const Version* version,
2113 const base::FilePath& path,
2114 Manifest::Location location,
2115 int creation_flags,
2116 bool mark_acknowledged,
2117 bool install_immediately) {
2118 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2119 CHECK(crx_file::id_util::IdIsValid(id));
2120 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2121 return false;
2123 // Before even bothering to unpack, check and see if we already have this
2124 // version. This is important because these extensions are going to get
2125 // installed on every startup.
2126 const Extension* existing = GetExtensionById(id, true);
2128 if (existing) {
2129 // The default apps will have the location set as INTERNAL. Since older
2130 // default apps are installed as EXTERNAL, we override them. However, if the
2131 // app is already installed as internal, then do the version check.
2132 // TODO(grv) : Remove after Q1-2013.
2133 bool is_default_apps_migration =
2134 (location == Manifest::INTERNAL &&
2135 Manifest::IsExternalLocation(existing->location()));
2137 if (!is_default_apps_migration) {
2138 DCHECK(version);
2140 switch (existing->version()->CompareTo(*version)) {
2141 case -1: // existing version is older, we should upgrade
2142 break;
2143 case 0: // existing version is same, do nothing
2144 return false;
2145 case 1: // existing version is newer, uh-oh
2146 LOG(WARNING) << "Found external version of extension " << id
2147 << "that is older than current version. Current version "
2148 << "is: " << existing->VersionString() << ". New "
2149 << "version is: " << version->GetString()
2150 << ". Keeping current version.";
2151 return false;
2156 // If the extension is already pending, don't start an install.
2157 if (!pending_extension_manager()->AddFromExternalFile(
2158 id, location, *version, creation_flags, mark_acknowledged)) {
2159 return false;
2162 // no client (silent install)
2163 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2164 installer->set_install_source(location);
2165 installer->set_expected_id(id);
2166 installer->set_expected_version(*version,
2167 true /* fail_install_if_unexpected */);
2168 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2169 installer->set_install_immediately(install_immediately);
2170 installer->set_creation_flags(creation_flags);
2171 #if defined(OS_CHROMEOS)
2172 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2173 #else
2174 installer->InstallCrx(path);
2175 #endif
2177 // Depending on the source, a new external extension might not need a user
2178 // notification on installation. For such extensions, mark them acknowledged
2179 // now to suppress the notification.
2180 if (mark_acknowledged)
2181 external_install_manager_->AcknowledgeExternalExtension(id);
2183 return true;
2186 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2187 extensions::ExtensionHost* host) {
2188 OrphanedDevTools::iterator iter =
2189 orphaned_dev_tools_.find(host->extension_id());
2190 if (iter == orphaned_dev_tools_.end())
2191 return;
2193 iter->second->ConnectWebContents(host->host_contents());
2194 orphaned_dev_tools_.erase(iter);
2197 void ExtensionService::Observe(int type,
2198 const content::NotificationSource& source,
2199 const content::NotificationDetails& details) {
2200 switch (type) {
2201 case chrome::NOTIFICATION_APP_TERMINATING:
2202 // Shutdown has started. Don't start any more extension installs.
2203 // (We cannot use ExtensionService::Shutdown() for this because it
2204 // happens too late in browser teardown.)
2205 browser_terminating_ = true;
2206 break;
2207 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2208 if (profile_ !=
2209 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2210 break;
2213 extensions::ExtensionHost* host =
2214 content::Details<extensions::ExtensionHost>(details).ptr();
2216 // If the extension is already being terminated, there is nothing left to
2217 // do.
2218 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2219 break;
2221 // Mark the extension as terminated and Unload it. We want it to
2222 // be in a consistent state: either fully working or not loaded
2223 // at all, but never half-crashed. We do it in a PostTask so
2224 // that other handlers of this notification will still have
2225 // access to the Extension and ExtensionHost.
2226 base::ThreadTaskRunnerHandle::Get()->PostTask(
2227 FROM_HERE, base::Bind(&ExtensionService::TrackTerminatedExtension,
2228 AsWeakPtr(), host->extension()->id()));
2229 break;
2231 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2232 content::RenderProcessHost* process =
2233 content::Source<content::RenderProcessHost>(source).ptr();
2234 Profile* host_profile =
2235 Profile::FromBrowserContext(process->GetBrowserContext());
2236 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2237 break;
2239 extensions::ProcessMap* process_map =
2240 extensions::ProcessMap::Get(profile_);
2241 if (process_map->Contains(process->GetID())) {
2242 // An extension process was terminated, this might have resulted in an
2243 // app or extension becoming idle.
2244 std::set<std::string> extension_ids =
2245 process_map->GetExtensionsInProcess(process->GetID());
2246 // In addition to the extensions listed in the process map, one of those
2247 // extensions could be referencing a shared module which is waiting for
2248 // idle to update. Check all imports of these extensions, too.
2249 std::set<std::string> import_ids;
2250 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2251 it != extension_ids.end();
2252 ++it) {
2253 const Extension* extension = GetExtensionById(*it, true);
2254 if (!extension)
2255 continue;
2256 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2257 SharedModuleInfo::GetImports(extension);
2258 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2259 for (import_it = imports.begin(); import_it != imports.end();
2260 import_it++) {
2261 import_ids.insert((*import_it).extension_id);
2264 extension_ids.insert(import_ids.begin(), import_ids.end());
2266 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2267 it != extension_ids.end(); ++it) {
2268 if (delayed_installs_.Contains(*it)) {
2269 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2270 FROM_HERE,
2271 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2272 AsWeakPtr(), *it),
2273 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2278 process_map->RemoveAllFromProcess(process->GetID());
2279 BrowserThread::PostTask(
2280 BrowserThread::IO,
2281 FROM_HERE,
2282 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2283 system_->info_map(),
2284 process->GetID()));
2285 break;
2287 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2288 // Notify observers that chrome update is available.
2289 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2290 OnChromeUpdateAvailable());
2291 break;
2293 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2294 OnProfileDestructionStarted();
2295 break;
2298 default:
2299 NOTREACHED() << "Unexpected notification type.";
2303 int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
2304 Extension::DisableReason disable_reason;
2305 // Extensions disabled by management policy should always be disabled, even
2306 // if it's force-installed.
2307 if (system_->management_policy()->MustRemainDisabled(
2308 extension, &disable_reason, nullptr)) {
2309 // A specified reason is required to disable the extension.
2310 DCHECK(disable_reason != Extension::DISABLE_NONE);
2311 return disable_reason;
2314 // Extensions installed by policy can't be disabled. So even if a previous
2315 // installation disabled the extension, make sure it is now enabled.
2316 if (system_->management_policy()->MustRemainEnabled(extension, nullptr))
2317 return Extension::DISABLE_NONE;
2319 // An already disabled extension should inherit the disable reasons and
2320 // remain disabled.
2321 if (extension_prefs_->IsExtensionDisabled(extension->id())) {
2322 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2323 // If an extension was disabled without specified reason, presume it's
2324 // disabled by user.
2325 return disable_reasons == Extension::DISABLE_NONE
2326 ? Extension::DISABLE_USER_ACTION
2327 : disable_reasons;
2330 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2331 // External extensions are initially disabled. We prompt the user before
2332 // enabling them. Hosted apps are excepted because they are not dangerous
2333 // (they need to be launched by the user anyway).
2334 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2335 Manifest::IsExternalLocation(extension->location()) &&
2336 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2337 return Extension::DISABLE_EXTERNAL_EXTENSION;
2341 return Extension::DISABLE_NONE;
2344 // Helper method to determine if an extension can be blocked.
2345 bool ExtensionService::CanBlockExtension(const Extension* extension) const {
2346 DCHECK(extension);
2347 return extension->location() != Manifest::COMPONENT &&
2348 extension->location() != Manifest::EXTERNAL_COMPONENT &&
2349 !system_->management_policy()->MustRemainEnabled(extension, NULL);
2352 bool ExtensionService::ShouldDelayExtensionUpdate(
2353 const std::string& extension_id,
2354 bool install_immediately) const {
2355 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2357 // If delayed updates are globally disabled, or just for this extension,
2358 // don't delay.
2359 if (!install_updates_when_idle_ || install_immediately)
2360 return false;
2362 const Extension* old = GetInstalledExtension(extension_id);
2363 // If there is no old extension, this is not an update, so don't delay.
2364 if (!old)
2365 return false;
2367 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2368 // Delay installation if the extension listens for the onUpdateAvailable
2369 // event.
2370 return extensions::EventRouter::Get(profile_)
2371 ->ExtensionHasEventListener(extension_id, kOnUpdateAvailableEvent);
2372 } else {
2373 // Delay installation if the extension is not idle.
2374 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2378 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2379 DCHECK(!installs_delayed_for_gc_);
2380 installs_delayed_for_gc_ = true;
2383 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2384 DCHECK(installs_delayed_for_gc_);
2385 installs_delayed_for_gc_ = false;
2386 MaybeFinishDelayedInstallations();
2389 void ExtensionService::MaybeFinishDelayedInstallations() {
2390 std::vector<std::string> to_be_installed;
2391 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2392 it != delayed_installs_.end();
2393 ++it) {
2394 to_be_installed.push_back((*it)->id());
2396 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2397 it != to_be_installed.end();
2398 ++it) {
2399 MaybeFinishDelayedInstallation(*it);
2403 void ExtensionService::OnBlacklistUpdated() {
2404 blacklist_->GetBlacklistedIDs(
2405 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2406 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2409 void ExtensionService::ManageBlacklist(
2410 const extensions::Blacklist::BlacklistStateMap& state_map) {
2411 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2413 std::set<std::string> blacklisted;
2414 ExtensionIdSet greylist;
2415 ExtensionIdSet unchanged;
2416 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2417 state_map.begin();
2418 it != state_map.end();
2419 ++it) {
2420 switch (it->second) {
2421 case extensions::NOT_BLACKLISTED:
2422 break;
2424 case extensions::BLACKLISTED_MALWARE:
2425 blacklisted.insert(it->first);
2426 break;
2428 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2429 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2430 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2431 greylist.insert(it->first);
2432 break;
2434 case extensions::BLACKLISTED_UNKNOWN:
2435 unchanged.insert(it->first);
2436 break;
2440 UpdateBlacklistedExtensions(blacklisted, unchanged);
2441 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2443 error_controller_->ShowErrorIfNeeded();
2446 namespace {
2447 void Partition(const ExtensionIdSet& before,
2448 const ExtensionIdSet& after,
2449 const ExtensionIdSet& unchanged,
2450 ExtensionIdSet* no_longer,
2451 ExtensionIdSet* not_yet) {
2452 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2453 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2454 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2456 } // namespace
2458 void ExtensionService::UpdateBlacklistedExtensions(
2459 const ExtensionIdSet& blacklisted,
2460 const ExtensionIdSet& unchanged) {
2461 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2462 Partition(registry_->blacklisted_extensions().GetIDs(), blacklisted,
2463 unchanged, &no_longer_blocked, &not_yet_blocked);
2465 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2466 it != no_longer_blocked.end(); ++it) {
2467 scoped_refptr<const Extension> extension =
2468 registry_->blacklisted_extensions().GetByID(*it);
2469 if (!extension.get()) {
2470 NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
2471 << "but it was never blacklisted.";
2472 continue;
2474 registry_->RemoveBlacklisted(*it);
2475 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2476 AddExtension(extension.get());
2477 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2478 extension->location(),
2479 Manifest::NUM_LOCATIONS);
2482 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2483 it != not_yet_blocked.end(); ++it) {
2484 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2485 if (!extension.get()) {
2486 NOTREACHED() << "Extension " << *it << " needs to be "
2487 << "blacklisted, but it's not installed.";
2488 continue;
2490 registry_->AddBlacklisted(extension);
2491 extension_prefs_->SetExtensionBlacklistState(
2492 extension->id(), extensions::BLACKLISTED_MALWARE);
2493 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2494 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2495 extension->location(), Manifest::NUM_LOCATIONS);
2499 // TODO(oleg): UMA logging
2500 void ExtensionService::UpdateGreylistedExtensions(
2501 const ExtensionIdSet& greylist,
2502 const ExtensionIdSet& unchanged,
2503 const extensions::Blacklist::BlacklistStateMap& state_map) {
2504 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2505 Partition(greylist_.GetIDs(),
2506 greylist, unchanged,
2507 &no_longer_greylisted, &not_yet_greylisted);
2509 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2510 it != no_longer_greylisted.end(); ++it) {
2511 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2512 if (!extension.get()) {
2513 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2514 << "but it was not marked as greylisted.";
2515 continue;
2518 greylist_.Remove(*it);
2519 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2520 extensions::NOT_BLACKLISTED);
2521 if (extension_prefs_->GetDisableReasons(extension->id()) &
2522 extensions::Extension::DISABLE_GREYLIST)
2523 EnableExtension(*it);
2526 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2527 it != not_yet_greylisted.end(); ++it) {
2528 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2529 if (!extension.get()) {
2530 NOTREACHED() << "Extension " << *it << " needs to be "
2531 << "disabled, but it's not installed.";
2532 continue;
2534 greylist_.Insert(extension);
2535 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2536 state_map.find(*it)->second);
2537 if (registry_->enabled_extensions().Contains(extension->id()))
2538 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2542 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2543 update_observers_.AddObserver(observer);
2546 void ExtensionService::RemoveUpdateObserver(
2547 extensions::UpdateObserver* observer) {
2548 update_observers_.RemoveObserver(observer);
2551 // Used only by test code.
2552 void ExtensionService::UnloadAllExtensionsInternal() {
2553 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2555 registry_->ClearAll();
2556 system_->runtime_data()->ClearAll();
2558 // TODO(erikkay) should there be a notification for this? We can't use
2559 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2560 // or uninstalled.
2563 void ExtensionService::OnProfileDestructionStarted() {
2564 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2565 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2566 it != ids_to_unload.end();
2567 ++it) {
2568 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);