Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blob94c94fd0ea520a682d770420c3796bac62c9d288
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/event_router.h"
69 #include "extensions/browser/extension_host.h"
70 #include "extensions/browser/extension_prefs.h"
71 #include "extensions/browser/extension_registry.h"
72 #include "extensions/browser/extension_system.h"
73 #include "extensions/browser/extensions_browser_client.h"
74 #include "extensions/browser/install_flag.h"
75 #include "extensions/browser/runtime_data.h"
76 #include "extensions/browser/uninstall_reason.h"
77 #include "extensions/browser/update_observer.h"
78 #include "extensions/browser/updater/extension_cache.h"
79 #include "extensions/browser/updater/extension_downloader.h"
80 #include "extensions/common/extension_messages.h"
81 #include "extensions/common/extension_urls.h"
82 #include "extensions/common/feature_switch.h"
83 #include "extensions/common/file_util.h"
84 #include "extensions/common/manifest_constants.h"
85 #include "extensions/common/manifest_handlers/background_info.h"
86 #include "extensions/common/manifest_url_handlers.h"
87 #include "extensions/common/one_shot_event.h"
88 #include "extensions/common/permissions/api_permission.h"
89 #include "extensions/common/permissions/permission_message_provider.h"
90 #include "extensions/common/permissions/permissions_data.h"
92 #if defined(ENABLE_SUPERVISED_USERS)
93 #include "chrome/browser/supervised_user/supervised_user_service.h"
94 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
95 #endif
97 #if defined(OS_CHROMEOS)
98 #include "chrome/browser/chromeos/extensions/install_limiter.h"
99 #include "storage/browser/fileapi/file_system_backend.h"
100 #include "storage/browser/fileapi/file_system_context.h"
101 #endif
103 using content::BrowserContext;
104 using content::BrowserThread;
105 using content::DevToolsAgentHost;
106 using extensions::APIPermission;
107 using extensions::CrxInstaller;
108 using extensions::Extension;
109 using extensions::ExtensionIdSet;
110 using extensions::ExtensionInfo;
111 using extensions::ExtensionRegistry;
112 using extensions::ExtensionSet;
113 using extensions::FeatureSwitch;
114 using extensions::InstallVerifier;
115 using extensions::ManagementPolicy;
116 using extensions::Manifest;
117 using extensions::PermissionID;
118 using extensions::PermissionIDSet;
119 using extensions::PermissionMessage;
120 using extensions::PermissionMessageIDs;
121 using extensions::PermissionSet;
122 using extensions::SharedModuleInfo;
123 using extensions::SharedModuleService;
124 using extensions::UnloadedExtensionInfo;
126 namespace {
128 // Wait this many seconds after an extensions becomes idle before updating it.
129 const int kUpdateIdleDelay = 5;
131 #if defined(ENABLE_SUPERVISED_USERS)
132 // Callback for SupervisedUserService::AddExtensionUpdateRequest.
133 void ExtensionUpdateRequestSent(const std::string& id, bool success) {
134 LOG_IF(WARNING, !success) << "Failed sending update request for " << id;
136 #endif
138 } // namespace
140 // ExtensionService.
142 void ExtensionService::CheckExternalUninstall(const std::string& id) {
143 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
145 // Check if the providers know about this extension.
146 extensions::ProviderCollection::const_iterator i;
147 for (i = external_extension_providers_.begin();
148 i != external_extension_providers_.end(); ++i) {
149 DCHECK(i->get()->IsReady());
150 if (i->get()->HasExtension(id))
151 return; // Yup, known extension, don't uninstall.
154 // We get the list of external extensions to check from preferences.
155 // It is possible that an extension has preferences but is not loaded.
156 // For example, an extension that requires experimental permissions
157 // will not be loaded if the experimental command line flag is not used.
158 // In this case, do not uninstall.
159 if (!GetInstalledExtension(id)) {
160 // We can't call UninstallExtension with an unloaded/invalid
161 // extension ID.
162 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
163 << "with id: " << id;
164 return;
166 UninstallExtension(id,
167 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
168 base::Bind(&base::DoNothing),
169 NULL);
172 void ExtensionService::SetFileTaskRunnerForTesting(
173 const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
174 file_task_runner_ = task_runner;
177 void ExtensionService::ClearProvidersForTesting() {
178 external_extension_providers_.clear();
181 void ExtensionService::AddProviderForTesting(
182 extensions::ExternalProviderInterface* test_provider) {
183 CHECK(test_provider);
184 external_extension_providers_.push_back(
185 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
188 void ExtensionService::BlacklistExtensionForTest(
189 const std::string& extension_id) {
190 ExtensionIdSet blacklisted;
191 ExtensionIdSet unchanged;
192 blacklisted.insert(extension_id);
193 UpdateBlacklistedExtensions(blacklisted, unchanged);
196 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
197 const std::string& id,
198 const std::string& install_parameter,
199 const GURL& update_url,
200 Manifest::Location location,
201 int creation_flags,
202 bool mark_acknowledged) {
203 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
204 CHECK(crx_file::id_util::IdIsValid(id));
206 if (Manifest::IsExternalLocation(location)) {
207 // All extensions that are not user specific can be cached.
208 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
209 ->AllowCaching(id);
212 const Extension* extension = GetExtensionById(id, true);
213 if (extension) {
214 // Already installed. Skip this install if the current location has
215 // higher priority than |location|.
216 Manifest::Location current = extension->location();
217 if (current == Manifest::GetHigherPriorityLocation(current, location))
218 return false;
219 // Otherwise, overwrite the current installation.
222 // Add |id| to the set of pending extensions. If it can not be added,
223 // then there is already a pending record from a higher-priority install
224 // source. In this case, signal that this extension will not be
225 // installed by returning false.
226 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
228 install_parameter,
229 update_url,
230 location,
231 creation_flags,
232 mark_acknowledged)) {
233 return false;
236 update_once_all_providers_are_ready_ = true;
237 return true;
240 // static
241 // This function is used to uninstall an extension via sync. The LOG statements
242 // within this function are used to inform the user if the uninstall cannot be
243 // done.
244 bool ExtensionService::UninstallExtensionHelper(
245 ExtensionService* extensions_service,
246 const std::string& extension_id,
247 extensions::UninstallReason reason) {
248 // We can't call UninstallExtension with an invalid extension ID.
249 if (!extensions_service->GetInstalledExtension(extension_id)) {
250 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
251 << "id: " << extension_id;
252 return false;
255 // The following call to UninstallExtension will not allow an uninstall of a
256 // policy-controlled extension.
257 base::string16 error;
258 if (!extensions_service->UninstallExtension(
259 extension_id, reason, base::Bind(&base::DoNothing), &error)) {
260 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
261 << ": " << error;
262 return false;
265 return true;
268 ExtensionService::ExtensionService(Profile* profile,
269 const base::CommandLine* command_line,
270 const base::FilePath& install_directory,
271 extensions::ExtensionPrefs* extension_prefs,
272 extensions::Blacklist* blacklist,
273 bool autoupdate_enabled,
274 bool extensions_enabled,
275 extensions::OneShotEvent* ready)
276 : extensions::Blacklist::Observer(blacklist),
277 profile_(profile),
278 system_(extensions::ExtensionSystem::Get(profile)),
279 extension_prefs_(extension_prefs),
280 blacklist_(blacklist),
281 registry_(extensions::ExtensionRegistry::Get(profile)),
282 pending_extension_manager_(profile),
283 install_directory_(install_directory),
284 extensions_enabled_(extensions_enabled),
285 show_extensions_prompts_(true),
286 install_updates_when_idle_(true),
287 ready_(ready),
288 update_once_all_providers_are_ready_(false),
289 browser_terminating_(false),
290 installs_delayed_for_gc_(false),
291 is_first_run_(false),
292 block_extensions_(false),
293 shared_module_service_(new extensions::SharedModuleService(profile_)),
294 app_data_migrator_(new extensions::AppDataMigrator(profile_, registry_)) {
295 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
296 TRACE_EVENT0("browser,startup", "ExtensionService::ExtensionService::ctor");
298 // Figure out if extension installation should be enabled.
299 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
300 *command_line, profile))
301 extensions_enabled_ = false;
303 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
304 content::NotificationService::AllBrowserContextsAndSources());
305 registrar_.Add(this,
306 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
307 content::NotificationService::AllBrowserContextsAndSources());
308 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
309 content::NotificationService::AllBrowserContextsAndSources());
310 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
311 content::NotificationService::AllBrowserContextsAndSources());
312 registrar_.Add(this,
313 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
314 content::Source<Profile>(profile_));
316 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
317 ->AddObserver(this);
319 // Set up the ExtensionUpdater.
320 if (autoupdate_enabled) {
321 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
322 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
323 base::StringToInt(command_line->GetSwitchValueASCII(
324 switches::kExtensionsUpdateFrequency),
325 &update_frequency);
327 updater_.reset(new extensions::ExtensionUpdater(
328 this,
329 extension_prefs,
330 profile->GetPrefs(),
331 profile,
332 update_frequency,
333 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
334 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
335 profile)));
338 component_loader_.reset(
339 new extensions::ComponentLoader(this,
340 profile->GetPrefs(),
341 g_browser_process->local_state(),
342 profile));
344 if (extensions_enabled_) {
345 extensions::ExternalProviderImpl::CreateExternalProviders(
346 this, profile_, &external_extension_providers_);
349 // Set this as the ExtensionService for app sorting to ensure it causes syncs
350 // if required.
351 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
353 error_controller_.reset(
354 new extensions::ExtensionErrorController(profile_, is_first_run_));
355 external_install_manager_.reset(
356 new extensions::ExternalInstallManager(profile_, is_first_run_));
358 extension_action_storage_manager_.reset(
359 new extensions::ExtensionActionStorageManager(profile_));
361 // How long is the path to the Extensions directory?
362 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
363 install_directory_.value().length(), 0, 500, 100);
366 extensions::PendingExtensionManager*
367 ExtensionService::pending_extension_manager() {
368 return &pending_extension_manager_;
371 ExtensionService::~ExtensionService() {
372 // No need to unload extensions here because they are profile-scoped, and the
373 // profile is in the process of being deleted.
375 extensions::ProviderCollection::const_iterator i;
376 for (i = external_extension_providers_.begin();
377 i != external_extension_providers_.end(); ++i) {
378 extensions::ExternalProviderInterface* provider = i->get();
379 provider->ServiceShutdown();
383 void ExtensionService::Shutdown() {
384 extensions::ExtensionManagementFactory::GetInstance()
385 ->GetForBrowserContext(profile())
386 ->RemoveObserver(this);
387 system_->management_policy()->UnregisterProvider(
388 shared_module_policy_provider_.get());
391 const Extension* ExtensionService::GetExtensionById(
392 const std::string& id, bool include_disabled) const {
393 int include_mask = ExtensionRegistry::ENABLED;
394 if (include_disabled) {
395 // Include blacklisted and blocked extensions here because there are
396 // hundreds of callers of this function, and many might assume that this
397 // includes those that have been disabled due to blacklisting or blocking.
398 include_mask |= ExtensionRegistry::DISABLED |
399 ExtensionRegistry::BLACKLISTED | ExtensionRegistry::BLOCKED;
401 return registry_->GetExtensionById(id, include_mask);
404 void ExtensionService::Init() {
405 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
406 TRACE_EVENT0("browser,startup", "ExtensionService::Init");
407 TRACK_SCOPED_REGION("Startup", "ExtensionService::Init");
408 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.ExtensionServiceInitTime");
410 DCHECK(!is_ready()); // Can't redo init.
411 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
413 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
414 if (cmd_line->HasSwitch(switches::kInstallEphemeralAppFromWebstore)) {
415 // The sole purpose of this launch is to install a new extension from CWS
416 // and immediately terminate: loading already installed extensions is
417 // unnecessary and may interfere with the inline install dialog (e.g. if an
418 // extension listens to onStartup and opens a window).
419 SetReadyAndNotifyListeners();
420 } else {
421 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
422 component_loader_->LoadAll();
423 extensions::InstalledLoader(this).LoadAllExtensions();
425 EnabledReloadableExtensions();
426 MaybeFinishShutdownDelayed();
427 SetReadyAndNotifyListeners();
429 // TODO(erikkay): this should probably be deferred to a future point
430 // rather than running immediately at startup.
431 CheckForExternalUpdates();
433 LoadGreylistFromPrefs();
437 void ExtensionService::EnabledReloadableExtensions() {
438 TRACE_EVENT0("browser,startup",
439 "ExtensionService::EnabledReloadableExtensions");
441 std::vector<std::string> extensions_to_enable;
442 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
443 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
444 iter != disabled_extensions.end(); ++iter) {
445 const Extension* e = iter->get();
446 if (extension_prefs_->GetDisableReasons(e->id()) ==
447 Extension::DISABLE_RELOAD) {
448 extensions_to_enable.push_back(e->id());
451 for (const std::string& extension : extensions_to_enable) {
452 EnableExtension(extension);
456 void ExtensionService::MaybeFinishShutdownDelayed() {
457 TRACE_EVENT0("browser,startup",
458 "ExtensionService::MaybeFinishShutdownDelayed");
460 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
461 extension_prefs_->GetAllDelayedInstallInfo());
462 for (size_t i = 0; i < delayed_info->size(); ++i) {
463 ExtensionInfo* info = delayed_info->at(i).get();
464 scoped_refptr<const Extension> extension(NULL);
465 if (info->extension_manifest) {
466 std::string error;
467 extension = Extension::Create(
468 info->extension_path, info->extension_location,
469 *info->extension_manifest,
470 extension_prefs_->GetDelayedInstallCreationFlags(info->extension_id),
471 info->extension_id, &error);
472 if (extension.get())
473 delayed_installs_.Insert(extension);
476 MaybeFinishDelayedInstallations();
477 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
478 extension_prefs_->GetAllDelayedInstallInfo());
479 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
480 delayed_info2->size() - delayed_info->size());
483 void ExtensionService::LoadGreylistFromPrefs() {
484 TRACE_EVENT0("browser,startup", "ExtensionService::LoadGreylistFromPrefs");
486 scoped_ptr<ExtensionSet> all_extensions =
487 registry_->GenerateInstalledExtensionsSet();
489 for (ExtensionSet::const_iterator it = all_extensions->begin();
490 it != all_extensions->end(); ++it) {
491 extensions::BlacklistState state =
492 extension_prefs_->GetExtensionBlacklistState((*it)->id());
493 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
494 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
495 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
496 greylist_.Insert(*it);
500 bool ExtensionService::UpdateExtension(const extensions::CRXFileInfo& file,
501 bool file_ownership_passed,
502 CrxInstaller** out_crx_installer) {
503 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
504 if (browser_terminating_) {
505 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
506 // Leak the temp file at extension_path. We don't want to add to the disk
507 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
508 // the file is in the OS temp directory which should be cleaned up for us.
509 return false;
512 const std::string& id = file.extension_id;
514 const extensions::PendingExtensionInfo* pending_extension_info =
515 pending_extension_manager()->GetById(id);
517 const Extension* extension = GetInstalledExtension(id);
518 if (!pending_extension_info && !extension) {
519 LOG(WARNING) << "Will not update extension " << id
520 << " because it is not installed or pending";
521 // Delete extension_path since we're not creating a CrxInstaller
522 // that would do it for us.
523 if (!GetFileTaskRunner()->PostTask(
524 FROM_HERE,
525 base::Bind(&extensions::file_util::DeleteFile, file.path, false)))
526 NOTREACHED();
528 return false;
531 scoped_refptr<CrxInstaller> installer(
532 CrxInstaller::Create(this, scoped_ptr<ExtensionInstallPrompt>()));
533 installer->set_expected_id(id);
534 installer->set_expected_hash(file.expected_hash);
535 int creation_flags = Extension::NO_FLAGS;
536 if (pending_extension_info) {
537 installer->set_install_source(pending_extension_info->install_source());
538 installer->set_allow_silent_install(true);
539 if (pending_extension_info->remote_install())
540 installer->set_grant_permissions(false);
541 creation_flags = pending_extension_info->creation_flags();
542 if (pending_extension_info->mark_acknowledged())
543 external_install_manager_->AcknowledgeExternalExtension(id);
545 // If the extension came in disabled due to a permission increase, then
546 // don't grant it all the permissions. crbug.com/484214
547 if (extensions::ExtensionPrefs::Get(profile_)->HasDisableReason(
548 id, Extension::DISABLE_PERMISSIONS_INCREASE)) {
549 installer->set_grant_permissions(false);
551 } else if (extension) {
552 installer->set_install_source(extension->location());
554 // If the extension was installed from or has migrated to the webstore, or
555 // its auto-update URL is from the webstore, treat it as a webstore install.
556 // Note that we ignore some older extensions with blank auto-update URLs
557 // because we are mostly concerned with restrictions on NaCl extensions,
558 // which are newer.
559 if ((extension && extension->from_webstore()) ||
560 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
561 (!extension && extension_urls::IsWebstoreUpdateUrl(
562 pending_extension_info->update_url()))) {
563 creation_flags |= Extension::FROM_WEBSTORE;
566 // Bookmark apps being updated is kind of a contradiction, but that's because
567 // we mark the default apps as bookmark apps, and they're hosted in the web
568 // store, thus they can get updated. See http://crbug.com/101605 for more
569 // details.
570 if (extension && extension->from_bookmark())
571 creation_flags |= Extension::FROM_BOOKMARK;
573 if (extension && extension->was_installed_by_default())
574 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
576 if (extension && extension->was_installed_by_oem())
577 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
579 if (extension && extension->was_installed_by_custodian())
580 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
582 if (extension) {
583 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
584 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
587 installer->set_creation_flags(creation_flags);
589 installer->set_delete_source(file_ownership_passed);
590 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
591 installer->InstallCrxFile(file);
593 if (out_crx_installer)
594 *out_crx_installer = installer.get();
596 return true;
599 void ExtensionService::ReloadExtensionImpl(
600 // "transient" because the process of reloading may cause the reference
601 // to become invalid. Instead, use |extension_id|, a copy.
602 const std::string& transient_extension_id,
603 bool be_noisy) {
604 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
606 // If the extension is already reloading, don't reload again.
607 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
608 Extension::DISABLE_RELOAD) {
609 return;
612 // Ignore attempts to reload a blacklisted or blocked extension. Sometimes
613 // this can happen in a convoluted reload sequence triggered by the
614 // termination of a blacklisted or blocked extension and a naive attempt to
615 // reload it. For an example see http://crbug.com/373842.
616 if (registry_->blacklisted_extensions().Contains(transient_extension_id) ||
617 registry_->blocked_extensions().Contains(transient_extension_id)) {
618 return;
621 base::FilePath path;
623 std::string extension_id = transient_extension_id;
624 const Extension* transient_current_extension =
625 GetExtensionById(extension_id, false);
627 // Disable the extension if it's loaded. It might not be loaded if it crashed.
628 if (transient_current_extension) {
629 // If the extension has an inspector open for its background page, detach
630 // the inspector and hang onto a cookie for it, so that we can reattach
631 // later.
632 // TODO(yoz): this is not incognito-safe!
633 extensions::ProcessManager* manager =
634 extensions::ProcessManager::Get(profile_);
635 extensions::ExtensionHost* host =
636 manager->GetBackgroundHostForExtension(extension_id);
637 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
638 // Look for an open inspector for the background page.
639 scoped_refptr<DevToolsAgentHost> agent_host =
640 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
641 agent_host->DisconnectWebContents();
642 orphaned_dev_tools_[extension_id] = agent_host;
645 path = transient_current_extension->path();
646 // BeingUpgraded is set back to false when the extension is added.
647 system_->runtime_data()->SetBeingUpgraded(transient_current_extension->id(),
648 true);
649 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
650 reloading_extensions_.insert(extension_id);
651 } else {
652 std::map<std::string, base::FilePath>::const_iterator iter =
653 unloaded_extension_paths_.find(extension_id);
654 if (iter == unloaded_extension_paths_.end()) {
655 return;
657 path = unloaded_extension_paths_[extension_id];
660 transient_current_extension = NULL;
662 if (delayed_installs_.Contains(extension_id)) {
663 FinishDelayedInstallation(extension_id);
664 return;
667 // If we're reloading a component extension, use the component extension
668 // loader's reloader.
669 if (component_loader_->Exists(extension_id)) {
670 component_loader_->Reload(extension_id);
671 return;
674 // Check the installed extensions to see if what we're reloading was already
675 // installed.
676 scoped_ptr<ExtensionInfo> installed_extension(
677 extension_prefs_->GetInstalledExtensionInfo(extension_id));
678 if (installed_extension.get() &&
679 installed_extension->extension_manifest.get()) {
680 extensions::InstalledLoader(this).Load(*installed_extension, false);
681 } else {
682 // Otherwise, the extension is unpacked (location LOAD).
683 // We should always be able to remember the extension's path. If it's not in
684 // the map, someone failed to update |unloaded_extension_paths_|.
685 CHECK(!path.empty());
686 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
687 extensions::UnpackedInstaller::Create(this);
688 unpacked_installer->set_be_noisy_on_failure(be_noisy);
689 unpacked_installer->Load(path);
693 void ExtensionService::ReloadExtension(const std::string& extension_id) {
694 ReloadExtensionImpl(extension_id, true); // be_noisy
697 void ExtensionService::ReloadExtensionWithQuietFailure(
698 const std::string& extension_id) {
699 ReloadExtensionImpl(extension_id, false); // be_noisy
702 bool ExtensionService::UninstallExtension(
703 // "transient" because the process of uninstalling may cause the reference
704 // to become invalid. Instead, use |extenson->id()|.
705 const std::string& transient_extension_id,
706 extensions::UninstallReason reason,
707 const base::Closure& deletion_done_callback,
708 base::string16* error) {
709 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
711 scoped_refptr<const Extension> extension =
712 GetInstalledExtension(transient_extension_id);
714 // Callers should not send us nonexistent extensions.
715 CHECK(extension.get());
717 ManagementPolicy* by_policy = system_->management_policy();
718 // Policy change which triggers an uninstall will always set
719 // |external_uninstall| to true so this is the only way to uninstall
720 // managed extensions.
721 // Shared modules being uninstalled will also set |external_uninstall| to true
722 // so that we can guarantee users don't uninstall a shared module.
723 // (crbug.com/273300)
724 // TODO(rdevlin.cronin): This is probably not right. We should do something
725 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
726 // we don't do this.
727 bool external_uninstall =
728 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
729 (reason == extensions::UNINSTALL_REASON_COMPONENT_REMOVED) ||
730 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
731 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
732 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
733 (reason == extensions::UNINSTALL_REASON_SYNC &&
734 extension->was_installed_by_custodian());
735 if (!external_uninstall &&
736 (!by_policy->UserMayModifySettings(extension.get(), error) ||
737 by_policy->MustRemainInstalled(extension.get(), error))) {
738 content::NotificationService::current()->Notify(
739 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
740 content::Source<Profile>(profile_),
741 content::Details<const Extension>(extension.get()));
742 return false;
745 InstallVerifier::Get(GetBrowserContext())->Remove(extension->id());
747 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
748 extension->GetType(), 100);
749 RecordPermissionMessagesHistogram(extension.get(), "Uninstall");
751 // Unload before doing more cleanup to ensure that nothing is hanging on to
752 // any of these resources.
753 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
755 // Tell the backend to start deleting installed extensions on the file thread.
756 if (!Manifest::IsUnpackedLocation(extension->location())) {
757 if (!GetFileTaskRunner()->PostTask(
758 FROM_HERE,
759 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
760 extension->id(),
761 profile_,
762 install_directory_,
763 extension->path())))
764 NOTREACHED();
767 extensions::DataDeleter::StartDeleting(
768 profile_, extension.get(), deletion_done_callback);
770 UntrackTerminatedExtension(extension->id());
772 // Notify interested parties that we've uninstalled this extension.
773 ExtensionRegistry::Get(profile_)
774 ->TriggerOnUninstalled(extension.get(), reason);
776 // Don't sync the uninstall if we're going to reinstall the extension
777 // momentarily.
778 if (reason != extensions::UNINSTALL_REASON_REINSTALL) {
779 ExtensionSyncService::Get(profile_)->SyncUninstallExtension(*extension);
782 delayed_installs_.Remove(extension->id());
784 extension_prefs_->OnExtensionUninstalled(
785 extension->id(), extension->location(), external_uninstall);
787 // Track the uninstallation.
788 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
790 return true;
793 // static
794 void ExtensionService::UninstallExtensionOnFileThread(
795 const std::string& id,
796 Profile* profile,
797 const base::FilePath& install_dir,
798 const base::FilePath& extension_path) {
799 extensions::ExtensionAssetsManager* assets_manager =
800 extensions::ExtensionAssetsManager::GetInstance();
801 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
804 bool ExtensionService::IsExtensionEnabled(
805 const std::string& extension_id) const {
806 if (registry_->enabled_extensions().Contains(extension_id) ||
807 registry_->terminated_extensions().Contains(extension_id)) {
808 return true;
811 if (registry_->disabled_extensions().Contains(extension_id) ||
812 registry_->blacklisted_extensions().Contains(extension_id) ||
813 registry_->blocked_extensions().Contains(extension_id)) {
814 return false;
817 // Blocked extensions aren't marked as such in prefs, thus if
818 // |block_extensions_| is true then CanBlockExtension() must be called with an
819 // Extension object. If the |extension_id| is not loaded, assume not enabled.
820 if (block_extensions_) {
821 const Extension* extension = GetInstalledExtension(extension_id);
822 if (!extension || CanBlockExtension(extension))
823 return false;
826 // If the extension hasn't been loaded yet, check the prefs for it. Assume
827 // enabled unless otherwise noted.
828 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
829 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
830 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
833 void ExtensionService::EnableExtension(const std::string& extension_id) {
834 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
836 if (IsExtensionEnabled(extension_id))
837 return;
838 const Extension* extension =
839 registry_->disabled_extensions().GetByID(extension_id);
841 ManagementPolicy* policy = system_->management_policy();
842 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
843 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
844 return;
847 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
848 extension_prefs_->ClearDisableReasons(extension_id);
850 // This can happen if sync enables an extension that is not
851 // installed yet.
852 if (!extension)
853 return;
855 // Move it over to the enabled list.
856 registry_->AddEnabled(make_scoped_refptr(extension));
857 registry_->RemoveDisabled(extension->id());
859 NotifyExtensionLoaded(extension);
861 // Notify listeners that the extension was enabled.
862 content::NotificationService::current()->Notify(
863 extensions::NOTIFICATION_EXTENSION_ENABLED,
864 content::Source<Profile>(profile_),
865 content::Details<const Extension>(extension));
867 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(*extension);
870 void ExtensionService::DisableExtension(const std::string& extension_id,
871 int disable_reasons) {
872 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
874 // The extension may have been disabled already. Just add a disable reason.
875 if (!IsExtensionEnabled(extension_id)) {
876 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
877 return;
880 const Extension* extension = GetInstalledExtension(extension_id);
881 // |extension| can be NULL if sync disables an extension that is not
882 // installed yet.
883 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
884 // can be uninstalled by the browser if the user sets extension-specific
885 // preferences.
886 if (extension &&
887 !(disable_reasons & Extension::DISABLE_RELOAD) &&
888 !(disable_reasons & Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) &&
889 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
890 extension->location() != Manifest::EXTERNAL_COMPONENT) {
891 return;
894 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
895 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
897 int include_mask =
898 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
899 extension = registry_->GetExtensionById(extension_id, include_mask);
900 if (!extension)
901 return;
903 // The extension is either enabled or terminated.
904 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
905 registry_->terminated_extensions().Contains(extension->id()));
907 // Move it over to the disabled list. Don't send a second unload notification
908 // for terminated extensions being disabled.
909 registry_->AddDisabled(make_scoped_refptr(extension));
910 if (registry_->enabled_extensions().Contains(extension->id())) {
911 registry_->RemoveEnabled(extension->id());
912 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
913 } else {
914 registry_->RemoveTerminated(extension->id());
917 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(*extension);
920 void ExtensionService::DisableUserExtensions(
921 const std::vector<std::string>& except_ids) {
922 extensions::ManagementPolicy* management_policy =
923 system_->management_policy();
924 extensions::ExtensionList to_disable;
926 const ExtensionSet& enabled_set = registry_->enabled_extensions();
927 for (ExtensionSet::const_iterator extension = enabled_set.begin();
928 extension != enabled_set.end(); ++extension) {
929 if (management_policy->UserMayModifySettings(extension->get(), NULL))
930 to_disable.push_back(*extension);
932 const ExtensionSet& terminated_set = registry_->terminated_extensions();
933 for (ExtensionSet::const_iterator extension = terminated_set.begin();
934 extension != terminated_set.end(); ++extension) {
935 if (management_policy->UserMayModifySettings(extension->get(), NULL))
936 to_disable.push_back(*extension);
939 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
940 extension != to_disable.end(); ++extension) {
941 if ((*extension)->was_installed_by_default() &&
942 extension_urls::IsWebstoreUpdateUrl(
943 extensions::ManifestURL::GetUpdateURL(extension->get())))
944 continue;
945 const std::string& id = (*extension)->id();
946 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
947 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
951 // Extensions that are not locked, components or forced by policy should be
952 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
953 // extensions are now considered both blacklisted and locked.
954 void ExtensionService::BlockAllExtensions() {
955 if (block_extensions_)
956 return;
957 block_extensions_ = true;
959 // Blacklisted extensions are already unloaded, need not be blocked.
960 scoped_ptr<ExtensionSet> extensions =
961 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED |
962 ExtensionRegistry::DISABLED |
963 ExtensionRegistry::TERMINATED);
965 for (const scoped_refptr<const Extension>& extension : *extensions) {
966 const std::string& id = extension->id();
968 if (!CanBlockExtension(extension.get()))
969 continue;
971 registry_->RemoveEnabled(id);
972 registry_->RemoveDisabled(id);
973 registry_->RemoveTerminated(id);
975 registry_->AddBlocked(extension.get());
976 UnloadExtension(id, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL);
980 // All locked extensions should revert to being either enabled or disabled
981 // as appropriate.
982 void ExtensionService::UnblockAllExtensions() {
983 block_extensions_ = false;
984 scoped_ptr<ExtensionSet> to_unblock =
985 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED);
987 for (const scoped_refptr<const Extension>& extension : *to_unblock) {
988 registry_->RemoveBlocked(extension->id());
989 AddExtension(extension.get());
993 void ExtensionService::GrantPermissionsAndEnableExtension(
994 const Extension* extension) {
995 GrantPermissions(extension);
996 RecordPermissionMessagesHistogram(extension, "ReEnable");
997 EnableExtension(extension->id());
1000 void ExtensionService::GrantPermissions(const Extension* extension) {
1001 CHECK(extension);
1002 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
1005 // static
1006 void ExtensionService::RecordPermissionMessagesHistogram(
1007 const Extension* extension, const char* histogram) {
1008 // Since this is called from multiple sources, and since the histogram macros
1009 // use statics, we need to manually lookup the histogram ourselves.
1010 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
1011 base::StringPrintf("Extensions.Permissions_%s3", histogram),
1013 APIPermission::kEnumBoundary,
1014 APIPermission::kEnumBoundary + 1,
1015 base::HistogramBase::kUmaTargetedHistogramFlag);
1017 base::HistogramBase* counter_has_any = base::BooleanHistogram::FactoryGet(
1018 base::StringPrintf("Extensions.HasPermissions_%s3", histogram),
1019 base::HistogramBase::kUmaTargetedHistogramFlag);
1021 PermissionIDSet permissions =
1022 extensions::PermissionMessageProvider::Get()->GetAllPermissionIDs(
1023 extension->permissions_data()->active_permissions().get(),
1024 extension->GetType());
1025 counter_has_any->AddBoolean(!permissions.empty());
1026 for (const PermissionID& id : permissions)
1027 counter->Add(id.id());
1030 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1031 // The URLRequestContexts need to be first to know that the extension
1032 // was loaded, otherwise a race can arise where a renderer that is created
1033 // for the extension may try to load an extension URL with an extension id
1034 // that the request context doesn't yet know about. The profile is responsible
1035 // for ensuring its URLRequestContexts appropriately discover the loaded
1036 // extension.
1037 system_->RegisterExtensionWithRequestContexts(extension);
1039 // Tell renderers about the new extension, unless it's a theme (renderers
1040 // don't need to know about themes).
1041 if (!extension->is_theme()) {
1042 for (content::RenderProcessHost::iterator i(
1043 content::RenderProcessHost::AllHostsIterator());
1044 !i.IsAtEnd(); i.Advance()) {
1045 content::RenderProcessHost* host = i.GetCurrentValue();
1046 Profile* host_profile =
1047 Profile::FromBrowserContext(host->GetBrowserContext());
1048 if (host_profile->GetOriginalProfile() ==
1049 profile_->GetOriginalProfile()) {
1050 // We don't need to include tab permisisons here, since the extension
1051 // was just loaded.
1052 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1053 1, ExtensionMsg_Loaded_Params(extension,
1054 false /* no tab permissions */));
1055 host->Send(
1056 new ExtensionMsg_Loaded(loaded_extensions));
1061 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1062 // extension.
1064 // NOTE: It is important that this happen after notifying the renderers about
1065 // the new extensions so that if we navigate to an extension URL in
1066 // ExtensionRegistryObserver::OnLoaded or
1067 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1068 // renderer is guaranteed to know about it.
1069 registry_->TriggerOnLoaded(extension);
1071 content::NotificationService::current()->Notify(
1072 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1073 content::Source<Profile>(profile_),
1074 content::Details<const Extension>(extension));
1076 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1077 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1078 profile_->GetExtensionSpecialStoragePolicy()->
1079 GrantRightsForExtension(extension, profile_);
1081 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1082 // work properly multi-profile. Besides which, it should be using
1083 // ExtensionRegistryObserver. See http://crbug.com/355029.
1084 UpdateActiveExtensionsInCrashReporter();
1086 const extensions::PermissionsData* permissions_data =
1087 extension->permissions_data();
1089 // If the extension has permission to load chrome://favicon/ resources we need
1090 // to make sure that the FaviconSource is registered with the
1091 // ChromeURLDataManager.
1092 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1093 FaviconSource* favicon_source = new FaviconSource(profile_,
1094 FaviconSource::FAVICON);
1095 content::URLDataSource::Add(profile_, favicon_source);
1098 // Same for chrome://theme/ resources.
1099 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1100 ThemeSource* theme_source = new ThemeSource(profile_);
1101 content::URLDataSource::Add(profile_, theme_source);
1104 // Same for chrome://thumb/ resources.
1105 if (permissions_data->HasHostPermission(
1106 GURL(chrome::kChromeUIThumbnailURL))) {
1107 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1108 content::URLDataSource::Add(profile_, thumbnail_source);
1112 void ExtensionService::NotifyExtensionUnloaded(
1113 const Extension* extension,
1114 UnloadedExtensionInfo::Reason reason) {
1115 UnloadedExtensionInfo details(extension, reason);
1117 registry_->TriggerOnUnloaded(extension, reason);
1119 content::NotificationService::current()->Notify(
1120 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1121 content::Source<Profile>(profile_),
1122 content::Details<UnloadedExtensionInfo>(&details));
1124 for (content::RenderProcessHost::iterator i(
1125 content::RenderProcessHost::AllHostsIterator());
1126 !i.IsAtEnd(); i.Advance()) {
1127 content::RenderProcessHost* host = i.GetCurrentValue();
1128 Profile* host_profile =
1129 Profile::FromBrowserContext(host->GetBrowserContext());
1130 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1131 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1134 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1136 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1137 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1138 profile_->GetExtensionSpecialStoragePolicy()->
1139 RevokeRightsForExtension(extension);
1141 #if defined(OS_CHROMEOS)
1142 // Revoke external file access for the extension from its file system context.
1143 // It is safe to access the extension's storage partition at this point. The
1144 // storage partition may get destroyed only after the extension gets unloaded.
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, since the
1671 // supervised user themselves can't re-enable the extension.
1672 if (extensions::util::IsExtensionSupervised(extension, profile_)) {
1673 SupervisedUserService* supervised_user_service =
1674 SupervisedUserServiceFactory::GetForProfile(profile_);
1675 supervised_user_service->AddExtensionUpdateRequest(
1676 extension->id(), *extension->version(),
1677 base::Bind(ExtensionUpdateRequestSent, extension->id()));
1679 #endif
1681 if (disable_reasons != Extension::DISABLE_NONE)
1682 extension_prefs_->AddDisableReasons(extension->id(), disable_reasons);
1685 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1686 std::set<std::string> extension_ids;
1687 const ExtensionSet& extensions = registry_->enabled_extensions();
1688 for (ExtensionSet::const_iterator iter = extensions.begin();
1689 iter != extensions.end(); ++iter) {
1690 const Extension* extension = iter->get();
1691 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1692 extension_ids.insert(extension->id());
1695 // TODO(kalman): This is broken. ExtensionService is per-profile.
1696 // crash_keys::SetActiveExtensions is per-process. See
1697 // http://crbug.com/355029.
1698 crash_keys::SetActiveExtensions(extension_ids);
1701 void ExtensionService::OnExtensionInstalled(
1702 const Extension* extension,
1703 const syncer::StringOrdinal& page_ordinal,
1704 int install_flags) {
1705 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1707 const std::string& id = extension->id();
1708 int disable_reasons = GetDisableReasonsOnInstalled(extension);
1709 std::string install_parameter;
1710 const extensions::PendingExtensionInfo* pending_extension_info =
1711 pending_extension_manager()->GetById(id);
1712 if (pending_extension_info) {
1713 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1714 pending_extension_manager()->Remove(id);
1716 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1717 << id << " of type " << extension->GetType()
1718 << " and update URL "
1719 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1720 << "; not installing";
1722 // Delete the extension directory since we're not going to
1723 // load it.
1724 if (!GetFileTaskRunner()->PostTask(
1725 FROM_HERE,
1726 base::Bind(&extensions::file_util::DeleteFile,
1727 extension->path(),
1728 true))) {
1729 NOTREACHED();
1731 return;
1734 install_parameter = pending_extension_info->install_parameter();
1735 pending_extension_manager()->Remove(id);
1736 } else {
1737 // We explicitly want to re-enable an uninstalled external
1738 // extension; if we're here, that means the user is manually
1739 // installing the extension.
1740 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1741 disable_reasons = Extension::DISABLE_NONE;
1745 // Unsupported requirements overrides the management policy.
1746 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1747 disable_reasons |= Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1748 } else {
1749 // Requirement is supported now, remove the corresponding disable reason
1750 // instead.
1751 extension_prefs_->RemoveDisableReason(
1752 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1753 disable_reasons &= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1756 // Check if the extension was disabled because of the minimum version
1757 // requirements from enterprise policy, and satisfies it now.
1758 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1759 ->CheckMinimumVersion(extension, nullptr)) {
1760 // And remove the corresponding disable reason.
1761 extension_prefs_->RemoveDisableReason(
1762 id, Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1763 disable_reasons &= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY;
1766 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1767 // Installation of a blacklisted extension can happen from sync, policy,
1768 // etc, where to maintain consistency we need to install it, just never
1769 // load it (see AddExtension). Usually it should be the job of callers to
1770 // intercept blacklisted extensions earlier (e.g. CrxInstaller, before even
1771 // showing the install dialogue).
1772 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1773 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1774 extension->location(),
1775 Manifest::NUM_LOCATIONS);
1778 if (!GetInstalledExtension(extension->id())) {
1779 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1780 extension->GetType(), 100);
1781 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1782 extension->location(), Manifest::NUM_LOCATIONS);
1783 RecordPermissionMessagesHistogram(extension, "Install");
1784 } else {
1785 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1786 extension->GetType(), 100);
1787 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1788 extension->location(), Manifest::NUM_LOCATIONS);
1790 // A fully installed app cannot be demoted to an ephemeral app.
1791 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1792 !extension_prefs_->IsEphemeralApp(id)) {
1793 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1797 if (disable_reasons)
1798 extension_prefs_->AddDisableReasons(id, disable_reasons);
1800 const Extension::State initial_state =
1801 disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED
1802 : Extension::DISABLED;
1804 if (ShouldDelayExtensionUpdate(
1806 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1807 extension_prefs_->SetDelayedInstallInfo(
1808 extension,
1809 initial_state,
1810 install_flags,
1811 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1812 page_ordinal,
1813 install_parameter);
1815 // Transfer ownership of |extension|.
1816 delayed_installs_.Insert(extension);
1818 // Notify observers that app update is available.
1819 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1820 OnAppUpdateAvailable(extension));
1821 return;
1824 extensions::SharedModuleService::ImportStatus status =
1825 shared_module_service_->SatisfyImports(extension);
1826 if (installs_delayed_for_gc_) {
1827 extension_prefs_->SetDelayedInstallInfo(
1828 extension,
1829 initial_state,
1830 install_flags,
1831 extensions::ExtensionPrefs::DELAY_REASON_GC,
1832 page_ordinal,
1833 install_parameter);
1834 delayed_installs_.Insert(extension);
1835 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1836 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1837 extension_prefs_->SetDelayedInstallInfo(
1838 extension,
1839 initial_state,
1840 install_flags,
1841 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1842 page_ordinal,
1843 install_parameter);
1844 delayed_installs_.Insert(extension);
1846 } else {
1847 AddNewOrUpdatedExtension(extension,
1848 initial_state,
1849 install_flags,
1850 page_ordinal,
1851 install_parameter);
1855 void ExtensionService::OnExtensionManagementSettingsChanged() {
1856 error_controller_->ShowErrorIfNeeded();
1858 // Revokes blocked permissions from active_permissions for all extensions.
1859 extensions::ExtensionManagement* settings =
1860 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1861 CHECK(settings);
1862 scoped_ptr<ExtensionSet> all_extensions(
1863 registry_->GenerateInstalledExtensionsSet());
1864 for (const auto& extension : *all_extensions.get()) {
1865 if (!settings->IsPermissionSetAllowed(
1866 extension.get(),
1867 extension->permissions_data()->active_permissions())) {
1868 extensions::PermissionsUpdater(profile()).RemovePermissions(
1869 extension.get(),
1870 settings->GetBlockedPermissions(extension.get()).get());
1874 CheckManagementPolicy();
1877 void ExtensionService::AddNewOrUpdatedExtension(
1878 const Extension* extension,
1879 Extension::State initial_state,
1880 int install_flags,
1881 const syncer::StringOrdinal& page_ordinal,
1882 const std::string& install_parameter) {
1883 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1884 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1885 extension_prefs_->OnExtensionInstalled(
1886 extension, initial_state, page_ordinal, install_flags, install_parameter);
1887 delayed_installs_.Remove(extension->id());
1888 if (InstallVerifier::NeedsVerification(*extension))
1889 InstallVerifier::Get(GetBrowserContext())->VerifyExtension(extension->id());
1891 const Extension* old = GetInstalledExtension(extension->id());
1892 if (extensions::AppDataMigrator::NeedsMigration(old, extension)) {
1893 app_data_migrator_->DoMigrationAndReply(
1894 old, extension,
1895 base::Bind(&ExtensionService::FinishInstallation, AsWeakPtr(),
1896 make_scoped_refptr(extension), was_ephemeral));
1897 return;
1900 FinishInstallation(extension, was_ephemeral);
1903 void ExtensionService::MaybeFinishDelayedInstallation(
1904 const std::string& extension_id) {
1905 // Check if the extension already got installed.
1906 if (!delayed_installs_.Contains(extension_id))
1907 return;
1908 extensions::ExtensionPrefs::DelayReason reason =
1909 extension_prefs_->GetDelayedInstallReason(extension_id);
1911 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1912 // preferences files that will not have set this field but it was previously
1913 // only used for idle updates.
1914 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1915 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1916 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1917 return;
1919 const Extension* extension = delayed_installs_.GetByID(extension_id);
1920 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1921 extensions::SharedModuleService::ImportStatus status =
1922 shared_module_service_->SatisfyImports(extension);
1923 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1924 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1925 delayed_installs_.Remove(extension_id);
1926 // Make sure no version of the extension is actually installed, (i.e.,
1927 // that this delayed install was not an update).
1928 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1929 extension_prefs_->DeleteExtensionPrefs(extension_id);
1931 return;
1935 FinishDelayedInstallation(extension_id);
1938 void ExtensionService::FinishDelayedInstallation(
1939 const std::string& extension_id) {
1940 scoped_refptr<const Extension> extension(
1941 GetPendingExtensionUpdate(extension_id));
1942 CHECK(extension.get());
1943 delayed_installs_.Remove(extension_id);
1945 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1946 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1947 NOTREACHED();
1949 FinishInstallation(extension.get(), was_ephemeral);
1952 void ExtensionService::FinishInstallation(
1953 const Extension* extension, bool was_ephemeral) {
1954 const extensions::Extension* existing_extension =
1955 GetInstalledExtension(extension->id());
1956 bool is_update = false;
1957 std::string old_name;
1958 if (existing_extension) {
1959 is_update = true;
1960 old_name = existing_extension->name();
1962 bool from_ephemeral =
1963 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1964 extensions::InstalledExtensionInfo details(
1965 extension, is_update, from_ephemeral, old_name);
1966 content::NotificationService::current()->Notify(
1967 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1968 content::Source<Profile>(profile_),
1969 content::Details<const extensions::InstalledExtensionInfo>(&details));
1971 registry_->TriggerOnWillBeInstalled(
1972 extension, is_update, from_ephemeral, old_name);
1974 // Unpacked extensions default to allowing file access, but if that has been
1975 // overridden, don't reset the value.
1976 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1977 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1978 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1981 AddExtension(extension);
1983 // Notify observers that need to know when an installation is complete.
1984 registry_->TriggerOnInstalled(extension, is_update);
1986 // Check extensions that may have been delayed only because this shared module
1987 // was not available.
1988 if (SharedModuleInfo::IsSharedModule(extension))
1989 MaybeFinishDelayedInstallations();
1992 void ExtensionService::PromoteEphemeralApp(
1993 const extensions::Extension* extension, bool is_from_sync) {
1994 DCHECK(GetInstalledExtension(extension->id()) &&
1995 extension_prefs_->IsEphemeralApp(extension->id()));
1997 if (extension->RequiresSortOrdinal()) {
1998 extension_prefs_->app_sorting()->SetExtensionVisible(
1999 extension->id(), extension->ShouldDisplayInNewTabPage());
2001 if (!is_from_sync) {
2002 // Reset the sort ordinals of the app to ensure it is added to the default
2003 // position, like newly installed apps would.
2004 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
2007 extension_prefs_->app_sorting()->EnsureValidOrdinals(
2008 extension->id(), syncer::StringOrdinal());
2011 // Remove the ephemeral flags from the preferences.
2012 extension_prefs_->OnEphemeralAppPromoted(extension->id());
2014 // Fire install-related events to allow observers to handle the promotion
2015 // of the ephemeral app.
2016 extensions::InstalledExtensionInfo details(
2017 extension,
2018 true /* is update */,
2019 true /* from ephemeral */,
2020 extension->name() /* old name */);
2021 content::NotificationService::current()->Notify(
2022 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2023 content::Source<Profile>(profile_),
2024 content::Details<const extensions::InstalledExtensionInfo>(&details));
2026 registry_->TriggerOnWillBeInstalled(
2027 extension,
2028 true /* is update */,
2029 true /* from ephemeral */,
2030 extension->name() /* old name */);
2032 if (registry_->enabled_extensions().Contains(extension->id())) {
2033 // If the app is already enabled and loaded, fire the load events to allow
2034 // observers to handle the promotion of the ephemeral app.
2035 content::NotificationService::current()->Notify(
2036 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
2037 content::Source<Profile>(profile_),
2038 content::Details<const Extension>(extension));
2040 registry_->TriggerOnLoaded(extension);
2041 } else {
2042 // Cached ephemeral apps may be updated and disabled due to permissions
2043 // increase. The app can be enabled (as long as no other disable reasons
2044 // exist) as the install was user-acknowledged.
2045 int disable_mask = Extension::DISABLE_NONE;
2046 if (!is_from_sync)
2047 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
2049 int other_disable_reasons =
2050 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
2051 if (!other_disable_reasons) {
2052 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
2053 GrantPermissionsAndEnableExtension(extension);
2054 else
2055 EnableExtension(extension->id());
2059 registry_->TriggerOnInstalled(extension, true);
2061 if (!is_from_sync) {
2062 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(
2063 *extension);
2067 const Extension* ExtensionService::GetPendingExtensionUpdate(
2068 const std::string& id) const {
2069 return delayed_installs_.GetByID(id);
2072 void ExtensionService::RegisterContentSettings(
2073 HostContentSettingsMap* host_content_settings_map) {
2074 TRACE_EVENT0("browser,startup", "ExtensionService::RegisterContentSettings");
2075 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2076 host_content_settings_map->RegisterProvider(
2077 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
2078 scoped_ptr<content_settings::ObservableProvider>(
2079 new content_settings::InternalExtensionProvider(profile_)));
2081 host_content_settings_map->RegisterProvider(
2082 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
2083 scoped_ptr<content_settings::ObservableProvider>(
2084 new content_settings::CustomExtensionProvider(
2085 extensions::ContentSettingsService::Get(
2086 profile_)->content_settings_store(),
2087 profile_->GetOriginalProfile() != profile_)));
2090 void ExtensionService::TrackTerminatedExtension(
2091 const std::string& extension_id) {
2092 extensions_being_terminated_.erase(extension_id);
2094 const Extension* extension = GetInstalledExtension(extension_id);
2095 if (!extension) {
2096 return;
2099 // No need to check for duplicates; inserting a duplicate is a no-op.
2100 registry_->AddTerminated(make_scoped_refptr(extension));
2101 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2104 void ExtensionService::TerminateExtension(const std::string& extension_id) {
2105 TrackTerminatedExtension(extension_id);
2108 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2109 std::string lowercase_id = base::StringToLowerASCII(id);
2110 const Extension* extension =
2111 registry_->terminated_extensions().GetByID(lowercase_id);
2112 registry_->RemoveTerminated(lowercase_id);
2113 if (extension) {
2114 content::NotificationService::current()->Notify(
2115 extensions::NOTIFICATION_EXTENSION_REMOVED,
2116 content::Source<Profile>(profile_),
2117 content::Details<const Extension>(extension));
2121 const Extension* ExtensionService::GetInstalledExtension(
2122 const std::string& id) const {
2123 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2126 bool ExtensionService::OnExternalExtensionFileFound(
2127 const std::string& id,
2128 const Version* version,
2129 const base::FilePath& path,
2130 Manifest::Location location,
2131 int creation_flags,
2132 bool mark_acknowledged,
2133 bool install_immediately) {
2134 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2135 CHECK(crx_file::id_util::IdIsValid(id));
2136 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2137 return false;
2139 // Before even bothering to unpack, check and see if we already have this
2140 // version. This is important because these extensions are going to get
2141 // installed on every startup.
2142 const Extension* existing = GetExtensionById(id, true);
2144 if (existing) {
2145 // The default apps will have the location set as INTERNAL. Since older
2146 // default apps are installed as EXTERNAL, we override them. However, if the
2147 // app is already installed as internal, then do the version check.
2148 // TODO(grv) : Remove after Q1-2013.
2149 bool is_default_apps_migration =
2150 (location == Manifest::INTERNAL &&
2151 Manifest::IsExternalLocation(existing->location()));
2153 if (!is_default_apps_migration) {
2154 DCHECK(version);
2156 switch (existing->version()->CompareTo(*version)) {
2157 case -1: // existing version is older, we should upgrade
2158 break;
2159 case 0: // existing version is same, do nothing
2160 return false;
2161 case 1: // existing version is newer, uh-oh
2162 LOG(WARNING) << "Found external version of extension " << id
2163 << "that is older than current version. Current version "
2164 << "is: " << existing->VersionString() << ". New "
2165 << "version is: " << version->GetString()
2166 << ". Keeping current version.";
2167 return false;
2172 // If the extension is already pending, don't start an install.
2173 if (!pending_extension_manager()->AddFromExternalFile(
2174 id, location, *version, creation_flags, mark_acknowledged)) {
2175 return false;
2178 // no client (silent install)
2179 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2180 installer->set_install_source(location);
2181 installer->set_expected_id(id);
2182 installer->set_expected_version(*version);
2183 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2184 installer->set_install_immediately(install_immediately);
2185 installer->set_creation_flags(creation_flags);
2186 #if defined(OS_CHROMEOS)
2187 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2188 #else
2189 installer->InstallCrx(path);
2190 #endif
2192 // Depending on the source, a new external extension might not need a user
2193 // notification on installation. For such extensions, mark them acknowledged
2194 // now to suppress the notification.
2195 if (mark_acknowledged)
2196 external_install_manager_->AcknowledgeExternalExtension(id);
2198 return true;
2201 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2202 extensions::ExtensionHost* host) {
2203 OrphanedDevTools::iterator iter =
2204 orphaned_dev_tools_.find(host->extension_id());
2205 if (iter == orphaned_dev_tools_.end())
2206 return;
2208 iter->second->ConnectWebContents(host->host_contents());
2209 orphaned_dev_tools_.erase(iter);
2212 void ExtensionService::Observe(int type,
2213 const content::NotificationSource& source,
2214 const content::NotificationDetails& details) {
2215 switch (type) {
2216 case chrome::NOTIFICATION_APP_TERMINATING:
2217 // Shutdown has started. Don't start any more extension installs.
2218 // (We cannot use ExtensionService::Shutdown() for this because it
2219 // happens too late in browser teardown.)
2220 browser_terminating_ = true;
2221 break;
2222 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2223 if (profile_ !=
2224 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2225 break;
2228 extensions::ExtensionHost* host =
2229 content::Details<extensions::ExtensionHost>(details).ptr();
2231 // If the extension is already being terminated, there is nothing left to
2232 // do.
2233 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2234 break;
2236 // Mark the extension as terminated and Unload it. We want it to
2237 // be in a consistent state: either fully working or not loaded
2238 // at all, but never half-crashed. We do it in a PostTask so
2239 // that other handlers of this notification will still have
2240 // access to the Extension and ExtensionHost.
2241 base::ThreadTaskRunnerHandle::Get()->PostTask(
2242 FROM_HERE, base::Bind(&ExtensionService::TrackTerminatedExtension,
2243 AsWeakPtr(), host->extension()->id()));
2244 break;
2246 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2247 content::RenderProcessHost* process =
2248 content::Source<content::RenderProcessHost>(source).ptr();
2249 Profile* host_profile =
2250 Profile::FromBrowserContext(process->GetBrowserContext());
2251 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2252 break;
2254 extensions::ProcessMap* process_map =
2255 extensions::ProcessMap::Get(profile_);
2256 if (process_map->Contains(process->GetID())) {
2257 // An extension process was terminated, this might have resulted in an
2258 // app or extension becoming idle.
2259 std::set<std::string> extension_ids =
2260 process_map->GetExtensionsInProcess(process->GetID());
2261 // In addition to the extensions listed in the process map, one of those
2262 // extensions could be referencing a shared module which is waiting for
2263 // idle to update. Check all imports of these extensions, too.
2264 std::set<std::string> import_ids;
2265 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2266 it != extension_ids.end();
2267 ++it) {
2268 const Extension* extension = GetExtensionById(*it, true);
2269 if (!extension)
2270 continue;
2271 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2272 SharedModuleInfo::GetImports(extension);
2273 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2274 for (import_it = imports.begin(); import_it != imports.end();
2275 import_it++) {
2276 import_ids.insert((*import_it).extension_id);
2279 extension_ids.insert(import_ids.begin(), import_ids.end());
2281 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2282 it != extension_ids.end(); ++it) {
2283 if (delayed_installs_.Contains(*it)) {
2284 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2285 FROM_HERE,
2286 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2287 AsWeakPtr(), *it),
2288 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2293 process_map->RemoveAllFromProcess(process->GetID());
2294 BrowserThread::PostTask(
2295 BrowserThread::IO,
2296 FROM_HERE,
2297 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2298 system_->info_map(),
2299 process->GetID()));
2300 break;
2302 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2303 // Notify observers that chrome update is available.
2304 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2305 OnChromeUpdateAvailable());
2306 break;
2308 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2309 OnProfileDestructionStarted();
2310 break;
2313 default:
2314 NOTREACHED() << "Unexpected notification type.";
2318 int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
2319 Extension::DisableReason disable_reason;
2320 // Extensions disabled by management policy should always be disabled, even
2321 // if it's force-installed.
2322 if (system_->management_policy()->MustRemainDisabled(
2323 extension, &disable_reason, nullptr)) {
2324 // A specified reason is required to disable the extension.
2325 DCHECK(disable_reason != Extension::DISABLE_NONE);
2326 return disable_reason;
2329 // Extensions installed by policy can't be disabled. So even if a previous
2330 // installation disabled the extension, make sure it is now enabled.
2331 if (system_->management_policy()->MustRemainEnabled(extension, nullptr))
2332 return Extension::DISABLE_NONE;
2334 // An already disabled extension should inherit the disable reasons and
2335 // remain disabled.
2336 if (extension_prefs_->IsExtensionDisabled(extension->id())) {
2337 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2338 // If an extension was disabled without specified reason, presume it's
2339 // disabled by user.
2340 return disable_reasons == Extension::DISABLE_NONE
2341 ? Extension::DISABLE_USER_ACTION
2342 : disable_reasons;
2345 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2346 // External extensions are initially disabled. We prompt the user before
2347 // enabling them. Hosted apps are excepted because they are not dangerous
2348 // (they need to be launched by the user anyway).
2349 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2350 Manifest::IsExternalLocation(extension->location()) &&
2351 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2352 return Extension::DISABLE_EXTERNAL_EXTENSION;
2356 return Extension::DISABLE_NONE;
2359 // Helper method to determine if an extension can be blocked.
2360 bool ExtensionService::CanBlockExtension(const Extension* extension) const {
2361 DCHECK(extension);
2362 return extension->location() != Manifest::COMPONENT &&
2363 extension->location() != Manifest::EXTERNAL_COMPONENT &&
2364 !system_->management_policy()->MustRemainEnabled(extension, NULL);
2367 bool ExtensionService::ShouldDelayExtensionUpdate(
2368 const std::string& extension_id,
2369 bool install_immediately) const {
2370 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2372 // If delayed updates are globally disabled, or just for this extension,
2373 // don't delay.
2374 if (!install_updates_when_idle_ || install_immediately)
2375 return false;
2377 const Extension* old = GetInstalledExtension(extension_id);
2378 // If there is no old extension, this is not an update, so don't delay.
2379 if (!old)
2380 return false;
2382 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2383 // Delay installation if the extension listens for the onUpdateAvailable
2384 // event.
2385 return extensions::EventRouter::Get(profile_)
2386 ->ExtensionHasEventListener(extension_id, kOnUpdateAvailableEvent);
2387 } else {
2388 // Delay installation if the extension is not idle.
2389 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2393 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2394 DCHECK(!installs_delayed_for_gc_);
2395 installs_delayed_for_gc_ = true;
2398 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2399 DCHECK(installs_delayed_for_gc_);
2400 installs_delayed_for_gc_ = false;
2401 MaybeFinishDelayedInstallations();
2404 void ExtensionService::MaybeFinishDelayedInstallations() {
2405 std::vector<std::string> to_be_installed;
2406 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2407 it != delayed_installs_.end();
2408 ++it) {
2409 to_be_installed.push_back((*it)->id());
2411 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2412 it != to_be_installed.end();
2413 ++it) {
2414 MaybeFinishDelayedInstallation(*it);
2418 void ExtensionService::OnBlacklistUpdated() {
2419 blacklist_->GetBlacklistedIDs(
2420 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2421 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2424 void ExtensionService::ManageBlacklist(
2425 const extensions::Blacklist::BlacklistStateMap& state_map) {
2426 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2428 std::set<std::string> blacklisted;
2429 ExtensionIdSet greylist;
2430 ExtensionIdSet unchanged;
2431 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2432 state_map.begin();
2433 it != state_map.end();
2434 ++it) {
2435 switch (it->second) {
2436 case extensions::NOT_BLACKLISTED:
2437 break;
2439 case extensions::BLACKLISTED_MALWARE:
2440 blacklisted.insert(it->first);
2441 break;
2443 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2444 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2445 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2446 greylist.insert(it->first);
2447 break;
2449 case extensions::BLACKLISTED_UNKNOWN:
2450 unchanged.insert(it->first);
2451 break;
2455 UpdateBlacklistedExtensions(blacklisted, unchanged);
2456 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2458 error_controller_->ShowErrorIfNeeded();
2461 namespace {
2462 void Partition(const ExtensionIdSet& before,
2463 const ExtensionIdSet& after,
2464 const ExtensionIdSet& unchanged,
2465 ExtensionIdSet* no_longer,
2466 ExtensionIdSet* not_yet) {
2467 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2468 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2469 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2471 } // namespace
2473 void ExtensionService::UpdateBlacklistedExtensions(
2474 const ExtensionIdSet& blacklisted,
2475 const ExtensionIdSet& unchanged) {
2476 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2477 Partition(registry_->blacklisted_extensions().GetIDs(), blacklisted,
2478 unchanged, &no_longer_blocked, &not_yet_blocked);
2480 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2481 it != no_longer_blocked.end(); ++it) {
2482 scoped_refptr<const Extension> extension =
2483 registry_->blacklisted_extensions().GetByID(*it);
2484 if (!extension.get()) {
2485 NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
2486 << "but it was never blacklisted.";
2487 continue;
2489 registry_->RemoveBlacklisted(*it);
2490 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2491 AddExtension(extension.get());
2492 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2493 extension->location(),
2494 Manifest::NUM_LOCATIONS);
2497 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2498 it != not_yet_blocked.end(); ++it) {
2499 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2500 if (!extension.get()) {
2501 NOTREACHED() << "Extension " << *it << " needs to be "
2502 << "blacklisted, but it's not installed.";
2503 continue;
2505 registry_->AddBlacklisted(extension);
2506 extension_prefs_->SetExtensionBlacklistState(
2507 extension->id(), extensions::BLACKLISTED_MALWARE);
2508 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2509 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2510 extension->location(), Manifest::NUM_LOCATIONS);
2514 // TODO(oleg): UMA logging
2515 void ExtensionService::UpdateGreylistedExtensions(
2516 const ExtensionIdSet& greylist,
2517 const ExtensionIdSet& unchanged,
2518 const extensions::Blacklist::BlacklistStateMap& state_map) {
2519 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2520 Partition(greylist_.GetIDs(),
2521 greylist, unchanged,
2522 &no_longer_greylisted, &not_yet_greylisted);
2524 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2525 it != no_longer_greylisted.end(); ++it) {
2526 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2527 if (!extension.get()) {
2528 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2529 << "but it was not marked as greylisted.";
2530 continue;
2533 greylist_.Remove(*it);
2534 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2535 extensions::NOT_BLACKLISTED);
2536 if (extension_prefs_->GetDisableReasons(extension->id()) &
2537 extensions::Extension::DISABLE_GREYLIST)
2538 EnableExtension(*it);
2541 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2542 it != not_yet_greylisted.end(); ++it) {
2543 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2544 if (!extension.get()) {
2545 NOTREACHED() << "Extension " << *it << " needs to be "
2546 << "disabled, but it's not installed.";
2547 continue;
2549 greylist_.Insert(extension);
2550 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2551 state_map.find(*it)->second);
2552 if (registry_->enabled_extensions().Contains(extension->id()))
2553 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2557 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2558 update_observers_.AddObserver(observer);
2561 void ExtensionService::RemoveUpdateObserver(
2562 extensions::UpdateObserver* observer) {
2563 update_observers_.RemoveObserver(observer);
2566 // Used only by test code.
2567 void ExtensionService::UnloadAllExtensionsInternal() {
2568 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2570 registry_->ClearAll();
2571 system_->runtime_data()->ClearAll();
2573 // TODO(erikkay) should there be a notification for this? We can't use
2574 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2575 // or uninstalled.
2578 void ExtensionService::OnProfileDestructionStarted() {
2579 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2580 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2581 it != ids_to_unload.end();
2582 ++it) {
2583 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);