1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/extension_service.h"
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/callback.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/logging.h"
17 #include "base/metrics/histogram.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/threading/sequenced_worker_pool.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "base/time/time.h"
27 #include "base/values.h"
28 #include "base/version.h"
29 #include "chrome/browser/browser_process.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
32 #include "chrome/browser/extensions/api/storage/settings_frontend.h"
33 #include "chrome/browser/extensions/component_loader.h"
34 #include "chrome/browser/extensions/crx_installer.h"
35 #include "chrome/browser/extensions/data_deleter.h"
36 #include "chrome/browser/extensions/extension_disabled_ui.h"
37 #include "chrome/browser/extensions/extension_error_reporter.h"
38 #include "chrome/browser/extensions/extension_error_ui.h"
39 #include "chrome/browser/extensions/extension_host.h"
40 #include "chrome/browser/extensions/extension_install_ui.h"
41 #include "chrome/browser/extensions/extension_special_storage_policy.h"
42 #include "chrome/browser/extensions/extension_sync_service.h"
43 #include "chrome/browser/extensions/extension_system.h"
44 #include "chrome/browser/extensions/extension_util.h"
45 #include "chrome/browser/extensions/external_install_ui.h"
46 #include "chrome/browser/extensions/external_provider_impl.h"
47 #include "chrome/browser/extensions/install_verifier.h"
48 #include "chrome/browser/extensions/installed_loader.h"
49 #include "chrome/browser/extensions/permissions_updater.h"
50 #include "chrome/browser/extensions/unpacked_installer.h"
51 #include "chrome/browser/extensions/updater/extension_updater.h"
52 #include "chrome/browser/profiles/profile.h"
53 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
54 #include "chrome/browser/ui/webui/favicon_source.h"
55 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
56 #include "chrome/browser/ui/webui/theme_source.h"
57 #include "chrome/common/chrome_switches.h"
58 #include "chrome/common/crash_keys.h"
59 #include "chrome/common/extensions/extension_constants.h"
60 #include "chrome/common/extensions/extension_file_util.h"
61 #include "chrome/common/extensions/extension_messages.h"
62 #include "chrome/common/extensions/features/feature_channel.h"
63 #include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
64 #include "chrome/common/extensions/manifest_url_handler.h"
65 #include "chrome/common/pref_names.h"
66 #include "chrome/common/url_constants.h"
67 #include "components/startup_metric_utils/startup_metric_utils.h"
68 #include "content/public/browser/browser_thread.h"
69 #include "content/public/browser/devtools_agent_host.h"
70 #include "content/public/browser/notification_service.h"
71 #include "content/public/browser/notification_types.h"
72 #include "content/public/browser/render_process_host.h"
73 #include "content/public/browser/site_instance.h"
74 #include "content/public/browser/storage_partition.h"
75 #include "content/public/browser/url_data_source.h"
76 #include "extensions/browser/app_sorting.h"
77 #include "extensions/browser/event_router.h"
78 #include "extensions/browser/extension_registry.h"
79 #include "extensions/browser/extensions_browser_client.h"
80 #include "extensions/browser/external_provider_interface.h"
81 #include "extensions/browser/management_policy.h"
82 #include "extensions/browser/pending_extension_manager.h"
83 #include "extensions/browser/pref_names.h"
84 #include "extensions/browser/process_manager.h"
85 #include "extensions/browser/process_map.h"
86 #include "extensions/browser/update_observer.h"
87 #include "extensions/common/constants.h"
88 #include "extensions/common/error_utils.h"
89 #include "extensions/common/extension.h"
90 #include "extensions/common/extensions_client.h"
91 #include "extensions/common/feature_switch.h"
92 #include "extensions/common/manifest.h"
93 #include "extensions/common/manifest_constants.h"
94 #include "extensions/common/manifest_handlers/background_info.h"
95 #include "extensions/common/manifest_handlers/incognito_info.h"
96 #include "extensions/common/manifest_handlers/shared_module_info.h"
97 #include "extensions/common/permissions/permission_message_provider.h"
98 #include "extensions/common/permissions/permissions_data.h"
99 #include "grit/generated_resources.h"
100 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
101 #include "ui/base/webui/web_ui_util.h"
102 #include "url/gurl.h"
103 #include "webkit/browser/database/database_tracker.h"
104 #include "webkit/browser/database/database_util.h"
106 #if defined(OS_CHROMEOS)
107 #include "chrome/browser/chromeos/extensions/install_limiter.h"
108 #include "webkit/browser/fileapi/file_system_backend.h"
109 #include "webkit/browser/fileapi/file_system_context.h"
112 using content::BrowserContext
;
113 using content::BrowserThread
;
114 using content::DevToolsAgentHost
;
115 using extensions::CrxInstaller
;
116 using extensions::Extension
;
117 using extensions::ExtensionIdSet
;
118 using extensions::ExtensionInfo
;
119 using extensions::ExtensionRegistry
;
120 using extensions::ExtensionSet
;
121 using extensions::FeatureSwitch
;
122 using extensions::InstallVerifier
;
123 using extensions::ManagementPolicy
;
124 using extensions::Manifest
;
125 using extensions::PermissionMessage
;
126 using extensions::PermissionMessages
;
127 using extensions::PermissionSet
;
128 using extensions::SharedModuleInfo
;
129 using extensions::UnloadedExtensionInfo
;
131 namespace errors
= extensions::manifest_errors
;
135 // Histogram values for logging events related to externally installed
137 enum ExternalExtensionEvent
{
138 EXTERNAL_EXTENSION_INSTALLED
= 0,
139 EXTERNAL_EXTENSION_IGNORED
,
140 EXTERNAL_EXTENSION_REENABLED
,
141 EXTERNAL_EXTENSION_UNINSTALLED
,
142 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
,
145 // Prompt the user this many times before considering an extension acknowledged.
146 static const int kMaxExtensionAcknowledgePromptCount
= 3;
148 // Wait this many seconds after an extensions becomes idle before updating it.
149 static const int kUpdateIdleDelay
= 5;
151 // Wait this many seconds before trying to garbage collect extensions again.
152 static const int kGarbageCollectRetryDelay
= 30;
154 // Wait this many seconds after startup to see if there are any extensions
155 // which can be garbage collected.
156 static const int kGarbageCollectStartupDelay
= 30;
158 static bool IsSharedModule(const Extension
* extension
) {
159 return SharedModuleInfo::IsSharedModule(extension
);
162 static bool IsCWSSharedModule(const Extension
* extension
) {
163 return extension
->from_webstore() && IsSharedModule(extension
);
166 class SharedModuleProvider
: public extensions::ManagementPolicy::Provider
{
168 SharedModuleProvider() {}
169 virtual ~SharedModuleProvider() {}
171 virtual std::string
GetDebugPolicyProviderName() const OVERRIDE
{
172 return "SharedModuleProvider";
175 virtual bool UserMayModifySettings(const Extension
* extension
,
176 base::string16
* error
) const OVERRIDE
{
177 return !IsCWSSharedModule(extension
);
180 virtual bool MustRemainEnabled(const Extension
* extension
,
181 base::string16
* error
) const OVERRIDE
{
182 return IsCWSSharedModule(extension
);
186 DISALLOW_COPY_AND_ASSIGN(SharedModuleProvider
);
192 ExtensionService::ExtensionRuntimeData::ExtensionRuntimeData()
193 : background_page_ready(false),
194 being_upgraded(false),
195 has_used_webrequest(false) {
198 ExtensionService::ExtensionRuntimeData::~ExtensionRuntimeData() {
203 void ExtensionService::CheckExternalUninstall(const std::string
& id
) {
204 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
206 // Check if the providers know about this extension.
207 extensions::ProviderCollection::const_iterator i
;
208 for (i
= external_extension_providers_
.begin();
209 i
!= external_extension_providers_
.end(); ++i
) {
210 DCHECK(i
->get()->IsReady());
211 if (i
->get()->HasExtension(id
))
212 return; // Yup, known extension, don't uninstall.
215 // We get the list of external extensions to check from preferences.
216 // It is possible that an extension has preferences but is not loaded.
217 // For example, an extension that requires experimental permissions
218 // will not be loaded if the experimental command line flag is not used.
219 // In this case, do not uninstall.
220 if (!GetInstalledExtension(id
)) {
221 // We can't call UninstallExtension with an unloaded/invalid
223 LOG(WARNING
) << "Attempted uninstallation of unloaded/invalid extension "
224 << "with id: " << id
;
227 UninstallExtension(id
, true, NULL
);
230 void ExtensionService::SetFileTaskRunnerForTesting(
231 base::SequencedTaskRunner
* task_runner
) {
232 file_task_runner_
= task_runner
;
235 void ExtensionService::ClearProvidersForTesting() {
236 external_extension_providers_
.clear();
239 void ExtensionService::AddProviderForTesting(
240 extensions::ExternalProviderInterface
* test_provider
) {
241 CHECK(test_provider
);
242 external_extension_providers_
.push_back(
243 linked_ptr
<extensions::ExternalProviderInterface
>(test_provider
));
246 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
247 const std::string
& id
,
248 const GURL
& update_url
,
249 Manifest::Location location
,
251 bool mark_acknowledged
) {
252 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
253 CHECK(Extension::IdIsValid(id
));
255 const Extension
* extension
= GetExtensionById(id
, true);
257 // Already installed. Skip this install if the current location has
258 // higher priority than |location|.
259 Manifest::Location current
= extension
->location();
260 if (current
== Manifest::GetHigherPriorityLocation(current
, location
))
262 // Otherwise, overwrite the current installation.
265 // Add |id| to the set of pending extensions. If it can not be added,
266 // then there is already a pending record from a higher-priority install
267 // source. In this case, signal that this extension will not be
268 // installed by returning false.
269 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
270 id
, update_url
, location
, creation_flags
, mark_acknowledged
)) {
274 update_once_all_providers_are_ready_
= true;
278 const Extension
* ExtensionService::GetInstalledExtensionByUrl(
279 const GURL
& url
) const {
280 return registry_
->enabled_extensions().GetExtensionOrAppByURL(url
);
283 const Extension
* ExtensionService::GetInstalledApp(const GURL
& url
) const {
284 const Extension
* extension
= GetInstalledExtensionByUrl(url
);
285 return (extension
&& extension
->is_app()) ? extension
: NULL
;
288 bool ExtensionService::IsInstalledApp(const GURL
& url
) const {
289 return !!GetInstalledApp(url
);
293 // This function is used to implement the command-line switch
294 // --uninstall-extension, and to uninstall an extension via sync. The LOG
295 // statements within this function are used to inform the user if the uninstall
297 bool ExtensionService::UninstallExtensionHelper(
298 ExtensionService
* extensions_service
,
299 const std::string
& extension_id
) {
300 // We can't call UninstallExtension with an invalid extension ID.
301 if (!extensions_service
->GetInstalledExtension(extension_id
)) {
302 LOG(WARNING
) << "Attempted uninstallation of non-existent extension with "
303 << "id: " << extension_id
;
307 // The following call to UninstallExtension will not allow an uninstall of a
308 // policy-controlled extension.
309 base::string16 error
;
310 if (!extensions_service
->UninstallExtension(extension_id
, false, &error
)) {
311 LOG(WARNING
) << "Cannot uninstall extension with id " << extension_id
319 ExtensionService::ExtensionService(Profile
* profile
,
320 const CommandLine
* command_line
,
321 const base::FilePath
& install_directory
,
322 extensions::ExtensionPrefs
* extension_prefs
,
323 extensions::Blacklist
* blacklist
,
324 bool autoupdate_enabled
,
325 bool extensions_enabled
,
326 extensions::OneShotEvent
* ready
)
327 : extensions::Blacklist::Observer(blacklist
),
329 system_(extensions::ExtensionSystem::Get(profile
)),
330 extension_prefs_(extension_prefs
),
331 blacklist_(blacklist
),
332 settings_frontend_(extensions::SettingsFrontend::Create(profile
)),
333 extension_sync_service_(NULL
),
334 registry_(extensions::ExtensionRegistry::Get(profile
)),
335 pending_extension_manager_(*this),
336 install_directory_(install_directory
),
337 extensions_enabled_(extensions_enabled
),
338 show_extensions_prompts_(true),
339 install_updates_when_idle_(true),
341 update_once_all_providers_are_ready_(false),
342 browser_terminating_(false),
343 installs_delayed_for_gc_(false),
344 is_first_run_(false) {
345 #if defined(OS_CHROMEOS)
346 disable_garbage_collection_
= false;
348 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
350 // Figure out if extension installation should be enabled.
351 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
352 *command_line
, profile
))
353 extensions_enabled_
= false;
355 registrar_
.Add(this, chrome::NOTIFICATION_APP_TERMINATING
,
356 content::NotificationService::AllBrowserContextsAndSources());
357 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
358 content::NotificationService::AllBrowserContextsAndSources());
359 registrar_
.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED
,
360 content::NotificationService::AllBrowserContextsAndSources());
361 registrar_
.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED
,
362 content::NotificationService::AllBrowserContextsAndSources());
363 registrar_
.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED
,
364 content::NotificationService::AllBrowserContextsAndSources());
365 pref_change_registrar_
.Init(profile
->GetPrefs());
366 base::Closure callback
=
367 base::Bind(&ExtensionService::OnExtensionInstallPrefChanged
,
368 base::Unretained(this));
369 pref_change_registrar_
.Add(extensions::pref_names::kInstallAllowList
,
371 pref_change_registrar_
.Add(extensions::pref_names::kInstallDenyList
,
373 pref_change_registrar_
.Add(extensions::pref_names::kAllowedTypes
, callback
);
375 // Set up the ExtensionUpdater
376 if (autoupdate_enabled
) {
377 int update_frequency
= extensions::kDefaultUpdateFrequencySeconds
;
378 if (command_line
->HasSwitch(switches::kExtensionsUpdateFrequency
)) {
379 base::StringToInt(command_line
->GetSwitchValueASCII(
380 switches::kExtensionsUpdateFrequency
),
383 updater_
.reset(new extensions::ExtensionUpdater(this,
390 component_loader_
.reset(
391 new extensions::ComponentLoader(this,
393 g_browser_process
->local_state(),
396 if (extensions_enabled_
) {
397 extensions::ExternalProviderImpl::CreateExternalProviders(
398 this, profile_
, &external_extension_providers_
);
401 // Set this as the ExtensionService for app sorting to ensure it causes syncs
403 is_first_run_
= !extension_prefs_
->SetAlertSystemFirstRun();
405 #if defined(ENABLE_EXTENSIONS)
406 extension_action_storage_manager_
.reset(
407 new extensions::ExtensionActionStorageManager(profile_
));
410 shared_module_policy_provider_
.reset(new SharedModuleProvider
);
412 // How long is the path to the Extensions directory?
413 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
414 install_directory_
.value().length(), 0, 500, 100);
417 const ExtensionSet
* ExtensionService::extensions() const {
418 return ®istry_
->enabled_extensions();
421 const ExtensionSet
* ExtensionService::disabled_extensions() const {
422 return ®istry_
->disabled_extensions();
425 const ExtensionSet
* ExtensionService::delayed_installs() const {
426 return &delayed_installs_
;
429 scoped_ptr
<ExtensionSet
>
430 ExtensionService::GenerateInstalledExtensionsSet() const {
431 scoped_ptr
<ExtensionSet
> installed_extensions(new ExtensionSet());
432 installed_extensions
->InsertAll(registry_
->enabled_extensions());
433 installed_extensions
->InsertAll(registry_
->disabled_extensions());
434 installed_extensions
->InsertAll(registry_
->terminated_extensions());
435 installed_extensions
->InsertAll(registry_
->blacklisted_extensions());
436 return installed_extensions
.Pass();
439 extensions::PendingExtensionManager
*
440 ExtensionService::pending_extension_manager() {
441 return &pending_extension_manager_
;
444 ExtensionService::~ExtensionService() {
445 // No need to unload extensions here because they are profile-scoped, and the
446 // profile is in the process of being deleted.
448 extensions::ProviderCollection::const_iterator i
;
449 for (i
= external_extension_providers_
.begin();
450 i
!= external_extension_providers_
.end(); ++i
) {
451 extensions::ExternalProviderInterface
* provider
= i
->get();
452 provider
->ServiceShutdown();
456 void ExtensionService::Shutdown() {
457 system_
->management_policy()->UnregisterProvider(
458 shared_module_policy_provider_
.get());
461 const Extension
* ExtensionService::GetExtensionById(
462 const std::string
& id
, bool include_disabled
) const {
463 int include_mask
= ExtensionRegistry::ENABLED
;
464 if (include_disabled
) {
465 // Include blacklisted extensions here because there are hundreds of
466 // callers of this function, and many might assume that this includes those
467 // that have been disabled due to blacklisting.
468 include_mask
|= ExtensionRegistry::DISABLED
|
469 ExtensionRegistry::BLACKLISTED
;
471 return registry_
->GetExtensionById(id
, include_mask
);
474 GURL
ExtensionService::GetSiteForExtensionId(const std::string
& extension_id
) {
475 return content::SiteInstance::GetSiteForURL(
477 Extension::GetBaseURLFromExtensionId(extension_id
));
480 void ExtensionService::Init() {
481 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
483 base::Time begin_time
= base::Time::Now();
485 DCHECK(!is_ready()); // Can't redo init.
486 DCHECK_EQ(registry_
->enabled_extensions().size(), 0u);
488 const CommandLine
* cmd_line
= CommandLine::ForCurrentProcess();
489 if (cmd_line
->HasSwitch(switches::kInstallFromWebstore
) ||
490 cmd_line
->HasSwitch(switches::kLimitedInstallFromWebstore
)) {
491 // The sole purpose of this launch is to install a new extension from CWS
492 // and immediately terminate: loading already installed extensions is
493 // unnecessary and may interfere with the inline install dialog (e.g. if an
494 // extension listens to onStartup and opens a window).
495 SetReadyAndNotifyListeners();
497 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
498 component_loader_
->LoadAll();
499 extensions::InstalledLoader(this).LoadAllExtensions();
501 ReconcileKnownDisabled();
503 // Attempt to re-enable extensions whose only disable reason is reloading.
504 std::vector
<std::string
> extensions_to_enable
;
505 const ExtensionSet
& disabled_extensions
= registry_
->disabled_extensions();
506 for (ExtensionSet::const_iterator iter
= disabled_extensions
.begin();
507 iter
!= disabled_extensions
.end(); ++iter
) {
508 const Extension
* e
= iter
->get();
509 if (extension_prefs_
->GetDisableReasons(e
->id()) ==
510 Extension::DISABLE_RELOAD
) {
511 extensions_to_enable
.push_back(e
->id());
514 for (std::vector
<std::string
>::iterator it
= extensions_to_enable
.begin();
515 it
!= extensions_to_enable
.end(); ++it
) {
516 EnableExtension(*it
);
519 // Finish install (if possible) of extensions that were still delayed while
520 // the browser was shut down.
521 scoped_ptr
<extensions::ExtensionPrefs::ExtensionsInfo
> delayed_info(
522 extension_prefs_
->GetAllDelayedInstallInfo());
523 for (size_t i
= 0; i
< delayed_info
->size(); ++i
) {
524 ExtensionInfo
* info
= delayed_info
->at(i
).get();
525 scoped_refptr
<const Extension
> extension(NULL
);
526 if (info
->extension_manifest
) {
528 extension
= Extension::Create(
529 info
->extension_path
,
530 info
->extension_location
,
531 *info
->extension_manifest
,
532 extension_prefs_
->GetDelayedInstallCreationFlags(
537 delayed_installs_
.Insert(extension
);
540 MaybeFinishDelayedInstallations();
542 scoped_ptr
<extensions::ExtensionPrefs::ExtensionsInfo
> delayed_info2(
543 extension_prefs_
->GetAllDelayedInstallInfo());
544 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
545 delayed_info2
->size() - delayed_info
->size());
547 SetReadyAndNotifyListeners();
549 // TODO(erikkay) this should probably be deferred to a future point
550 // rather than running immediately at startup.
551 CheckForExternalUpdates();
553 InstallVerifier
* verifier
=
554 extensions::ExtensionSystem::Get(profile_
)->install_verifier();
555 if (verifier
->NeedsBootstrap())
556 VerifyAllExtensions();
557 base::MessageLoop::current()->PostDelayedTask(
559 base::Bind(&ExtensionService::GarbageCollectExtensions
, AsWeakPtr()),
560 base::TimeDelta::FromSeconds(kGarbageCollectStartupDelay
));
562 if (extension_prefs_
->NeedsStorageGarbageCollection()) {
563 GarbageCollectIsolatedStorage();
564 extension_prefs_
->SetNeedsStorageGarbageCollection(false);
566 system_
->management_policy()->RegisterProvider(
567 shared_module_policy_provider_
.get());
570 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
571 base::Time::Now() - begin_time
);
574 void ExtensionService::VerifyAllExtensions() {
575 ExtensionIdSet to_add
;
576 scoped_ptr
<ExtensionSet
> all_extensions
= GenerateInstalledExtensionsSet();
578 for (ExtensionSet::const_iterator i
= all_extensions
->begin();
579 i
!= all_extensions
->end(); ++i
) {
580 const Extension
& extension
= **i
;
582 if (InstallVerifier::NeedsVerification(extension
))
583 to_add
.insert(extension
.id());
585 extensions::ExtensionSystem::Get(profile_
)->install_verifier()->AddMany(
586 to_add
, base::Bind(&ExtensionService::FinishVerifyAllExtensions
,
590 void ExtensionService::FinishVerifyAllExtensions(bool success
) {
592 // Check to see if any currently unverified extensions became verified.
593 InstallVerifier
* verifier
=
594 extensions::ExtensionSystem::Get(profile_
)->install_verifier();
595 const ExtensionSet
& disabled_extensions
= registry_
->disabled_extensions();
596 for (ExtensionSet::const_iterator i
= disabled_extensions
.begin();
597 i
!= disabled_extensions
.end(); ++i
) {
598 const Extension
& extension
= **i
;
599 int disable_reasons
= extension_prefs_
->GetDisableReasons(extension
.id());
600 if (disable_reasons
& Extension::DISABLE_NOT_VERIFIED
&&
601 !verifier
->MustRemainDisabled(&extension
, NULL
, NULL
)) {
602 extension_prefs_
->RemoveDisableReason(extension
.id(),
603 Extension::DISABLE_NOT_VERIFIED
);
604 // Notify interested observers (eg the extensions settings page) by
605 // sending an UNLOADED notification.
607 // TODO(asargent) - this is a slight hack because it's already
608 // disabled; the right solution might be to add a separate listener
609 // interface for DisableReason's changing. http://crbug.com/328916
610 UnloadedExtensionInfo
details(&extension
,
611 UnloadedExtensionInfo::REASON_DISABLE
);
612 content::NotificationService::current()->Notify(
613 chrome::NOTIFICATION_EXTENSION_UNLOADED
,
614 content::Source
<Profile
>(profile_
),
615 content::Details
<UnloadedExtensionInfo
>(&details
));
618 // Might disable some extensions.
619 CheckManagementPolicy();
623 bool ExtensionService::UpdateExtension(const std::string
& id
,
624 const base::FilePath
& extension_path
,
625 const GURL
& download_url
,
626 CrxInstaller
** out_crx_installer
) {
627 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
628 if (browser_terminating_
) {
629 LOG(WARNING
) << "Skipping UpdateExtension due to browser shutdown";
630 // Leak the temp file at extension_path. We don't want to add to the disk
631 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
632 // the file is in the OS temp directory which should be cleaned up for us.
636 const extensions::PendingExtensionInfo
* pending_extension_info
=
637 pending_extension_manager()->GetById(id
);
639 const Extension
* extension
= GetInstalledExtension(id
);
640 if (!pending_extension_info
&& !extension
) {
641 LOG(WARNING
) << "Will not update extension " << id
642 << " because it is not installed or pending";
643 // Delete extension_path since we're not creating a CrxInstaller
644 // that would do it for us.
645 if (!GetFileTaskRunner()->PostTask(
648 &extension_file_util::DeleteFile
, extension_path
, false)))
654 // We want a silent install only for non-pending extensions and
655 // pending extensions that have install_silently set.
656 scoped_ptr
<ExtensionInstallPrompt
> client
;
657 if (pending_extension_info
&& !pending_extension_info
->install_silently())
658 client
.reset(ExtensionInstallUI::CreateInstallPromptWithProfile(profile_
));
660 scoped_refptr
<CrxInstaller
> installer(
661 CrxInstaller::Create(this, client
.Pass()));
662 installer
->set_expected_id(id
);
663 int creation_flags
= Extension::NO_FLAGS
;
664 if (pending_extension_info
) {
665 installer
->set_install_source(pending_extension_info
->install_source());
666 if (pending_extension_info
->install_silently())
667 installer
->set_allow_silent_install(true);
668 creation_flags
= pending_extension_info
->creation_flags();
669 if (pending_extension_info
->mark_acknowledged())
670 AcknowledgeExternalExtension(id
);
671 } else if (extension
) {
672 installer
->set_install_source(extension
->location());
674 // If the extension was installed from or has migrated to the webstore, or
675 // its auto-update URL is from the webstore, treat it as a webstore install.
676 // Note that we ignore some older extensions with blank auto-update URLs
677 // because we are mostly concerned with restrictions on NaCl extensions,
679 if ((extension
&& extension
->from_webstore()) ||
680 (extension
&& extensions::ManifestURL::UpdatesFromGallery(extension
)) ||
681 (!extension
&& extension_urls::IsWebstoreUpdateUrl(
682 pending_extension_info
->update_url()))) {
683 creation_flags
|= Extension::FROM_WEBSTORE
;
686 // Bookmark apps being updated is kind of a contradiction, but that's because
687 // we mark the default apps as bookmark apps, and they're hosted in the web
688 // store, thus they can get updated. See http://crbug.com/101605 for more
690 if (extension
&& extension
->from_bookmark())
691 creation_flags
|= Extension::FROM_BOOKMARK
;
693 if (extension
&& extension
->was_installed_by_default())
694 creation_flags
|= Extension::WAS_INSTALLED_BY_DEFAULT
;
696 if (extension
&& extension
->is_ephemeral())
697 creation_flags
|= Extension::IS_EPHEMERAL
;
699 installer
->set_creation_flags(creation_flags
);
701 installer
->set_delete_source(true);
702 installer
->set_download_url(download_url
);
703 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE
);
704 installer
->InstallCrx(extension_path
);
706 if (out_crx_installer
)
707 *out_crx_installer
= installer
.get();
712 void ExtensionService::ReloadExtension(const std::string extension_id
) {
713 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
715 // If the extension is already reloading, don't reload again.
716 if (extension_prefs_
->GetDisableReasons(extension_id
) &
717 Extension::DISABLE_RELOAD
) {
722 const Extension
* current_extension
= GetExtensionById(extension_id
, false);
724 // Disable the extension if it's loaded. It might not be loaded if it crashed.
725 if (current_extension
) {
726 // If the extension has an inspector open for its background page, detach
727 // the inspector and hang onto a cookie for it, so that we can reattach
729 // TODO(yoz): this is not incognito-safe!
730 extensions::ProcessManager
* manager
= system_
->process_manager();
731 extensions::ExtensionHost
* host
=
732 manager
->GetBackgroundHostForExtension(extension_id
);
733 if (host
&& DevToolsAgentHost::HasFor(host
->render_view_host())) {
734 // Look for an open inspector for the background page.
735 scoped_refptr
<DevToolsAgentHost
> agent_host
=
736 DevToolsAgentHost::GetOrCreateFor(host
->render_view_host());
737 agent_host
->DisconnectRenderViewHost();
738 orphaned_dev_tools_
[extension_id
] = agent_host
;
741 path
= current_extension
->path();
742 // BeingUpgraded is set back to false when the extension is added.
743 SetBeingUpgraded(current_extension
, true);
744 DisableExtension(extension_id
, Extension::DISABLE_RELOAD
);
745 reloading_extensions_
.insert(extension_id
);
747 path
= unloaded_extension_paths_
[extension_id
];
750 if (delayed_installs_
.Contains(extension_id
)) {
751 FinishDelayedInstallation(extension_id
);
755 // If we're reloading a component extension, use the component extension
756 // loader's reloader.
757 if (component_loader_
->Exists(extension_id
)) {
758 SetBeingReloaded(extension_id
, true);
759 component_loader_
->Reload(extension_id
);
760 SetBeingReloaded(extension_id
, false);
764 // Check the installed extensions to see if what we're reloading was already
766 SetBeingReloaded(extension_id
, true);
767 scoped_ptr
<ExtensionInfo
> installed_extension(
768 extension_prefs_
->GetInstalledExtensionInfo(extension_id
));
769 if (installed_extension
.get() &&
770 installed_extension
->extension_manifest
.get()) {
771 extensions::InstalledLoader(this).Load(*installed_extension
, false);
773 // Otherwise, the extension is unpacked (location LOAD).
774 // We should always be able to remember the extension's path. If it's not in
775 // the map, someone failed to update |unloaded_extension_paths_|.
776 CHECK(!path
.empty());
777 extensions::UnpackedInstaller::Create(this)->Load(path
);
779 // When reloading is done, mark this extension as done reloading.
780 SetBeingReloaded(extension_id
, false);
783 bool ExtensionService::UninstallExtension(
784 std::string extension_id
,
785 bool external_uninstall
,
786 base::string16
* error
) {
787 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
789 scoped_refptr
<const Extension
> extension(GetInstalledExtension(extension_id
));
791 // Callers should not send us nonexistent extensions.
792 CHECK(extension
.get());
794 // Policy change which triggers an uninstall will always set
795 // |external_uninstall| to true so this is the only way to uninstall
796 // managed extensions.
797 if (!external_uninstall
&&
798 !system_
->management_policy()->UserMayModifySettings(
799 extension
.get(), error
)) {
800 content::NotificationService::current()->Notify(
801 chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED
,
802 content::Source
<Profile
>(profile_
),
803 content::Details
<const Extension
>(extension
.get()));
807 syncer::SyncChange sync_change
;
808 if (extension_sync_service_
) {
809 sync_change
= extension_sync_service_
->PrepareToSyncUninstallExtension(
810 extension
.get(), is_ready());
813 extensions::ExtensionSystem::Get(profile_
)->install_verifier()->Remove(
816 if (IsUnacknowledgedExternalExtension(extension
.get())) {
817 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
818 EXTERNAL_EXTENSION_UNINSTALLED
,
819 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
820 if (extensions::ManifestURL::UpdatesFromGallery(extension
.get())) {
821 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
822 EXTERNAL_EXTENSION_UNINSTALLED
,
823 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
825 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
826 EXTERNAL_EXTENSION_UNINSTALLED
,
827 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
830 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
831 extension
->GetType(), 100);
832 RecordPermissionMessagesHistogram(extension
.get(),
833 "Extensions.Permissions_Uninstall");
835 // Unload before doing more cleanup to ensure that nothing is hanging on to
836 // any of these resources.
837 UnloadExtension(extension_id
, UnloadedExtensionInfo::REASON_UNINSTALL
);
839 // Tell the backend to start deleting installed extensions on the file thread.
840 if (!Manifest::IsUnpackedLocation(extension
->location())) {
841 if (!GetFileTaskRunner()->PostTask(
844 &extension_file_util::UninstallExtension
,
850 extensions::DataDeleter::StartDeleting(profile_
, extension
.get());
852 UntrackTerminatedExtension(extension_id
);
854 // Notify interested parties that we've uninstalled this extension.
855 content::NotificationService::current()->Notify(
856 chrome::NOTIFICATION_EXTENSION_UNINSTALLED
,
857 content::Source
<Profile
>(profile_
),
858 content::Details
<const Extension
>(extension
.get()));
860 if (extension_sync_service_
) {
861 extension_sync_service_
->ProcessSyncUninstallExtension(extension_id
,
865 delayed_installs_
.Remove(extension_id
);
867 PruneSharedModulesOnUninstall(extension
.get());
869 extension_prefs_
->OnExtensionUninstalled(extension_id
, extension
->location(),
872 // Track the uninstallation.
873 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
878 bool ExtensionService::IsExtensionEnabled(
879 const std::string
& extension_id
) const {
880 if (registry_
->enabled_extensions().Contains(extension_id
) ||
881 registry_
->terminated_extensions().Contains(extension_id
)) {
885 if (registry_
->disabled_extensions().Contains(extension_id
) ||
886 registry_
->blacklisted_extensions().Contains(extension_id
)) {
890 // If the extension hasn't been loaded yet, check the prefs for it. Assume
891 // enabled unless otherwise noted.
892 return !extension_prefs_
->IsExtensionDisabled(extension_id
) &&
893 !extension_prefs_
->IsExternalExtensionUninstalled(extension_id
);
896 bool ExtensionService::IsExternalExtensionUninstalled(
897 const std::string
& extension_id
) const {
898 return extension_prefs_
->IsExternalExtensionUninstalled(extension_id
);
901 void ExtensionService::EnableExtension(const std::string
& extension_id
) {
902 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
904 if (IsExtensionEnabled(extension_id
))
906 const Extension
* extension
=
907 registry_
->disabled_extensions().GetByID(extension_id
);
909 ManagementPolicy
* policy
= system_
->management_policy();
910 if (extension
&& policy
->MustRemainDisabled(extension
, NULL
, NULL
)) {
911 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
915 extension_prefs_
->SetExtensionState(extension_id
, Extension::ENABLED
);
916 extension_prefs_
->ClearDisableReasons(extension_id
);
918 // This can happen if sync enables an extension that is not
923 if (IsUnacknowledgedExternalExtension(extension
)) {
924 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
925 EXTERNAL_EXTENSION_REENABLED
,
926 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
927 if (extensions::ManifestURL::UpdatesFromGallery(extension
)) {
928 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
929 EXTERNAL_EXTENSION_REENABLED
,
930 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
932 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
933 EXTERNAL_EXTENSION_REENABLED
,
934 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
936 AcknowledgeExternalExtension(extension
->id());
939 // Move it over to the enabled list.
940 registry_
->AddEnabled(make_scoped_refptr(extension
));
941 registry_
->RemoveDisabled(extension
->id());
943 NotifyExtensionLoaded(extension
);
945 // Notify listeners that the extension was enabled.
946 content::NotificationService::current()->Notify(
947 chrome::NOTIFICATION_EXTENSION_ENABLED
,
948 content::Source
<Profile
>(profile_
),
949 content::Details
<const Extension
>(extension
));
951 if (extension_sync_service_
)
952 extension_sync_service_
->SyncEnableExtension(*extension
);
955 void ExtensionService::DisableExtension(
956 const std::string
& extension_id
,
957 Extension::DisableReason disable_reason
) {
958 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
960 // The extension may have been disabled already.
961 if (!IsExtensionEnabled(extension_id
))
964 const Extension
* extension
= GetInstalledExtension(extension_id
);
965 // |extension| can be NULL if sync disables an extension that is not
968 disable_reason
!= Extension::DISABLE_RELOAD
&&
969 !system_
->management_policy()->UserMayModifySettings(extension
, NULL
)) {
973 extension_prefs_
->SetExtensionState(extension_id
, Extension::DISABLED
);
974 extension_prefs_
->AddDisableReason(extension_id
, disable_reason
);
977 ExtensionRegistry::EVERYTHING
& ~ExtensionRegistry::DISABLED
;
978 extension
= registry_
->GetExtensionById(extension_id
, include_mask
);
982 // Reset the background_page_ready flag
983 if (extensions::BackgroundInfo::HasBackgroundPage(extension
))
984 extension_runtime_data_
[extension
->id()].background_page_ready
= false;
986 // Move it over to the disabled list. Don't send a second unload notification
987 // for terminated extensions being disabled.
988 registry_
->AddDisabled(make_scoped_refptr(extension
));
989 if (registry_
->enabled_extensions().Contains(extension
->id())) {
990 registry_
->RemoveEnabled(extension
->id());
991 NotifyExtensionUnloaded(extension
, UnloadedExtensionInfo::REASON_DISABLE
);
993 registry_
->RemoveTerminated(extension
->id());
996 if (extension_sync_service_
)
997 extension_sync_service_
->SyncDisableExtension(*extension
);
1000 void ExtensionService::DisableUserExtensions(
1001 const std::vector
<std::string
>& except_ids
) {
1002 extensions::ManagementPolicy
* management_policy
=
1003 system_
->management_policy();
1004 extensions::ExtensionList to_disable
;
1006 const ExtensionSet
& enabled_set
= registry_
->enabled_extensions();
1007 for (ExtensionSet::const_iterator extension
= enabled_set
.begin();
1008 extension
!= enabled_set
.end(); ++extension
) {
1009 if (management_policy
->UserMayModifySettings(extension
->get(), NULL
))
1010 to_disable
.push_back(*extension
);
1012 const ExtensionSet
& terminated_set
= registry_
->terminated_extensions();
1013 for (ExtensionSet::const_iterator extension
= terminated_set
.begin();
1014 extension
!= terminated_set
.end(); ++extension
) {
1015 if (management_policy
->UserMayModifySettings(extension
->get(), NULL
))
1016 to_disable
.push_back(*extension
);
1019 for (extensions::ExtensionList::const_iterator extension
= to_disable
.begin();
1020 extension
!= to_disable
.end(); ++extension
) {
1021 if ((*extension
)->was_installed_by_default() &&
1022 extension_urls::IsWebstoreUpdateUrl(
1023 extensions::ManifestURL::GetUpdateURL(*extension
)))
1025 const std::string
& id
= (*extension
)->id();
1026 if (except_ids
.end() == std::find(except_ids
.begin(), except_ids
.end(), id
))
1027 DisableExtension(id
, extensions::Extension::DISABLE_USER_ACTION
);
1031 void ExtensionService::GrantPermissionsAndEnableExtension(
1032 const Extension
* extension
) {
1033 GrantPermissions(extension
);
1034 RecordPermissionMessagesHistogram(
1035 extension
, "Extensions.Permissions_ReEnable");
1036 extension_prefs_
->SetDidExtensionEscalatePermissions(extension
, false);
1037 EnableExtension(extension
->id());
1040 void ExtensionService::GrantPermissions(const Extension
* extension
) {
1042 extensions::PermissionsUpdater
perms_updater(profile());
1043 perms_updater
.GrantActivePermissions(extension
);
1047 void ExtensionService::RecordPermissionMessagesHistogram(
1048 const Extension
* extension
, const char* histogram
) {
1049 // Since this is called from multiple sources, and since the histogram macros
1050 // use statics, we need to manually lookup the histogram ourselves.
1051 base::HistogramBase
* counter
= base::LinearHistogram::FactoryGet(
1054 PermissionMessage::kEnumBoundary
,
1055 PermissionMessage::kEnumBoundary
+ 1,
1056 base::HistogramBase::kUmaTargetedHistogramFlag
);
1058 PermissionMessages permissions
=
1059 extensions::PermissionsData::GetPermissionMessages(extension
);
1060 if (permissions
.empty()) {
1061 counter
->Add(PermissionMessage::kNone
);
1063 for (PermissionMessages::iterator it
= permissions
.begin();
1064 it
!= permissions
.end(); ++it
)
1065 counter
->Add(it
->id());
1069 void ExtensionService::NotifyExtensionLoaded(const Extension
* extension
) {
1070 // The ChromeURLRequestContexts need to be first to know that the extension
1071 // was loaded, otherwise a race can arise where a renderer that is created
1072 // for the extension may try to load an extension URL with an extension id
1073 // that the request context doesn't yet know about. The profile is responsible
1074 // for ensuring its URLRequestContexts appropriately discover the loaded
1076 system_
->RegisterExtensionWithRequestContexts(extension
);
1078 // Tell renderers about the new extension, unless it's a theme (renderers
1079 // don't need to know about themes).
1080 if (!extension
->is_theme()) {
1081 for (content::RenderProcessHost::iterator
i(
1082 content::RenderProcessHost::AllHostsIterator());
1083 !i
.IsAtEnd(); i
.Advance()) {
1084 content::RenderProcessHost
* host
= i
.GetCurrentValue();
1085 Profile
* host_profile
=
1086 Profile::FromBrowserContext(host
->GetBrowserContext());
1087 if (host_profile
->GetOriginalProfile() ==
1088 profile_
->GetOriginalProfile()) {
1089 std::vector
<ExtensionMsg_Loaded_Params
> loaded_extensions(
1090 1, ExtensionMsg_Loaded_Params(extension
));
1092 new ExtensionMsg_Loaded(loaded_extensions
));
1097 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1100 // NOTE: It is important that this happen after notifying the renderers about
1101 // the new extensions so that if we navigate to an extension URL in
1102 // NOTIFICATION_EXTENSION_LOADED, the renderer is guaranteed to know about it.
1103 content::NotificationService::current()->Notify(
1104 chrome::NOTIFICATION_EXTENSION_LOADED
,
1105 content::Source
<Profile
>(profile_
),
1106 content::Details
<const Extension
>(extension
));
1108 // Tell a random-ass collection of other subsystems about the new extension.
1109 // TODO(aa): What should we do with all this goop? Can it move into the
1110 // relevant objects via EXTENSION_LOADED?
1112 profile_
->GetExtensionSpecialStoragePolicy()->
1113 GrantRightsForExtension(extension
);
1115 UpdateActiveExtensionsInCrashReporter();
1117 // If the extension has permission to load chrome://favicon/ resources we need
1118 // to make sure that the FaviconSource is registered with the
1119 // ChromeURLDataManager.
1120 if (extensions::PermissionsData::HasHostPermission(
1121 extension
, GURL(chrome::kChromeUIFaviconURL
))) {
1122 FaviconSource
* favicon_source
= new FaviconSource(profile_
,
1123 FaviconSource::FAVICON
);
1124 content::URLDataSource::Add(profile_
, favicon_source
);
1127 #if !defined(OS_ANDROID)
1128 // Same for chrome://theme/ resources.
1129 if (extensions::PermissionsData::HasHostPermission(
1130 extension
, GURL(chrome::kChromeUIThemeURL
))) {
1131 ThemeSource
* theme_source
= new ThemeSource(profile_
);
1132 content::URLDataSource::Add(profile_
, theme_source
);
1136 // Same for chrome://thumb/ resources.
1137 if (extensions::PermissionsData::HasHostPermission(
1138 extension
, GURL(chrome::kChromeUIThumbnailURL
))) {
1139 ThumbnailSource
* thumbnail_source
= new ThumbnailSource(profile_
, false);
1140 content::URLDataSource::Add(profile_
, thumbnail_source
);
1144 void ExtensionService::NotifyExtensionUnloaded(
1145 const Extension
* extension
,
1146 UnloadedExtensionInfo::Reason reason
) {
1147 UnloadedExtensionInfo
details(extension
, reason
);
1148 content::NotificationService::current()->Notify(
1149 chrome::NOTIFICATION_EXTENSION_UNLOADED
,
1150 content::Source
<Profile
>(profile_
),
1151 content::Details
<UnloadedExtensionInfo
>(&details
));
1153 for (content::RenderProcessHost::iterator
i(
1154 content::RenderProcessHost::AllHostsIterator());
1155 !i
.IsAtEnd(); i
.Advance()) {
1156 content::RenderProcessHost
* host
= i
.GetCurrentValue();
1157 Profile
* host_profile
=
1158 Profile::FromBrowserContext(host
->GetBrowserContext());
1159 if (host_profile
->GetOriginalProfile() == profile_
->GetOriginalProfile())
1160 host
->Send(new ExtensionMsg_Unloaded(extension
->id()));
1163 system_
->UnregisterExtensionWithRequestContexts(extension
->id(), reason
);
1164 profile_
->GetExtensionSpecialStoragePolicy()->
1165 RevokeRightsForExtension(extension
);
1167 #if defined(OS_CHROMEOS)
1168 // Revoke external file access for the extension from its file system context.
1169 // It is safe to access the extension's storage partition at this point. The
1170 // storage partition may get destroyed only after the extension gets unloaded.
1171 GURL site
= extensions::ExtensionSystem::Get(profile_
)->extension_service()->
1172 GetSiteForExtensionId(extension
->id());
1173 fileapi::FileSystemContext
* filesystem_context
=
1174 BrowserContext::GetStoragePartitionForSite(profile_
, site
)->
1175 GetFileSystemContext();
1176 if (filesystem_context
&& filesystem_context
->external_backend()) {
1177 filesystem_context
->external_backend()->
1178 RevokeAccessForExtension(extension
->id());
1182 UpdateActiveExtensionsInCrashReporter();
1185 Profile
* ExtensionService::profile() {
1189 content::BrowserContext
* ExtensionService::GetBrowserContext() const {
1190 // Implemented in the .cc file to avoid adding a profile.h dependency to
1191 // extension_service.h.
1195 extensions::ExtensionPrefs
* ExtensionService::extension_prefs() {
1196 return extension_prefs_
;
1199 const extensions::ExtensionPrefs
* ExtensionService::extension_prefs() const {
1200 return extension_prefs_
;
1203 extensions::SettingsFrontend
* ExtensionService::settings_frontend() {
1204 return settings_frontend_
.get();
1207 extensions::ContentSettingsStore
* ExtensionService::GetContentSettingsStore() {
1208 return extension_prefs()->content_settings_store();
1211 bool ExtensionService::is_ready() {
1212 return ready_
->is_signaled();
1215 base::SequencedTaskRunner
* ExtensionService::GetFileTaskRunner() {
1216 if (file_task_runner_
.get())
1217 return file_task_runner_
.get();
1219 // We should be able to interrupt any part of extension install process during
1220 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1221 // will be ignored/deleted while we will block on started tasks.
1222 std::string
token("ext_install-");
1223 token
.append(profile_
->GetPath().AsUTF8Unsafe());
1224 file_task_runner_
= BrowserThread::GetBlockingPool()->
1225 GetSequencedTaskRunnerWithShutdownBehavior(
1226 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token
),
1227 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN
);
1228 return file_task_runner_
.get();
1231 extensions::ExtensionUpdater
* ExtensionService::updater() {
1232 return updater_
.get();
1235 void ExtensionService::CheckManagementPolicy() {
1236 std::vector
<std::string
> to_unload
;
1237 std::map
<std::string
, Extension::DisableReason
> to_disable
;
1239 // Loop through the extensions list, finding extensions we need to unload or
1241 const ExtensionSet
& extensions
= registry_
->enabled_extensions();
1242 for (ExtensionSet::const_iterator iter
= extensions
.begin();
1243 iter
!= extensions
.end(); ++iter
) {
1244 const Extension
* extension
= (iter
->get());
1245 if (!system_
->management_policy()->UserMayLoad(extension
, NULL
))
1246 to_unload
.push_back(extension
->id());
1247 Extension::DisableReason disable_reason
= Extension::DISABLE_NONE
;
1248 if (system_
->management_policy()->MustRemainDisabled(
1249 extension
, &disable_reason
, NULL
))
1250 to_disable
[extension
->id()] = disable_reason
;
1253 for (size_t i
= 0; i
< to_unload
.size(); ++i
)
1254 UnloadExtension(to_unload
[i
], UnloadedExtensionInfo::REASON_DISABLE
);
1256 for (std::map
<std::string
, Extension::DisableReason
>::const_iterator i
=
1257 to_disable
.begin(); i
!= to_disable
.end(); ++i
)
1258 DisableExtension(i
->first
, i
->second
);
1261 void ExtensionService::CheckForUpdatesSoon() {
1263 if (AreAllExternalProvidersReady()) {
1264 updater()->CheckSoon();
1266 // Sync can start updating before all the external providers are ready
1267 // during startup. Start the update as soon as those providers are ready,
1269 update_once_all_providers_are_ready_
= true;
1272 LOG(WARNING
) << "CheckForUpdatesSoon() called with auto-update turned off";
1276 void ExtensionService::OnExtensionMoved(
1277 const std::string
& moved_extension_id
,
1278 const std::string
& predecessor_extension_id
,
1279 const std::string
& successor_extension_id
) {
1280 extension_prefs_
->app_sorting()->OnExtensionMoved(
1282 predecessor_extension_id
,
1283 successor_extension_id
);
1285 const Extension
* extension
= GetInstalledExtension(moved_extension_id
);
1286 if (extension_sync_service_
&& extension
) {
1287 extension_sync_service_
->SyncExtensionChangeIfNeeded(*extension
);
1291 // Some extensions will autoupdate themselves externally from Chrome. These
1292 // are typically part of some larger client application package. To support
1293 // these, the extension will register its location in the the preferences file
1294 // (and also, on Windows, in the registry) and this code will periodically
1295 // check that location for a .crx file, which it will then install locally if
1296 // a new version is available.
1297 // Errors are reported through ExtensionErrorReporter. Succcess is not
1299 void ExtensionService::CheckForExternalUpdates() {
1300 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1302 // Note that this installation is intentionally silent (since it didn't
1303 // go through the front-end). Extensions that are registered in this
1304 // way are effectively considered 'pre-bundled', and so implicitly
1305 // trusted. In general, if something has HKLM or filesystem access,
1306 // they could install an extension manually themselves anyway.
1308 // Ask each external extension provider to give us a call back for each
1309 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1310 extensions::ProviderCollection::const_iterator i
;
1311 for (i
= external_extension_providers_
.begin();
1312 i
!= external_extension_providers_
.end(); ++i
) {
1313 extensions::ExternalProviderInterface
* provider
= i
->get();
1314 provider
->VisitRegisteredExtension();
1317 // Do any required work that we would have done after completion of all
1319 if (external_extension_providers_
.empty()) {
1320 OnAllExternalProvidersReady();
1324 void ExtensionService::OnExternalProviderReady(
1325 const extensions::ExternalProviderInterface
* provider
) {
1326 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1327 CHECK(provider
->IsReady());
1329 // An external provider has finished loading. We only take action
1330 // if all of them are finished. So we check them first.
1331 if (AreAllExternalProvidersReady())
1332 OnAllExternalProvidersReady();
1335 bool ExtensionService::AreAllExternalProvidersReady() const {
1336 extensions::ProviderCollection::const_iterator i
;
1337 for (i
= external_extension_providers_
.begin();
1338 i
!= external_extension_providers_
.end(); ++i
) {
1339 if (!i
->get()->IsReady())
1345 void ExtensionService::OnAllExternalProvidersReady() {
1346 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1347 base::TimeDelta elapsed
= base::Time::Now() - profile_
->GetStartTime();
1348 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed
);
1350 // Install any pending extensions.
1351 if (update_once_all_providers_are_ready_
&& updater()) {
1352 update_once_all_providers_are_ready_
= false;
1353 extensions::ExtensionUpdater::CheckParams params
;
1354 params
.callback
= external_updates_finished_callback_
;
1355 updater()->CheckNow(params
);
1358 // Uninstall all the unclaimed extensions.
1359 scoped_ptr
<extensions::ExtensionPrefs::ExtensionsInfo
> extensions_info(
1360 extension_prefs_
->GetInstalledExtensionsInfo());
1361 for (size_t i
= 0; i
< extensions_info
->size(); ++i
) {
1362 ExtensionInfo
* info
= extensions_info
->at(i
).get();
1363 if (Manifest::IsExternalLocation(info
->extension_location
))
1364 CheckExternalUninstall(info
->extension_id
);
1366 IdentifyAlertableExtensions();
1369 void ExtensionService::IdentifyAlertableExtensions() {
1370 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1372 // Build up the lists of extensions that require acknowledgment. If this is
1373 // the first time, grandfather extensions that would have caused
1375 extension_error_ui_
.reset(ExtensionErrorUI::Create(this));
1377 bool did_show_alert
= false;
1378 if (PopulateExtensionErrorUI(extension_error_ui_
.get())) {
1379 if (!is_first_run_
) {
1380 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
1381 did_show_alert
= extension_error_ui_
->ShowErrorInBubbleView();
1383 // First run. Just acknowledge all the extensions, silently, by
1384 // shortcutting the display of the UI and going straight to the
1385 // callback for pressing the Accept button.
1386 HandleExtensionAlertAccept();
1390 UpdateExternalExtensionAlert();
1392 if (!did_show_alert
)
1393 extension_error_ui_
.reset();
1396 bool ExtensionService::PopulateExtensionErrorUI(
1397 ExtensionErrorUI
* extension_error_ui
) {
1398 bool needs_alert
= false;
1400 // Extensions that are blacklisted.
1401 const ExtensionSet
& blacklisted_set
= registry_
->blacklisted_extensions();
1402 for (ExtensionSet::const_iterator it
= blacklisted_set
.begin();
1403 it
!= blacklisted_set
.end(); ++it
) {
1404 std::string id
= (*it
)->id();
1405 if (!extension_prefs_
->IsBlacklistedExtensionAcknowledged(id
)) {
1406 extension_error_ui
->AddBlacklistedExtension(id
);
1411 const ExtensionSet
& enabled_set
= registry_
->enabled_extensions();
1412 for (ExtensionSet::const_iterator iter
= enabled_set
.begin();
1413 iter
!= enabled_set
.end(); ++iter
) {
1414 const Extension
* e
= iter
->get();
1416 // Skip for extensions that have pending updates. They will be checked again
1417 // once the pending update is finished.
1418 if (pending_extension_manager()->IsIdPending(e
->id()))
1421 // Extensions disabled by policy. Note: this no longer includes blacklisted
1422 // extensions, though we still show the same UI.
1423 if (!system_
->management_policy()->UserMayLoad(e
, NULL
)) {
1424 if (!extension_prefs_
->IsBlacklistedExtensionAcknowledged(e
->id())) {
1425 extension_error_ui
->AddBlacklistedExtension(e
->id());
1434 void ExtensionService::HandleExtensionAlertClosed() {
1435 const ExtensionIdSet
* extension_ids
=
1436 extension_error_ui_
->get_blacklisted_extension_ids();
1437 for (ExtensionIdSet::const_iterator iter
= extension_ids
->begin();
1438 iter
!= extension_ids
->end(); ++iter
) {
1439 extension_prefs_
->AcknowledgeBlacklistedExtension(*iter
);
1441 extension_error_ui_
.reset();
1444 void ExtensionService::HandleExtensionAlertAccept() {
1445 extension_error_ui_
->Close();
1448 void ExtensionService::AcknowledgeExternalExtension(const std::string
& id
) {
1449 extension_prefs_
->AcknowledgeExternalExtension(id
);
1450 UpdateExternalExtensionAlert();
1453 bool ExtensionService::IsUnacknowledgedExternalExtension(
1454 const Extension
* extension
) {
1455 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1458 return (Manifest::IsExternalLocation(extension
->location()) &&
1459 !extension_prefs_
->IsExternalExtensionAcknowledged(extension
->id()) &&
1460 !(extension_prefs_
->GetDisableReasons(extension
->id()) &
1461 Extension::DISABLE_SIDELOAD_WIPEOUT
));
1464 void ExtensionService::ReconcileKnownDisabled() {
1465 ExtensionIdSet known_disabled_ids
;
1466 if (!extension_prefs_
->GetKnownDisabled(&known_disabled_ids
)) {
1467 extension_prefs_
->SetKnownDisabled(
1468 registry_
->disabled_extensions().GetIDs());
1469 UMA_HISTOGRAM_BOOLEAN("Extensions.KnownDisabledInitialized", true);
1473 // Both |known_disabled_ids| and |extensions| are ordered (by definition
1474 // of std::map and std::set). Iterate forward over both sets in parallel
1475 // to find matching IDs and disable the corresponding extensions.
1476 const ExtensionSet
& enabled_set
= registry_
->enabled_extensions();
1477 ExtensionSet::const_iterator extensions_it
= enabled_set
.begin();
1478 ExtensionIdSet::const_iterator known_disabled_ids_it
=
1479 known_disabled_ids
.begin();
1480 int known_disabled_count
= 0;
1481 while (extensions_it
!= enabled_set
.end() &&
1482 known_disabled_ids_it
!= known_disabled_ids
.end()) {
1483 const std::string
& extension_id
= extensions_it
->get()->id();
1484 const int comparison
= extension_id
.compare(*known_disabled_ids_it
);
1485 if (comparison
< 0) {
1487 } else if (comparison
> 0) {
1488 ++known_disabled_ids_it
;
1490 ++known_disabled_count
;
1491 // Advance |extensions_it| immediately as it will be invalidated upon
1492 // disabling the extension it points to.
1494 ++known_disabled_ids_it
;
1495 DisableExtension(extension_id
, Extension::DISABLE_KNOWN_DISABLED
);
1498 UMA_HISTOGRAM_COUNTS_100("Extensions.KnownDisabledReDisabled",
1499 known_disabled_count
);
1501 // Update the list of known disabled to reflect every change to
1502 // |disabled_extensions_| from this point forward.
1503 registry_
->SetDisabledModificationCallback(
1504 base::Bind(&extensions::ExtensionPrefs::SetKnownDisabled
,
1505 base::Unretained(extension_prefs_
)));
1508 void ExtensionService::HandleExtensionAlertDetails() {
1509 extension_error_ui_
->ShowExtensions();
1510 // ShowExtensions may cause the error UI to close synchronously, e.g. if it
1511 // causes a navigation.
1512 if (extension_error_ui_
)
1513 extension_error_ui_
->Close();
1516 void ExtensionService::UpdateExternalExtensionAlert() {
1517 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1520 const Extension
* extension
= NULL
;
1521 const ExtensionSet
& disabled_extensions
= registry_
->disabled_extensions();
1522 for (ExtensionSet::const_iterator iter
= disabled_extensions
.begin();
1523 iter
!= disabled_extensions
.end(); ++iter
) {
1524 const Extension
* e
= iter
->get();
1525 if (IsUnacknowledgedExternalExtension(e
)) {
1532 if (!extensions::HasExternalInstallError(this)) {
1533 if (extension_prefs_
->IncrementAcknowledgePromptCount(extension
->id()) >
1534 kMaxExtensionAcknowledgePromptCount
) {
1535 // Stop prompting for this extension, and check if there's another
1536 // one that needs prompting.
1537 extension_prefs_
->AcknowledgeExternalExtension(extension
->id());
1538 UpdateExternalExtensionAlert();
1539 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
1540 EXTERNAL_EXTENSION_IGNORED
,
1541 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
1542 if (extensions::ManifestURL::UpdatesFromGallery(extension
)) {
1543 UMA_HISTOGRAM_ENUMERATION(
1544 "Extensions.ExternalExtensionEventWebstore",
1545 EXTERNAL_EXTENSION_IGNORED
,
1546 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
1548 UMA_HISTOGRAM_ENUMERATION(
1549 "Extensions.ExternalExtensionEventNonWebstore",
1550 EXTERNAL_EXTENSION_IGNORED
,
1551 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
1556 extension_prefs_
->SetExternalInstallFirstRun(extension
->id());
1557 // first_run is true if the extension was installed during a first run
1558 // (even if it's post-first run now).
1559 bool first_run
= extension_prefs_
->IsExternalInstallFirstRun(
1561 extensions::AddExternalInstallError(this, extension
, first_run
);
1564 extensions::RemoveExternalInstallError(this);
1568 void ExtensionService::UnloadExtension(
1569 const std::string
& extension_id
,
1570 UnloadedExtensionInfo::Reason reason
) {
1571 // Make sure the extension gets deleted after we return from this function.
1573 ExtensionRegistry::EVERYTHING
& ~ExtensionRegistry::TERMINATED
;
1574 scoped_refptr
<const Extension
> extension(
1575 registry_
->GetExtensionById(extension_id
, include_mask
));
1577 // This method can be called via PostTask, so the extension may have been
1578 // unloaded by the time this runs.
1579 if (!extension
.get()) {
1580 // In case the extension may have crashed/uninstalled. Allow the profile to
1581 // clean up its RequestContexts.
1582 system_
->UnregisterExtensionWithRequestContexts(extension_id
, reason
);
1586 // Keep information about the extension so that we can reload it later
1587 // even if it's not permanently installed.
1588 unloaded_extension_paths_
[extension
->id()] = extension
->path();
1590 // Clean up if the extension is meant to be enabled after a reload.
1591 reloading_extensions_
.erase(extension
->id());
1593 // Clean up runtime data.
1594 extension_runtime_data_
.erase(extension_id
);
1596 if (registry_
->disabled_extensions().Contains(extension
->id())) {
1597 registry_
->RemoveDisabled(extension
->id());
1598 // Make sure the profile cleans up its RequestContexts when an already
1599 // disabled extension is unloaded (since they are also tracking the disabled
1601 system_
->UnregisterExtensionWithRequestContexts(extension_id
, reason
);
1603 // Remove the extension from the enabled list.
1604 registry_
->RemoveEnabled(extension
->id());
1605 NotifyExtensionUnloaded(extension
.get(), reason
);
1608 content::NotificationService::current()->Notify(
1609 chrome::NOTIFICATION_EXTENSION_REMOVED
,
1610 content::Source
<Profile
>(profile_
),
1611 content::Details
<const Extension
>(extension
.get()));
1614 void ExtensionService::RemoveComponentExtension(
1615 const std::string
& extension_id
) {
1616 scoped_refptr
<const Extension
> extension(
1617 GetExtensionById(extension_id
, false));
1618 UnloadExtension(extension_id
, UnloadedExtensionInfo::REASON_UNINSTALL
);
1619 content::NotificationService::current()->Notify(
1620 chrome::NOTIFICATION_EXTENSION_UNINSTALLED
,
1621 content::Source
<Profile
>(profile_
),
1622 content::Details
<const Extension
>(extension
.get()));
1625 void ExtensionService::UnloadAllExtensionsForTest() {
1626 UnloadAllExtensionsInternal();
1629 void ExtensionService::ReloadExtensionsForTest() {
1630 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1631 // warning about calling test code in production.
1632 UnloadAllExtensionsInternal();
1633 component_loader_
->LoadAll();
1634 extensions::InstalledLoader(this).LoadAllExtensions();
1635 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1639 void ExtensionService::GarbageCollectExtensions() {
1640 #if defined(OS_CHROMEOS)
1641 if (disable_garbage_collection_
)
1645 if (extension_prefs_
->pref_service()->ReadOnly())
1648 bool clean_temp_dir
= true;
1650 if (pending_extension_manager()->HasPendingExtensions()) {
1651 // Don't garbage collect temp dir while there are pending installations,
1652 // which may be using the temporary installation directory. Try to garbage
1653 // collect again later.
1654 clean_temp_dir
= false;
1655 base::MessageLoop::current()->PostDelayedTask(
1657 base::Bind(&ExtensionService::GarbageCollectExtensions
, AsWeakPtr()),
1658 base::TimeDelta::FromSeconds(kGarbageCollectRetryDelay
));
1661 scoped_ptr
<extensions::ExtensionPrefs::ExtensionsInfo
> info(
1662 extension_prefs_
->GetInstalledExtensionsInfo());
1664 std::multimap
<std::string
, base::FilePath
> extension_paths
;
1665 for (size_t i
= 0; i
< info
->size(); ++i
)
1666 extension_paths
.insert(std::make_pair(info
->at(i
)->extension_id
,
1667 info
->at(i
)->extension_path
));
1669 info
= extension_prefs_
->GetAllDelayedInstallInfo();
1670 for (size_t i
= 0; i
< info
->size(); ++i
)
1671 extension_paths
.insert(std::make_pair(info
->at(i
)->extension_id
,
1672 info
->at(i
)->extension_path
));
1674 if (!GetFileTaskRunner()->PostTask(
1677 &extension_file_util::GarbageCollectExtensions
,
1685 void ExtensionService::SetReadyAndNotifyListeners() {
1687 content::NotificationService::current()->Notify(
1688 chrome::NOTIFICATION_EXTENSIONS_READY
,
1689 content::Source
<Profile
>(profile_
),
1690 content::NotificationService::NoDetails());
1693 void ExtensionService::OnLoadedInstalledExtensions() {
1697 OnBlacklistUpdated();
1700 void ExtensionService::AddExtension(const Extension
* extension
) {
1701 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1702 // default extension state to DISABLED when the --disable-extensions flag
1703 // is set (http://crbug.com/29067).
1704 if (!extensions_enabled() &&
1705 !extension
->is_theme() &&
1706 extension
->location() != Manifest::COMPONENT
&&
1707 !Manifest::IsExternalLocation(extension
->location())) {
1711 bool is_extension_upgrade
= false;
1712 bool is_extension_installed
= false;
1713 const Extension
* old
= GetInstalledExtension(extension
->id());
1715 is_extension_installed
= true;
1716 int version_compare_result
=
1717 extension
->version()->CompareTo(*(old
->version()));
1718 is_extension_upgrade
= version_compare_result
> 0;
1719 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1720 // that we aren't downgrading.
1721 if (!Manifest::IsUnpackedLocation(extension
->location()))
1722 CHECK_GE(version_compare_result
, 0);
1724 SetBeingUpgraded(extension
, is_extension_upgrade
);
1726 // The extension is now loaded, remove its data from unloaded extension map.
1727 unloaded_extension_paths_
.erase(extension
->id());
1729 // If a terminated extension is loaded, remove it from the terminated list.
1730 UntrackTerminatedExtension(extension
->id());
1732 // If the extension was disabled for a reload, then enable it.
1733 bool reloading
= reloading_extensions_
.erase(extension
->id()) > 0;
1735 // Check if the extension's privileges have changed and mark the
1736 // extension disabled if necessary.
1737 CheckPermissionsIncrease(extension
, is_extension_installed
);
1739 if (is_extension_installed
&& !reloading
) {
1740 // To upgrade an extension in place, unload the old one and then load the
1741 // new one. ReloadExtension disables the extension, which is sufficient.
1742 UnloadExtension(extension
->id(), UnloadedExtensionInfo::REASON_UPDATE
);
1745 if (extension_prefs_
->IsExtensionBlacklisted(extension
->id())) {
1746 // Only prefs is checked for the blacklist. We rely on callers to check the
1747 // blacklist before calling into here, e.g. CrxInstaller checks before
1748 // installation then threads through the install and pending install flow
1749 // of this class, and we check when loading installed extensions.
1750 registry_
->AddBlacklisted(extension
);
1751 } else if (!reloading
&&
1752 extension_prefs_
->IsExtensionDisabled(extension
->id())) {
1753 registry_
->AddDisabled(extension
);
1754 if (extension_sync_service_
)
1755 extension_sync_service_
->SyncExtensionChangeIfNeeded(*extension
);
1756 content::NotificationService::current()->Notify(
1757 chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED
,
1758 content::Source
<Profile
>(profile_
),
1759 content::Details
<const Extension
>(extension
));
1761 // Show the extension disabled error if a permissions increase was the
1762 // only reason it was disabled.
1763 if (extension_prefs_
->GetDisableReasons(extension
->id()) ==
1764 Extension::DISABLE_PERMISSIONS_INCREASE
) {
1765 extensions::AddExtensionDisabledError(this, extension
);
1767 } else if (reloading
) {
1768 // Replace the old extension with the new version.
1769 CHECK(!registry_
->AddDisabled(extension
));
1770 EnableExtension(extension
->id());
1772 // All apps that are displayed in the launcher are ordered by their ordinals
1773 // so we must ensure they have valid ordinals.
1774 if (extension
->RequiresSortOrdinal()) {
1775 if (!extension
->ShouldDisplayInNewTabPage()) {
1776 extension_prefs_
->app_sorting()->MarkExtensionAsHidden(extension
->id());
1778 extension_prefs_
->app_sorting()->EnsureValidOrdinals(
1779 extension
->id(), syncer::StringOrdinal());
1782 registry_
->AddEnabled(extension
);
1783 if (extension_sync_service_
)
1784 extension_sync_service_
->SyncExtensionChangeIfNeeded(*extension
);
1785 NotifyExtensionLoaded(extension
);
1787 SetBeingUpgraded(extension
, false);
1790 void ExtensionService::AddComponentExtension(const Extension
* extension
) {
1791 const std::string
old_version_string(
1792 extension_prefs_
->GetVersionString(extension
->id()));
1793 const Version
old_version(old_version_string
);
1795 VLOG(1) << "AddComponentExtension " << extension
->name();
1796 if (!old_version
.IsValid() || !old_version
.Equals(*extension
->version())) {
1797 VLOG(1) << "Component extension " << extension
->name() << " ("
1798 << extension
->id() << ") installing/upgrading from '"
1799 << old_version_string
<< "' to " << extension
->version()->GetString();
1801 AddNewOrUpdatedExtension(extension
,
1802 Extension::ENABLED_COMPONENT
,
1803 extensions::NOT_BLACKLISTED
,
1804 syncer::StringOrdinal());
1808 AddExtension(extension
);
1811 void ExtensionService::UpdateActivePermissions(const Extension
* extension
) {
1812 // If the extension has used the optional permissions API, it will have a
1813 // custom set of active permissions defined in the extension prefs. Here,
1814 // we update the extension's active permissions based on the prefs.
1815 scoped_refptr
<PermissionSet
> active_permissions
=
1816 extension_prefs()->GetActivePermissions(extension
->id());
1818 if (active_permissions
.get()) {
1819 // We restrict the active permissions to be within the bounds defined in the
1820 // extension's manifest.
1821 // a) active permissions must be a subset of optional + default permissions
1822 // b) active permissions must contains all default permissions
1823 scoped_refptr
<PermissionSet
> total_permissions
=
1824 PermissionSet::CreateUnion(
1825 extensions::PermissionsData::GetRequiredPermissions(extension
),
1826 extensions::PermissionsData::GetOptionalPermissions(extension
));
1828 // Make sure the active permissions contain no more than optional + default.
1829 scoped_refptr
<PermissionSet
> adjusted_active
=
1830 PermissionSet::CreateIntersection(
1831 total_permissions
.get(), active_permissions
.get());
1833 // Make sure the active permissions contain the default permissions.
1834 adjusted_active
= PermissionSet::CreateUnion(
1835 extensions::PermissionsData::GetRequiredPermissions(extension
),
1836 adjusted_active
.get());
1838 extensions::PermissionsUpdater
perms_updater(profile());
1839 perms_updater
.UpdateActivePermissions(extension
, adjusted_active
.get());
1843 void ExtensionService::CheckPermissionsIncrease(const Extension
* extension
,
1844 bool is_extension_installed
) {
1845 UpdateActivePermissions(extension
);
1847 // We keep track of all permissions the user has granted each extension.
1848 // This allows extensions to gracefully support backwards compatibility
1849 // by including unknown permissions in their manifests. When the user
1850 // installs the extension, only the recognized permissions are recorded.
1851 // When the unknown permissions become recognized (e.g., through browser
1852 // upgrade), we can prompt the user to accept these new permissions.
1853 // Extensions can also silently upgrade to less permissions, and then
1854 // silently upgrade to a version that adds these permissions back.
1856 // For example, pretend that Chrome 10 includes a permission "omnibox"
1857 // for an API that adds suggestions to the omnibox. An extension can
1858 // maintain backwards compatibility while still having "omnibox" in the
1859 // manifest. If a user installs the extension on Chrome 9, the browser
1860 // will record the permissions it recognized, not including "omnibox."
1861 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1862 // will disable the extension and prompt the user to approve the increase
1863 // in privileges. The extension could then release a new version that
1864 // removes the "omnibox" permission. When the user upgrades, Chrome will
1865 // still remember that "omnibox" had been granted, so that if the
1866 // extension once again includes "omnibox" in an upgrade, the extension
1867 // can upgrade without requiring this user's approval.
1868 int disable_reasons
= extension_prefs_
->GetDisableReasons(extension
->id());
1870 bool auto_grant_permission
=
1871 (!is_extension_installed
&& extension
->was_installed_by_default()) ||
1872 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1873 // Silently grant all active permissions to default apps only on install.
1874 // After install they should behave like other apps.
1875 // Silently grant all active permissions to apps install in kiosk mode on both
1876 // install and update.
1877 if (auto_grant_permission
)
1878 GrantPermissions(extension
);
1880 bool is_privilege_increase
= false;
1881 // We only need to compare the granted permissions to the current permissions
1882 // if the extension is not allowed to silently increase its permissions.
1883 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension
) &&
1884 !auto_grant_permission
) {
1885 // Add all the recognized permissions if the granted permissions list
1886 // hasn't been initialized yet.
1887 scoped_refptr
<PermissionSet
> granted_permissions
=
1888 extension_prefs_
->GetGrantedPermissions(extension
->id());
1889 CHECK(granted_permissions
.get());
1891 // Here, we check if an extension's privileges have increased in a manner
1892 // that requires the user's approval. This could occur because the browser
1893 // upgraded and recognized additional privileges, or an extension upgrades
1894 // to a version that requires additional privileges.
1895 is_privilege_increase
=
1896 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1897 granted_permissions
,
1898 extension
->GetActivePermissions().get(),
1899 extension
->GetType());
1902 if (is_extension_installed
) {
1903 // If the extension was already disabled, suppress any alerts for becoming
1904 // disabled on permissions increase.
1905 bool previously_disabled
=
1906 extension_prefs_
->IsExtensionDisabled(extension
->id());
1907 // Legacy disabled extensions do not have a disable reason. Infer that if
1908 // there was no permission increase, it was likely disabled by the user.
1909 if (previously_disabled
&& disable_reasons
== Extension::DISABLE_NONE
&&
1910 !extension_prefs_
->DidExtensionEscalatePermissions(extension
->id())) {
1911 disable_reasons
|= Extension::DISABLE_USER_ACTION
;
1913 // Extensions that came to us disabled from sync need a similar inference,
1914 // except based on the new version's permissions.
1915 if (previously_disabled
&&
1916 disable_reasons
== Extension::DISABLE_UNKNOWN_FROM_SYNC
) {
1917 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1918 extension_prefs_
->ClearDisableReasons(extension
->id());
1919 if (!is_privilege_increase
)
1920 disable_reasons
|= Extension::DISABLE_USER_ACTION
;
1922 disable_reasons
&= ~Extension::DISABLE_UNKNOWN_FROM_SYNC
;
1925 // Extension has changed permissions significantly. Disable it. A
1926 // notification should be sent by the caller.
1927 if (is_privilege_increase
) {
1928 disable_reasons
|= Extension::DISABLE_PERMISSIONS_INCREASE
;
1929 if (!extension_prefs_
->DidExtensionEscalatePermissions(extension
->id())) {
1930 RecordPermissionMessagesHistogram(
1931 extension
, "Extensions.Permissions_AutoDisable");
1933 extension_prefs_
->SetExtensionState(extension
->id(), Extension::DISABLED
);
1934 extension_prefs_
->SetDidExtensionEscalatePermissions(extension
, true);
1936 if (disable_reasons
!= Extension::DISABLE_NONE
) {
1937 extension_prefs_
->AddDisableReason(
1939 static_cast<Extension::DisableReason
>(disable_reasons
));
1943 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1944 std::set
<std::string
> extension_ids
;
1945 const ExtensionSet
& extensions
= registry_
->enabled_extensions();
1946 for (ExtensionSet::const_iterator iter
= extensions
.begin();
1947 iter
!= extensions
.end(); ++iter
) {
1948 const Extension
* extension
= iter
->get();
1949 if (!extension
->is_theme() && extension
->location() != Manifest::COMPONENT
)
1950 extension_ids
.insert(extension
->id());
1953 crash_keys::SetActiveExtensions(extension_ids
);
1956 ExtensionService::ImportStatus
ExtensionService::CheckImports(
1957 const extensions::Extension
* extension
,
1958 std::list
<SharedModuleInfo::ImportInfo
>* missing_modules
,
1959 std::list
<SharedModuleInfo::ImportInfo
>* outdated_modules
) {
1961 DCHECK(missing_modules
&& missing_modules
->empty());
1962 DCHECK(outdated_modules
&& outdated_modules
->empty());
1963 ImportStatus status
= IMPORT_STATUS_OK
;
1964 if (SharedModuleInfo::ImportsModules(extension
)) {
1965 const std::vector
<SharedModuleInfo::ImportInfo
>& imports
=
1966 SharedModuleInfo::GetImports(extension
);
1967 std::vector
<SharedModuleInfo::ImportInfo
>::const_iterator i
;
1968 for (i
= imports
.begin(); i
!= imports
.end(); ++i
) {
1969 Version
version_required(i
->minimum_version
);
1970 const Extension
* imported_module
=
1971 GetExtensionById(i
->extension_id
, true);
1972 if (!imported_module
) {
1973 if (extension
->from_webstore()) {
1974 status
= IMPORT_STATUS_UNSATISFIED
;
1975 missing_modules
->push_back(*i
);
1977 return IMPORT_STATUS_UNRECOVERABLE
;
1979 } else if (!SharedModuleInfo::IsSharedModule(imported_module
)) {
1980 return IMPORT_STATUS_UNRECOVERABLE
;
1981 } else if (version_required
.IsValid() &&
1982 imported_module
->version()->CompareTo(version_required
) < 0) {
1983 if (imported_module
->from_webstore()) {
1984 outdated_modules
->push_back(*i
);
1985 status
= IMPORT_STATUS_UNSATISFIED
;
1987 return IMPORT_STATUS_UNRECOVERABLE
;
1995 ExtensionService::ImportStatus
ExtensionService::SatisfyImports(
1996 const Extension
* extension
) {
1997 std::list
<SharedModuleInfo::ImportInfo
> noinstalled
;
1998 std::list
<SharedModuleInfo::ImportInfo
> outdated
;
1999 ImportStatus status
= CheckImports(extension
, &noinstalled
, &outdated
);
2000 if (status
== IMPORT_STATUS_UNRECOVERABLE
)
2002 if (status
== IMPORT_STATUS_UNSATISFIED
) {
2003 std::list
<SharedModuleInfo::ImportInfo
>::const_iterator iter
;
2004 for (iter
= noinstalled
.begin(); iter
!= noinstalled
.end(); ++iter
) {
2005 pending_extension_manager()->AddFromExtensionImport(
2007 extension_urls::GetWebstoreUpdateUrl(),
2010 CheckForUpdatesSoon();
2015 scoped_ptr
<const ExtensionSet
>
2016 ExtensionService::GetDependentExtensions(const Extension
* extension
) {
2017 scoped_ptr
<ExtensionSet
> dependents(new ExtensionSet());
2018 scoped_ptr
<ExtensionSet
> set_to_check(new ExtensionSet());
2019 if (SharedModuleInfo::IsSharedModule(extension
)) {
2020 set_to_check
->InsertAll(registry_
->disabled_extensions());
2021 set_to_check
->InsertAll(delayed_installs_
);
2022 set_to_check
->InsertAll(registry_
->enabled_extensions());
2023 for (ExtensionSet::const_iterator iter
= set_to_check
->begin();
2024 iter
!= set_to_check
->end(); ++iter
) {
2025 if (SharedModuleInfo::ImportsExtensionById(iter
->get(),
2027 dependents
->Insert(*iter
);
2031 return dependents
.PassAs
<const ExtensionSet
>();
2034 void ExtensionService::PruneSharedModulesOnUninstall(
2035 const Extension
* extension
) {
2036 if (SharedModuleInfo::ImportsModules(extension
)) {
2037 const std::vector
<SharedModuleInfo::ImportInfo
>& imports
=
2038 SharedModuleInfo::GetImports(extension
);
2039 std::vector
<SharedModuleInfo::ImportInfo
>::const_iterator i
;
2040 for (i
= imports
.begin(); i
!= imports
.end(); ++i
) {
2041 const Extension
* imported_module
=
2042 GetExtensionById(i
->extension_id
, true);
2043 if (imported_module
&& imported_module
->from_webstore()) {
2044 scoped_ptr
<const ExtensionSet
> dependents
=
2045 GetDependentExtensions(imported_module
);
2046 if (dependents
->size() == 0) {
2047 UninstallExtension(i
->extension_id
, true, NULL
);
2054 void ExtensionService::OnExtensionInstalled(
2055 const Extension
* extension
,
2056 const syncer::StringOrdinal
& page_ordinal
,
2057 bool has_requirement_errors
,
2058 extensions::BlacklistState blacklist_state
,
2059 bool wait_for_idle
) {
2060 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
2062 const std::string
& id
= extension
->id();
2063 bool initial_enable
= ShouldEnableOnInstall(extension
);
2064 const extensions::PendingExtensionInfo
* pending_extension_info
= NULL
;
2065 if ((pending_extension_info
= pending_extension_manager()->GetById(id
))) {
2066 if (!pending_extension_info
->ShouldAllowInstall(extension
)) {
2067 pending_extension_manager()->Remove(id
);
2069 LOG(WARNING
) << "ShouldAllowInstall() returned false for "
2070 << id
<< " of type " << extension
->GetType()
2071 << " and update URL "
2072 << extensions::ManifestURL::GetUpdateURL(extension
).spec()
2073 << "; not installing";
2075 // Delete the extension directory since we're not going to
2077 if (!GetFileTaskRunner()->PostTask(
2079 base::Bind(&extension_file_util::DeleteFile
,
2080 extension
->path(), true))) {
2086 pending_extension_manager()->Remove(id
);
2088 // We explicitly want to re-enable an uninstalled external
2089 // extension; if we're here, that means the user is manually
2090 // installing the extension.
2091 if (IsExternalExtensionUninstalled(id
)) {
2092 initial_enable
= true;
2096 // Unsupported requirements overrides the management policy.
2097 if (has_requirement_errors
) {
2098 initial_enable
= false;
2099 extension_prefs_
->AddDisableReason(
2100 id
, Extension::DISABLE_UNSUPPORTED_REQUIREMENT
);
2101 // If the extension was disabled because of unsupported requirements but
2102 // now supports all requirements after an update and there are not other
2103 // disable reasons, enable it.
2104 } else if (extension_prefs_
->GetDisableReasons(id
) ==
2105 Extension::DISABLE_UNSUPPORTED_REQUIREMENT
) {
2106 initial_enable
= true;
2107 extension_prefs_
->ClearDisableReasons(id
);
2110 if (blacklist_state
== extensions::BLACKLISTED_MALWARE
) {
2111 // Installation of a blacklisted extension can happen from sync, policy,
2112 // etc, where to maintain consistency we need to install it, just never
2113 // load it (see AddExtension). Usually it should be the job of callers to
2114 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
2115 // showing the install dialogue).
2116 extension_prefs()->AcknowledgeBlacklistedExtension(id
);
2117 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
2118 extension
->location(),
2119 Manifest::NUM_LOCATIONS
);
2122 if (!GetInstalledExtension(extension
->id())) {
2123 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
2124 extension
->GetType(), 100);
2125 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
2126 extension
->location(), Manifest::NUM_LOCATIONS
);
2127 RecordPermissionMessagesHistogram(
2128 extension
, "Extensions.Permissions_Install");
2130 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
2131 extension
->GetType(), 100);
2132 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
2133 extension
->location(), Manifest::NUM_LOCATIONS
);
2136 // Certain extension locations are specific enough that we can
2137 // auto-acknowledge any extension that came from one of them.
2138 if (Manifest::IsPolicyLocation(extension
->location()))
2139 AcknowledgeExternalExtension(extension
->id());
2140 const Extension::State initial_state
=
2141 initial_enable
? Extension::ENABLED
: Extension::DISABLED
;
2142 const bool blacklisted_for_malware
=
2143 blacklist_state
== extensions::BLACKLISTED_MALWARE
;
2144 if (ShouldDelayExtensionUpdate(id
, wait_for_idle
)) {
2145 extension_prefs_
->SetDelayedInstallInfo(
2148 blacklisted_for_malware
,
2149 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE
,
2152 // Transfer ownership of |extension|.
2153 delayed_installs_
.Insert(extension
);
2155 // Notify observers that app update is available.
2156 FOR_EACH_OBSERVER(extensions::UpdateObserver
, update_observers_
,
2157 OnAppUpdateAvailable(extension
));
2161 ImportStatus status
= SatisfyImports(extension
);
2162 if (installs_delayed_for_gc()) {
2163 extension_prefs_
->SetDelayedInstallInfo(
2166 blacklisted_for_malware
,
2167 extensions::ExtensionPrefs::DELAY_REASON_GC
,
2169 delayed_installs_
.Insert(extension
);
2170 } else if (status
!= IMPORT_STATUS_OK
) {
2171 if (status
== IMPORT_STATUS_UNSATISFIED
) {
2172 extension_prefs_
->SetDelayedInstallInfo(
2175 blacklisted_for_malware
,
2176 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS
,
2178 delayed_installs_
.Insert(extension
);
2181 AddNewOrUpdatedExtension(extension
,
2188 void ExtensionService::AddNewOrUpdatedExtension(
2189 const Extension
* extension
,
2190 Extension::State initial_state
,
2191 extensions::BlacklistState blacklist_state
,
2192 const syncer::StringOrdinal
& page_ordinal
) {
2193 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
2194 const bool blacklisted_for_malware
=
2195 blacklist_state
== extensions::BLACKLISTED_MALWARE
;
2196 extension_prefs_
->OnExtensionInstalled(extension
,
2198 blacklisted_for_malware
,
2200 delayed_installs_
.Remove(extension
->id());
2201 if (InstallVerifier::NeedsVerification(*extension
)) {
2202 extensions::ExtensionSystem::Get(profile_
)->install_verifier()->Add(
2203 extension
->id(), InstallVerifier::AddResultCallback());
2205 FinishInstallation(extension
);
2208 void ExtensionService::MaybeFinishDelayedInstallation(
2209 const std::string
& extension_id
) {
2210 // Check if the extension already got installed.
2211 if (!delayed_installs_
.Contains(extension_id
))
2213 extensions::ExtensionPrefs::DelayReason reason
=
2214 extension_prefs_
->GetDelayedInstallReason(extension_id
);
2216 // Check if the extension is idle. DELAY_REASON_NONE is used for older
2217 // preferences files that will not have set this field but it was previously
2218 // only used for idle updates.
2219 if ((reason
== extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE
||
2220 reason
== extensions::ExtensionPrefs::DELAY_REASON_NONE
) &&
2221 is_ready() && !extension_util::IsExtensionIdle(extension_id
, system_
))
2224 const Extension
* extension
= delayed_installs_
.GetByID(extension_id
);
2225 if (reason
== extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS
) {
2226 ImportStatus status
= SatisfyImports(extension
);
2227 if (status
!= IMPORT_STATUS_OK
) {
2228 if (status
== IMPORT_STATUS_UNRECOVERABLE
) {
2229 delayed_installs_
.Remove(extension_id
);
2230 // Make sure no version of the extension is actually installed, (i.e.,
2231 // that this delayed install was not an update).
2232 CHECK(!extension_prefs_
->GetInstalledExtensionInfo(extension_id
).get());
2233 extension_prefs_
->DeleteExtensionPrefs(extension_id
);
2239 FinishDelayedInstallation(extension_id
);
2242 void ExtensionService::FinishDelayedInstallation(
2243 const std::string
& extension_id
) {
2244 scoped_refptr
<const Extension
> extension(
2245 GetPendingExtensionUpdate(extension_id
));
2246 CHECK(extension
.get());
2247 delayed_installs_
.Remove(extension_id
);
2249 if (!extension_prefs_
->FinishDelayedInstallInfo(extension_id
))
2252 FinishInstallation(extension
.get());
2255 void ExtensionService::FinishInstallation(const Extension
* extension
) {
2256 const extensions::Extension
* existing_extension
=
2257 GetInstalledExtension(extension
->id());
2258 bool is_update
= false;
2259 std::string old_name
;
2260 if (existing_extension
) {
2262 old_name
= existing_extension
->name();
2264 extensions::InstalledExtensionInfo
details(extension
, is_update
, old_name
);
2265 content::NotificationService::current()->Notify(
2266 chrome::NOTIFICATION_EXTENSION_INSTALLED
,
2267 content::Source
<Profile
>(profile_
),
2268 content::Details
<const extensions::InstalledExtensionInfo
>(&details
));
2270 bool unacknowledged_external
= IsUnacknowledgedExternalExtension(extension
);
2272 // Unpacked extensions default to allowing file access, but if that has been
2273 // overridden, don't reset the value.
2274 if (Manifest::ShouldAlwaysAllowFileAccess(extension
->location()) &&
2275 !extension_prefs_
->HasAllowFileAccessSetting(extension
->id())) {
2276 extension_prefs_
->SetAllowFileAccess(extension
->id(), true);
2279 AddExtension(extension
);
2281 // If this is a new external extension that was disabled, alert the user
2282 // so he can reenable it. We do this last so that it has already been
2283 // added to our list of extensions.
2284 if (unacknowledged_external
&& !is_update
) {
2285 UpdateExternalExtensionAlert();
2286 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
2287 EXTERNAL_EXTENSION_INSTALLED
,
2288 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
2289 if (extensions::ManifestURL::UpdatesFromGallery(extension
)) {
2290 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore",
2291 EXTERNAL_EXTENSION_INSTALLED
,
2292 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
2294 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore",
2295 EXTERNAL_EXTENSION_INSTALLED
,
2296 EXTERNAL_EXTENSION_BUCKET_BOUNDARY
);
2300 // Check extensions that may have been delayed only because this shared module
2301 // was not available.
2302 if (SharedModuleInfo::IsSharedModule(extension
)) {
2303 MaybeFinishDelayedInstallations();
2307 const Extension
* ExtensionService::GetPendingExtensionUpdate(
2308 const std::string
& id
) const {
2309 return delayed_installs_
.GetByID(id
);
2312 void ExtensionService::TrackTerminatedExtension(const Extension
* extension
) {
2313 // No need to check for duplicates; inserting a duplicate is a no-op.
2314 registry_
->AddTerminated(make_scoped_refptr(extension
));
2315 UnloadExtension(extension
->id(), UnloadedExtensionInfo::REASON_TERMINATE
);
2318 void ExtensionService::UntrackTerminatedExtension(const std::string
& id
) {
2319 std::string lowercase_id
= StringToLowerASCII(id
);
2320 const Extension
* extension
=
2321 registry_
->terminated_extensions().GetByID(lowercase_id
);
2322 registry_
->RemoveTerminated(lowercase_id
);
2324 content::NotificationService::current()->Notify(
2325 chrome::NOTIFICATION_EXTENSION_REMOVED
,
2326 content::Source
<Profile
>(profile_
),
2327 content::Details
<const Extension
>(extension
));
2331 const Extension
* ExtensionService::GetTerminatedExtension(
2332 const std::string
& id
) const {
2333 return registry_
->GetExtensionById(id
, ExtensionRegistry::TERMINATED
);
2336 const Extension
* ExtensionService::GetInstalledExtension(
2337 const std::string
& id
) const {
2338 return registry_
->GetExtensionById(id
, ExtensionRegistry::EVERYTHING
);
2341 bool ExtensionService::ExtensionBindingsAllowed(const GURL
& url
) {
2342 // Allow bindings for all packaged extensions and component hosted apps.
2343 const Extension
* extension
=
2344 registry_
->enabled_extensions().GetExtensionOrAppByURL(url
);
2345 return extension
&& (!extension
->is_hosted_app() ||
2346 extension
->location() == Manifest::COMPONENT
);
2349 bool ExtensionService::ShouldBlockUrlInBrowserTab(GURL
* url
) {
2350 const Extension
* extension
=
2351 registry_
->enabled_extensions().GetExtensionOrAppByURL(*url
);
2352 if (extension
&& extension
->is_platform_app()) {
2353 *url
= GURL(chrome::kExtensionInvalidRequestURL
);
2360 bool ExtensionService::OnExternalExtensionFileFound(
2361 const std::string
& id
,
2362 const Version
* version
,
2363 const base::FilePath
& path
,
2364 Manifest::Location location
,
2366 bool mark_acknowledged
) {
2367 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
2368 CHECK(Extension::IdIsValid(id
));
2369 if (extension_prefs_
->IsExternalExtensionUninstalled(id
))
2372 // Before even bothering to unpack, check and see if we already have this
2373 // version. This is important because these extensions are going to get
2374 // installed on every startup.
2375 const Extension
* existing
= GetExtensionById(id
, true);
2378 // The default apps will have the location set as INTERNAL. Since older
2379 // default apps are installed as EXTERNAL, we override them. However, if the
2380 // app is already installed as internal, then do the version check.
2381 // TODO(grv) : Remove after Q1-2013.
2382 bool is_default_apps_migration
=
2383 (location
== Manifest::INTERNAL
&&
2384 Manifest::IsExternalLocation(existing
->location()));
2386 if (!is_default_apps_migration
) {
2389 switch (existing
->version()->CompareTo(*version
)) {
2390 case -1: // existing version is older, we should upgrade
2392 case 0: // existing version is same, do nothing
2394 case 1: // existing version is newer, uh-oh
2395 LOG(WARNING
) << "Found external version of extension " << id
2396 << "that is older than current version. Current version "
2397 << "is: " << existing
->VersionString() << ". New "
2398 << "version is: " << version
->GetString()
2399 << ". Keeping current version.";
2405 // If the extension is already pending, don't start an install.
2406 if (!pending_extension_manager()->AddFromExternalFile(
2407 id
, location
, *version
, creation_flags
, mark_acknowledged
)) {
2411 // no client (silent install)
2412 scoped_refptr
<CrxInstaller
> installer(CrxInstaller::CreateSilent(this));
2413 installer
->set_install_source(location
);
2414 installer
->set_expected_id(id
);
2415 installer
->set_expected_version(*version
);
2416 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE
);
2417 installer
->set_creation_flags(creation_flags
);
2418 #if defined(OS_CHROMEOS)
2419 extensions::InstallLimiter::Get(profile_
)->Add(installer
, path
);
2421 installer
->InstallCrx(path
);
2424 // Depending on the source, a new external extension might not need a user
2425 // notification on installation. For such extensions, mark them acknowledged
2426 // now to suppress the notification.
2427 if (mark_acknowledged
)
2428 AcknowledgeExternalExtension(id
);
2433 scoped_ptr
<base::DictionaryValue
> ExtensionService::GetExtensionInfo(
2434 const std::string
& extension_id
) const {
2435 scoped_ptr
<base::DictionaryValue
> dictionary(new base::DictionaryValue
);
2436 const extensions::Extension
* extension
=
2437 registry_
->enabled_extensions().GetByID(extension_id
);
2439 GURL icon
= extensions::ExtensionIconSource::GetIconURL(
2440 extension
, extension_misc::EXTENSION_ICON_SMALLISH
,
2441 ExtensionIconSet::MATCH_BIGGER
, false, NULL
);
2442 dictionary
->SetString("id", extension_id
);
2443 dictionary
->SetString("name", extension
->name());
2444 dictionary
->SetString("icon", icon
.spec());
2446 return dictionary
.Pass();
2449 void ExtensionService::ReportExtensionLoadError(
2450 const base::FilePath
& extension_path
,
2451 const std::string
&error
,
2453 content::NotificationService::current()->Notify(
2454 chrome::NOTIFICATION_EXTENSION_LOAD_ERROR
,
2455 content::Source
<Profile
>(profile_
),
2456 content::Details
<const std::string
>(&error
));
2458 std::string path_str
= base::UTF16ToUTF8(extension_path
.LossyDisplayName());
2459 base::string16 message
= base::UTF8ToUTF16(base::StringPrintf(
2460 "Could not load extension from '%s'. %s",
2461 path_str
.c_str(), error
.c_str()));
2462 ExtensionErrorReporter::GetInstance()->ReportError(message
, be_noisy
);
2465 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2466 extensions::ExtensionHost
* host
) {
2467 OrphanedDevTools::iterator iter
=
2468 orphaned_dev_tools_
.find(host
->extension_id());
2469 if (iter
== orphaned_dev_tools_
.end())
2472 iter
->second
->ConnectRenderViewHost(host
->render_view_host());
2473 orphaned_dev_tools_
.erase(iter
);
2476 void ExtensionService::Observe(int type
,
2477 const content::NotificationSource
& source
,
2478 const content::NotificationDetails
& details
) {
2480 case chrome::NOTIFICATION_APP_TERMINATING
:
2481 // Shutdown has started. Don't start any more extension installs.
2482 // (We cannot use ExtensionService::Shutdown() for this because it
2483 // happens too late in browser teardown.)
2484 browser_terminating_
= true;
2486 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
: {
2488 content::Source
<Profile
>(source
).ptr()->GetOriginalProfile()) {
2492 extensions::ExtensionHost
* host
=
2493 content::Details
<extensions::ExtensionHost
>(details
).ptr();
2495 // Mark the extension as terminated and Unload it. We want it to
2496 // be in a consistent state: either fully working or not loaded
2497 // at all, but never half-crashed. We do it in a PostTask so
2498 // that other handlers of this notification will still have
2499 // access to the Extension and ExtensionHost.
2500 base::MessageLoop::current()->PostTask(
2503 &ExtensionService::TrackTerminatedExtension
,
2505 host
->extension()));
2508 case content::NOTIFICATION_RENDERER_PROCESS_CREATED
: {
2509 // TODO(jamescook): Extract this block of code to src/extensions so it
2510 // can be shared with app_shell.
2511 content::RenderProcessHost
* process
=
2512 content::Source
<content::RenderProcessHost
>(source
).ptr();
2513 Profile
* host_profile
=
2514 Profile::FromBrowserContext(process
->GetBrowserContext());
2515 if (!profile_
->IsSameProfile(host_profile
->GetOriginalProfile()))
2518 // Extensions need to know the channel for API restrictions.
2519 process
->Send(new ExtensionMsg_SetChannel(
2520 extensions::GetCurrentChannel()));
2522 // Platform apps need to know the system font.
2523 scoped_ptr
<base::DictionaryValue
> fonts(new base::DictionaryValue
);
2524 webui::SetFontAndTextDirection(fonts
.get());
2525 std::string font_family
, font_size
;
2526 fonts
->GetString("fontfamily", &font_family
);
2527 fonts
->GetString("fontsize", &font_size
);
2528 process
->Send(new ExtensionMsg_SetSystemFont(
2529 font_family
, font_size
));
2531 // Valid extension function names, used to setup bindings in renderer.
2532 std::vector
<std::string
> function_names
;
2533 ExtensionFunctionDispatcher::GetAllFunctionNames(&function_names
);
2534 process
->Send(new ExtensionMsg_SetFunctionNames(function_names
));
2536 // Scripting whitelist. This is modified by tests and must be communicated
2538 process
->Send(new ExtensionMsg_SetScriptingWhitelist(
2539 extensions::ExtensionsClient::Get()->GetScriptingWhitelist()));
2541 // Loaded extensions.
2542 std::vector
<ExtensionMsg_Loaded_Params
> loaded_extensions
;
2543 const ExtensionSet
& extensions
= registry_
->enabled_extensions();
2544 for (ExtensionSet::const_iterator iter
= extensions
.begin();
2545 iter
!= extensions
.end(); ++iter
) {
2546 // Renderers don't need to know about themes.
2547 if (!(*iter
)->is_theme())
2548 loaded_extensions
.push_back(ExtensionMsg_Loaded_Params(iter
->get()));
2550 process
->Send(new ExtensionMsg_Loaded(loaded_extensions
));
2553 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED
: {
2554 content::RenderProcessHost
* process
=
2555 content::Source
<content::RenderProcessHost
>(source
).ptr();
2556 Profile
* host_profile
=
2557 Profile::FromBrowserContext(process
->GetBrowserContext());
2558 if (!profile_
->IsSameProfile(host_profile
->GetOriginalProfile()))
2561 extensions::ProcessMap
* process_map
=
2562 extensions::ProcessMap::Get(profile_
);
2563 if (process_map
->Contains(process
->GetID())) {
2564 // An extension process was terminated, this might have resulted in an
2565 // app or extension becoming idle.
2566 std::set
<std::string
> extension_ids
=
2567 process_map
->GetExtensionsInProcess(process
->GetID());
2568 for (std::set
<std::string
>::const_iterator it
= extension_ids
.begin();
2569 it
!= extension_ids
.end(); ++it
) {
2570 if (delayed_installs_
.Contains(*it
)) {
2571 base::MessageLoop::current()->PostDelayedTask(
2573 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation
,
2575 base::TimeDelta::FromSeconds(kUpdateIdleDelay
));
2580 process_map
->RemoveAllFromProcess(process
->GetID());
2581 BrowserThread::PostTask(
2584 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess
,
2585 system_
->info_map(),
2589 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED
: {
2590 // Notify observers that chrome update is available.
2591 FOR_EACH_OBSERVER(extensions::UpdateObserver
, update_observers_
,
2592 OnChromeUpdateAvailable());
2597 NOTREACHED() << "Unexpected notification type.";
2601 void ExtensionService::OnExtensionInstallPrefChanged() {
2602 IdentifyAlertableExtensions();
2603 CheckManagementPolicy();
2606 bool ExtensionService::HasApps() const {
2607 return !GetAppIds().empty();
2610 ExtensionIdSet
ExtensionService::GetAppIds() const {
2611 ExtensionIdSet result
;
2612 const ExtensionSet
& extensions
= registry_
->enabled_extensions();
2613 for (ExtensionSet::const_iterator it
= extensions
.begin();
2614 it
!= extensions
.end(); ++it
) {
2615 if ((*it
)->is_app() && (*it
)->location() != Manifest::COMPONENT
)
2616 result
.insert((*it
)->id());
2622 bool ExtensionService::IsBackgroundPageReady(const Extension
* extension
) const {
2623 if (!extensions::BackgroundInfo::HasPersistentBackgroundPage(extension
))
2625 ExtensionRuntimeDataMap::const_iterator it
=
2626 extension_runtime_data_
.find(extension
->id());
2627 return it
== extension_runtime_data_
.end() ? false :
2628 it
->second
.background_page_ready
;
2631 void ExtensionService::SetBackgroundPageReady(const Extension
* extension
) {
2632 DCHECK(extensions::BackgroundInfo::HasBackgroundPage(extension
));
2633 extension_runtime_data_
[extension
->id()].background_page_ready
= true;
2636 bool ExtensionService::IsBeingUpgraded(const Extension
* extension
) const {
2637 ExtensionRuntimeDataMap::const_iterator it
=
2638 extension_runtime_data_
.find(extension
->id());
2639 return it
== extension_runtime_data_
.end() ? false :
2640 it
->second
.being_upgraded
;
2643 void ExtensionService::SetBeingUpgraded(const Extension
* extension
,
2645 extension_runtime_data_
[extension
->id()].being_upgraded
= value
;
2648 bool ExtensionService::IsBeingReloaded(
2649 const std::string
& extension_id
) const {
2650 return ContainsKey(extensions_being_reloaded_
, extension_id
);
2653 void ExtensionService::SetBeingReloaded(const std::string
& extension_id
,
2654 bool isBeingReloaded
) {
2655 if (isBeingReloaded
)
2656 extensions_being_reloaded_
.insert(extension_id
);
2658 extensions_being_reloaded_
.erase(extension_id
);
2661 bool ExtensionService::HasUsedWebRequest(const Extension
* extension
) const {
2662 ExtensionRuntimeDataMap::const_iterator it
=
2663 extension_runtime_data_
.find(extension
->id());
2664 return it
== extension_runtime_data_
.end() ? false :
2665 it
->second
.has_used_webrequest
;
2668 void ExtensionService::SetHasUsedWebRequest(const Extension
* extension
,
2670 extension_runtime_data_
[extension
->id()].has_used_webrequest
= value
;
2673 bool ExtensionService::ShouldEnableOnInstall(const Extension
* extension
) {
2674 // Extensions installed by policy can't be disabled. So even if a previous
2675 // installation disabled the extension, make sure it is now enabled.
2676 if (system_
->management_policy()->MustRemainEnabled(extension
, NULL
))
2679 if (extension_prefs_
->IsExtensionDisabled(extension
->id()))
2682 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2683 // External extensions are initially disabled. We prompt the user before
2684 // enabling them. Hosted apps are excepted because they are not dangerous
2685 // (they need to be launched by the user anyway).
2686 if (extension
->GetType() != Manifest::TYPE_HOSTED_APP
&&
2687 Manifest::IsExternalLocation(extension
->location()) &&
2688 !extension_prefs_
->IsExternalExtensionAcknowledged(extension
->id())) {
2696 bool ExtensionService::ShouldDelayExtensionUpdate(
2697 const std::string
& extension_id
,
2698 bool wait_for_idle
) const {
2699 const char kOnUpdateAvailableEvent
[] = "runtime.onUpdateAvailable";
2701 // If delayed updates are globally disabled, or just for this extension,
2703 if (!install_updates_when_idle_
|| !wait_for_idle
)
2706 const Extension
* old
= GetInstalledExtension(extension_id
);
2707 // If there is no old extension, this is not an update, so don't delay.
2711 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old
)) {
2712 // Delay installation if the extension listens for the onUpdateAvailable
2714 return system_
->event_router()->ExtensionHasEventListener(
2715 extension_id
, kOnUpdateAvailableEvent
);
2717 // Delay installation if the extension is not idle.
2718 return !extension_util::IsExtensionIdle(extension_id
, system_
);
2722 void ExtensionService::GarbageCollectIsolatedStorage() {
2723 scoped_ptr
<base::hash_set
<base::FilePath
> > active_paths(
2724 new base::hash_set
<base::FilePath
>());
2725 const ExtensionSet
& extensions
= registry_
->enabled_extensions();
2726 for (ExtensionSet::const_iterator it
= extensions
.begin();
2727 it
!= extensions
.end(); ++it
) {
2728 if (extensions::AppIsolationInfo::HasIsolatedStorage(it
->get())) {
2729 active_paths
->insert(BrowserContext::GetStoragePartitionForSite(
2730 profile_
, GetSiteForExtensionId((*it
)->id()))->GetPath());
2734 DCHECK(!installs_delayed_for_gc());
2735 set_installs_delayed_for_gc(true);
2736 BrowserContext::GarbageCollectStoragePartitions(
2737 profile_
, active_paths
.Pass(),
2738 base::Bind(&ExtensionService::OnGarbageCollectIsolatedStorageFinished
,
2742 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2743 set_installs_delayed_for_gc(false);
2744 MaybeFinishDelayedInstallations();
2747 void ExtensionService::MaybeFinishDelayedInstallations() {
2748 std::vector
<std::string
> to_be_installed
;
2749 for (ExtensionSet::const_iterator it
= delayed_installs_
.begin();
2750 it
!= delayed_installs_
.end();
2752 to_be_installed
.push_back((*it
)->id());
2754 for (std::vector
<std::string
>::const_iterator it
= to_be_installed
.begin();
2755 it
!= to_be_installed
.end();
2757 MaybeFinishDelayedInstallation(*it
);
2761 void ExtensionService::OnBlacklistUpdated() {
2762 blacklist_
->GetMalwareIDs(
2763 GenerateInstalledExtensionsSet()->GetIDs(),
2764 base::Bind(&ExtensionService::ManageBlacklist
, AsWeakPtr()));
2767 void ExtensionService::ManageBlacklist(const std::set
<std::string
>& updated
) {
2768 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
2770 std::set
<std::string
> before
= registry_
->blacklisted_extensions().GetIDs();
2771 std::set
<std::string
> no_longer_blacklisted
=
2772 base::STLSetDifference
<std::set
<std::string
> >(before
, updated
);
2773 std::set
<std::string
> not_yet_blacklisted
=
2774 base::STLSetDifference
<std::set
<std::string
> >(updated
, before
);
2776 for (std::set
<std::string
>::iterator it
= no_longer_blacklisted
.begin();
2777 it
!= no_longer_blacklisted
.end(); ++it
) {
2778 scoped_refptr
<const Extension
> extension
=
2779 registry_
->blacklisted_extensions().GetByID(*it
);
2780 if (!extension
.get()) {
2781 NOTREACHED() << "Extension " << *it
<< " no longer blacklisted, "
2782 << "but it was never blacklisted.";
2785 registry_
->RemoveBlacklisted(*it
);
2786 extension_prefs_
->SetExtensionBlacklisted(extension
->id(), false);
2787 AddExtension(extension
.get());
2788 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2789 extension
->location(),
2790 Manifest::NUM_LOCATIONS
);
2793 for (std::set
<std::string
>::iterator it
= not_yet_blacklisted
.begin();
2794 it
!= not_yet_blacklisted
.end(); ++it
) {
2795 scoped_refptr
<const Extension
> extension
= GetInstalledExtension(*it
);
2796 if (!extension
.get()) {
2797 NOTREACHED() << "Extension " << *it
<< " needs to be "
2798 << "blacklisted, but it's not installed.";
2801 registry_
->AddBlacklisted(extension
);
2802 extension_prefs_
->SetExtensionBlacklisted(extension
->id(), true);
2803 UnloadExtension(*it
, UnloadedExtensionInfo::REASON_BLACKLIST
);
2804 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2805 extension
->location(), Manifest::NUM_LOCATIONS
);
2808 IdentifyAlertableExtensions();
2811 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver
* observer
) {
2812 update_observers_
.AddObserver(observer
);
2815 void ExtensionService::RemoveUpdateObserver(
2816 extensions::UpdateObserver
* observer
) {
2817 update_observers_
.RemoveObserver(observer
);
2820 // Used only by test code.
2821 void ExtensionService::UnloadAllExtensionsInternal() {
2822 profile_
->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2824 registry_
->ClearAll();
2825 extension_runtime_data_
.clear();
2827 // TODO(erikkay) should there be a notification for this? We can't use
2828 // EXTENSION_UNLOADED since that implies that the extension has been disabled