Update broken references to image assets
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blob96e5fbff576f359e088cb9e4f2ed6823668c5b42
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 // Don't sync the uninstall if we're going to reinstall the extension
767 // momentarily.
768 if (reason != extensions::UNINSTALL_REASON_REINSTALL) {
769 ExtensionSyncService::Get(profile_)->SyncUninstallExtension(*extension);
772 delayed_installs_.Remove(extension->id());
774 extension_prefs_->OnExtensionUninstalled(
775 extension->id(), extension->location(), external_uninstall);
777 // Track the uninstallation.
778 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
780 return true;
783 // static
784 void ExtensionService::UninstallExtensionOnFileThread(
785 const std::string& id,
786 Profile* profile,
787 const base::FilePath& install_dir,
788 const base::FilePath& extension_path) {
789 extensions::ExtensionAssetsManager* assets_manager =
790 extensions::ExtensionAssetsManager::GetInstance();
791 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
794 bool ExtensionService::IsExtensionEnabled(
795 const std::string& extension_id) const {
796 if (registry_->enabled_extensions().Contains(extension_id) ||
797 registry_->terminated_extensions().Contains(extension_id)) {
798 return true;
801 if (registry_->disabled_extensions().Contains(extension_id) ||
802 registry_->blacklisted_extensions().Contains(extension_id) ||
803 registry_->blocked_extensions().Contains(extension_id)) {
804 return false;
807 // Blocked extensions aren't marked as such in prefs, thus if
808 // |block_extensions_| is true then CanBlockExtension() must be called with an
809 // Extension object. If the |extension_id| is not loaded, assume not enabled.
810 if (block_extensions_) {
811 const Extension* extension = GetInstalledExtension(extension_id);
812 if (!extension || CanBlockExtension(extension))
813 return false;
816 // If the extension hasn't been loaded yet, check the prefs for it. Assume
817 // enabled unless otherwise noted.
818 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
819 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
820 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
823 void ExtensionService::EnableExtension(const std::string& extension_id) {
824 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
826 if (IsExtensionEnabled(extension_id))
827 return;
828 const Extension* extension =
829 registry_->disabled_extensions().GetByID(extension_id);
831 ManagementPolicy* policy = system_->management_policy();
832 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
833 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
834 return;
837 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
838 extension_prefs_->ClearDisableReasons(extension_id);
840 // This can happen if sync enables an extension that is not
841 // installed yet.
842 if (!extension)
843 return;
845 // Move it over to the enabled list.
846 registry_->AddEnabled(make_scoped_refptr(extension));
847 registry_->RemoveDisabled(extension->id());
849 NotifyExtensionLoaded(extension);
851 // Notify listeners that the extension was enabled.
852 content::NotificationService::current()->Notify(
853 extensions::NOTIFICATION_EXTENSION_ENABLED,
854 content::Source<Profile>(profile_),
855 content::Details<const Extension>(extension));
857 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(*extension);
860 void ExtensionService::DisableExtension(const std::string& extension_id,
861 int disable_reasons) {
862 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
864 // The extension may have been disabled already. Just add a disable reason.
865 if (!IsExtensionEnabled(extension_id)) {
866 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
867 return;
870 const Extension* extension = GetInstalledExtension(extension_id);
871 // |extension| can be NULL if sync disables an extension that is not
872 // installed yet.
873 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
874 // can be uninstalled by the browser if the user sets extension-specific
875 // preferences.
876 if (extension &&
877 !(disable_reasons & Extension::DISABLE_RELOAD) &&
878 !(disable_reasons & Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) &&
879 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
880 extension->location() != Manifest::EXTERNAL_COMPONENT) {
881 return;
884 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
885 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
887 int include_mask =
888 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
889 extension = registry_->GetExtensionById(extension_id, include_mask);
890 if (!extension)
891 return;
893 // The extension is either enabled or terminated.
894 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
895 registry_->terminated_extensions().Contains(extension->id()));
897 // Move it over to the disabled list. Don't send a second unload notification
898 // for terminated extensions being disabled.
899 registry_->AddDisabled(make_scoped_refptr(extension));
900 if (registry_->enabled_extensions().Contains(extension->id())) {
901 registry_->RemoveEnabled(extension->id());
902 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
903 } else {
904 registry_->RemoveTerminated(extension->id());
907 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(*extension);
910 void ExtensionService::DisableUserExtensions(
911 const std::vector<std::string>& except_ids) {
912 extensions::ManagementPolicy* management_policy =
913 system_->management_policy();
914 extensions::ExtensionList to_disable;
916 const ExtensionSet& enabled_set = registry_->enabled_extensions();
917 for (ExtensionSet::const_iterator extension = enabled_set.begin();
918 extension != enabled_set.end(); ++extension) {
919 if (management_policy->UserMayModifySettings(extension->get(), NULL))
920 to_disable.push_back(*extension);
922 const ExtensionSet& terminated_set = registry_->terminated_extensions();
923 for (ExtensionSet::const_iterator extension = terminated_set.begin();
924 extension != terminated_set.end(); ++extension) {
925 if (management_policy->UserMayModifySettings(extension->get(), NULL))
926 to_disable.push_back(*extension);
929 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
930 extension != to_disable.end(); ++extension) {
931 if ((*extension)->was_installed_by_default() &&
932 extension_urls::IsWebstoreUpdateUrl(
933 extensions::ManifestURL::GetUpdateURL(extension->get())))
934 continue;
935 const std::string& id = (*extension)->id();
936 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
937 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
941 // Extensions that are not locked, components or forced by policy should be
942 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
943 // extensions are now considered both blacklisted and locked.
944 void ExtensionService::BlockAllExtensions() {
945 if (block_extensions_)
946 return;
947 block_extensions_ = true;
949 // Blacklisted extensions are already unloaded, need not be blocked.
950 scoped_ptr<ExtensionSet> extensions =
951 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED |
952 ExtensionRegistry::DISABLED |
953 ExtensionRegistry::TERMINATED);
955 for (const scoped_refptr<const Extension>& extension : *extensions) {
956 const std::string& id = extension->id();
958 if (!CanBlockExtension(extension.get()))
959 continue;
961 registry_->RemoveEnabled(id);
962 registry_->RemoveDisabled(id);
963 registry_->RemoveTerminated(id);
965 registry_->AddBlocked(extension.get());
966 UnloadExtension(id, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL);
970 // All locked extensions should revert to being either enabled or disabled
971 // as appropriate.
972 void ExtensionService::UnblockAllExtensions() {
973 block_extensions_ = false;
974 scoped_ptr<ExtensionSet> to_unblock =
975 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED);
977 for (const scoped_refptr<const Extension>& extension : *to_unblock) {
978 registry_->RemoveBlocked(extension->id());
979 AddExtension(extension.get());
983 void ExtensionService::GrantPermissionsAndEnableExtension(
984 const Extension* extension) {
985 GrantPermissions(extension);
986 RecordPermissionMessagesHistogram(extension, "ReEnable");
987 EnableExtension(extension->id());
990 void ExtensionService::GrantPermissions(const Extension* extension) {
991 CHECK(extension);
992 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
995 // static
996 void ExtensionService::RecordPermissionMessagesHistogram(
997 const Extension* extension, const char* histogram) {
998 // Since this is called from multiple sources, and since the histogram macros
999 // use statics, we need to manually lookup the histogram ourselves.
1000 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
1001 base::StringPrintf("Extensions.Permissions_%s3", histogram),
1003 APIPermission::kEnumBoundary,
1004 APIPermission::kEnumBoundary + 1,
1005 base::HistogramBase::kUmaTargetedHistogramFlag);
1007 base::HistogramBase* counter_has_any = base::BooleanHistogram::FactoryGet(
1008 base::StringPrintf("Extensions.HasPermissions_%s3", histogram),
1009 base::HistogramBase::kUmaTargetedHistogramFlag);
1011 PermissionIDSet permissions =
1012 extensions::PermissionMessageProvider::Get()->GetAllPermissionIDs(
1013 extension->permissions_data()->active_permissions().get(),
1014 extension->GetType());
1015 counter_has_any->AddBoolean(!permissions.empty());
1016 for (const PermissionID& id : permissions)
1017 counter->Add(id.id());
1020 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1021 // The URLRequestContexts need to be first to know that the extension
1022 // was loaded, otherwise a race can arise where a renderer that is created
1023 // for the extension may try to load an extension URL with an extension id
1024 // that the request context doesn't yet know about. The profile is responsible
1025 // for ensuring its URLRequestContexts appropriately discover the loaded
1026 // extension.
1027 system_->RegisterExtensionWithRequestContexts(
1028 extension,
1029 base::Bind(&ExtensionService::OnExtensionRegisteredWithRequestContexts,
1030 AsWeakPtr(), make_scoped_refptr(extension)));
1032 // Tell renderers about the new extension, unless it's a theme (renderers
1033 // don't need to know about themes).
1034 if (!extension->is_theme()) {
1035 for (content::RenderProcessHost::iterator i(
1036 content::RenderProcessHost::AllHostsIterator());
1037 !i.IsAtEnd(); i.Advance()) {
1038 content::RenderProcessHost* host = i.GetCurrentValue();
1039 Profile* host_profile =
1040 Profile::FromBrowserContext(host->GetBrowserContext());
1041 if (host_profile->GetOriginalProfile() ==
1042 profile_->GetOriginalProfile()) {
1043 // We don't need to include tab permisisons here, since the extension
1044 // was just loaded.
1045 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1046 1, ExtensionMsg_Loaded_Params(extension,
1047 false /* no tab permissions */));
1048 host->Send(
1049 new ExtensionMsg_Loaded(loaded_extensions));
1054 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1055 // extension.
1057 // NOTE: It is important that this happen after notifying the renderers about
1058 // the new extensions so that if we navigate to an extension URL in
1059 // ExtensionRegistryObserver::OnLoaded or
1060 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1061 // renderer is guaranteed to know about it.
1062 registry_->TriggerOnLoaded(extension);
1064 content::NotificationService::current()->Notify(
1065 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1066 content::Source<Profile>(profile_),
1067 content::Details<const Extension>(extension));
1069 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1070 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1071 profile_->GetExtensionSpecialStoragePolicy()->
1072 GrantRightsForExtension(extension, profile_);
1074 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1075 // work properly multi-profile. Besides which, it should be using
1076 // ExtensionRegistryObserver. See http://crbug.com/355029.
1077 UpdateActiveExtensionsInCrashReporter();
1079 const extensions::PermissionsData* permissions_data =
1080 extension->permissions_data();
1082 // If the extension has permission to load chrome://favicon/ resources we need
1083 // to make sure that the FaviconSource is registered with the
1084 // ChromeURLDataManager.
1085 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1086 FaviconSource* favicon_source = new FaviconSource(profile_,
1087 FaviconSource::FAVICON);
1088 content::URLDataSource::Add(profile_, favicon_source);
1091 // Same for chrome://theme/ resources.
1092 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1093 ThemeSource* theme_source = new ThemeSource(profile_);
1094 content::URLDataSource::Add(profile_, theme_source);
1097 // Same for chrome://thumb/ resources.
1098 if (permissions_data->HasHostPermission(
1099 GURL(chrome::kChromeUIThumbnailURL))) {
1100 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1101 content::URLDataSource::Add(profile_, thumbnail_source);
1105 void ExtensionService::OnExtensionRegisteredWithRequestContexts(
1106 scoped_refptr<const extensions::Extension> extension) {
1107 registry_->AddReady(extension);
1108 if (registry_->enabled_extensions().Contains(extension->id()))
1109 registry_->TriggerOnReady(extension.get());
1112 void ExtensionService::NotifyExtensionUnloaded(
1113 const Extension* extension,
1114 UnloadedExtensionInfo::Reason reason) {
1115 UnloadedExtensionInfo details(extension, reason);
1117 registry_->TriggerOnUnloaded(extension, reason);
1119 content::NotificationService::current()->Notify(
1120 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1121 content::Source<Profile>(profile_),
1122 content::Details<UnloadedExtensionInfo>(&details));
1124 for (content::RenderProcessHost::iterator i(
1125 content::RenderProcessHost::AllHostsIterator());
1126 !i.IsAtEnd(); i.Advance()) {
1127 content::RenderProcessHost* host = i.GetCurrentValue();
1128 Profile* host_profile =
1129 Profile::FromBrowserContext(host->GetBrowserContext());
1130 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1131 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1134 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1136 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1137 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1138 profile_->GetExtensionSpecialStoragePolicy()->
1139 RevokeRightsForExtension(extension);
1141 #if defined(OS_CHROMEOS)
1142 // Revoke external file access for the extension from its file system context.
1143 // It is safe to access the extension's storage partition at this point. The
1144 // storage partition may get destroyed only after the extension gets unloaded.
1145 GURL site =
1146 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1147 storage::FileSystemContext* filesystem_context =
1148 BrowserContext::GetStoragePartitionForSite(profile_, site)
1149 ->GetFileSystemContext();
1150 if (filesystem_context && filesystem_context->external_backend()) {
1151 filesystem_context->external_backend()->
1152 RevokeAccessForExtension(extension->id());
1154 #endif
1156 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1157 // work properly multi-profile. Besides which, it should be using
1158 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1159 UpdateActiveExtensionsInCrashReporter();
1162 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1163 // Implemented in the .cc file to avoid adding a profile.h dependency to
1164 // extension_service.h.
1165 return profile_;
1168 bool ExtensionService::is_ready() {
1169 return ready_->is_signaled();
1172 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1173 if (file_task_runner_.get())
1174 return file_task_runner_.get();
1176 // We should be able to interrupt any part of extension install process during
1177 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1178 // will be ignored/deleted while we will block on started tasks.
1179 std::string token("ext_install-");
1180 token.append(profile_->GetPath().AsUTF8Unsafe());
1181 file_task_runner_ = BrowserThread::GetBlockingPool()->
1182 GetSequencedTaskRunnerWithShutdownBehavior(
1183 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1184 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1185 return file_task_runner_.get();
1188 void ExtensionService::CheckManagementPolicy() {
1189 std::vector<std::string> to_unload;
1190 std::map<std::string, Extension::DisableReason> to_disable;
1191 std::vector<std::string> to_enable;
1193 // Loop through the extensions list, finding extensions we need to unload or
1194 // disable.
1195 for (scoped_refptr<const Extension> extension :
1196 registry_->enabled_extensions()) {
1197 if (!system_->management_policy()->UserMayLoad(extension.get(), nullptr))
1198 to_unload.push_back(extension->id());
1199 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1200 if (system_->management_policy()->MustRemainDisabled(
1201 extension.get(), &disable_reason, nullptr))
1202 to_disable[extension->id()] = disable_reason;
1205 extensions::ExtensionManagement* management =
1206 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1208 // Loop through the disabled extension list, find extensions to re-enable
1209 // automatically. These extensions are exclusive from the |to_disable| and
1210 // |to_unload| lists constructed above, since disabled_extensions() and
1211 // enabled_extensions() are supposed to be mutually exclusive.
1212 for (scoped_refptr<const Extension> extension :
1213 registry_->disabled_extensions()) {
1214 // Find all disabled extensions disabled due to minimum version requirement,
1215 // but now satisfying it.
1216 if (management->CheckMinimumVersion(extension.get(), nullptr) &&
1217 extension_prefs_->HasDisableReason(
1218 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY)) {
1219 // Is DISABLE_UPDATE_REQUIRED_BY_POLICY the *only* reason?
1220 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1221 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1222 // We need to enable those disabled *only* due to minimum version
1223 // requirement.
1224 to_enable.push_back(extension->id());
1226 extension_prefs_->RemoveDisableReason(
1227 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1231 for (const std::string& id : to_unload)
1232 UnloadExtension(id, UnloadedExtensionInfo::REASON_DISABLE);
1234 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1235 to_disable.begin(); i != to_disable.end(); ++i)
1236 DisableExtension(i->first, i->second);
1238 // No extension is getting re-enabled here after disabling/unloading
1239 // because to_enable is mutually exclusive to to_disable + to_unload.
1240 for (const std::string& id : to_enable)
1241 EnableExtension(id);
1243 if (updater_.get()) {
1244 // Find all extensions disabled due to minimum version requirement from
1245 // policy (including the ones that got disabled just now), and check
1246 // for update.
1247 extensions::ExtensionUpdater::CheckParams to_recheck;
1248 for (scoped_refptr<const Extension> extension :
1249 registry_->disabled_extensions()) {
1250 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1251 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1252 // The minimum version check is the only thing holding this extension
1253 // back, so check if it can be updated to fix that.
1254 to_recheck.ids.push_back(extension->id());
1257 if (!to_recheck.ids.empty())
1258 updater_->CheckNow(to_recheck);
1262 void ExtensionService::CheckForUpdatesSoon() {
1263 // This can legitimately happen in unit tests.
1264 if (!updater_.get())
1265 return;
1267 if (AreAllExternalProvidersReady()) {
1268 updater_->CheckSoon();
1269 } else {
1270 // Sync can start updating before all the external providers are ready
1271 // during startup. Start the update as soon as those providers are ready,
1272 // but not before.
1273 update_once_all_providers_are_ready_ = true;
1277 // Some extensions will autoupdate themselves externally from Chrome. These
1278 // are typically part of some larger client application package. To support
1279 // these, the extension will register its location in the preferences file
1280 // (and also, on Windows, in the registry) and this code will periodically
1281 // check that location for a .crx file, which it will then install locally if
1282 // a new version is available.
1283 // Errors are reported through ExtensionErrorReporter. Success is not
1284 // reported.
1285 void ExtensionService::CheckForExternalUpdates() {
1286 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1287 TRACE_EVENT0("browser,startup", "ExtensionService::CheckForExternalUpdates");
1288 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.CheckForExternalUpdatesTime");
1290 // Note that this installation is intentionally silent (since it didn't
1291 // go through the front-end). Extensions that are registered in this
1292 // way are effectively considered 'pre-bundled', and so implicitly
1293 // trusted. In general, if something has HKLM or filesystem access,
1294 // they could install an extension manually themselves anyway.
1296 // Ask each external extension provider to give us a call back for each
1297 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1298 extensions::ProviderCollection::const_iterator i;
1299 for (i = external_extension_providers_.begin();
1300 i != external_extension_providers_.end(); ++i) {
1301 extensions::ExternalProviderInterface* provider = i->get();
1302 provider->VisitRegisteredExtension();
1305 // Do any required work that we would have done after completion of all
1306 // providers.
1307 if (external_extension_providers_.empty())
1308 OnAllExternalProvidersReady();
1311 void ExtensionService::OnExternalProviderReady(
1312 const extensions::ExternalProviderInterface* provider) {
1313 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1314 CHECK(provider->IsReady());
1316 // An external provider has finished loading. We only take action
1317 // if all of them are finished. So we check them first.
1318 if (AreAllExternalProvidersReady())
1319 OnAllExternalProvidersReady();
1322 bool ExtensionService::AreAllExternalProvidersReady() const {
1323 extensions::ProviderCollection::const_iterator i;
1324 for (i = external_extension_providers_.begin();
1325 i != external_extension_providers_.end(); ++i) {
1326 if (!i->get()->IsReady())
1327 return false;
1329 return true;
1332 void ExtensionService::OnAllExternalProvidersReady() {
1333 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1334 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1335 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1337 // Install any pending extensions.
1338 if (update_once_all_providers_are_ready_ && updater()) {
1339 update_once_all_providers_are_ready_ = false;
1340 extensions::ExtensionUpdater::CheckParams params;
1341 params.callback = external_updates_finished_callback_;
1342 updater()->CheckNow(params);
1345 // Uninstall all the unclaimed extensions.
1346 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1347 extension_prefs_->GetInstalledExtensionsInfo());
1348 for (size_t i = 0; i < extensions_info->size(); ++i) {
1349 ExtensionInfo* info = extensions_info->at(i).get();
1350 if (Manifest::IsExternalLocation(info->extension_location))
1351 CheckExternalUninstall(info->extension_id);
1354 error_controller_->ShowErrorIfNeeded();
1356 external_install_manager_->UpdateExternalExtensionAlert();
1359 void ExtensionService::UnloadExtension(
1360 const std::string& extension_id,
1361 UnloadedExtensionInfo::Reason reason) {
1362 // Make sure the extension gets deleted after we return from this function.
1363 int include_mask =
1364 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1365 scoped_refptr<const Extension> extension(
1366 registry_->GetExtensionById(extension_id, include_mask));
1368 // This method can be called via PostTask, so the extension may have been
1369 // unloaded by the time this runs.
1370 if (!extension.get()) {
1371 // In case the extension may have crashed/uninstalled. Allow the profile to
1372 // clean up its RequestContexts.
1373 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1374 return;
1377 // Keep information about the extension so that we can reload it later
1378 // even if it's not permanently installed.
1379 unloaded_extension_paths_[extension->id()] = extension->path();
1381 // Clean up if the extension is meant to be enabled after a reload.
1382 reloading_extensions_.erase(extension->id());
1384 if (registry_->disabled_extensions().Contains(extension->id())) {
1385 registry_->RemoveDisabled(extension->id());
1386 // Make sure the profile cleans up its RequestContexts when an already
1387 // disabled extension is unloaded (since they are also tracking the disabled
1388 // extensions).
1389 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1390 // Don't send the unloaded notification. It was sent when the extension
1391 // was disabled.
1392 } else {
1393 // Remove the extension from the enabled list.
1394 registry_->RemoveEnabled(extension->id());
1395 NotifyExtensionUnloaded(extension.get(), reason);
1398 content::NotificationService::current()->Notify(
1399 extensions::NOTIFICATION_EXTENSION_REMOVED,
1400 content::Source<Profile>(profile_),
1401 content::Details<const Extension>(extension.get()));
1404 void ExtensionService::RemoveComponentExtension(
1405 const std::string& extension_id) {
1406 scoped_refptr<const Extension> extension(
1407 GetExtensionById(extension_id, false));
1408 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1409 if (extension.get()) {
1410 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1411 extension.get(), extensions::UNINSTALL_REASON_COMPONENT_REMOVED);
1415 void ExtensionService::UnloadAllExtensionsForTest() {
1416 UnloadAllExtensionsInternal();
1419 void ExtensionService::ReloadExtensionsForTest() {
1420 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1421 // warning about calling test code in production.
1422 UnloadAllExtensionsInternal();
1423 component_loader_->LoadAll();
1424 extensions::InstalledLoader(this).LoadAllExtensions();
1425 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1426 // times.
1429 void ExtensionService::SetReadyAndNotifyListeners() {
1430 TRACE_EVENT0("browser,startup",
1431 "ExtensionService::SetReadyAndNotifyListeners");
1432 TRACK_SCOPED_REGION(
1433 "Startup", "ExtensionService::SetReadyAndNotifyListeners");
1434 SCOPED_UMA_HISTOGRAM_TIMER(
1435 "Extensions.ExtensionServiceNotifyReadyListenersTime");
1437 ready_->Signal();
1438 content::NotificationService::current()->Notify(
1439 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1440 content::Source<Profile>(profile_),
1441 content::NotificationService::NoDetails());
1444 void ExtensionService::OnLoadedInstalledExtensions() {
1445 if (updater_)
1446 updater_->Start();
1448 OnBlacklistUpdated();
1451 void ExtensionService::AddExtension(const Extension* extension) {
1452 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1453 // default extension state to DISABLED when the --disable-extensions flag
1454 // is set (http://crbug.com/29067).
1455 if (!extensions_enabled() &&
1456 !extension->is_theme() &&
1457 extension->location() != Manifest::COMPONENT &&
1458 !Manifest::IsExternalLocation(extension->location())) {
1459 return;
1462 bool is_extension_upgrade = false;
1463 bool is_extension_installed = false;
1464 const Extension* old = GetInstalledExtension(extension->id());
1465 if (old) {
1466 is_extension_installed = true;
1467 int version_compare_result =
1468 extension->version()->CompareTo(*(old->version()));
1469 is_extension_upgrade = version_compare_result > 0;
1470 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1471 // that we aren't downgrading.
1472 if (!Manifest::IsUnpackedLocation(extension->location()))
1473 CHECK_GE(version_compare_result, 0);
1475 // If the extension was disabled for a reload, then enable it.
1476 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1478 // Set the upgraded bit; we consider reloads upgrades.
1479 system_->runtime_data()->SetBeingUpgraded(extension->id(),
1480 is_extension_upgrade || reloading);
1482 // The extension is now loaded, remove its data from unloaded extension map.
1483 unloaded_extension_paths_.erase(extension->id());
1485 // If a terminated extension is loaded, remove it from the terminated list.
1486 UntrackTerminatedExtension(extension->id());
1488 // Check if the extension's privileges have changed and mark the
1489 // extension disabled if necessary.
1490 CheckPermissionsIncrease(extension, is_extension_installed);
1492 if (is_extension_installed && !reloading) {
1493 // To upgrade an extension in place, unload the old one and then load the
1494 // new one. ReloadExtension disables the extension, which is sufficient.
1495 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1498 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1499 // Only prefs is checked for the blacklist. We rely on callers to check the
1500 // blacklist before calling into here, e.g. CrxInstaller checks before
1501 // installation then threads through the install and pending install flow
1502 // of this class, and we check when loading installed extensions.
1503 registry_->AddBlacklisted(extension);
1504 } else if (block_extensions_ && CanBlockExtension(extension)) {
1505 registry_->AddBlocked(extension);
1506 } else if (!reloading &&
1507 extension_prefs_->IsExtensionDisabled(extension->id())) {
1508 registry_->AddDisabled(extension);
1509 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(
1510 *extension);
1511 content::NotificationService::current()->Notify(
1512 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1513 content::Source<Profile>(profile_),
1514 content::Details<const Extension>(extension));
1516 // Show the extension disabled error if a permissions increase or a remote
1517 // installation is the reason it was disabled, and no other reasons exist.
1518 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1519 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1520 Extension::DISABLE_REMOTE_INSTALL;
1521 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1522 extensions::AddExtensionDisabledError(
1523 this,
1524 extension,
1525 extension_prefs_->HasDisableReason(
1526 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1528 } else if (reloading) {
1529 // Replace the old extension with the new version.
1530 CHECK(!registry_->AddDisabled(extension));
1531 EnableExtension(extension->id());
1532 } else {
1533 // All apps that are displayed in the launcher are ordered by their ordinals
1534 // so we must ensure they have valid ordinals.
1535 if (extension->RequiresSortOrdinal()) {
1536 extension_prefs_->app_sorting()->SetExtensionVisible(
1537 extension->id(),
1538 extension->ShouldDisplayInNewTabPage() &&
1539 !extension_prefs_->IsEphemeralApp(extension->id()));
1540 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1541 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1542 extension->id(), syncer::StringOrdinal());
1546 registry_->AddEnabled(extension);
1547 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(
1548 *extension);
1549 NotifyExtensionLoaded(extension);
1551 system_->runtime_data()->SetBeingUpgraded(extension->id(), false);
1554 void ExtensionService::AddComponentExtension(const Extension* extension) {
1555 const std::string old_version_string(
1556 extension_prefs_->GetVersionString(extension->id()));
1557 const Version old_version(old_version_string);
1559 VLOG(1) << "AddComponentExtension " << extension->name();
1560 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1561 VLOG(1) << "Component extension " << extension->name() << " ("
1562 << extension->id() << ") installing/upgrading from '"
1563 << old_version_string << "' to " << extension->version()->GetString();
1565 AddNewOrUpdatedExtension(extension,
1566 Extension::ENABLED,
1567 extensions::kInstallFlagNone,
1568 syncer::StringOrdinal(),
1569 std::string());
1570 return;
1573 AddExtension(extension);
1576 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1577 bool is_extension_installed) {
1578 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1580 // We keep track of all permissions the user has granted each extension.
1581 // This allows extensions to gracefully support backwards compatibility
1582 // by including unknown permissions in their manifests. When the user
1583 // installs the extension, only the recognized permissions are recorded.
1584 // When the unknown permissions become recognized (e.g., through browser
1585 // upgrade), we can prompt the user to accept these new permissions.
1586 // Extensions can also silently upgrade to less permissions, and then
1587 // silently upgrade to a version that adds these permissions back.
1589 // For example, pretend that Chrome 10 includes a permission "omnibox"
1590 // for an API that adds suggestions to the omnibox. An extension can
1591 // maintain backwards compatibility while still having "omnibox" in the
1592 // manifest. If a user installs the extension on Chrome 9, the browser
1593 // will record the permissions it recognized, not including "omnibox."
1594 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1595 // will disable the extension and prompt the user to approve the increase
1596 // in privileges. The extension could then release a new version that
1597 // removes the "omnibox" permission. When the user upgrades, Chrome will
1598 // still remember that "omnibox" had been granted, so that if the
1599 // extension once again includes "omnibox" in an upgrade, the extension
1600 // can upgrade without requiring this user's approval.
1601 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1603 // Silently grant all active permissions to default apps and apps installed
1604 // in kiosk mode.
1605 bool auto_grant_permission =
1606 extension->was_installed_by_default() ||
1607 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1608 if (auto_grant_permission)
1609 GrantPermissions(extension);
1611 bool is_privilege_increase = false;
1612 // We only need to compare the granted permissions to the current permissions
1613 // if the extension has not been auto-granted its permissions above and is
1614 // installed internally.
1615 if (extension->location() == Manifest::INTERNAL && !auto_grant_permission) {
1616 // Add all the recognized permissions if the granted permissions list
1617 // hasn't been initialized yet.
1618 scoped_refptr<PermissionSet> granted_permissions =
1619 extension_prefs_->GetGrantedPermissions(extension->id());
1620 CHECK(granted_permissions.get());
1622 // Here, we check if an extension's privileges have increased in a manner
1623 // that requires the user's approval. This could occur because the browser
1624 // upgraded and recognized additional privileges, or an extension upgrades
1625 // to a version that requires additional privileges.
1626 is_privilege_increase =
1627 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1628 granted_permissions.get(),
1629 extension->permissions_data()->active_permissions().get(),
1630 extension->GetType());
1633 if (is_extension_installed) {
1634 // If the extension was already disabled, suppress any alerts for becoming
1635 // disabled on permissions increase.
1636 bool previously_disabled =
1637 extension_prefs_->IsExtensionDisabled(extension->id());
1638 // Legacy disabled extensions do not have a disable reason. Infer that if
1639 // there was no permission increase, it was likely disabled by the user.
1640 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1641 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1642 disable_reasons |= Extension::DISABLE_USER_ACTION;
1644 // Extensions that came to us disabled from sync need a similar inference,
1645 // except based on the new version's permissions.
1646 if (previously_disabled &&
1647 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1648 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1649 extension_prefs_->ClearDisableReasons(extension->id());
1650 if (!is_privilege_increase)
1651 disable_reasons |= Extension::DISABLE_USER_ACTION;
1653 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1656 // Extension has changed permissions significantly. Disable it. A
1657 // notification should be sent by the caller. If the extension is already
1658 // disabled because it was installed remotely, don't add another disable
1659 // reason.
1660 if (is_privilege_increase &&
1661 disable_reasons != Extension::DISABLE_REMOTE_INSTALL) {
1662 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1663 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1664 RecordPermissionMessagesHistogram(extension, "AutoDisable");
1666 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1668 #if defined(ENABLE_SUPERVISED_USERS)
1669 // If a custodian-installed extension is disabled for a supervised user due
1670 // to a permissions increase, send a request to the custodian if the
1671 // supervised user themselves can't re-enable the extension.
1672 if (extensions::util::IsExtensionSupervised(extension, profile_) &&
1673 extensions::util::NeedCustodianApprovalForPermissionIncrease()) {
1674 SupervisedUserService* supervised_user_service =
1675 SupervisedUserServiceFactory::GetForProfile(profile_);
1676 supervised_user_service->AddExtensionUpdateRequest(
1677 extension->id(), *extension->version(),
1678 base::Bind(ExtensionUpdateRequestSent, extension->id()));
1680 #endif
1682 if (disable_reasons != Extension::DISABLE_NONE)
1683 extension_prefs_->AddDisableReasons(extension->id(), disable_reasons);
1686 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1687 std::set<std::string> extension_ids;
1688 const ExtensionSet& extensions = registry_->enabled_extensions();
1689 for (ExtensionSet::const_iterator iter = extensions.begin();
1690 iter != extensions.end(); ++iter) {
1691 const Extension* extension = iter->get();
1692 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1693 extension_ids.insert(extension->id());
1696 // TODO(kalman): This is broken. ExtensionService is per-profile.
1697 // crash_keys::SetActiveExtensions is per-process. See
1698 // http://crbug.com/355029.
1699 crash_keys::SetActiveExtensions(extension_ids);
1702 void ExtensionService::OnExtensionInstalled(
1703 const Extension* extension,
1704 const syncer::StringOrdinal& page_ordinal,
1705 int install_flags) {
1706 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1708 const std::string& id = extension->id();
1709 int disable_reasons = GetDisableReasonsOnInstalled(extension);
1710 std::string install_parameter;
1711 const extensions::PendingExtensionInfo* pending_extension_info =
1712 pending_extension_manager()->GetById(id);
1713 if (pending_extension_info) {
1714 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1715 pending_extension_manager()->Remove(id);
1717 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1718 << id << " of type " << extension->GetType()
1719 << " and update URL "
1720 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1721 << "; not installing";
1723 // Delete the extension directory since we're not going to
1724 // load it.
1725 if (!GetFileTaskRunner()->PostTask(
1726 FROM_HERE,
1727 base::Bind(&extensions::file_util::DeleteFile,
1728 extension->path(),
1729 true))) {
1730 NOTREACHED();
1732 return;
1735 install_parameter = pending_extension_info->install_parameter();
1736 pending_extension_manager()->Remove(id);
1737 } else {
1738 // We explicitly want to re-enable an uninstalled external
1739 // extension; if we're here, that means the user is manually
1740 // installing the extension.
1741 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1742 disable_reasons = Extension::DISABLE_NONE;
1746 // Unsupported requirements overrides the management policy.
1747 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1748 disable_reasons |= Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1749 } else {
1750 // Requirement is supported now, remove the corresponding disable reason
1751 // instead.
1752 extension_prefs_->RemoveDisableReason(
1753 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1754 disable_reasons &= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1757 // Check if the extension was disabled because of the minimum version
1758 // requirements from enterprise policy, and satisfies it now.
1759 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1760 ->CheckMinimumVersion(extension, nullptr)) {
1761 // And remove the corresponding disable reason.
1762 extension_prefs_->RemoveDisableReason(
1763 id, Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1764 disable_reasons &= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY;
1767 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1768 // Installation of a blacklisted extension can happen from sync, policy,
1769 // etc, where to maintain consistency we need to install it, just never
1770 // load it (see AddExtension). Usually it should be the job of callers to
1771 // intercept blacklisted extensions earlier (e.g. CrxInstaller, before even
1772 // showing the install dialogue).
1773 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1774 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1775 extension->location(),
1776 Manifest::NUM_LOCATIONS);
1779 if (!GetInstalledExtension(extension->id())) {
1780 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1781 extension->GetType(), 100);
1782 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1783 extension->location(), Manifest::NUM_LOCATIONS);
1784 RecordPermissionMessagesHistogram(extension, "Install");
1785 } else {
1786 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1787 extension->GetType(), 100);
1788 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1789 extension->location(), Manifest::NUM_LOCATIONS);
1791 // A fully installed app cannot be demoted to an ephemeral app.
1792 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1793 !extension_prefs_->IsEphemeralApp(id)) {
1794 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1798 if (disable_reasons)
1799 extension_prefs_->AddDisableReasons(id, disable_reasons);
1801 const Extension::State initial_state =
1802 disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED
1803 : Extension::DISABLED;
1805 if (ShouldDelayExtensionUpdate(
1807 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1808 extension_prefs_->SetDelayedInstallInfo(
1809 extension,
1810 initial_state,
1811 install_flags,
1812 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1813 page_ordinal,
1814 install_parameter);
1816 // Transfer ownership of |extension|.
1817 delayed_installs_.Insert(extension);
1819 // Notify observers that app update is available.
1820 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1821 OnAppUpdateAvailable(extension));
1822 return;
1825 extensions::SharedModuleService::ImportStatus status =
1826 shared_module_service_->SatisfyImports(extension);
1827 if (installs_delayed_for_gc_) {
1828 extension_prefs_->SetDelayedInstallInfo(
1829 extension,
1830 initial_state,
1831 install_flags,
1832 extensions::ExtensionPrefs::DELAY_REASON_GC,
1833 page_ordinal,
1834 install_parameter);
1835 delayed_installs_.Insert(extension);
1836 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1837 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1838 extension_prefs_->SetDelayedInstallInfo(
1839 extension,
1840 initial_state,
1841 install_flags,
1842 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1843 page_ordinal,
1844 install_parameter);
1845 delayed_installs_.Insert(extension);
1847 } else {
1848 AddNewOrUpdatedExtension(extension,
1849 initial_state,
1850 install_flags,
1851 page_ordinal,
1852 install_parameter);
1856 void ExtensionService::OnExtensionManagementSettingsChanged() {
1857 error_controller_->ShowErrorIfNeeded();
1859 // Revokes blocked permissions from active_permissions for all extensions.
1860 extensions::ExtensionManagement* settings =
1861 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1862 CHECK(settings);
1863 scoped_ptr<ExtensionSet> all_extensions(
1864 registry_->GenerateInstalledExtensionsSet());
1865 for (const auto& extension : *all_extensions.get()) {
1866 if (!settings->IsPermissionSetAllowed(
1867 extension.get(),
1868 extension->permissions_data()->active_permissions())) {
1869 extensions::PermissionsUpdater(profile()).RemovePermissions(
1870 extension.get(),
1871 settings->GetBlockedPermissions(extension.get()).get());
1875 CheckManagementPolicy();
1878 void ExtensionService::AddNewOrUpdatedExtension(
1879 const Extension* extension,
1880 Extension::State initial_state,
1881 int install_flags,
1882 const syncer::StringOrdinal& page_ordinal,
1883 const std::string& install_parameter) {
1884 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1885 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1886 extension_prefs_->OnExtensionInstalled(
1887 extension, initial_state, page_ordinal, install_flags, install_parameter);
1888 delayed_installs_.Remove(extension->id());
1889 if (InstallVerifier::NeedsVerification(*extension))
1890 InstallVerifier::Get(GetBrowserContext())->VerifyExtension(extension->id());
1892 const Extension* old = GetInstalledExtension(extension->id());
1893 if (extensions::AppDataMigrator::NeedsMigration(old, extension)) {
1894 app_data_migrator_->DoMigrationAndReply(
1895 old, extension,
1896 base::Bind(&ExtensionService::FinishInstallation, AsWeakPtr(),
1897 make_scoped_refptr(extension), was_ephemeral));
1898 return;
1901 FinishInstallation(extension, was_ephemeral);
1904 void ExtensionService::MaybeFinishDelayedInstallation(
1905 const std::string& extension_id) {
1906 // Check if the extension already got installed.
1907 if (!delayed_installs_.Contains(extension_id))
1908 return;
1909 extensions::ExtensionPrefs::DelayReason reason =
1910 extension_prefs_->GetDelayedInstallReason(extension_id);
1912 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1913 // preferences files that will not have set this field but it was previously
1914 // only used for idle updates.
1915 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1916 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1917 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1918 return;
1920 const Extension* extension = delayed_installs_.GetByID(extension_id);
1921 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1922 extensions::SharedModuleService::ImportStatus status =
1923 shared_module_service_->SatisfyImports(extension);
1924 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1925 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1926 delayed_installs_.Remove(extension_id);
1927 // Make sure no version of the extension is actually installed, (i.e.,
1928 // that this delayed install was not an update).
1929 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1930 extension_prefs_->DeleteExtensionPrefs(extension_id);
1932 return;
1936 FinishDelayedInstallation(extension_id);
1939 void ExtensionService::FinishDelayedInstallation(
1940 const std::string& extension_id) {
1941 scoped_refptr<const Extension> extension(
1942 GetPendingExtensionUpdate(extension_id));
1943 CHECK(extension.get());
1944 delayed_installs_.Remove(extension_id);
1946 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1947 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1948 NOTREACHED();
1950 FinishInstallation(extension.get(), was_ephemeral);
1953 void ExtensionService::FinishInstallation(
1954 const Extension* extension, bool was_ephemeral) {
1955 const extensions::Extension* existing_extension =
1956 GetInstalledExtension(extension->id());
1957 bool is_update = false;
1958 std::string old_name;
1959 if (existing_extension) {
1960 is_update = true;
1961 old_name = existing_extension->name();
1963 bool from_ephemeral =
1964 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1965 extensions::InstalledExtensionInfo details(
1966 extension, is_update, from_ephemeral, old_name);
1967 content::NotificationService::current()->Notify(
1968 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1969 content::Source<Profile>(profile_),
1970 content::Details<const extensions::InstalledExtensionInfo>(&details));
1972 registry_->TriggerOnWillBeInstalled(
1973 extension, is_update, from_ephemeral, old_name);
1975 // Unpacked extensions default to allowing file access, but if that has been
1976 // overridden, don't reset the value.
1977 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1978 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1979 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1982 AddExtension(extension);
1984 // Notify observers that need to know when an installation is complete.
1985 registry_->TriggerOnInstalled(extension, is_update);
1987 // Check extensions that may have been delayed only because this shared module
1988 // was not available.
1989 if (SharedModuleInfo::IsSharedModule(extension))
1990 MaybeFinishDelayedInstallations();
1993 void ExtensionService::PromoteEphemeralApp(
1994 const extensions::Extension* extension, bool is_from_sync) {
1995 DCHECK(GetInstalledExtension(extension->id()) &&
1996 extension_prefs_->IsEphemeralApp(extension->id()));
1998 if (extension->RequiresSortOrdinal()) {
1999 extension_prefs_->app_sorting()->SetExtensionVisible(
2000 extension->id(), extension->ShouldDisplayInNewTabPage());
2002 if (!is_from_sync) {
2003 // Reset the sort ordinals of the app to ensure it is added to the default
2004 // position, like newly installed apps would.
2005 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
2008 extension_prefs_->app_sorting()->EnsureValidOrdinals(
2009 extension->id(), syncer::StringOrdinal());
2012 // Remove the ephemeral flags from the preferences.
2013 extension_prefs_->OnEphemeralAppPromoted(extension->id());
2015 // Fire install-related events to allow observers to handle the promotion
2016 // of the ephemeral app.
2017 extensions::InstalledExtensionInfo details(
2018 extension,
2019 true /* is update */,
2020 true /* from ephemeral */,
2021 extension->name() /* old name */);
2022 content::NotificationService::current()->Notify(
2023 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2024 content::Source<Profile>(profile_),
2025 content::Details<const extensions::InstalledExtensionInfo>(&details));
2027 registry_->TriggerOnWillBeInstalled(
2028 extension,
2029 true /* is update */,
2030 true /* from ephemeral */,
2031 extension->name() /* old name */);
2033 if (registry_->enabled_extensions().Contains(extension->id())) {
2034 // If the app is already enabled and loaded, fire the load events to allow
2035 // observers to handle the promotion of the ephemeral app.
2036 content::NotificationService::current()->Notify(
2037 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
2038 content::Source<Profile>(profile_),
2039 content::Details<const Extension>(extension));
2041 registry_->TriggerOnLoaded(extension);
2042 } else {
2043 // Cached ephemeral apps may be updated and disabled due to permissions
2044 // increase. The app can be enabled (as long as no other disable reasons
2045 // exist) as the install was user-acknowledged.
2046 int disable_mask = Extension::DISABLE_NONE;
2047 if (!is_from_sync)
2048 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
2050 int other_disable_reasons =
2051 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
2052 if (!other_disable_reasons) {
2053 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
2054 GrantPermissionsAndEnableExtension(extension);
2055 else
2056 EnableExtension(extension->id());
2060 registry_->TriggerOnInstalled(extension, true);
2062 if (!is_from_sync) {
2063 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(
2064 *extension);
2068 const Extension* ExtensionService::GetPendingExtensionUpdate(
2069 const std::string& id) const {
2070 return delayed_installs_.GetByID(id);
2073 void ExtensionService::RegisterContentSettings(
2074 HostContentSettingsMap* host_content_settings_map) {
2075 TRACE_EVENT0("browser,startup", "ExtensionService::RegisterContentSettings");
2076 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2077 host_content_settings_map->RegisterProvider(
2078 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
2079 scoped_ptr<content_settings::ObservableProvider>(
2080 new content_settings::InternalExtensionProvider(profile_)));
2082 host_content_settings_map->RegisterProvider(
2083 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
2084 scoped_ptr<content_settings::ObservableProvider>(
2085 new content_settings::CustomExtensionProvider(
2086 extensions::ContentSettingsService::Get(
2087 profile_)->content_settings_store(),
2088 profile_->GetOriginalProfile() != profile_)));
2091 void ExtensionService::TrackTerminatedExtension(
2092 const std::string& extension_id) {
2093 extensions_being_terminated_.erase(extension_id);
2095 const Extension* extension = GetInstalledExtension(extension_id);
2096 if (!extension) {
2097 return;
2100 // No need to check for duplicates; inserting a duplicate is a no-op.
2101 registry_->AddTerminated(make_scoped_refptr(extension));
2102 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2105 void ExtensionService::TerminateExtension(const std::string& extension_id) {
2106 TrackTerminatedExtension(extension_id);
2109 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2110 std::string lowercase_id = base::ToLowerASCII(id);
2111 const Extension* extension =
2112 registry_->terminated_extensions().GetByID(lowercase_id);
2113 registry_->RemoveTerminated(lowercase_id);
2114 if (extension) {
2115 content::NotificationService::current()->Notify(
2116 extensions::NOTIFICATION_EXTENSION_REMOVED,
2117 content::Source<Profile>(profile_),
2118 content::Details<const Extension>(extension));
2122 const Extension* ExtensionService::GetInstalledExtension(
2123 const std::string& id) const {
2124 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2127 bool ExtensionService::OnExternalExtensionFileFound(
2128 const std::string& id,
2129 const Version* version,
2130 const base::FilePath& path,
2131 Manifest::Location location,
2132 int creation_flags,
2133 bool mark_acknowledged,
2134 bool install_immediately) {
2135 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2136 CHECK(crx_file::id_util::IdIsValid(id));
2137 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2138 return false;
2140 // Before even bothering to unpack, check and see if we already have this
2141 // version. This is important because these extensions are going to get
2142 // installed on every startup.
2143 const Extension* existing = GetExtensionById(id, true);
2145 if (existing) {
2146 // The default apps will have the location set as INTERNAL. Since older
2147 // default apps are installed as EXTERNAL, we override them. However, if the
2148 // app is already installed as internal, then do the version check.
2149 // TODO(grv) : Remove after Q1-2013.
2150 bool is_default_apps_migration =
2151 (location == Manifest::INTERNAL &&
2152 Manifest::IsExternalLocation(existing->location()));
2154 if (!is_default_apps_migration) {
2155 DCHECK(version);
2157 switch (existing->version()->CompareTo(*version)) {
2158 case -1: // existing version is older, we should upgrade
2159 break;
2160 case 0: // existing version is same, do nothing
2161 return false;
2162 case 1: // existing version is newer, uh-oh
2163 LOG(WARNING) << "Found external version of extension " << id
2164 << "that is older than current version. Current version "
2165 << "is: " << existing->VersionString() << ". New "
2166 << "version is: " << version->GetString()
2167 << ". Keeping current version.";
2168 return false;
2173 // If the extension is already pending, don't start an install.
2174 if (!pending_extension_manager()->AddFromExternalFile(
2175 id, location, *version, creation_flags, mark_acknowledged)) {
2176 return false;
2179 // no client (silent install)
2180 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2181 installer->set_install_source(location);
2182 installer->set_expected_id(id);
2183 installer->set_expected_version(*version);
2184 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2185 installer->set_install_immediately(install_immediately);
2186 installer->set_creation_flags(creation_flags);
2187 #if defined(OS_CHROMEOS)
2188 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2189 #else
2190 installer->InstallCrx(path);
2191 #endif
2193 // Depending on the source, a new external extension might not need a user
2194 // notification on installation. For such extensions, mark them acknowledged
2195 // now to suppress the notification.
2196 if (mark_acknowledged)
2197 external_install_manager_->AcknowledgeExternalExtension(id);
2199 return true;
2202 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2203 extensions::ExtensionHost* host) {
2204 OrphanedDevTools::iterator iter =
2205 orphaned_dev_tools_.find(host->extension_id());
2206 if (iter == orphaned_dev_tools_.end())
2207 return;
2209 iter->second->ConnectWebContents(host->host_contents());
2210 orphaned_dev_tools_.erase(iter);
2213 void ExtensionService::Observe(int type,
2214 const content::NotificationSource& source,
2215 const content::NotificationDetails& details) {
2216 switch (type) {
2217 case chrome::NOTIFICATION_APP_TERMINATING:
2218 // Shutdown has started. Don't start any more extension installs.
2219 // (We cannot use ExtensionService::Shutdown() for this because it
2220 // happens too late in browser teardown.)
2221 browser_terminating_ = true;
2222 break;
2223 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2224 if (profile_ !=
2225 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2226 break;
2229 extensions::ExtensionHost* host =
2230 content::Details<extensions::ExtensionHost>(details).ptr();
2232 // If the extension is already being terminated, there is nothing left to
2233 // do.
2234 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2235 break;
2237 // Mark the extension as terminated and Unload it. We want it to
2238 // be in a consistent state: either fully working or not loaded
2239 // at all, but never half-crashed. We do it in a PostTask so
2240 // that other handlers of this notification will still have
2241 // access to the Extension and ExtensionHost.
2242 base::ThreadTaskRunnerHandle::Get()->PostTask(
2243 FROM_HERE, base::Bind(&ExtensionService::TrackTerminatedExtension,
2244 AsWeakPtr(), host->extension()->id()));
2245 break;
2247 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2248 content::RenderProcessHost* process =
2249 content::Source<content::RenderProcessHost>(source).ptr();
2250 Profile* host_profile =
2251 Profile::FromBrowserContext(process->GetBrowserContext());
2252 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2253 break;
2255 extensions::ProcessMap* process_map =
2256 extensions::ProcessMap::Get(profile_);
2257 if (process_map->Contains(process->GetID())) {
2258 // An extension process was terminated, this might have resulted in an
2259 // app or extension becoming idle.
2260 std::set<std::string> extension_ids =
2261 process_map->GetExtensionsInProcess(process->GetID());
2262 // In addition to the extensions listed in the process map, one of those
2263 // extensions could be referencing a shared module which is waiting for
2264 // idle to update. Check all imports of these extensions, too.
2265 std::set<std::string> import_ids;
2266 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2267 it != extension_ids.end();
2268 ++it) {
2269 const Extension* extension = GetExtensionById(*it, true);
2270 if (!extension)
2271 continue;
2272 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2273 SharedModuleInfo::GetImports(extension);
2274 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2275 for (import_it = imports.begin(); import_it != imports.end();
2276 import_it++) {
2277 import_ids.insert((*import_it).extension_id);
2280 extension_ids.insert(import_ids.begin(), import_ids.end());
2282 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2283 it != extension_ids.end(); ++it) {
2284 if (delayed_installs_.Contains(*it)) {
2285 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2286 FROM_HERE,
2287 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2288 AsWeakPtr(), *it),
2289 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2294 process_map->RemoveAllFromProcess(process->GetID());
2295 BrowserThread::PostTask(
2296 BrowserThread::IO,
2297 FROM_HERE,
2298 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2299 system_->info_map(),
2300 process->GetID()));
2301 break;
2303 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2304 // Notify observers that chrome update is available.
2305 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2306 OnChromeUpdateAvailable());
2307 break;
2309 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2310 OnProfileDestructionStarted();
2311 break;
2314 default:
2315 NOTREACHED() << "Unexpected notification type.";
2319 int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
2320 Extension::DisableReason disable_reason;
2321 // Extensions disabled by management policy should always be disabled, even
2322 // if it's force-installed.
2323 if (system_->management_policy()->MustRemainDisabled(
2324 extension, &disable_reason, nullptr)) {
2325 // A specified reason is required to disable the extension.
2326 DCHECK(disable_reason != Extension::DISABLE_NONE);
2327 return disable_reason;
2330 // Extensions installed by policy can't be disabled. So even if a previous
2331 // installation disabled the extension, make sure it is now enabled.
2332 if (system_->management_policy()->MustRemainEnabled(extension, nullptr))
2333 return Extension::DISABLE_NONE;
2335 // An already disabled extension should inherit the disable reasons and
2336 // remain disabled.
2337 if (extension_prefs_->IsExtensionDisabled(extension->id())) {
2338 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2339 // If an extension was disabled without specified reason, presume it's
2340 // disabled by user.
2341 return disable_reasons == Extension::DISABLE_NONE
2342 ? Extension::DISABLE_USER_ACTION
2343 : disable_reasons;
2346 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2347 // External extensions are initially disabled. We prompt the user before
2348 // enabling them. Hosted apps are excepted because they are not dangerous
2349 // (they need to be launched by the user anyway).
2350 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2351 Manifest::IsExternalLocation(extension->location()) &&
2352 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2353 return Extension::DISABLE_EXTERNAL_EXTENSION;
2357 return Extension::DISABLE_NONE;
2360 // Helper method to determine if an extension can be blocked.
2361 bool ExtensionService::CanBlockExtension(const Extension* extension) const {
2362 DCHECK(extension);
2363 return extension->location() != Manifest::COMPONENT &&
2364 extension->location() != Manifest::EXTERNAL_COMPONENT &&
2365 !system_->management_policy()->MustRemainEnabled(extension, NULL);
2368 bool ExtensionService::ShouldDelayExtensionUpdate(
2369 const std::string& extension_id,
2370 bool install_immediately) const {
2371 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2373 // If delayed updates are globally disabled, or just for this extension,
2374 // don't delay.
2375 if (!install_updates_when_idle_ || install_immediately)
2376 return false;
2378 const Extension* old = GetInstalledExtension(extension_id);
2379 // If there is no old extension, this is not an update, so don't delay.
2380 if (!old)
2381 return false;
2383 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2384 // Delay installation if the extension listens for the onUpdateAvailable
2385 // event.
2386 return extensions::EventRouter::Get(profile_)
2387 ->ExtensionHasEventListener(extension_id, kOnUpdateAvailableEvent);
2388 } else {
2389 // Delay installation if the extension is not idle.
2390 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2394 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2395 DCHECK(!installs_delayed_for_gc_);
2396 installs_delayed_for_gc_ = true;
2399 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2400 DCHECK(installs_delayed_for_gc_);
2401 installs_delayed_for_gc_ = false;
2402 MaybeFinishDelayedInstallations();
2405 void ExtensionService::MaybeFinishDelayedInstallations() {
2406 std::vector<std::string> to_be_installed;
2407 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2408 it != delayed_installs_.end();
2409 ++it) {
2410 to_be_installed.push_back((*it)->id());
2412 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2413 it != to_be_installed.end();
2414 ++it) {
2415 MaybeFinishDelayedInstallation(*it);
2419 void ExtensionService::OnBlacklistUpdated() {
2420 blacklist_->GetBlacklistedIDs(
2421 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2422 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2425 void ExtensionService::ManageBlacklist(
2426 const extensions::Blacklist::BlacklistStateMap& state_map) {
2427 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2429 std::set<std::string> blacklisted;
2430 ExtensionIdSet greylist;
2431 ExtensionIdSet unchanged;
2432 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2433 state_map.begin();
2434 it != state_map.end();
2435 ++it) {
2436 switch (it->second) {
2437 case extensions::NOT_BLACKLISTED:
2438 break;
2440 case extensions::BLACKLISTED_MALWARE:
2441 blacklisted.insert(it->first);
2442 break;
2444 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2445 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2446 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2447 greylist.insert(it->first);
2448 break;
2450 case extensions::BLACKLISTED_UNKNOWN:
2451 unchanged.insert(it->first);
2452 break;
2456 UpdateBlacklistedExtensions(blacklisted, unchanged);
2457 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2459 error_controller_->ShowErrorIfNeeded();
2462 namespace {
2463 void Partition(const ExtensionIdSet& before,
2464 const ExtensionIdSet& after,
2465 const ExtensionIdSet& unchanged,
2466 ExtensionIdSet* no_longer,
2467 ExtensionIdSet* not_yet) {
2468 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2469 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2470 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2472 } // namespace
2474 void ExtensionService::UpdateBlacklistedExtensions(
2475 const ExtensionIdSet& blacklisted,
2476 const ExtensionIdSet& unchanged) {
2477 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2478 Partition(registry_->blacklisted_extensions().GetIDs(), blacklisted,
2479 unchanged, &no_longer_blocked, &not_yet_blocked);
2481 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2482 it != no_longer_blocked.end(); ++it) {
2483 scoped_refptr<const Extension> extension =
2484 registry_->blacklisted_extensions().GetByID(*it);
2485 if (!extension.get()) {
2486 NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
2487 << "but it was never blacklisted.";
2488 continue;
2490 registry_->RemoveBlacklisted(*it);
2491 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2492 AddExtension(extension.get());
2493 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2494 extension->location(),
2495 Manifest::NUM_LOCATIONS);
2498 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2499 it != not_yet_blocked.end(); ++it) {
2500 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2501 if (!extension.get()) {
2502 NOTREACHED() << "Extension " << *it << " needs to be "
2503 << "blacklisted, but it's not installed.";
2504 continue;
2506 registry_->AddBlacklisted(extension);
2507 extension_prefs_->SetExtensionBlacklistState(
2508 extension->id(), extensions::BLACKLISTED_MALWARE);
2509 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2510 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2511 extension->location(), Manifest::NUM_LOCATIONS);
2515 // TODO(oleg): UMA logging
2516 void ExtensionService::UpdateGreylistedExtensions(
2517 const ExtensionIdSet& greylist,
2518 const ExtensionIdSet& unchanged,
2519 const extensions::Blacklist::BlacklistStateMap& state_map) {
2520 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2521 Partition(greylist_.GetIDs(),
2522 greylist, unchanged,
2523 &no_longer_greylisted, &not_yet_greylisted);
2525 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2526 it != no_longer_greylisted.end(); ++it) {
2527 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2528 if (!extension.get()) {
2529 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2530 << "but it was not marked as greylisted.";
2531 continue;
2534 greylist_.Remove(*it);
2535 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2536 extensions::NOT_BLACKLISTED);
2537 if (extension_prefs_->GetDisableReasons(extension->id()) &
2538 extensions::Extension::DISABLE_GREYLIST)
2539 EnableExtension(*it);
2542 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2543 it != not_yet_greylisted.end(); ++it) {
2544 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2545 if (!extension.get()) {
2546 NOTREACHED() << "Extension " << *it << " needs to be "
2547 << "disabled, but it's not installed.";
2548 continue;
2550 greylist_.Insert(extension);
2551 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2552 state_map.find(*it)->second);
2553 if (registry_->enabled_extensions().Contains(extension->id()))
2554 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2558 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2559 update_observers_.AddObserver(observer);
2562 void ExtensionService::RemoveUpdateObserver(
2563 extensions::UpdateObserver* observer) {
2564 update_observers_.RemoveObserver(observer);
2567 // Used only by test code.
2568 void ExtensionService::UnloadAllExtensionsInternal() {
2569 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2571 registry_->ClearAll();
2572 system_->runtime_data()->ClearAll();
2574 // TODO(erikkay) should there be a notification for this? We can't use
2575 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2576 // or uninstalled.
2579 void ExtensionService::OnProfileDestructionStarted() {
2580 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2581 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2582 it != ids_to_unload.end();
2583 ++it) {
2584 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);