1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/extension_service.h"
11 #include "base/command_line.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "base/time/time.h"
19 #include "base/trace_event/trace_event.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/content_settings/content_settings_internal_extension_provider.h"
23 #include "chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h"
24 #include "chrome/browser/extensions/api/content_settings/content_settings_service.h"
25 #include "chrome/browser/extensions/app_data_migrator.h"
26 #include "chrome/browser/extensions/component_loader.h"
27 #include "chrome/browser/extensions/crx_installer.h"
28 #include "chrome/browser/extensions/data_deleter.h"
29 #include "chrome/browser/extensions/extension_action_storage_manager.h"
30 #include "chrome/browser/extensions/extension_assets_manager.h"
31 #include "chrome/browser/extensions/extension_disabled_ui.h"
32 #include "chrome/browser/extensions/extension_error_controller.h"
33 #include "chrome/browser/extensions/extension_special_storage_policy.h"
34 #include "chrome/browser/extensions/extension_sync_service.h"
35 #include "chrome/browser/extensions/extension_util.h"
36 #include "chrome/browser/extensions/external_install_manager.h"
37 #include "chrome/browser/extensions/external_provider_impl.h"
38 #include "chrome/browser/extensions/install_verifier.h"
39 #include "chrome/browser/extensions/installed_loader.h"
40 #include "chrome/browser/extensions/pending_extension_manager.h"
41 #include "chrome/browser/extensions/permissions_updater.h"
42 #include "chrome/browser/extensions/shared_module_service.h"
43 #include "chrome/browser/extensions/unpacked_installer.h"
44 #include "chrome/browser/extensions/updater/chrome_extension_downloader_factory.h"
45 #include "chrome/browser/extensions/updater/extension_updater.h"
46 #include "chrome/browser/google/google_brand.h"
47 #include "chrome/browser/profiles/profile.h"
48 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
49 #include "chrome/browser/ui/webui/favicon_source.h"
50 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
51 #include "chrome/browser/ui/webui/theme_source.h"
52 #include "chrome/common/chrome_switches.h"
53 #include "chrome/common/crash_keys.h"
54 #include "chrome/common/extensions/extension_constants.h"
55 #include "chrome/common/extensions/features/feature_channel.h"
56 #include "chrome/common/url_constants.h"
57 #include "components/content_settings/core/browser/host_content_settings_map.h"
58 #include "components/crx_file/id_util.h"
59 #include "components/startup_metric_utils/startup_metric_utils.h"
60 #include "content/public/browser/devtools_agent_host.h"
61 #include "content/public/browser/notification_service.h"
62 #include "content/public/browser/render_process_host.h"
63 #include "content/public/browser/storage_partition.h"
64 #include "extensions/browser/event_router.h"
65 #include "extensions/browser/extension_host.h"
66 #include "extensions/browser/extension_prefs.h"
67 #include "extensions/browser/extension_registry.h"
68 #include "extensions/browser/extension_system.h"
69 #include "extensions/browser/extensions_browser_client.h"
70 #include "extensions/browser/install_flag.h"
71 #include "extensions/browser/runtime_data.h"
72 #include "extensions/browser/uninstall_reason.h"
73 #include "extensions/browser/update_observer.h"
74 #include "extensions/browser/updater/extension_cache.h"
75 #include "extensions/browser/updater/extension_downloader.h"
76 #include "extensions/common/extension_messages.h"
77 #include "extensions/common/extension_urls.h"
78 #include "extensions/common/feature_switch.h"
79 #include "extensions/common/file_util.h"
80 #include "extensions/common/manifest_constants.h"
81 #include "extensions/common/manifest_handlers/background_info.h"
82 #include "extensions/common/manifest_url_handlers.h"
83 #include "extensions/common/one_shot_event.h"
84 #include "extensions/common/permissions/permission_message_provider.h"
85 #include "extensions/common/permissions/permissions_data.h"
87 #if defined(ENABLE_SUPERVISED_USERS)
88 #include "chrome/browser/supervised_user/supervised_user_service.h"
89 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
92 #if defined(OS_CHROMEOS)
93 #include "chrome/browser/chromeos/extensions/install_limiter.h"
94 #include "storage/browser/fileapi/file_system_backend.h"
95 #include "storage/browser/fileapi/file_system_context.h"
98 using content::BrowserContext
;
99 using content::BrowserThread
;
100 using content::DevToolsAgentHost
;
101 using extensions::CrxInstaller
;
102 using extensions::Extension
;
103 using extensions::ExtensionIdSet
;
104 using extensions::ExtensionInfo
;
105 using extensions::ExtensionRegistry
;
106 using extensions::ExtensionSet
;
107 using extensions::FeatureSwitch
;
108 using extensions::InstallVerifier
;
109 using extensions::ManagementPolicy
;
110 using extensions::Manifest
;
111 using extensions::PermissionMessage
;
112 using extensions::PermissionMessageIDs
;
113 using extensions::PermissionSet
;
114 using extensions::SharedModuleInfo
;
115 using extensions::SharedModuleService
;
116 using extensions::UnloadedExtensionInfo
;
120 // Wait this many seconds after an extensions becomes idle before updating it.
121 const int kUpdateIdleDelay
= 5;
123 #if defined(ENABLE_SUPERVISED_USERS)
124 // Callback for SupervisedUserService::AddExtensionUpdateRequest.
125 void ExtensionUpdateRequestSent(const std::string
& id
, bool success
) {
126 LOG_IF(WARNING
, !success
) << "Failed sending update request for " << id
;
134 void ExtensionService::CheckExternalUninstall(const std::string
& id
) {
135 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
137 // Check if the providers know about this extension.
138 extensions::ProviderCollection::const_iterator i
;
139 for (i
= external_extension_providers_
.begin();
140 i
!= external_extension_providers_
.end(); ++i
) {
141 DCHECK(i
->get()->IsReady());
142 if (i
->get()->HasExtension(id
))
143 return; // Yup, known extension, don't uninstall.
146 // We get the list of external extensions to check from preferences.
147 // It is possible that an extension has preferences but is not loaded.
148 // For example, an extension that requires experimental permissions
149 // will not be loaded if the experimental command line flag is not used.
150 // In this case, do not uninstall.
151 if (!GetInstalledExtension(id
)) {
152 // We can't call UninstallExtension with an unloaded/invalid
154 LOG(WARNING
) << "Attempted uninstallation of unloaded/invalid extension "
155 << "with id: " << id
;
158 UninstallExtension(id
,
159 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION
,
160 base::Bind(&base::DoNothing
),
164 void ExtensionService::SetFileTaskRunnerForTesting(
165 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
) {
166 file_task_runner_
= task_runner
;
169 void ExtensionService::ClearProvidersForTesting() {
170 external_extension_providers_
.clear();
173 void ExtensionService::AddProviderForTesting(
174 extensions::ExternalProviderInterface
* test_provider
) {
175 CHECK(test_provider
);
176 external_extension_providers_
.push_back(
177 linked_ptr
<extensions::ExternalProviderInterface
>(test_provider
));
180 void ExtensionService::BlacklistExtensionForTest(
181 const std::string
& extension_id
) {
182 ExtensionIdSet blacklisted
;
183 ExtensionIdSet unchanged
;
184 blacklisted
.insert(extension_id
);
185 UpdateBlacklistedExtensions(blacklisted
, unchanged
);
188 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
189 const std::string
& id
,
190 const std::string
& install_parameter
,
191 const GURL
& update_url
,
192 Manifest::Location location
,
194 bool mark_acknowledged
) {
195 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
196 CHECK(crx_file::id_util::IdIsValid(id
));
198 if (Manifest::IsExternalLocation(location
)) {
199 // All extensions that are not user specific can be cached.
200 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
204 const Extension
* extension
= GetExtensionById(id
, true);
206 // Already installed. Skip this install if the current location has
207 // higher priority than |location|.
208 Manifest::Location current
= extension
->location();
209 if (current
== Manifest::GetHigherPriorityLocation(current
, location
))
211 // Otherwise, overwrite the current installation.
214 // Add |id| to the set of pending extensions. If it can not be added,
215 // then there is already a pending record from a higher-priority install
216 // source. In this case, signal that this extension will not be
217 // installed by returning false.
218 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
224 mark_acknowledged
)) {
228 update_once_all_providers_are_ready_
= true;
233 // This function is used to uninstall an extension via sync. The LOG statements
234 // within this function are used to inform the user if the uninstall cannot be
236 bool ExtensionService::UninstallExtensionHelper(
237 ExtensionService
* extensions_service
,
238 const std::string
& extension_id
,
239 extensions::UninstallReason reason
) {
240 // We can't call UninstallExtension with an invalid extension ID.
241 if (!extensions_service
->GetInstalledExtension(extension_id
)) {
242 LOG(WARNING
) << "Attempted uninstallation of non-existent extension with "
243 << "id: " << extension_id
;
247 // The following call to UninstallExtension will not allow an uninstall of a
248 // policy-controlled extension.
249 base::string16 error
;
250 if (!extensions_service
->UninstallExtension(
251 extension_id
, reason
, base::Bind(&base::DoNothing
), &error
)) {
252 LOG(WARNING
) << "Cannot uninstall extension with id " << extension_id
260 ExtensionService::ExtensionService(Profile
* profile
,
261 const base::CommandLine
* command_line
,
262 const base::FilePath
& install_directory
,
263 extensions::ExtensionPrefs
* extension_prefs
,
264 extensions::Blacklist
* blacklist
,
265 bool autoupdate_enabled
,
266 bool extensions_enabled
,
267 extensions::OneShotEvent
* ready
)
268 : extensions::Blacklist::Observer(blacklist
),
270 system_(extensions::ExtensionSystem::Get(profile
)),
271 extension_prefs_(extension_prefs
),
272 blacklist_(blacklist
),
273 extension_sync_service_(NULL
),
274 registry_(extensions::ExtensionRegistry::Get(profile
)),
275 pending_extension_manager_(profile
),
276 install_directory_(install_directory
),
277 extensions_enabled_(extensions_enabled
),
278 show_extensions_prompts_(true),
279 install_updates_when_idle_(true),
281 update_once_all_providers_are_ready_(false),
282 browser_terminating_(false),
283 installs_delayed_for_gc_(false),
284 is_first_run_(false),
285 block_extensions_(false),
286 shared_module_service_(new extensions::SharedModuleService(profile_
)),
287 app_data_migrator_(new extensions::AppDataMigrator(profile_
, registry_
)) {
288 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
289 TRACE_EVENT0("browser,startup", "ExtensionService::ExtensionService::ctor");
291 // Figure out if extension installation should be enabled.
292 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
293 *command_line
, profile
))
294 extensions_enabled_
= false;
296 registrar_
.Add(this, chrome::NOTIFICATION_APP_TERMINATING
,
297 content::NotificationService::AllBrowserContextsAndSources());
299 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
300 content::NotificationService::AllBrowserContextsAndSources());
301 registrar_
.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED
,
302 content::NotificationService::AllBrowserContextsAndSources());
303 registrar_
.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED
,
304 content::NotificationService::AllBrowserContextsAndSources());
306 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED
,
307 content::Source
<Profile
>(profile_
));
309 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_
)
312 // Set up the ExtensionUpdater.
313 if (autoupdate_enabled
) {
314 int update_frequency
= extensions::kDefaultUpdateFrequencySeconds
;
315 if (command_line
->HasSwitch(switches::kExtensionsUpdateFrequency
)) {
316 base::StringToInt(command_line
->GetSwitchValueASCII(
317 switches::kExtensionsUpdateFrequency
),
320 updater_
.reset(new extensions::ExtensionUpdater(
326 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
327 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile
,
331 component_loader_
.reset(
332 new extensions::ComponentLoader(this,
334 g_browser_process
->local_state(),
337 if (extensions_enabled_
) {
338 extensions::ExternalProviderImpl::CreateExternalProviders(
339 this, profile_
, &external_extension_providers_
);
342 // Set this as the ExtensionService for app sorting to ensure it causes syncs
344 is_first_run_
= !extension_prefs_
->SetAlertSystemFirstRun();
346 error_controller_
.reset(
347 new extensions::ExtensionErrorController(profile_
, is_first_run_
));
348 external_install_manager_
.reset(
349 new extensions::ExternalInstallManager(profile_
, is_first_run_
));
351 extension_action_storage_manager_
.reset(
352 new extensions::ExtensionActionStorageManager(profile_
));
354 // How long is the path to the Extensions directory?
355 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
356 install_directory_
.value().length(), 0, 500, 100);
359 extensions::PendingExtensionManager
*
360 ExtensionService::pending_extension_manager() {
361 return &pending_extension_manager_
;
364 ExtensionService::~ExtensionService() {
365 // No need to unload extensions here because they are profile-scoped, and the
366 // profile is in the process of being deleted.
368 extensions::ProviderCollection::const_iterator i
;
369 for (i
= external_extension_providers_
.begin();
370 i
!= external_extension_providers_
.end(); ++i
) {
371 extensions::ExternalProviderInterface
* provider
= i
->get();
372 provider
->ServiceShutdown();
376 void ExtensionService::Shutdown() {
377 extensions::ExtensionManagementFactory::GetInstance()
378 ->GetForBrowserContext(profile())
379 ->RemoveObserver(this);
380 system_
->management_policy()->UnregisterProvider(
381 shared_module_policy_provider_
.get());
384 const Extension
* ExtensionService::GetExtensionById(
385 const std::string
& id
, bool include_disabled
) const {
386 int include_mask
= ExtensionRegistry::ENABLED
;
387 if (include_disabled
) {
388 // Include blacklisted and blocked extensions here because there are
389 // hundreds of callers of this function, and many might assume that this
390 // includes those that have been disabled due to blacklisting or blocking.
391 include_mask
|= ExtensionRegistry::DISABLED
|
392 ExtensionRegistry::BLACKLISTED
| ExtensionRegistry::BLOCKED
;
394 return registry_
->GetExtensionById(id
, include_mask
);
397 void ExtensionService::Init() {
398 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
399 TRACE_EVENT0("browser,startup", "ExtensionService::Init");
400 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.ExtensionServiceInitTime");
402 DCHECK(!is_ready()); // Can't redo init.
403 DCHECK_EQ(registry_
->enabled_extensions().size(), 0u);
405 const base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
406 if (cmd_line
->HasSwitch(switches::kInstallEphemeralAppFromWebstore
)) {
407 // The sole purpose of this launch is to install a new extension from CWS
408 // and immediately terminate: loading already installed extensions is
409 // unnecessary and may interfere with the inline install dialog (e.g. if an
410 // extension listens to onStartup and opens a window).
411 SetReadyAndNotifyListeners();
413 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
414 component_loader_
->LoadAll();
415 extensions::InstalledLoader(this).LoadAllExtensions();
417 EnabledReloadableExtensions();
418 MaybeFinishShutdownDelayed();
419 SetReadyAndNotifyListeners();
421 // TODO(erikkay): this should probably be deferred to a future point
422 // rather than running immediately at startup.
423 CheckForExternalUpdates();
425 LoadGreylistFromPrefs();
429 void ExtensionService::EnabledReloadableExtensions() {
430 TRACE_EVENT0("browser,startup",
431 "ExtensionService::EnabledReloadableExtensions");
433 std::vector
<std::string
> extensions_to_enable
;
434 const ExtensionSet
& disabled_extensions
= registry_
->disabled_extensions();
435 for (ExtensionSet::const_iterator iter
= disabled_extensions
.begin();
436 iter
!= disabled_extensions
.end(); ++iter
) {
437 const Extension
* e
= iter
->get();
438 if (extension_prefs_
->GetDisableReasons(e
->id()) ==
439 Extension::DISABLE_RELOAD
) {
440 extensions_to_enable
.push_back(e
->id());
443 for (const std::string
& extension
: extensions_to_enable
) {
444 EnableExtension(extension
);
448 void ExtensionService::MaybeFinishShutdownDelayed() {
449 TRACE_EVENT0("browser,startup",
450 "ExtensionService::MaybeFinishShutdownDelayed");
452 scoped_ptr
<extensions::ExtensionPrefs::ExtensionsInfo
> delayed_info(
453 extension_prefs_
->GetAllDelayedInstallInfo());
454 for (size_t i
= 0; i
< delayed_info
->size(); ++i
) {
455 ExtensionInfo
* info
= delayed_info
->at(i
).get();
456 scoped_refptr
<const Extension
> extension(NULL
);
457 if (info
->extension_manifest
) {
459 extension
= Extension::Create(
460 info
->extension_path
, info
->extension_location
,
461 *info
->extension_manifest
,
462 extension_prefs_
->GetDelayedInstallCreationFlags(info
->extension_id
),
463 info
->extension_id
, &error
);
465 delayed_installs_
.Insert(extension
);
468 MaybeFinishDelayedInstallations();
469 scoped_ptr
<extensions::ExtensionPrefs::ExtensionsInfo
> delayed_info2(
470 extension_prefs_
->GetAllDelayedInstallInfo());
471 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
472 delayed_info2
->size() - delayed_info
->size());
475 void ExtensionService::LoadGreylistFromPrefs() {
476 TRACE_EVENT0("browser,startup", "ExtensionService::LoadGreylistFromPrefs");
478 scoped_ptr
<ExtensionSet
> all_extensions
=
479 registry_
->GenerateInstalledExtensionsSet();
481 for (ExtensionSet::const_iterator it
= all_extensions
->begin();
482 it
!= all_extensions
->end(); ++it
) {
483 extensions::BlacklistState state
=
484 extension_prefs_
->GetExtensionBlacklistState((*it
)->id());
485 if (state
== extensions::BLACKLISTED_SECURITY_VULNERABILITY
||
486 state
== extensions::BLACKLISTED_POTENTIALLY_UNWANTED
||
487 state
== extensions::BLACKLISTED_CWS_POLICY_VIOLATION
)
488 greylist_
.Insert(*it
);
492 bool ExtensionService::UpdateExtension(const extensions::CRXFileInfo
& file
,
493 bool file_ownership_passed
,
494 CrxInstaller
** out_crx_installer
) {
495 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
496 if (browser_terminating_
) {
497 LOG(WARNING
) << "Skipping UpdateExtension due to browser shutdown";
498 // Leak the temp file at extension_path. We don't want to add to the disk
499 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
500 // the file is in the OS temp directory which should be cleaned up for us.
504 const std::string
& id
= file
.extension_id
;
506 const extensions::PendingExtensionInfo
* pending_extension_info
=
507 pending_extension_manager()->GetById(id
);
509 const Extension
* extension
= GetInstalledExtension(id
);
510 if (!pending_extension_info
&& !extension
) {
511 LOG(WARNING
) << "Will not update extension " << id
512 << " because it is not installed or pending";
513 // Delete extension_path since we're not creating a CrxInstaller
514 // that would do it for us.
515 if (!GetFileTaskRunner()->PostTask(
517 base::Bind(&extensions::file_util::DeleteFile
, file
.path
, false)))
523 scoped_refptr
<CrxInstaller
> installer(
524 CrxInstaller::Create(this, scoped_ptr
<ExtensionInstallPrompt
>()));
525 installer
->set_expected_id(id
);
526 installer
->set_expected_hash(file
.expected_hash
);
527 int creation_flags
= Extension::NO_FLAGS
;
528 if (pending_extension_info
) {
529 installer
->set_install_source(pending_extension_info
->install_source());
530 installer
->set_allow_silent_install(true);
531 if (pending_extension_info
->remote_install())
532 installer
->set_grant_permissions(false);
533 creation_flags
= pending_extension_info
->creation_flags();
534 if (pending_extension_info
->mark_acknowledged())
535 external_install_manager_
->AcknowledgeExternalExtension(id
);
536 } else if (extension
) {
537 installer
->set_install_source(extension
->location());
539 // If the extension was installed from or has migrated to the webstore, or
540 // its auto-update URL is from the webstore, treat it as a webstore install.
541 // Note that we ignore some older extensions with blank auto-update URLs
542 // because we are mostly concerned with restrictions on NaCl extensions,
544 if ((extension
&& extension
->from_webstore()) ||
545 (extension
&& extensions::ManifestURL::UpdatesFromGallery(extension
)) ||
546 (!extension
&& extension_urls::IsWebstoreUpdateUrl(
547 pending_extension_info
->update_url()))) {
548 creation_flags
|= Extension::FROM_WEBSTORE
;
551 // Bookmark apps being updated is kind of a contradiction, but that's because
552 // we mark the default apps as bookmark apps, and they're hosted in the web
553 // store, thus they can get updated. See http://crbug.com/101605 for more
555 if (extension
&& extension
->from_bookmark())
556 creation_flags
|= Extension::FROM_BOOKMARK
;
558 if (extension
&& extension
->was_installed_by_default())
559 creation_flags
|= Extension::WAS_INSTALLED_BY_DEFAULT
;
561 if (extension
&& extension
->was_installed_by_oem())
562 creation_flags
|= Extension::WAS_INSTALLED_BY_OEM
;
564 if (extension
&& extension
->was_installed_by_custodian())
565 creation_flags
|= Extension::WAS_INSTALLED_BY_CUSTODIAN
;
568 installer
->set_is_ephemeral(extension_prefs_
->IsEphemeralApp(id
));
569 installer
->set_do_not_sync(extension_prefs_
->DoNotSync(id
));
572 installer
->set_creation_flags(creation_flags
);
574 installer
->set_delete_source(file_ownership_passed
);
575 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE
);
576 installer
->InstallCrxFile(file
);
578 if (out_crx_installer
)
579 *out_crx_installer
= installer
.get();
584 void ExtensionService::ReloadExtensionImpl(
585 // "transient" because the process of reloading may cause the reference
586 // to become invalid. Instead, use |extension_id|, a copy.
587 const std::string
& transient_extension_id
,
589 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
591 // If the extension is already reloading, don't reload again.
592 if (extension_prefs_
->GetDisableReasons(transient_extension_id
) &
593 Extension::DISABLE_RELOAD
) {
597 // Ignore attempts to reload a blacklisted or blocked extension. Sometimes
598 // this can happen in a convoluted reload sequence triggered by the
599 // termination of a blacklisted or blocked extension and a naive attempt to
600 // reload it. For an example see http://crbug.com/373842.
601 if (registry_
->blacklisted_extensions().Contains(transient_extension_id
) ||
602 registry_
->blocked_extensions().Contains(transient_extension_id
)) {
608 std::string extension_id
= transient_extension_id
;
609 const Extension
* transient_current_extension
=
610 GetExtensionById(extension_id
, false);
612 // Disable the extension if it's loaded. It might not be loaded if it crashed.
613 if (transient_current_extension
) {
614 // If the extension has an inspector open for its background page, detach
615 // the inspector and hang onto a cookie for it, so that we can reattach
617 // TODO(yoz): this is not incognito-safe!
618 extensions::ProcessManager
* manager
=
619 extensions::ProcessManager::Get(profile_
);
620 extensions::ExtensionHost
* host
=
621 manager
->GetBackgroundHostForExtension(extension_id
);
622 if (host
&& DevToolsAgentHost::HasFor(host
->host_contents())) {
623 // Look for an open inspector for the background page.
624 scoped_refptr
<DevToolsAgentHost
> agent_host
=
625 DevToolsAgentHost::GetOrCreateFor(host
->host_contents());
626 agent_host
->DisconnectWebContents();
627 orphaned_dev_tools_
[extension_id
] = agent_host
;
630 path
= transient_current_extension
->path();
631 // BeingUpgraded is set back to false when the extension is added.
632 system_
->runtime_data()->SetBeingUpgraded(transient_current_extension
->id(),
634 DisableExtension(extension_id
, Extension::DISABLE_RELOAD
);
635 reloading_extensions_
.insert(extension_id
);
637 std::map
<std::string
, base::FilePath
>::const_iterator iter
=
638 unloaded_extension_paths_
.find(extension_id
);
639 if (iter
== unloaded_extension_paths_
.end()) {
642 path
= unloaded_extension_paths_
[extension_id
];
645 transient_current_extension
= NULL
;
647 if (delayed_installs_
.Contains(extension_id
)) {
648 FinishDelayedInstallation(extension_id
);
652 // If we're reloading a component extension, use the component extension
653 // loader's reloader.
654 if (component_loader_
->Exists(extension_id
)) {
655 component_loader_
->Reload(extension_id
);
659 // Check the installed extensions to see if what we're reloading was already
661 scoped_ptr
<ExtensionInfo
> installed_extension(
662 extension_prefs_
->GetInstalledExtensionInfo(extension_id
));
663 if (installed_extension
.get() &&
664 installed_extension
->extension_manifest
.get()) {
665 extensions::InstalledLoader(this).Load(*installed_extension
, false);
667 // Otherwise, the extension is unpacked (location LOAD).
668 // We should always be able to remember the extension's path. If it's not in
669 // the map, someone failed to update |unloaded_extension_paths_|.
670 CHECK(!path
.empty());
671 scoped_refptr
<extensions::UnpackedInstaller
> unpacked_installer
=
672 extensions::UnpackedInstaller::Create(this);
673 unpacked_installer
->set_be_noisy_on_failure(be_noisy
);
674 unpacked_installer
->Load(path
);
678 void ExtensionService::ReloadExtension(const std::string
& extension_id
) {
679 ReloadExtensionImpl(extension_id
, true); // be_noisy
682 void ExtensionService::ReloadExtensionWithQuietFailure(
683 const std::string
& extension_id
) {
684 ReloadExtensionImpl(extension_id
, false); // be_noisy
687 bool ExtensionService::UninstallExtension(
688 // "transient" because the process of uninstalling may cause the reference
689 // to become invalid. Instead, use |extenson->id()|.
690 const std::string
& transient_extension_id
,
691 extensions::UninstallReason reason
,
692 const base::Closure
& deletion_done_callback
,
693 base::string16
* error
) {
694 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
696 scoped_refptr
<const Extension
> extension
=
697 GetInstalledExtension(transient_extension_id
);
699 // Callers should not send us nonexistent extensions.
700 CHECK(extension
.get());
702 ManagementPolicy
* by_policy
= system_
->management_policy();
703 // Policy change which triggers an uninstall will always set
704 // |external_uninstall| to true so this is the only way to uninstall
705 // managed extensions.
706 // Shared modules being uninstalled will also set |external_uninstall| to true
707 // so that we can guarantee users don't uninstall a shared module.
708 // (crbug.com/273300)
709 // TODO(rdevlin.cronin): This is probably not right. We should do something
710 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
712 bool external_uninstall
=
713 (reason
== extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT
) ||
714 (reason
== extensions::UNINSTALL_REASON_COMPONENT_REMOVED
) ||
715 (reason
== extensions::UNINSTALL_REASON_REINSTALL
) ||
716 (reason
== extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION
) ||
717 (reason
== extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE
) ||
718 (reason
== extensions::UNINSTALL_REASON_SYNC
&&
719 extension
->was_installed_by_custodian());
720 if (!external_uninstall
&&
721 (!by_policy
->UserMayModifySettings(extension
.get(), error
) ||
722 by_policy
->MustRemainInstalled(extension
.get(), error
))) {
723 content::NotificationService::current()->Notify(
724 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED
,
725 content::Source
<Profile
>(profile_
),
726 content::Details
<const Extension
>(extension
.get()));
730 syncer::SyncChange sync_change
;
731 // Don't sync the uninstall if we're going to reinstall the extension
733 if (extension_sync_service_
&&
734 reason
!= extensions::UNINSTALL_REASON_REINSTALL
) {
735 sync_change
= extension_sync_service_
->PrepareToSyncUninstallExtension(
736 extension
.get(), is_ready());
739 system_
->install_verifier()->Remove(extension
->id());
741 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
742 extension
->GetType(), 100);
743 RecordPermissionMessagesHistogram(extension
.get(),
744 "Extensions.Permissions_Uninstall2");
746 // Unload before doing more cleanup to ensure that nothing is hanging on to
747 // any of these resources.
748 UnloadExtension(extension
->id(), UnloadedExtensionInfo::REASON_UNINSTALL
);
750 // Tell the backend to start deleting installed extensions on the file thread.
751 if (!Manifest::IsUnpackedLocation(extension
->location())) {
752 if (!GetFileTaskRunner()->PostTask(
754 base::Bind(&ExtensionService::UninstallExtensionOnFileThread
,
762 extensions::DataDeleter::StartDeleting(
763 profile_
, extension
.get(), deletion_done_callback
);
765 UntrackTerminatedExtension(extension
->id());
767 // Notify interested parties that we've uninstalled this extension.
768 content::NotificationService::current()->Notify(
769 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
,
770 content::Source
<Profile
>(profile_
),
771 content::Details
<const Extension
>(extension
.get()));
772 ExtensionRegistry::Get(profile_
)
773 ->TriggerOnUninstalled(extension
.get(), reason
);
775 if (sync_change
.IsValid()) {
776 extension_sync_service_
->ProcessSyncUninstallExtension(extension
->id(),
780 delayed_installs_
.Remove(extension
->id());
782 extension_prefs_
->OnExtensionUninstalled(
783 extension
->id(), extension
->location(), external_uninstall
);
785 // Track the uninstallation.
786 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
792 void ExtensionService::UninstallExtensionOnFileThread(
793 const std::string
& id
,
795 const base::FilePath
& install_dir
,
796 const base::FilePath
& extension_path
) {
797 extensions::ExtensionAssetsManager
* assets_manager
=
798 extensions::ExtensionAssetsManager::GetInstance();
799 assets_manager
->UninstallExtension(id
, profile
, install_dir
, extension_path
);
802 bool ExtensionService::IsExtensionEnabled(
803 const std::string
& extension_id
) const {
804 if (registry_
->enabled_extensions().Contains(extension_id
) ||
805 registry_
->terminated_extensions().Contains(extension_id
)) {
809 if (registry_
->disabled_extensions().Contains(extension_id
) ||
810 registry_
->blacklisted_extensions().Contains(extension_id
) ||
811 registry_
->blocked_extensions().Contains(extension_id
)) {
815 // Blocked extensions aren't marked as such in prefs, thus if
816 // |block_extensions_| is true then CanBlockExtension() must be called with an
817 // Extension object. If the |extension_id| is not loaded, assume not enabled.
818 if (block_extensions_
) {
819 const Extension
* extension
= GetInstalledExtension(extension_id
);
820 if (!extension
|| CanBlockExtension(extension
))
824 // If the extension hasn't been loaded yet, check the prefs for it. Assume
825 // enabled unless otherwise noted.
826 return !extension_prefs_
->IsExtensionDisabled(extension_id
) &&
827 !extension_prefs_
->IsExtensionBlacklisted(extension_id
) &&
828 !extension_prefs_
->IsExternalExtensionUninstalled(extension_id
);
831 void ExtensionService::EnableExtension(const std::string
& extension_id
) {
832 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
834 if (IsExtensionEnabled(extension_id
))
836 const Extension
* extension
=
837 registry_
->disabled_extensions().GetByID(extension_id
);
839 ManagementPolicy
* policy
= system_
->management_policy();
840 if (extension
&& policy
->MustRemainDisabled(extension
, NULL
, NULL
)) {
841 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
845 extension_prefs_
->SetExtensionState(extension_id
, Extension::ENABLED
);
846 extension_prefs_
->ClearDisableReasons(extension_id
);
848 // This can happen if sync enables an extension that is not
853 // Move it over to the enabled list.
854 registry_
->AddEnabled(make_scoped_refptr(extension
));
855 registry_
->RemoveDisabled(extension
->id());
857 NotifyExtensionLoaded(extension
);
859 // Notify listeners that the extension was enabled.
860 content::NotificationService::current()->Notify(
861 extensions::NOTIFICATION_EXTENSION_ENABLED
,
862 content::Source
<Profile
>(profile_
),
863 content::Details
<const Extension
>(extension
));
865 if (extension_sync_service_
)
866 extension_sync_service_
->SyncEnableExtension(*extension
);
869 void ExtensionService::DisableExtension(
870 const std::string
& extension_id
,
871 Extension::DisableReason disable_reason
) {
872 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
874 // The extension may have been disabled already. Just add a disable reason.
875 if (!IsExtensionEnabled(extension_id
)) {
876 extension_prefs_
->AddDisableReason(extension_id
, disable_reason
);
880 const Extension
* extension
= GetInstalledExtension(extension_id
);
881 // |extension| can be NULL if sync disables an extension that is not
883 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
884 // can be uninstalled by the browser if the user sets extension-specific
887 disable_reason
!= Extension::DISABLE_RELOAD
&&
888 disable_reason
!= Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
&&
889 !system_
->management_policy()->UserMayModifySettings(extension
, NULL
) &&
890 extension
->location() != Manifest::EXTERNAL_COMPONENT
) {
894 extension_prefs_
->SetExtensionState(extension_id
, Extension::DISABLED
);
895 extension_prefs_
->AddDisableReason(extension_id
, disable_reason
);
898 ExtensionRegistry::EVERYTHING
& ~ExtensionRegistry::DISABLED
;
899 extension
= registry_
->GetExtensionById(extension_id
, include_mask
);
903 // The extension is either enabled or terminated.
904 DCHECK(registry_
->enabled_extensions().Contains(extension
->id()) ||
905 registry_
->terminated_extensions().Contains(extension
->id()));
907 // Move it over to the disabled list. Don't send a second unload notification
908 // for terminated extensions being disabled.
909 registry_
->AddDisabled(make_scoped_refptr(extension
));
910 if (registry_
->enabled_extensions().Contains(extension
->id())) {
911 registry_
->RemoveEnabled(extension
->id());
912 NotifyExtensionUnloaded(extension
, UnloadedExtensionInfo::REASON_DISABLE
);
914 registry_
->RemoveTerminated(extension
->id());
917 if (extension_sync_service_
)
918 extension_sync_service_
->SyncDisableExtension(*extension
);
921 void ExtensionService::DisableUserExtensions(
922 const std::vector
<std::string
>& except_ids
) {
923 extensions::ManagementPolicy
* management_policy
=
924 system_
->management_policy();
925 extensions::ExtensionList to_disable
;
927 const ExtensionSet
& enabled_set
= registry_
->enabled_extensions();
928 for (ExtensionSet::const_iterator extension
= enabled_set
.begin();
929 extension
!= enabled_set
.end(); ++extension
) {
930 if (management_policy
->UserMayModifySettings(extension
->get(), NULL
))
931 to_disable
.push_back(*extension
);
933 const ExtensionSet
& terminated_set
= registry_
->terminated_extensions();
934 for (ExtensionSet::const_iterator extension
= terminated_set
.begin();
935 extension
!= terminated_set
.end(); ++extension
) {
936 if (management_policy
->UserMayModifySettings(extension
->get(), NULL
))
937 to_disable
.push_back(*extension
);
940 for (extensions::ExtensionList::const_iterator extension
= to_disable
.begin();
941 extension
!= to_disable
.end(); ++extension
) {
942 if ((*extension
)->was_installed_by_default() &&
943 extension_urls::IsWebstoreUpdateUrl(
944 extensions::ManifestURL::GetUpdateURL(extension
->get())))
946 const std::string
& id
= (*extension
)->id();
947 if (except_ids
.end() == std::find(except_ids
.begin(), except_ids
.end(), id
))
948 DisableExtension(id
, extensions::Extension::DISABLE_USER_ACTION
);
952 // Extensions that are not locked, components or forced by policy should be
953 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
954 // extensions are now considered both blacklisted and locked.
955 void ExtensionService::BlockAllExtensions() {
956 if (block_extensions_
)
958 block_extensions_
= true;
960 // Blacklisted extensions are already unloaded, need not be blocked.
961 scoped_ptr
<ExtensionSet
> extensions
=
962 registry_
->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED
|
963 ExtensionRegistry::DISABLED
|
964 ExtensionRegistry::TERMINATED
);
966 for (const scoped_refptr
<const Extension
>& extension
: *extensions
) {
967 const std::string
& id
= extension
->id();
969 if (!CanBlockExtension(extension
.get()))
972 registry_
->RemoveEnabled(id
);
973 registry_
->RemoveDisabled(id
);
974 registry_
->RemoveTerminated(id
);
976 registry_
->AddBlocked(extension
.get());
977 UnloadExtension(id
, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL
);
981 // All locked extensions should revert to being either enabled or disabled
983 void ExtensionService::UnblockAllExtensions() {
984 block_extensions_
= false;
985 scoped_ptr
<ExtensionSet
> to_unblock
=
986 registry_
->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED
);
988 for (const scoped_refptr
<const Extension
>& extension
: *to_unblock
) {
989 registry_
->RemoveBlocked(extension
->id());
990 AddExtension(extension
.get());
994 void ExtensionService::GrantPermissionsAndEnableExtension(
995 const Extension
* extension
) {
996 GrantPermissions(extension
);
997 RecordPermissionMessagesHistogram(extension
,
998 "Extensions.Permissions_ReEnable2");
999 extension_prefs_
->SetDidExtensionEscalatePermissions(extension
, false);
1000 EnableExtension(extension
->id());
1003 void ExtensionService::GrantPermissions(const Extension
* extension
) {
1005 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension
);
1009 void ExtensionService::RecordPermissionMessagesHistogram(
1010 const Extension
* extension
, const char* histogram
) {
1011 // Since this is called from multiple sources, and since the histogram macros
1012 // use statics, we need to manually lookup the histogram ourselves.
1013 base::HistogramBase
* counter
= base::LinearHistogram::FactoryGet(
1016 PermissionMessage::kEnumBoundary
,
1017 PermissionMessage::kEnumBoundary
+ 1,
1018 base::HistogramBase::kUmaTargetedHistogramFlag
);
1020 PermissionMessageIDs permissions
=
1021 extension
->permissions_data()->GetLegacyPermissionMessageIDs();
1022 if (permissions
.empty()) {
1023 counter
->Add(PermissionMessage::kNone
);
1025 for (PermissionMessage::ID id
: permissions
)
1030 void ExtensionService::NotifyExtensionLoaded(const Extension
* extension
) {
1031 // The URLRequestContexts need to be first to know that the extension
1032 // was loaded, otherwise a race can arise where a renderer that is created
1033 // for the extension may try to load an extension URL with an extension id
1034 // that the request context doesn't yet know about. The profile is responsible
1035 // for ensuring its URLRequestContexts appropriately discover the loaded
1037 system_
->RegisterExtensionWithRequestContexts(extension
);
1039 // Tell renderers about the new extension, unless it's a theme (renderers
1040 // don't need to know about themes).
1041 if (!extension
->is_theme()) {
1042 for (content::RenderProcessHost::iterator
i(
1043 content::RenderProcessHost::AllHostsIterator());
1044 !i
.IsAtEnd(); i
.Advance()) {
1045 content::RenderProcessHost
* host
= i
.GetCurrentValue();
1046 Profile
* host_profile
=
1047 Profile::FromBrowserContext(host
->GetBrowserContext());
1048 if (host_profile
->GetOriginalProfile() ==
1049 profile_
->GetOriginalProfile()) {
1050 // We don't need to include tab permisisons here, since the extension
1052 std::vector
<ExtensionMsg_Loaded_Params
> loaded_extensions(
1053 1, ExtensionMsg_Loaded_Params(extension
,
1054 false /* no tab permissions */));
1056 new ExtensionMsg_Loaded(loaded_extensions
));
1061 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1064 // NOTE: It is important that this happen after notifying the renderers about
1065 // the new extensions so that if we navigate to an extension URL in
1066 // ExtensionRegistryObserver::OnLoaded or
1067 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1068 // renderer is guaranteed to know about it.
1069 registry_
->TriggerOnLoaded(extension
);
1071 content::NotificationService::current()->Notify(
1072 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
1073 content::Source
<Profile
>(profile_
),
1074 content::Details
<const Extension
>(extension
));
1076 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1077 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1078 profile_
->GetExtensionSpecialStoragePolicy()->
1079 GrantRightsForExtension(extension
, profile_
);
1081 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1082 // work properly multi-profile. Besides which, it should be using
1083 // ExtensionRegistryObserver. See http://crbug.com/355029.
1084 UpdateActiveExtensionsInCrashReporter();
1086 const extensions::PermissionsData
* permissions_data
=
1087 extension
->permissions_data();
1089 // If the extension has permission to load chrome://favicon/ resources we need
1090 // to make sure that the FaviconSource is registered with the
1091 // ChromeURLDataManager.
1092 if (permissions_data
->HasHostPermission(GURL(chrome::kChromeUIFaviconURL
))) {
1093 FaviconSource
* favicon_source
= new FaviconSource(profile_
,
1094 FaviconSource::FAVICON
);
1095 content::URLDataSource::Add(profile_
, favicon_source
);
1098 // Same for chrome://theme/ resources.
1099 if (permissions_data
->HasHostPermission(GURL(chrome::kChromeUIThemeURL
))) {
1100 ThemeSource
* theme_source
= new ThemeSource(profile_
);
1101 content::URLDataSource::Add(profile_
, theme_source
);
1104 // Same for chrome://thumb/ resources.
1105 if (permissions_data
->HasHostPermission(
1106 GURL(chrome::kChromeUIThumbnailURL
))) {
1107 ThumbnailSource
* thumbnail_source
= new ThumbnailSource(profile_
, false);
1108 content::URLDataSource::Add(profile_
, thumbnail_source
);
1112 void ExtensionService::NotifyExtensionUnloaded(
1113 const Extension
* extension
,
1114 UnloadedExtensionInfo::Reason reason
) {
1115 UnloadedExtensionInfo
details(extension
, reason
);
1117 registry_
->TriggerOnUnloaded(extension
, reason
);
1119 content::NotificationService::current()->Notify(
1120 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
1121 content::Source
<Profile
>(profile_
),
1122 content::Details
<UnloadedExtensionInfo
>(&details
));
1124 for (content::RenderProcessHost::iterator
i(
1125 content::RenderProcessHost::AllHostsIterator());
1126 !i
.IsAtEnd(); i
.Advance()) {
1127 content::RenderProcessHost
* host
= i
.GetCurrentValue();
1128 Profile
* host_profile
=
1129 Profile::FromBrowserContext(host
->GetBrowserContext());
1130 if (host_profile
->GetOriginalProfile() == profile_
->GetOriginalProfile())
1131 host
->Send(new ExtensionMsg_Unloaded(extension
->id()));
1134 system_
->UnregisterExtensionWithRequestContexts(extension
->id(), reason
);
1136 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1137 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1138 profile_
->GetExtensionSpecialStoragePolicy()->
1139 RevokeRightsForExtension(extension
);
1141 #if defined(OS_CHROMEOS)
1142 // Revoke external file access for the extension from its file system context.
1143 // It is safe to access the extension's storage partition at this point. The
1144 // storage partition may get destroyed only after the extension gets unloaded.
1146 extensions::util::GetSiteForExtensionId(extension
->id(), profile_
);
1147 storage::FileSystemContext
* filesystem_context
=
1148 BrowserContext::GetStoragePartitionForSite(profile_
, site
)
1149 ->GetFileSystemContext();
1150 if (filesystem_context
&& filesystem_context
->external_backend()) {
1151 filesystem_context
->external_backend()->
1152 RevokeAccessForExtension(extension
->id());
1156 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1157 // work properly multi-profile. Besides which, it should be using
1158 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1159 UpdateActiveExtensionsInCrashReporter();
1162 content::BrowserContext
* ExtensionService::GetBrowserContext() const {
1163 // Implemented in the .cc file to avoid adding a profile.h dependency to
1164 // extension_service.h.
1168 bool ExtensionService::is_ready() {
1169 return ready_
->is_signaled();
1172 base::SequencedTaskRunner
* ExtensionService::GetFileTaskRunner() {
1173 if (file_task_runner_
.get())
1174 return file_task_runner_
.get();
1176 // We should be able to interrupt any part of extension install process during
1177 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1178 // will be ignored/deleted while we will block on started tasks.
1179 std::string
token("ext_install-");
1180 token
.append(profile_
->GetPath().AsUTF8Unsafe());
1181 file_task_runner_
= BrowserThread::GetBlockingPool()->
1182 GetSequencedTaskRunnerWithShutdownBehavior(
1183 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token
),
1184 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN
);
1185 return file_task_runner_
.get();
1188 void ExtensionService::CheckManagementPolicy() {
1189 std::vector
<std::string
> to_unload
;
1190 std::map
<std::string
, Extension::DisableReason
> to_disable
;
1191 std::vector
<std::string
> to_enable
;
1193 // Loop through the extensions list, finding extensions we need to unload or
1195 for (scoped_refptr
<const Extension
> extension
:
1196 registry_
->enabled_extensions()) {
1197 if (!system_
->management_policy()->UserMayLoad(extension
.get(), nullptr))
1198 to_unload
.push_back(extension
->id());
1199 Extension::DisableReason disable_reason
= Extension::DISABLE_NONE
;
1200 if (system_
->management_policy()->MustRemainDisabled(
1201 extension
.get(), &disable_reason
, nullptr))
1202 to_disable
[extension
->id()] = disable_reason
;
1205 extensions::ExtensionManagement
* management
=
1206 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1208 // Loop through the disabled extension list, find extensions to re-enable
1209 // automatically. These extensions are exclusive from the |to_disable| and
1210 // |to_unload| lists constructed above, since disabled_extensions() and
1211 // enabled_extensions() are supposed to be mutually exclusive.
1212 for (scoped_refptr
<const Extension
> extension
:
1213 registry_
->disabled_extensions()) {
1214 // Find all disabled extensions disabled due to minimum version requirement,
1215 // but now satisfying it.
1216 if (management
->CheckMinimumVersion(extension
.get(), nullptr) &&
1217 extension_prefs_
->HasDisableReason(
1218 extension
->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
)) {
1219 // Is DISABLE_UPDATE_REQUIRED_BY_POLICY the *only* reason?
1220 if (extension_prefs_
->GetDisableReasons(extension
->id()) ==
1221 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
) {
1222 // We need to enable those disabled *only* due to minimum version
1224 to_enable
.push_back(extension
->id());
1226 extension_prefs_
->RemoveDisableReason(
1227 extension
->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
);
1231 for (const std::string
& id
: to_unload
)
1232 UnloadExtension(id
, UnloadedExtensionInfo::REASON_DISABLE
);
1234 for (std::map
<std::string
, Extension::DisableReason
>::const_iterator i
=
1235 to_disable
.begin(); i
!= to_disable
.end(); ++i
)
1236 DisableExtension(i
->first
, i
->second
);
1238 // No extension is getting re-enabled here after disabling/unloading
1239 // because to_enable is mutually exclusive to to_disable + to_unload.
1240 for (const std::string
& id
: to_enable
)
1241 EnableExtension(id
);
1243 if (updater_
.get()) {
1244 // Find all extensions disabled due to minimum version requirement from
1245 // policy (including the ones that got disabled just now), and check
1247 extensions::ExtensionUpdater::CheckParams to_recheck
;
1248 for (scoped_refptr
<const Extension
> extension
:
1249 registry_
->disabled_extensions()) {
1250 if (extension_prefs_
->GetDisableReasons(extension
->id()) ==
1251 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
) {
1252 // The minimum version check is the only thing holding this extension
1253 // back, so check if it can be updated to fix that.
1254 to_recheck
.ids
.push_back(extension
->id());
1257 if (!to_recheck
.ids
.empty())
1258 updater_
->CheckNow(to_recheck
);
1262 void ExtensionService::CheckForUpdatesSoon() {
1263 // This can legitimately happen in unit tests.
1264 if (!updater_
.get())
1267 if (AreAllExternalProvidersReady()) {
1268 updater_
->CheckSoon();
1270 // Sync can start updating before all the external providers are ready
1271 // during startup. Start the update as soon as those providers are ready,
1273 update_once_all_providers_are_ready_
= true;
1277 // Some extensions will autoupdate themselves externally from Chrome. These
1278 // are typically part of some larger client application package. To support
1279 // these, the extension will register its location in the preferences file
1280 // (and also, on Windows, in the registry) and this code will periodically
1281 // check that location for a .crx file, which it will then install locally if
1282 // a new version is available.
1283 // Errors are reported through ExtensionErrorReporter. Success is not
1285 void ExtensionService::CheckForExternalUpdates() {
1286 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1287 TRACE_EVENT0("browser,startup", "ExtensionService::CheckForExternalUpdates");
1288 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.CheckForExternalUpdatesTime");
1290 // Note that this installation is intentionally silent (since it didn't
1291 // go through the front-end). Extensions that are registered in this
1292 // way are effectively considered 'pre-bundled', and so implicitly
1293 // trusted. In general, if something has HKLM or filesystem access,
1294 // they could install an extension manually themselves anyway.
1296 // Ask each external extension provider to give us a call back for each
1297 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1298 extensions::ProviderCollection::const_iterator i
;
1299 for (i
= external_extension_providers_
.begin();
1300 i
!= external_extension_providers_
.end(); ++i
) {
1301 extensions::ExternalProviderInterface
* provider
= i
->get();
1302 provider
->VisitRegisteredExtension();
1305 // Do any required work that we would have done after completion of all
1307 if (external_extension_providers_
.empty())
1308 OnAllExternalProvidersReady();
1311 void ExtensionService::OnExternalProviderReady(
1312 const extensions::ExternalProviderInterface
* provider
) {
1313 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1314 CHECK(provider
->IsReady());
1316 // An external provider has finished loading. We only take action
1317 // if all of them are finished. So we check them first.
1318 if (AreAllExternalProvidersReady())
1319 OnAllExternalProvidersReady();
1322 bool ExtensionService::AreAllExternalProvidersReady() const {
1323 extensions::ProviderCollection::const_iterator i
;
1324 for (i
= external_extension_providers_
.begin();
1325 i
!= external_extension_providers_
.end(); ++i
) {
1326 if (!i
->get()->IsReady())
1332 void ExtensionService::OnAllExternalProvidersReady() {
1333 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1334 base::TimeDelta elapsed
= base::Time::Now() - profile_
->GetStartTime();
1335 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed
);
1337 // Install any pending extensions.
1338 if (update_once_all_providers_are_ready_
&& updater()) {
1339 update_once_all_providers_are_ready_
= false;
1340 extensions::ExtensionUpdater::CheckParams params
;
1341 params
.callback
= external_updates_finished_callback_
;
1342 updater()->CheckNow(params
);
1345 // Uninstall all the unclaimed extensions.
1346 scoped_ptr
<extensions::ExtensionPrefs::ExtensionsInfo
> extensions_info(
1347 extension_prefs_
->GetInstalledExtensionsInfo());
1348 for (size_t i
= 0; i
< extensions_info
->size(); ++i
) {
1349 ExtensionInfo
* info
= extensions_info
->at(i
).get();
1350 if (Manifest::IsExternalLocation(info
->extension_location
))
1351 CheckExternalUninstall(info
->extension_id
);
1354 error_controller_
->ShowErrorIfNeeded();
1356 external_install_manager_
->UpdateExternalExtensionAlert();
1359 void ExtensionService::UnloadExtension(
1360 const std::string
& extension_id
,
1361 UnloadedExtensionInfo::Reason reason
) {
1362 // Make sure the extension gets deleted after we return from this function.
1364 ExtensionRegistry::EVERYTHING
& ~ExtensionRegistry::TERMINATED
;
1365 scoped_refptr
<const Extension
> extension(
1366 registry_
->GetExtensionById(extension_id
, include_mask
));
1368 // This method can be called via PostTask, so the extension may have been
1369 // unloaded by the time this runs.
1370 if (!extension
.get()) {
1371 // In case the extension may have crashed/uninstalled. Allow the profile to
1372 // clean up its RequestContexts.
1373 system_
->UnregisterExtensionWithRequestContexts(extension_id
, reason
);
1377 // Keep information about the extension so that we can reload it later
1378 // even if it's not permanently installed.
1379 unloaded_extension_paths_
[extension
->id()] = extension
->path();
1381 // Clean up if the extension is meant to be enabled after a reload.
1382 reloading_extensions_
.erase(extension
->id());
1384 if (registry_
->disabled_extensions().Contains(extension
->id())) {
1385 registry_
->RemoveDisabled(extension
->id());
1386 // Make sure the profile cleans up its RequestContexts when an already
1387 // disabled extension is unloaded (since they are also tracking the disabled
1389 system_
->UnregisterExtensionWithRequestContexts(extension_id
, reason
);
1390 // Don't send the unloaded notification. It was sent when the extension
1393 // Remove the extension from the enabled list.
1394 registry_
->RemoveEnabled(extension
->id());
1395 NotifyExtensionUnloaded(extension
.get(), reason
);
1398 content::NotificationService::current()->Notify(
1399 extensions::NOTIFICATION_EXTENSION_REMOVED
,
1400 content::Source
<Profile
>(profile_
),
1401 content::Details
<const Extension
>(extension
.get()));
1404 void ExtensionService::RemoveComponentExtension(
1405 const std::string
& extension_id
) {
1406 scoped_refptr
<const Extension
> extension(
1407 GetExtensionById(extension_id
, false));
1408 UnloadExtension(extension_id
, UnloadedExtensionInfo::REASON_UNINSTALL
);
1409 if (extension
.get()) {
1410 content::NotificationService::current()->Notify(
1411 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
,
1412 content::Source
<Profile
>(profile_
),
1413 content::Details
<const Extension
>(extension
.get()));
1414 ExtensionRegistry::Get(profile_
)->TriggerOnUninstalled(
1415 extension
.get(), extensions::UNINSTALL_REASON_COMPONENT_REMOVED
);
1419 void ExtensionService::UnloadAllExtensionsForTest() {
1420 UnloadAllExtensionsInternal();
1423 void ExtensionService::ReloadExtensionsForTest() {
1424 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1425 // warning about calling test code in production.
1426 UnloadAllExtensionsInternal();
1427 component_loader_
->LoadAll();
1428 extensions::InstalledLoader(this).LoadAllExtensions();
1429 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1433 void ExtensionService::SetReadyAndNotifyListeners() {
1434 TRACE_EVENT0("browser,startup",
1435 "ExtensionService::SetReadyAndNotifyListeners");
1436 SCOPED_UMA_HISTOGRAM_TIMER(
1437 "Extensions.ExtensionServiceNotifyReadyListenersTime");
1440 content::NotificationService::current()->Notify(
1441 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED
,
1442 content::Source
<Profile
>(profile_
),
1443 content::NotificationService::NoDetails());
1446 void ExtensionService::OnLoadedInstalledExtensions() {
1450 OnBlacklistUpdated();
1453 void ExtensionService::AddExtension(const Extension
* extension
) {
1454 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1455 // default extension state to DISABLED when the --disable-extensions flag
1456 // is set (http://crbug.com/29067).
1457 if (!extensions_enabled() &&
1458 !extension
->is_theme() &&
1459 extension
->location() != Manifest::COMPONENT
&&
1460 !Manifest::IsExternalLocation(extension
->location())) {
1464 bool is_extension_upgrade
= false;
1465 bool is_extension_installed
= false;
1466 const Extension
* old
= GetInstalledExtension(extension
->id());
1468 is_extension_installed
= true;
1469 int version_compare_result
=
1470 extension
->version()->CompareTo(*(old
->version()));
1471 is_extension_upgrade
= version_compare_result
> 0;
1472 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1473 // that we aren't downgrading.
1474 if (!Manifest::IsUnpackedLocation(extension
->location()))
1475 CHECK_GE(version_compare_result
, 0);
1477 // If the extension was disabled for a reload, then enable it.
1478 bool reloading
= reloading_extensions_
.erase(extension
->id()) > 0;
1480 // Set the upgraded bit; we consider reloads upgrades.
1481 system_
->runtime_data()->SetBeingUpgraded(extension
->id(),
1482 is_extension_upgrade
|| reloading
);
1484 // The extension is now loaded, remove its data from unloaded extension map.
1485 unloaded_extension_paths_
.erase(extension
->id());
1487 // If a terminated extension is loaded, remove it from the terminated list.
1488 UntrackTerminatedExtension(extension
->id());
1490 // Check if the extension's privileges have changed and mark the
1491 // extension disabled if necessary.
1492 CheckPermissionsIncrease(extension
, is_extension_installed
);
1494 if (is_extension_installed
&& !reloading
) {
1495 // To upgrade an extension in place, unload the old one and then load the
1496 // new one. ReloadExtension disables the extension, which is sufficient.
1497 UnloadExtension(extension
->id(), UnloadedExtensionInfo::REASON_UPDATE
);
1500 if (extension_prefs_
->IsExtensionBlacklisted(extension
->id())) {
1501 // Only prefs is checked for the blacklist. We rely on callers to check the
1502 // blacklist before calling into here, e.g. CrxInstaller checks before
1503 // installation then threads through the install and pending install flow
1504 // of this class, and we check when loading installed extensions.
1505 registry_
->AddBlacklisted(extension
);
1506 } else if (block_extensions_
&& CanBlockExtension(extension
)) {
1507 registry_
->AddBlocked(extension
);
1508 } else if (!reloading
&&
1509 extension_prefs_
->IsExtensionDisabled(extension
->id())) {
1510 registry_
->AddDisabled(extension
);
1511 if (extension_sync_service_
)
1512 extension_sync_service_
->SyncExtensionChangeIfNeeded(*extension
);
1513 content::NotificationService::current()->Notify(
1514 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED
,
1515 content::Source
<Profile
>(profile_
),
1516 content::Details
<const Extension
>(extension
));
1518 // Show the extension disabled error if a permissions increase or a remote
1519 // installation is the reason it was disabled, and no other reasons exist.
1520 int reasons
= extension_prefs_
->GetDisableReasons(extension
->id());
1521 const int kReasonMask
= Extension::DISABLE_PERMISSIONS_INCREASE
|
1522 Extension::DISABLE_REMOTE_INSTALL
;
1523 if (reasons
& kReasonMask
&& !(reasons
& ~kReasonMask
)) {
1524 extensions::AddExtensionDisabledError(
1527 extension_prefs_
->HasDisableReason(
1528 extension
->id(), Extension::DISABLE_REMOTE_INSTALL
));
1530 } else if (reloading
) {
1531 // Replace the old extension with the new version.
1532 CHECK(!registry_
->AddDisabled(extension
));
1533 EnableExtension(extension
->id());
1535 // All apps that are displayed in the launcher are ordered by their ordinals
1536 // so we must ensure they have valid ordinals.
1537 if (extension
->RequiresSortOrdinal()) {
1538 extension_prefs_
->app_sorting()->SetExtensionVisible(
1540 extension
->ShouldDisplayInNewTabPage() &&
1541 !extension_prefs_
->IsEphemeralApp(extension
->id()));
1542 if (!extension_prefs_
->IsEphemeralApp(extension
->id())) {
1543 extension_prefs_
->app_sorting()->EnsureValidOrdinals(
1544 extension
->id(), syncer::StringOrdinal());
1548 registry_
->AddEnabled(extension
);
1549 if (extension_sync_service_
)
1550 extension_sync_service_
->SyncExtensionChangeIfNeeded(*extension
);
1551 NotifyExtensionLoaded(extension
);
1553 system_
->runtime_data()->SetBeingUpgraded(extension
->id(), false);
1556 void ExtensionService::AddComponentExtension(const Extension
* extension
) {
1557 const std::string
old_version_string(
1558 extension_prefs_
->GetVersionString(extension
->id()));
1559 const Version
old_version(old_version_string
);
1561 VLOG(1) << "AddComponentExtension " << extension
->name();
1562 if (!old_version
.IsValid() || !old_version
.Equals(*extension
->version())) {
1563 VLOG(1) << "Component extension " << extension
->name() << " ("
1564 << extension
->id() << ") installing/upgrading from '"
1565 << old_version_string
<< "' to " << extension
->version()->GetString();
1567 AddNewOrUpdatedExtension(extension
,
1569 extensions::kInstallFlagNone
,
1570 syncer::StringOrdinal(),
1575 AddExtension(extension
);
1578 void ExtensionService::CheckPermissionsIncrease(const Extension
* extension
,
1579 bool is_extension_installed
) {
1580 extensions::PermissionsUpdater(profile_
).InitializePermissions(extension
);
1582 // We keep track of all permissions the user has granted each extension.
1583 // This allows extensions to gracefully support backwards compatibility
1584 // by including unknown permissions in their manifests. When the user
1585 // installs the extension, only the recognized permissions are recorded.
1586 // When the unknown permissions become recognized (e.g., through browser
1587 // upgrade), we can prompt the user to accept these new permissions.
1588 // Extensions can also silently upgrade to less permissions, and then
1589 // silently upgrade to a version that adds these permissions back.
1591 // For example, pretend that Chrome 10 includes a permission "omnibox"
1592 // for an API that adds suggestions to the omnibox. An extension can
1593 // maintain backwards compatibility while still having "omnibox" in the
1594 // manifest. If a user installs the extension on Chrome 9, the browser
1595 // will record the permissions it recognized, not including "omnibox."
1596 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1597 // will disable the extension and prompt the user to approve the increase
1598 // in privileges. The extension could then release a new version that
1599 // removes the "omnibox" permission. When the user upgrades, Chrome will
1600 // still remember that "omnibox" had been granted, so that if the
1601 // extension once again includes "omnibox" in an upgrade, the extension
1602 // can upgrade without requiring this user's approval.
1603 int disable_reasons
= extension_prefs_
->GetDisableReasons(extension
->id());
1605 // Silently grant all active permissions to default apps and apps installed
1607 bool auto_grant_permission
=
1608 extension
->was_installed_by_default() ||
1609 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1610 if (auto_grant_permission
)
1611 GrantPermissions(extension
);
1613 bool is_privilege_increase
= false;
1614 // We only need to compare the granted permissions to the current permissions
1615 // if the extension has not been auto-granted its permissions above and is
1616 // installed internally.
1617 if (extension
->location() == Manifest::INTERNAL
&& !auto_grant_permission
) {
1618 // Add all the recognized permissions if the granted permissions list
1619 // hasn't been initialized yet.
1620 scoped_refptr
<PermissionSet
> granted_permissions
=
1621 extension_prefs_
->GetGrantedPermissions(extension
->id());
1622 CHECK(granted_permissions
.get());
1624 // Here, we check if an extension's privileges have increased in a manner
1625 // that requires the user's approval. This could occur because the browser
1626 // upgraded and recognized additional privileges, or an extension upgrades
1627 // to a version that requires additional privileges.
1628 is_privilege_increase
=
1629 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1630 granted_permissions
.get(),
1631 extension
->permissions_data()->active_permissions().get(),
1632 extension
->GetType());
1635 if (is_extension_installed
) {
1636 // If the extension was already disabled, suppress any alerts for becoming
1637 // disabled on permissions increase.
1638 bool previously_disabled
=
1639 extension_prefs_
->IsExtensionDisabled(extension
->id());
1640 // Legacy disabled extensions do not have a disable reason. Infer that if
1641 // there was no permission increase, it was likely disabled by the user.
1642 if (previously_disabled
&& disable_reasons
== Extension::DISABLE_NONE
&&
1643 !extension_prefs_
->DidExtensionEscalatePermissions(extension
->id())) {
1644 disable_reasons
|= Extension::DISABLE_USER_ACTION
;
1646 // Extensions that came to us disabled from sync need a similar inference,
1647 // except based on the new version's permissions.
1648 if (previously_disabled
&&
1649 disable_reasons
== Extension::DISABLE_UNKNOWN_FROM_SYNC
) {
1650 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1651 extension_prefs_
->ClearDisableReasons(extension
->id());
1652 if (!is_privilege_increase
)
1653 disable_reasons
|= Extension::DISABLE_USER_ACTION
;
1655 disable_reasons
&= ~Extension::DISABLE_UNKNOWN_FROM_SYNC
;
1658 // Extension has changed permissions significantly. Disable it. A
1659 // notification should be sent by the caller. If the extension is already
1660 // disabled because it was installed remotely, don't add another disable
1661 // reason, but instead always set the "did escalate permissions" flag, to
1662 // ensure enabling it will always show a warning.
1663 if (disable_reasons
== Extension::DISABLE_REMOTE_INSTALL
) {
1664 extension_prefs_
->SetDidExtensionEscalatePermissions(extension
, true);
1665 } else if (is_privilege_increase
) {
1666 disable_reasons
|= Extension::DISABLE_PERMISSIONS_INCREASE
;
1667 if (!extension_prefs_
->DidExtensionEscalatePermissions(extension
->id())) {
1668 RecordPermissionMessagesHistogram(extension
,
1669 "Extensions.Permissions_AutoDisable2");
1671 extension_prefs_
->SetExtensionState(extension
->id(), Extension::DISABLED
);
1672 extension_prefs_
->SetDidExtensionEscalatePermissions(extension
, true);
1674 #if defined(ENABLE_SUPERVISED_USERS)
1675 // If a custodian-installed extension is disabled for a supervised user due
1676 // to a permissions increase, send a request to the custodian, since the
1677 // supervised user themselves can't re-enable the extension.
1678 if (extensions::util::IsExtensionSupervised(extension
, profile_
)) {
1679 SupervisedUserService
* supervised_user_service
=
1680 SupervisedUserServiceFactory::GetForProfile(profile_
);
1681 supervised_user_service
->AddExtensionUpdateRequest(
1682 extension
->id(), *extension
->version(),
1683 base::Bind(ExtensionUpdateRequestSent
, extension
->id()));
1687 if (disable_reasons
!= Extension::DISABLE_NONE
) {
1688 extension_prefs_
->AddDisableReason(
1690 static_cast<Extension::DisableReason
>(disable_reasons
));
1694 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1695 std::set
<std::string
> extension_ids
;
1696 const ExtensionSet
& extensions
= registry_
->enabled_extensions();
1697 for (ExtensionSet::const_iterator iter
= extensions
.begin();
1698 iter
!= extensions
.end(); ++iter
) {
1699 const Extension
* extension
= iter
->get();
1700 if (!extension
->is_theme() && extension
->location() != Manifest::COMPONENT
)
1701 extension_ids
.insert(extension
->id());
1704 // TODO(kalman): This is broken. ExtensionService is per-profile.
1705 // crash_keys::SetActiveExtensions is per-process. See
1706 // http://crbug.com/355029.
1707 crash_keys::SetActiveExtensions(extension_ids
);
1710 void ExtensionService::OnExtensionInstalled(
1711 const Extension
* extension
,
1712 const syncer::StringOrdinal
& page_ordinal
,
1713 int install_flags
) {
1714 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1716 const std::string
& id
= extension
->id();
1717 int disable_reasons
= GetDisableReasonsOnInstalled(extension
);
1718 std::string install_parameter
;
1719 const extensions::PendingExtensionInfo
* pending_extension_info
=
1720 pending_extension_manager()->GetById(id
);
1721 if (pending_extension_info
) {
1722 if (!pending_extension_info
->ShouldAllowInstall(extension
)) {
1723 pending_extension_manager()->Remove(id
);
1725 LOG(WARNING
) << "ShouldAllowInstall() returned false for "
1726 << id
<< " of type " << extension
->GetType()
1727 << " and update URL "
1728 << extensions::ManifestURL::GetUpdateURL(extension
).spec()
1729 << "; not installing";
1731 // Delete the extension directory since we're not going to
1733 if (!GetFileTaskRunner()->PostTask(
1735 base::Bind(&extensions::file_util::DeleteFile
,
1743 install_parameter
= pending_extension_info
->install_parameter();
1744 pending_extension_manager()->Remove(id
);
1746 // We explicitly want to re-enable an uninstalled external
1747 // extension; if we're here, that means the user is manually
1748 // installing the extension.
1749 if (extension_prefs_
->IsExternalExtensionUninstalled(id
)) {
1750 disable_reasons
= Extension::DISABLE_NONE
;
1754 // Unsupported requirements overrides the management policy.
1755 if (install_flags
& extensions::kInstallFlagHasRequirementErrors
) {
1756 disable_reasons
|= Extension::DISABLE_UNSUPPORTED_REQUIREMENT
;
1758 // Requirement is supported now, remove the corresponding disable reason
1760 extension_prefs_
->RemoveDisableReason(
1761 id
, Extension::DISABLE_UNSUPPORTED_REQUIREMENT
);
1762 disable_reasons
&= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT
;
1765 // Check if the extension was disabled because of the minimum version
1766 // requirements from enterprise policy, and satisfies it now.
1767 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1768 ->CheckMinimumVersion(extension
, nullptr)) {
1769 // And remove the corresponding disable reason.
1770 extension_prefs_
->RemoveDisableReason(
1771 id
, Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
);
1772 disable_reasons
&= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
;
1775 if (install_flags
& extensions::kInstallFlagIsBlacklistedForMalware
) {
1776 // Installation of a blacklisted extension can happen from sync, policy,
1777 // etc, where to maintain consistency we need to install it, just never
1778 // load it (see AddExtension). Usually it should be the job of callers to
1779 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
1780 // showing the install dialogue).
1781 extension_prefs_
->AcknowledgeBlacklistedExtension(id
);
1782 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1783 extension
->location(),
1784 Manifest::NUM_LOCATIONS
);
1787 if (!GetInstalledExtension(extension
->id())) {
1788 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1789 extension
->GetType(), 100);
1790 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1791 extension
->location(), Manifest::NUM_LOCATIONS
);
1792 RecordPermissionMessagesHistogram(extension
,
1793 "Extensions.Permissions_Install2");
1795 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1796 extension
->GetType(), 100);
1797 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1798 extension
->location(), Manifest::NUM_LOCATIONS
);
1800 // A fully installed app cannot be demoted to an ephemeral app.
1801 if ((install_flags
& extensions::kInstallFlagIsEphemeral
) &&
1802 !extension_prefs_
->IsEphemeralApp(id
)) {
1803 install_flags
&= ~static_cast<int>(extensions::kInstallFlagIsEphemeral
);
1807 if (disable_reasons
)
1808 extension_prefs_
->AddDisableReasons(id
, disable_reasons
);
1810 const Extension::State initial_state
=
1811 disable_reasons
== Extension::DISABLE_NONE
? Extension::ENABLED
1812 : Extension::DISABLED
;
1814 if (ShouldDelayExtensionUpdate(
1816 !!(install_flags
& extensions::kInstallFlagInstallImmediately
))) {
1817 extension_prefs_
->SetDelayedInstallInfo(
1821 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE
,
1825 // Transfer ownership of |extension|.
1826 delayed_installs_
.Insert(extension
);
1828 // Notify observers that app update is available.
1829 FOR_EACH_OBSERVER(extensions::UpdateObserver
, update_observers_
,
1830 OnAppUpdateAvailable(extension
));
1834 extensions::SharedModuleService::ImportStatus status
=
1835 shared_module_service_
->SatisfyImports(extension
);
1836 if (installs_delayed_for_gc_
) {
1837 extension_prefs_
->SetDelayedInstallInfo(
1841 extensions::ExtensionPrefs::DELAY_REASON_GC
,
1844 delayed_installs_
.Insert(extension
);
1845 } else if (status
!= SharedModuleService::IMPORT_STATUS_OK
) {
1846 if (status
== SharedModuleService::IMPORT_STATUS_UNSATISFIED
) {
1847 extension_prefs_
->SetDelayedInstallInfo(
1851 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS
,
1854 delayed_installs_
.Insert(extension
);
1857 AddNewOrUpdatedExtension(extension
,
1865 void ExtensionService::OnExtensionManagementSettingsChanged() {
1866 error_controller_
->ShowErrorIfNeeded();
1868 // Revokes blocked permissions from active_permissions for all extensions.
1869 extensions::ExtensionManagement
* settings
=
1870 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1872 scoped_ptr
<ExtensionSet
> all_extensions(
1873 registry_
->GenerateInstalledExtensionsSet());
1874 for (const auto& extension
: *all_extensions
.get()) {
1875 if (!settings
->IsPermissionSetAllowed(
1877 extension
->permissions_data()->active_permissions())) {
1878 extensions::PermissionsUpdater(profile()).RemovePermissions(
1880 settings
->GetBlockedPermissions(extension
.get()).get());
1884 CheckManagementPolicy();
1887 void ExtensionService::AddNewOrUpdatedExtension(
1888 const Extension
* extension
,
1889 Extension::State initial_state
,
1891 const syncer::StringOrdinal
& page_ordinal
,
1892 const std::string
& install_parameter
) {
1893 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1894 bool was_ephemeral
= extension_prefs_
->IsEphemeralApp(extension
->id());
1895 extension_prefs_
->OnExtensionInstalled(
1896 extension
, initial_state
, page_ordinal
, install_flags
, install_parameter
);
1897 delayed_installs_
.Remove(extension
->id());
1898 if (InstallVerifier::NeedsVerification(*extension
))
1899 system_
->install_verifier()->VerifyExtension(extension
->id());
1901 const Extension
* old
= GetInstalledExtension(extension
->id());
1902 if (extensions::AppDataMigrator::NeedsMigration(old
, extension
)) {
1903 app_data_migrator_
->DoMigrationAndReply(
1905 base::Bind(&ExtensionService::FinishInstallation
, AsWeakPtr(),
1906 make_scoped_refptr(extension
), was_ephemeral
));
1910 FinishInstallation(extension
, was_ephemeral
);
1913 void ExtensionService::MaybeFinishDelayedInstallation(
1914 const std::string
& extension_id
) {
1915 // Check if the extension already got installed.
1916 if (!delayed_installs_
.Contains(extension_id
))
1918 extensions::ExtensionPrefs::DelayReason reason
=
1919 extension_prefs_
->GetDelayedInstallReason(extension_id
);
1921 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1922 // preferences files that will not have set this field but it was previously
1923 // only used for idle updates.
1924 if ((reason
== extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE
||
1925 reason
== extensions::ExtensionPrefs::DELAY_REASON_NONE
) &&
1926 is_ready() && !extensions::util::IsExtensionIdle(extension_id
, profile_
))
1929 const Extension
* extension
= delayed_installs_
.GetByID(extension_id
);
1930 if (reason
== extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS
) {
1931 extensions::SharedModuleService::ImportStatus status
=
1932 shared_module_service_
->SatisfyImports(extension
);
1933 if (status
!= SharedModuleService::IMPORT_STATUS_OK
) {
1934 if (status
== SharedModuleService::IMPORT_STATUS_UNRECOVERABLE
) {
1935 delayed_installs_
.Remove(extension_id
);
1936 // Make sure no version of the extension is actually installed, (i.e.,
1937 // that this delayed install was not an update).
1938 CHECK(!extension_prefs_
->GetInstalledExtensionInfo(extension_id
).get());
1939 extension_prefs_
->DeleteExtensionPrefs(extension_id
);
1945 FinishDelayedInstallation(extension_id
);
1948 void ExtensionService::FinishDelayedInstallation(
1949 const std::string
& extension_id
) {
1950 scoped_refptr
<const Extension
> extension(
1951 GetPendingExtensionUpdate(extension_id
));
1952 CHECK(extension
.get());
1953 delayed_installs_
.Remove(extension_id
);
1955 bool was_ephemeral
= extension_prefs_
->IsEphemeralApp(extension
->id());
1956 if (!extension_prefs_
->FinishDelayedInstallInfo(extension_id
))
1959 FinishInstallation(extension
.get(), was_ephemeral
);
1962 void ExtensionService::FinishInstallation(
1963 const Extension
* extension
, bool was_ephemeral
) {
1964 const extensions::Extension
* existing_extension
=
1965 GetInstalledExtension(extension
->id());
1966 bool is_update
= false;
1967 std::string old_name
;
1968 if (existing_extension
) {
1970 old_name
= existing_extension
->name();
1972 bool from_ephemeral
=
1973 was_ephemeral
&& !extension_prefs_
->IsEphemeralApp(extension
->id());
1974 extensions::InstalledExtensionInfo
details(
1975 extension
, is_update
, from_ephemeral
, old_name
);
1976 content::NotificationService::current()->Notify(
1977 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1978 content::Source
<Profile
>(profile_
),
1979 content::Details
<const extensions::InstalledExtensionInfo
>(&details
));
1981 registry_
->TriggerOnWillBeInstalled(
1982 extension
, is_update
, from_ephemeral
, old_name
);
1984 // Unpacked extensions default to allowing file access, but if that has been
1985 // overridden, don't reset the value.
1986 if (Manifest::ShouldAlwaysAllowFileAccess(extension
->location()) &&
1987 !extension_prefs_
->HasAllowFileAccessSetting(extension
->id())) {
1988 extension_prefs_
->SetAllowFileAccess(extension
->id(), true);
1991 AddExtension(extension
);
1993 // Notify observers that need to know when an installation is complete.
1994 registry_
->TriggerOnInstalled(extension
, is_update
);
1996 // Check extensions that may have been delayed only because this shared module
1997 // was not available.
1998 if (SharedModuleInfo::IsSharedModule(extension
))
1999 MaybeFinishDelayedInstallations();
2002 void ExtensionService::PromoteEphemeralApp(
2003 const extensions::Extension
* extension
, bool is_from_sync
) {
2004 DCHECK(GetInstalledExtension(extension
->id()) &&
2005 extension_prefs_
->IsEphemeralApp(extension
->id()));
2007 if (extension
->RequiresSortOrdinal()) {
2008 extension_prefs_
->app_sorting()->SetExtensionVisible(
2009 extension
->id(), extension
->ShouldDisplayInNewTabPage());
2011 if (!is_from_sync
) {
2012 // Reset the sort ordinals of the app to ensure it is added to the default
2013 // position, like newly installed apps would.
2014 extension_prefs_
->app_sorting()->ClearOrdinals(extension
->id());
2017 extension_prefs_
->app_sorting()->EnsureValidOrdinals(
2018 extension
->id(), syncer::StringOrdinal());
2021 // Remove the ephemeral flags from the preferences.
2022 extension_prefs_
->OnEphemeralAppPromoted(extension
->id());
2024 // Fire install-related events to allow observers to handle the promotion
2025 // of the ephemeral app.
2026 extensions::InstalledExtensionInfo
details(
2028 true /* is update */,
2029 true /* from ephemeral */,
2030 extension
->name() /* old name */);
2031 content::NotificationService::current()->Notify(
2032 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2033 content::Source
<Profile
>(profile_
),
2034 content::Details
<const extensions::InstalledExtensionInfo
>(&details
));
2036 registry_
->TriggerOnWillBeInstalled(
2038 true /* is update */,
2039 true /* from ephemeral */,
2040 extension
->name() /* old name */);
2042 if (registry_
->enabled_extensions().Contains(extension
->id())) {
2043 // If the app is already enabled and loaded, fire the load events to allow
2044 // observers to handle the promotion of the ephemeral app.
2045 content::NotificationService::current()->Notify(
2046 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
2047 content::Source
<Profile
>(profile_
),
2048 content::Details
<const Extension
>(extension
));
2050 registry_
->TriggerOnLoaded(extension
);
2052 // Cached ephemeral apps may be updated and disabled due to permissions
2053 // increase. The app can be enabled (as long as no other disable reasons
2054 // exist) as the install was user-acknowledged.
2055 int disable_mask
= Extension::DISABLE_NONE
;
2057 disable_mask
|= Extension::DISABLE_PERMISSIONS_INCREASE
;
2059 int other_disable_reasons
=
2060 extension_prefs_
->GetDisableReasons(extension
->id()) & ~disable_mask
;
2061 if (!other_disable_reasons
) {
2062 if (extension_prefs_
->DidExtensionEscalatePermissions(extension
->id()))
2063 GrantPermissionsAndEnableExtension(extension
);
2065 EnableExtension(extension
->id());
2069 registry_
->TriggerOnInstalled(extension
, true);
2071 if (!is_from_sync
&& extension_sync_service_
)
2072 extension_sync_service_
->SyncExtensionChangeIfNeeded(*extension
);
2075 const Extension
* ExtensionService::GetPendingExtensionUpdate(
2076 const std::string
& id
) const {
2077 return delayed_installs_
.GetByID(id
);
2080 void ExtensionService::RegisterContentSettings(
2081 HostContentSettingsMap
* host_content_settings_map
) {
2082 TRACE_EVENT0("browser,startup", "ExtensionService::RegisterContentSettings");
2083 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2084 host_content_settings_map
->RegisterProvider(
2085 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER
,
2086 scoped_ptr
<content_settings::ObservableProvider
>(
2087 new content_settings::InternalExtensionProvider(profile_
)));
2089 host_content_settings_map
->RegisterProvider(
2090 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER
,
2091 scoped_ptr
<content_settings::ObservableProvider
>(
2092 new content_settings::CustomExtensionProvider(
2093 extensions::ContentSettingsService::Get(
2094 profile_
)->content_settings_store(),
2095 profile_
->GetOriginalProfile() != profile_
)));
2098 void ExtensionService::TrackTerminatedExtension(const Extension
* extension
) {
2099 // No need to check for duplicates; inserting a duplicate is a no-op.
2100 registry_
->AddTerminated(make_scoped_refptr(extension
));
2101 extensions_being_terminated_
.erase(extension
->id());
2102 UnloadExtension(extension
->id(), UnloadedExtensionInfo::REASON_TERMINATE
);
2105 void ExtensionService::TerminateExtension(const std::string
& extension_id
) {
2106 const Extension
* extension
= GetInstalledExtension(extension_id
);
2107 TrackTerminatedExtension(extension
);
2110 void ExtensionService::UntrackTerminatedExtension(const std::string
& id
) {
2111 std::string lowercase_id
= base::StringToLowerASCII(id
);
2112 const Extension
* extension
=
2113 registry_
->terminated_extensions().GetByID(lowercase_id
);
2114 registry_
->RemoveTerminated(lowercase_id
);
2116 content::NotificationService::current()->Notify(
2117 extensions::NOTIFICATION_EXTENSION_REMOVED
,
2118 content::Source
<Profile
>(profile_
),
2119 content::Details
<const Extension
>(extension
));
2123 const Extension
* ExtensionService::GetInstalledExtension(
2124 const std::string
& id
) const {
2125 return registry_
->GetExtensionById(id
, ExtensionRegistry::EVERYTHING
);
2128 bool ExtensionService::OnExternalExtensionFileFound(
2129 const std::string
& id
,
2130 const Version
* version
,
2131 const base::FilePath
& path
,
2132 Manifest::Location location
,
2134 bool mark_acknowledged
,
2135 bool install_immediately
) {
2136 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
2137 CHECK(crx_file::id_util::IdIsValid(id
));
2138 if (extension_prefs_
->IsExternalExtensionUninstalled(id
))
2141 // Before even bothering to unpack, check and see if we already have this
2142 // version. This is important because these extensions are going to get
2143 // installed on every startup.
2144 const Extension
* existing
= GetExtensionById(id
, true);
2147 // The default apps will have the location set as INTERNAL. Since older
2148 // default apps are installed as EXTERNAL, we override them. However, if the
2149 // app is already installed as internal, then do the version check.
2150 // TODO(grv) : Remove after Q1-2013.
2151 bool is_default_apps_migration
=
2152 (location
== Manifest::INTERNAL
&&
2153 Manifest::IsExternalLocation(existing
->location()));
2155 if (!is_default_apps_migration
) {
2158 switch (existing
->version()->CompareTo(*version
)) {
2159 case -1: // existing version is older, we should upgrade
2161 case 0: // existing version is same, do nothing
2163 case 1: // existing version is newer, uh-oh
2164 LOG(WARNING
) << "Found external version of extension " << id
2165 << "that is older than current version. Current version "
2166 << "is: " << existing
->VersionString() << ". New "
2167 << "version is: " << version
->GetString()
2168 << ". Keeping current version.";
2174 // If the extension is already pending, don't start an install.
2175 if (!pending_extension_manager()->AddFromExternalFile(
2176 id
, location
, *version
, creation_flags
, mark_acknowledged
)) {
2180 // no client (silent install)
2181 scoped_refptr
<CrxInstaller
> installer(CrxInstaller::CreateSilent(this));
2182 installer
->set_install_source(location
);
2183 installer
->set_expected_id(id
);
2184 installer
->set_expected_version(*version
);
2185 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE
);
2186 installer
->set_install_immediately(install_immediately
);
2187 installer
->set_creation_flags(creation_flags
);
2188 #if defined(OS_CHROMEOS)
2189 extensions::InstallLimiter::Get(profile_
)->Add(installer
, path
);
2191 installer
->InstallCrx(path
);
2194 // Depending on the source, a new external extension might not need a user
2195 // notification on installation. For such extensions, mark them acknowledged
2196 // now to suppress the notification.
2197 if (mark_acknowledged
)
2198 external_install_manager_
->AcknowledgeExternalExtension(id
);
2203 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2204 extensions::ExtensionHost
* host
) {
2205 OrphanedDevTools::iterator iter
=
2206 orphaned_dev_tools_
.find(host
->extension_id());
2207 if (iter
== orphaned_dev_tools_
.end())
2210 iter
->second
->ConnectWebContents(host
->host_contents());
2211 orphaned_dev_tools_
.erase(iter
);
2214 void ExtensionService::Observe(int type
,
2215 const content::NotificationSource
& source
,
2216 const content::NotificationDetails
& details
) {
2218 case chrome::NOTIFICATION_APP_TERMINATING
:
2219 // Shutdown has started. Don't start any more extension installs.
2220 // (We cannot use ExtensionService::Shutdown() for this because it
2221 // happens too late in browser teardown.)
2222 browser_terminating_
= true;
2224 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
2226 content::Source
<Profile
>(source
).ptr()->GetOriginalProfile()) {
2230 extensions::ExtensionHost
* host
=
2231 content::Details
<extensions::ExtensionHost
>(details
).ptr();
2233 // If the extension is already being terminated, there is nothing left to
2235 if (!extensions_being_terminated_
.insert(host
->extension_id()).second
)
2238 // Mark the extension as terminated and Unload it. We want it to
2239 // be in a consistent state: either fully working or not loaded
2240 // at all, but never half-crashed. We do it in a PostTask so
2241 // that other handlers of this notification will still have
2242 // access to the Extension and ExtensionHost.
2243 base::MessageLoop::current()->PostTask(
2246 &ExtensionService::TrackTerminatedExtension
,
2248 host
->extension()));
2251 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED
: {
2252 content::RenderProcessHost
* process
=
2253 content::Source
<content::RenderProcessHost
>(source
).ptr();
2254 Profile
* host_profile
=
2255 Profile::FromBrowserContext(process
->GetBrowserContext());
2256 if (!profile_
->IsSameProfile(host_profile
->GetOriginalProfile()))
2259 extensions::ProcessMap
* process_map
=
2260 extensions::ProcessMap::Get(profile_
);
2261 if (process_map
->Contains(process
->GetID())) {
2262 // An extension process was terminated, this might have resulted in an
2263 // app or extension becoming idle.
2264 std::set
<std::string
> extension_ids
=
2265 process_map
->GetExtensionsInProcess(process
->GetID());
2266 // In addition to the extensions listed in the process map, one of those
2267 // extensions could be referencing a shared module which is waiting for
2268 // idle to update. Check all imports of these extensions, too.
2269 std::set
<std::string
> import_ids
;
2270 for (std::set
<std::string
>::const_iterator it
= extension_ids
.begin();
2271 it
!= extension_ids
.end();
2273 const Extension
* extension
= GetExtensionById(*it
, true);
2276 const std::vector
<SharedModuleInfo::ImportInfo
>& imports
=
2277 SharedModuleInfo::GetImports(extension
);
2278 std::vector
<SharedModuleInfo::ImportInfo
>::const_iterator import_it
;
2279 for (import_it
= imports
.begin(); import_it
!= imports
.end();
2281 import_ids
.insert((*import_it
).extension_id
);
2284 extension_ids
.insert(import_ids
.begin(), import_ids
.end());
2286 for (std::set
<std::string
>::const_iterator it
= extension_ids
.begin();
2287 it
!= extension_ids
.end(); ++it
) {
2288 if (delayed_installs_
.Contains(*it
)) {
2289 base::MessageLoop::current()->PostDelayedTask(
2291 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation
,
2293 base::TimeDelta::FromSeconds(kUpdateIdleDelay
));
2298 process_map
->RemoveAllFromProcess(process
->GetID());
2299 BrowserThread::PostTask(
2302 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess
,
2303 system_
->info_map(),
2307 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED
: {
2308 // Notify observers that chrome update is available.
2309 FOR_EACH_OBSERVER(extensions::UpdateObserver
, update_observers_
,
2310 OnChromeUpdateAvailable());
2313 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED
: {
2314 OnProfileDestructionStarted();
2319 NOTREACHED() << "Unexpected notification type.";
2323 int ExtensionService::GetDisableReasonsOnInstalled(const Extension
* extension
) {
2324 Extension::DisableReason disable_reason
;
2325 // Extensions disabled by management policy should always be disabled, even
2326 // if it's force-installed.
2327 if (system_
->management_policy()->MustRemainDisabled(
2328 extension
, &disable_reason
, nullptr)) {
2329 // A specified reason is required to disable the extension.
2330 DCHECK(disable_reason
!= Extension::DISABLE_NONE
);
2331 return disable_reason
;
2334 // Extensions installed by policy can't be disabled. So even if a previous
2335 // installation disabled the extension, make sure it is now enabled.
2336 if (system_
->management_policy()->MustRemainEnabled(extension
, nullptr))
2337 return Extension::DISABLE_NONE
;
2339 // An already disabled extension should inherit the disable reasons and
2341 if (extension_prefs_
->IsExtensionDisabled(extension
->id())) {
2342 int disable_reasons
= extension_prefs_
->GetDisableReasons(extension
->id());
2343 // If an extension was disabled without specified reason, presume it's
2344 // disabled by user.
2345 return disable_reasons
== Extension::DISABLE_NONE
2346 ? Extension::DISABLE_USER_ACTION
2350 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2351 // External extensions are initially disabled. We prompt the user before
2352 // enabling them. Hosted apps are excepted because they are not dangerous
2353 // (they need to be launched by the user anyway).
2354 if (extension
->GetType() != Manifest::TYPE_HOSTED_APP
&&
2355 Manifest::IsExternalLocation(extension
->location()) &&
2356 !extension_prefs_
->IsExternalExtensionAcknowledged(extension
->id())) {
2357 return Extension::DISABLE_EXTERNAL_EXTENSION
;
2361 return Extension::DISABLE_NONE
;
2364 // Helper method to determine if an extension can be blocked.
2365 bool ExtensionService::CanBlockExtension(const Extension
* extension
) const {
2367 return extension
->location() != Manifest::COMPONENT
&&
2368 extension
->location() != Manifest::EXTERNAL_COMPONENT
&&
2369 !system_
->management_policy()->MustRemainEnabled(extension
, NULL
);
2372 bool ExtensionService::ShouldDelayExtensionUpdate(
2373 const std::string
& extension_id
,
2374 bool install_immediately
) const {
2375 const char kOnUpdateAvailableEvent
[] = "runtime.onUpdateAvailable";
2377 // If delayed updates are globally disabled, or just for this extension,
2379 if (!install_updates_when_idle_
|| install_immediately
)
2382 const Extension
* old
= GetInstalledExtension(extension_id
);
2383 // If there is no old extension, this is not an update, so don't delay.
2387 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old
)) {
2388 // Delay installation if the extension listens for the onUpdateAvailable
2390 return system_
->event_router()->ExtensionHasEventListener(
2391 extension_id
, kOnUpdateAvailableEvent
);
2393 // Delay installation if the extension is not idle.
2394 return !extensions::util::IsExtensionIdle(extension_id
, profile_
);
2398 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2399 DCHECK(!installs_delayed_for_gc_
);
2400 installs_delayed_for_gc_
= true;
2403 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2404 DCHECK(installs_delayed_for_gc_
);
2405 installs_delayed_for_gc_
= false;
2406 MaybeFinishDelayedInstallations();
2409 void ExtensionService::MaybeFinishDelayedInstallations() {
2410 std::vector
<std::string
> to_be_installed
;
2411 for (ExtensionSet::const_iterator it
= delayed_installs_
.begin();
2412 it
!= delayed_installs_
.end();
2414 to_be_installed
.push_back((*it
)->id());
2416 for (std::vector
<std::string
>::const_iterator it
= to_be_installed
.begin();
2417 it
!= to_be_installed
.end();
2419 MaybeFinishDelayedInstallation(*it
);
2423 void ExtensionService::OnBlacklistUpdated() {
2424 blacklist_
->GetBlacklistedIDs(
2425 registry_
->GenerateInstalledExtensionsSet()->GetIDs(),
2426 base::Bind(&ExtensionService::ManageBlacklist
, AsWeakPtr()));
2429 void ExtensionService::ManageBlacklist(
2430 const extensions::Blacklist::BlacklistStateMap
& state_map
) {
2431 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
2433 std::set
<std::string
> blacklisted
;
2434 ExtensionIdSet greylist
;
2435 ExtensionIdSet unchanged
;
2436 for (extensions::Blacklist::BlacklistStateMap::const_iterator it
=
2438 it
!= state_map
.end();
2440 switch (it
->second
) {
2441 case extensions::NOT_BLACKLISTED
:
2444 case extensions::BLACKLISTED_MALWARE
:
2445 blacklisted
.insert(it
->first
);
2448 case extensions::BLACKLISTED_SECURITY_VULNERABILITY
:
2449 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION
:
2450 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED
:
2451 greylist
.insert(it
->first
);
2454 case extensions::BLACKLISTED_UNKNOWN
:
2455 unchanged
.insert(it
->first
);
2460 UpdateBlacklistedExtensions(blacklisted
, unchanged
);
2461 UpdateGreylistedExtensions(greylist
, unchanged
, state_map
);
2463 error_controller_
->ShowErrorIfNeeded();
2467 void Partition(const ExtensionIdSet
& before
,
2468 const ExtensionIdSet
& after
,
2469 const ExtensionIdSet
& unchanged
,
2470 ExtensionIdSet
* no_longer
,
2471 ExtensionIdSet
* not_yet
) {
2472 *not_yet
= base::STLSetDifference
<ExtensionIdSet
>(after
, before
);
2473 *no_longer
= base::STLSetDifference
<ExtensionIdSet
>(before
, after
);
2474 *no_longer
= base::STLSetDifference
<ExtensionIdSet
>(*no_longer
, unchanged
);
2478 void ExtensionService::UpdateBlacklistedExtensions(
2479 const ExtensionIdSet
& blacklisted
,
2480 const ExtensionIdSet
& unchanged
) {
2481 ExtensionIdSet not_yet_blocked
, no_longer_blocked
;
2482 Partition(registry_
->blacklisted_extensions().GetIDs(), blacklisted
,
2483 unchanged
, &no_longer_blocked
, ¬_yet_blocked
);
2485 for (ExtensionIdSet::iterator it
= no_longer_blocked
.begin();
2486 it
!= no_longer_blocked
.end(); ++it
) {
2487 scoped_refptr
<const Extension
> extension
=
2488 registry_
->blacklisted_extensions().GetByID(*it
);
2489 if (!extension
.get()) {
2490 NOTREACHED() << "Extension " << *it
<< " no longer blacklisted, "
2491 << "but it was never blacklisted.";
2494 registry_
->RemoveBlacklisted(*it
);
2495 extension_prefs_
->SetExtensionBlacklisted(extension
->id(), false);
2496 AddExtension(extension
.get());
2497 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2498 extension
->location(),
2499 Manifest::NUM_LOCATIONS
);
2502 for (ExtensionIdSet::iterator it
= not_yet_blocked
.begin();
2503 it
!= not_yet_blocked
.end(); ++it
) {
2504 scoped_refptr
<const Extension
> extension
= GetInstalledExtension(*it
);
2505 if (!extension
.get()) {
2506 NOTREACHED() << "Extension " << *it
<< " needs to be "
2507 << "blacklisted, but it's not installed.";
2510 registry_
->AddBlacklisted(extension
);
2511 extension_prefs_
->SetExtensionBlacklistState(
2512 extension
->id(), extensions::BLACKLISTED_MALWARE
);
2513 UnloadExtension(*it
, UnloadedExtensionInfo::REASON_BLACKLIST
);
2514 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2515 extension
->location(), Manifest::NUM_LOCATIONS
);
2519 // TODO(oleg): UMA logging
2520 void ExtensionService::UpdateGreylistedExtensions(
2521 const ExtensionIdSet
& greylist
,
2522 const ExtensionIdSet
& unchanged
,
2523 const extensions::Blacklist::BlacklistStateMap
& state_map
) {
2524 ExtensionIdSet not_yet_greylisted
, no_longer_greylisted
;
2525 Partition(greylist_
.GetIDs(),
2526 greylist
, unchanged
,
2527 &no_longer_greylisted
, ¬_yet_greylisted
);
2529 for (ExtensionIdSet::iterator it
= no_longer_greylisted
.begin();
2530 it
!= no_longer_greylisted
.end(); ++it
) {
2531 scoped_refptr
<const Extension
> extension
= greylist_
.GetByID(*it
);
2532 if (!extension
.get()) {
2533 NOTREACHED() << "Extension " << *it
<< " no longer greylisted, "
2534 << "but it was not marked as greylisted.";
2538 greylist_
.Remove(*it
);
2539 extension_prefs_
->SetExtensionBlacklistState(extension
->id(),
2540 extensions::NOT_BLACKLISTED
);
2541 if (extension_prefs_
->GetDisableReasons(extension
->id()) &
2542 extensions::Extension::DISABLE_GREYLIST
)
2543 EnableExtension(*it
);
2546 for (ExtensionIdSet::iterator it
= not_yet_greylisted
.begin();
2547 it
!= not_yet_greylisted
.end(); ++it
) {
2548 scoped_refptr
<const Extension
> extension
= GetInstalledExtension(*it
);
2549 if (!extension
.get()) {
2550 NOTREACHED() << "Extension " << *it
<< " needs to be "
2551 << "disabled, but it's not installed.";
2554 greylist_
.Insert(extension
);
2555 extension_prefs_
->SetExtensionBlacklistState(extension
->id(),
2556 state_map
.find(*it
)->second
);
2557 if (registry_
->enabled_extensions().Contains(extension
->id()))
2558 DisableExtension(*it
, extensions::Extension::DISABLE_GREYLIST
);
2562 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver
* observer
) {
2563 update_observers_
.AddObserver(observer
);
2566 void ExtensionService::RemoveUpdateObserver(
2567 extensions::UpdateObserver
* observer
) {
2568 update_observers_
.RemoveObserver(observer
);
2571 // Used only by test code.
2572 void ExtensionService::UnloadAllExtensionsInternal() {
2573 profile_
->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2575 registry_
->ClearAll();
2576 system_
->runtime_data()->ClearAll();
2578 // TODO(erikkay) should there be a notification for this? We can't use
2579 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2583 void ExtensionService::OnProfileDestructionStarted() {
2584 ExtensionIdSet ids_to_unload
= registry_
->enabled_extensions().GetIDs();
2585 for (ExtensionIdSet::iterator it
= ids_to_unload
.begin();
2586 it
!= ids_to_unload
.end();
2588 UnloadExtension(*it
, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN
);