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