Remove keyboard_ui.css and manifest_keyboard.json
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blob16c3a6b5a46fcef99b55f4de0f248a4767fc4121
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 extension_sync_service_(NULL),
282 registry_(extensions::ExtensionRegistry::Get(profile)),
283 pending_extension_manager_(profile),
284 install_directory_(install_directory),
285 extensions_enabled_(extensions_enabled),
286 show_extensions_prompts_(true),
287 install_updates_when_idle_(true),
288 ready_(ready),
289 update_once_all_providers_are_ready_(false),
290 browser_terminating_(false),
291 installs_delayed_for_gc_(false),
292 is_first_run_(false),
293 block_extensions_(false),
294 shared_module_service_(new extensions::SharedModuleService(profile_)),
295 app_data_migrator_(new extensions::AppDataMigrator(profile_, registry_)) {
296 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
297 TRACE_EVENT0("browser,startup", "ExtensionService::ExtensionService::ctor");
299 // Figure out if extension installation should be enabled.
300 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
301 *command_line, profile))
302 extensions_enabled_ = false;
304 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
305 content::NotificationService::AllBrowserContextsAndSources());
306 registrar_.Add(this,
307 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
308 content::NotificationService::AllBrowserContextsAndSources());
309 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
310 content::NotificationService::AllBrowserContextsAndSources());
311 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
312 content::NotificationService::AllBrowserContextsAndSources());
313 registrar_.Add(this,
314 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
315 content::Source<Profile>(profile_));
317 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
318 ->AddObserver(this);
320 // Set up the ExtensionUpdater.
321 if (autoupdate_enabled) {
322 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
323 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
324 base::StringToInt(command_line->GetSwitchValueASCII(
325 switches::kExtensionsUpdateFrequency),
326 &update_frequency);
328 updater_.reset(new extensions::ExtensionUpdater(
329 this,
330 extension_prefs,
331 profile->GetPrefs(),
332 profile,
333 update_frequency,
334 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
335 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
336 profile)));
339 component_loader_.reset(
340 new extensions::ComponentLoader(this,
341 profile->GetPrefs(),
342 g_browser_process->local_state(),
343 profile));
345 if (extensions_enabled_) {
346 extensions::ExternalProviderImpl::CreateExternalProviders(
347 this, profile_, &external_extension_providers_);
350 // Set this as the ExtensionService for app sorting to ensure it causes syncs
351 // if required.
352 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
354 error_controller_.reset(
355 new extensions::ExtensionErrorController(profile_, is_first_run_));
356 external_install_manager_.reset(
357 new extensions::ExternalInstallManager(profile_, is_first_run_));
359 extension_action_storage_manager_.reset(
360 new extensions::ExtensionActionStorageManager(profile_));
362 // How long is the path to the Extensions directory?
363 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
364 install_directory_.value().length(), 0, 500, 100);
367 extensions::PendingExtensionManager*
368 ExtensionService::pending_extension_manager() {
369 return &pending_extension_manager_;
372 ExtensionService::~ExtensionService() {
373 // No need to unload extensions here because they are profile-scoped, and the
374 // profile is in the process of being deleted.
376 extensions::ProviderCollection::const_iterator i;
377 for (i = external_extension_providers_.begin();
378 i != external_extension_providers_.end(); ++i) {
379 extensions::ExternalProviderInterface* provider = i->get();
380 provider->ServiceShutdown();
384 void ExtensionService::Shutdown() {
385 extensions::ExtensionManagementFactory::GetInstance()
386 ->GetForBrowserContext(profile())
387 ->RemoveObserver(this);
388 system_->management_policy()->UnregisterProvider(
389 shared_module_policy_provider_.get());
392 const Extension* ExtensionService::GetExtensionById(
393 const std::string& id, bool include_disabled) const {
394 int include_mask = ExtensionRegistry::ENABLED;
395 if (include_disabled) {
396 // Include blacklisted and blocked extensions here because there are
397 // hundreds of callers of this function, and many might assume that this
398 // includes those that have been disabled due to blacklisting or blocking.
399 include_mask |= ExtensionRegistry::DISABLED |
400 ExtensionRegistry::BLACKLISTED | ExtensionRegistry::BLOCKED;
402 return registry_->GetExtensionById(id, include_mask);
405 void ExtensionService::Init() {
406 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
407 TRACE_EVENT0("browser,startup", "ExtensionService::Init");
408 TRACK_SCOPED_REGION("Startup", "ExtensionService::Init");
409 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.ExtensionServiceInitTime");
411 DCHECK(!is_ready()); // Can't redo init.
412 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
414 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
415 if (cmd_line->HasSwitch(switches::kInstallEphemeralAppFromWebstore)) {
416 // The sole purpose of this launch is to install a new extension from CWS
417 // and immediately terminate: loading already installed extensions is
418 // unnecessary and may interfere with the inline install dialog (e.g. if an
419 // extension listens to onStartup and opens a window).
420 SetReadyAndNotifyListeners();
421 } else {
422 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
423 component_loader_->LoadAll();
424 extensions::InstalledLoader(this).LoadAllExtensions();
426 EnabledReloadableExtensions();
427 MaybeFinishShutdownDelayed();
428 SetReadyAndNotifyListeners();
430 // TODO(erikkay): this should probably be deferred to a future point
431 // rather than running immediately at startup.
432 CheckForExternalUpdates();
434 LoadGreylistFromPrefs();
438 void ExtensionService::EnabledReloadableExtensions() {
439 TRACE_EVENT0("browser,startup",
440 "ExtensionService::EnabledReloadableExtensions");
442 std::vector<std::string> extensions_to_enable;
443 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
444 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
445 iter != disabled_extensions.end(); ++iter) {
446 const Extension* e = iter->get();
447 if (extension_prefs_->GetDisableReasons(e->id()) ==
448 Extension::DISABLE_RELOAD) {
449 extensions_to_enable.push_back(e->id());
452 for (const std::string& extension : extensions_to_enable) {
453 EnableExtension(extension);
457 void ExtensionService::MaybeFinishShutdownDelayed() {
458 TRACE_EVENT0("browser,startup",
459 "ExtensionService::MaybeFinishShutdownDelayed");
461 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
462 extension_prefs_->GetAllDelayedInstallInfo());
463 for (size_t i = 0; i < delayed_info->size(); ++i) {
464 ExtensionInfo* info = delayed_info->at(i).get();
465 scoped_refptr<const Extension> extension(NULL);
466 if (info->extension_manifest) {
467 std::string error;
468 extension = Extension::Create(
469 info->extension_path, info->extension_location,
470 *info->extension_manifest,
471 extension_prefs_->GetDelayedInstallCreationFlags(info->extension_id),
472 info->extension_id, &error);
473 if (extension.get())
474 delayed_installs_.Insert(extension);
477 MaybeFinishDelayedInstallations();
478 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
479 extension_prefs_->GetAllDelayedInstallInfo());
480 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
481 delayed_info2->size() - delayed_info->size());
484 void ExtensionService::LoadGreylistFromPrefs() {
485 TRACE_EVENT0("browser,startup", "ExtensionService::LoadGreylistFromPrefs");
487 scoped_ptr<ExtensionSet> all_extensions =
488 registry_->GenerateInstalledExtensionsSet();
490 for (ExtensionSet::const_iterator it = all_extensions->begin();
491 it != all_extensions->end(); ++it) {
492 extensions::BlacklistState state =
493 extension_prefs_->GetExtensionBlacklistState((*it)->id());
494 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
495 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
496 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
497 greylist_.Insert(*it);
501 bool ExtensionService::UpdateExtension(const extensions::CRXFileInfo& file,
502 bool file_ownership_passed,
503 CrxInstaller** out_crx_installer) {
504 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
505 if (browser_terminating_) {
506 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
507 // Leak the temp file at extension_path. We don't want to add to the disk
508 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
509 // the file is in the OS temp directory which should be cleaned up for us.
510 return false;
513 const std::string& id = file.extension_id;
515 const extensions::PendingExtensionInfo* pending_extension_info =
516 pending_extension_manager()->GetById(id);
518 const Extension* extension = GetInstalledExtension(id);
519 if (!pending_extension_info && !extension) {
520 LOG(WARNING) << "Will not update extension " << id
521 << " because it is not installed or pending";
522 // Delete extension_path since we're not creating a CrxInstaller
523 // that would do it for us.
524 if (!GetFileTaskRunner()->PostTask(
525 FROM_HERE,
526 base::Bind(&extensions::file_util::DeleteFile, file.path, false)))
527 NOTREACHED();
529 return false;
532 scoped_refptr<CrxInstaller> installer(
533 CrxInstaller::Create(this, scoped_ptr<ExtensionInstallPrompt>()));
534 installer->set_expected_id(id);
535 installer->set_expected_hash(file.expected_hash);
536 int creation_flags = Extension::NO_FLAGS;
537 if (pending_extension_info) {
538 installer->set_install_source(pending_extension_info->install_source());
539 installer->set_allow_silent_install(true);
540 if (pending_extension_info->remote_install())
541 installer->set_grant_permissions(false);
542 creation_flags = pending_extension_info->creation_flags();
543 if (pending_extension_info->mark_acknowledged())
544 external_install_manager_->AcknowledgeExternalExtension(id);
546 // If the extension came in disabled due to a permission increase, then
547 // don't grant it all the permissions. crbug.com/484214
548 if (extensions::ExtensionPrefs::Get(profile_)->HasDisableReason(
549 id, Extension::DISABLE_PERMISSIONS_INCREASE)) {
550 installer->set_grant_permissions(false);
552 } else if (extension) {
553 installer->set_install_source(extension->location());
555 // If the extension was installed from or has migrated to the webstore, or
556 // its auto-update URL is from the webstore, treat it as a webstore install.
557 // Note that we ignore some older extensions with blank auto-update URLs
558 // because we are mostly concerned with restrictions on NaCl extensions,
559 // which are newer.
560 if ((extension && extension->from_webstore()) ||
561 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
562 (!extension && extension_urls::IsWebstoreUpdateUrl(
563 pending_extension_info->update_url()))) {
564 creation_flags |= Extension::FROM_WEBSTORE;
567 // Bookmark apps being updated is kind of a contradiction, but that's because
568 // we mark the default apps as bookmark apps, and they're hosted in the web
569 // store, thus they can get updated. See http://crbug.com/101605 for more
570 // details.
571 if (extension && extension->from_bookmark())
572 creation_flags |= Extension::FROM_BOOKMARK;
574 if (extension && extension->was_installed_by_default())
575 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
577 if (extension && extension->was_installed_by_oem())
578 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
580 if (extension && extension->was_installed_by_custodian())
581 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
583 if (extension) {
584 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
585 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
588 installer->set_creation_flags(creation_flags);
590 installer->set_delete_source(file_ownership_passed);
591 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
592 installer->InstallCrxFile(file);
594 if (out_crx_installer)
595 *out_crx_installer = installer.get();
597 return true;
600 void ExtensionService::ReloadExtensionImpl(
601 // "transient" because the process of reloading may cause the reference
602 // to become invalid. Instead, use |extension_id|, a copy.
603 const std::string& transient_extension_id,
604 bool be_noisy) {
605 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
607 // If the extension is already reloading, don't reload again.
608 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
609 Extension::DISABLE_RELOAD) {
610 return;
613 // Ignore attempts to reload a blacklisted or blocked extension. Sometimes
614 // this can happen in a convoluted reload sequence triggered by the
615 // termination of a blacklisted or blocked extension and a naive attempt to
616 // reload it. For an example see http://crbug.com/373842.
617 if (registry_->blacklisted_extensions().Contains(transient_extension_id) ||
618 registry_->blocked_extensions().Contains(transient_extension_id)) {
619 return;
622 base::FilePath path;
624 std::string extension_id = transient_extension_id;
625 const Extension* transient_current_extension =
626 GetExtensionById(extension_id, false);
628 // Disable the extension if it's loaded. It might not be loaded if it crashed.
629 if (transient_current_extension) {
630 // If the extension has an inspector open for its background page, detach
631 // the inspector and hang onto a cookie for it, so that we can reattach
632 // later.
633 // TODO(yoz): this is not incognito-safe!
634 extensions::ProcessManager* manager =
635 extensions::ProcessManager::Get(profile_);
636 extensions::ExtensionHost* host =
637 manager->GetBackgroundHostForExtension(extension_id);
638 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
639 // Look for an open inspector for the background page.
640 scoped_refptr<DevToolsAgentHost> agent_host =
641 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
642 agent_host->DisconnectWebContents();
643 orphaned_dev_tools_[extension_id] = agent_host;
646 path = transient_current_extension->path();
647 // BeingUpgraded is set back to false when the extension is added.
648 system_->runtime_data()->SetBeingUpgraded(transient_current_extension->id(),
649 true);
650 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
651 reloading_extensions_.insert(extension_id);
652 } else {
653 std::map<std::string, base::FilePath>::const_iterator iter =
654 unloaded_extension_paths_.find(extension_id);
655 if (iter == unloaded_extension_paths_.end()) {
656 return;
658 path = unloaded_extension_paths_[extension_id];
661 transient_current_extension = NULL;
663 if (delayed_installs_.Contains(extension_id)) {
664 FinishDelayedInstallation(extension_id);
665 return;
668 // If we're reloading a component extension, use the component extension
669 // loader's reloader.
670 if (component_loader_->Exists(extension_id)) {
671 component_loader_->Reload(extension_id);
672 return;
675 // Check the installed extensions to see if what we're reloading was already
676 // installed.
677 scoped_ptr<ExtensionInfo> installed_extension(
678 extension_prefs_->GetInstalledExtensionInfo(extension_id));
679 if (installed_extension.get() &&
680 installed_extension->extension_manifest.get()) {
681 extensions::InstalledLoader(this).Load(*installed_extension, false);
682 } else {
683 // Otherwise, the extension is unpacked (location LOAD).
684 // We should always be able to remember the extension's path. If it's not in
685 // the map, someone failed to update |unloaded_extension_paths_|.
686 CHECK(!path.empty());
687 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
688 extensions::UnpackedInstaller::Create(this);
689 unpacked_installer->set_be_noisy_on_failure(be_noisy);
690 unpacked_installer->Load(path);
694 void ExtensionService::ReloadExtension(const std::string& extension_id) {
695 ReloadExtensionImpl(extension_id, true); // be_noisy
698 void ExtensionService::ReloadExtensionWithQuietFailure(
699 const std::string& extension_id) {
700 ReloadExtensionImpl(extension_id, false); // be_noisy
703 bool ExtensionService::UninstallExtension(
704 // "transient" because the process of uninstalling may cause the reference
705 // to become invalid. Instead, use |extenson->id()|.
706 const std::string& transient_extension_id,
707 extensions::UninstallReason reason,
708 const base::Closure& deletion_done_callback,
709 base::string16* error) {
710 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
712 scoped_refptr<const Extension> extension =
713 GetInstalledExtension(transient_extension_id);
715 // Callers should not send us nonexistent extensions.
716 CHECK(extension.get());
718 ManagementPolicy* by_policy = system_->management_policy();
719 // Policy change which triggers an uninstall will always set
720 // |external_uninstall| to true so this is the only way to uninstall
721 // managed extensions.
722 // Shared modules being uninstalled will also set |external_uninstall| to true
723 // so that we can guarantee users don't uninstall a shared module.
724 // (crbug.com/273300)
725 // TODO(rdevlin.cronin): This is probably not right. We should do something
726 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
727 // we don't do this.
728 bool external_uninstall =
729 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
730 (reason == extensions::UNINSTALL_REASON_COMPONENT_REMOVED) ||
731 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
732 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
733 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
734 (reason == extensions::UNINSTALL_REASON_SYNC &&
735 extension->was_installed_by_custodian());
736 if (!external_uninstall &&
737 (!by_policy->UserMayModifySettings(extension.get(), error) ||
738 by_policy->MustRemainInstalled(extension.get(), error))) {
739 content::NotificationService::current()->Notify(
740 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
741 content::Source<Profile>(profile_),
742 content::Details<const Extension>(extension.get()));
743 return false;
746 syncer::SyncChange sync_change;
747 // Don't sync the uninstall if we're going to reinstall the extension
748 // momentarily.
749 if (extension_sync_service_ &&
750 reason != extensions::UNINSTALL_REASON_REINSTALL) {
751 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
752 extension.get(), is_ready());
755 InstallVerifier::Get(GetBrowserContext())->Remove(extension->id());
757 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
758 extension->GetType(), 100);
759 RecordPermissionMessagesHistogram(extension.get(), "Uninstall");
761 // Unload before doing more cleanup to ensure that nothing is hanging on to
762 // any of these resources.
763 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
765 // Tell the backend to start deleting installed extensions on the file thread.
766 if (!Manifest::IsUnpackedLocation(extension->location())) {
767 if (!GetFileTaskRunner()->PostTask(
768 FROM_HERE,
769 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
770 extension->id(),
771 profile_,
772 install_directory_,
773 extension->path())))
774 NOTREACHED();
777 extensions::DataDeleter::StartDeleting(
778 profile_, extension.get(), deletion_done_callback);
780 UntrackTerminatedExtension(extension->id());
782 // Notify interested parties that we've uninstalled this extension.
783 ExtensionRegistry::Get(profile_)
784 ->TriggerOnUninstalled(extension.get(), reason);
786 if (sync_change.IsValid()) {
787 extension_sync_service_->ProcessSyncUninstallExtension(extension->id(),
788 sync_change);
791 delayed_installs_.Remove(extension->id());
793 extension_prefs_->OnExtensionUninstalled(
794 extension->id(), extension->location(), external_uninstall);
796 // Track the uninstallation.
797 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
799 return true;
802 // static
803 void ExtensionService::UninstallExtensionOnFileThread(
804 const std::string& id,
805 Profile* profile,
806 const base::FilePath& install_dir,
807 const base::FilePath& extension_path) {
808 extensions::ExtensionAssetsManager* assets_manager =
809 extensions::ExtensionAssetsManager::GetInstance();
810 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
813 bool ExtensionService::IsExtensionEnabled(
814 const std::string& extension_id) const {
815 if (registry_->enabled_extensions().Contains(extension_id) ||
816 registry_->terminated_extensions().Contains(extension_id)) {
817 return true;
820 if (registry_->disabled_extensions().Contains(extension_id) ||
821 registry_->blacklisted_extensions().Contains(extension_id) ||
822 registry_->blocked_extensions().Contains(extension_id)) {
823 return false;
826 // Blocked extensions aren't marked as such in prefs, thus if
827 // |block_extensions_| is true then CanBlockExtension() must be called with an
828 // Extension object. If the |extension_id| is not loaded, assume not enabled.
829 if (block_extensions_) {
830 const Extension* extension = GetInstalledExtension(extension_id);
831 if (!extension || CanBlockExtension(extension))
832 return false;
835 // If the extension hasn't been loaded yet, check the prefs for it. Assume
836 // enabled unless otherwise noted.
837 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
838 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
839 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
842 void ExtensionService::EnableExtension(const std::string& extension_id) {
843 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
845 if (IsExtensionEnabled(extension_id))
846 return;
847 const Extension* extension =
848 registry_->disabled_extensions().GetByID(extension_id);
850 ManagementPolicy* policy = system_->management_policy();
851 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
852 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
853 return;
856 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
857 extension_prefs_->ClearDisableReasons(extension_id);
859 // This can happen if sync enables an extension that is not
860 // installed yet.
861 if (!extension)
862 return;
864 // Move it over to the enabled list.
865 registry_->AddEnabled(make_scoped_refptr(extension));
866 registry_->RemoveDisabled(extension->id());
868 NotifyExtensionLoaded(extension);
870 // Notify listeners that the extension was enabled.
871 content::NotificationService::current()->Notify(
872 extensions::NOTIFICATION_EXTENSION_ENABLED,
873 content::Source<Profile>(profile_),
874 content::Details<const Extension>(extension));
876 if (extension_sync_service_)
877 extension_sync_service_->SyncEnableExtension(*extension);
880 void ExtensionService::DisableExtension(const std::string& extension_id,
881 int disable_reasons) {
882 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
884 // The extension may have been disabled already. Just add a disable reason.
885 if (!IsExtensionEnabled(extension_id)) {
886 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
887 return;
890 const Extension* extension = GetInstalledExtension(extension_id);
891 // |extension| can be NULL if sync disables an extension that is not
892 // installed yet.
893 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
894 // can be uninstalled by the browser if the user sets extension-specific
895 // preferences.
896 if (extension &&
897 !(disable_reasons & Extension::DISABLE_RELOAD) &&
898 !(disable_reasons & Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) &&
899 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
900 extension->location() != Manifest::EXTERNAL_COMPONENT) {
901 return;
904 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
905 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
907 int include_mask =
908 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
909 extension = registry_->GetExtensionById(extension_id, include_mask);
910 if (!extension)
911 return;
913 // The extension is either enabled or terminated.
914 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
915 registry_->terminated_extensions().Contains(extension->id()));
917 // Move it over to the disabled list. Don't send a second unload notification
918 // for terminated extensions being disabled.
919 registry_->AddDisabled(make_scoped_refptr(extension));
920 if (registry_->enabled_extensions().Contains(extension->id())) {
921 registry_->RemoveEnabled(extension->id());
922 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
923 } else {
924 registry_->RemoveTerminated(extension->id());
927 if (extension_sync_service_)
928 extension_sync_service_->SyncDisableExtension(*extension);
931 void ExtensionService::DisableUserExtensions(
932 const std::vector<std::string>& except_ids) {
933 extensions::ManagementPolicy* management_policy =
934 system_->management_policy();
935 extensions::ExtensionList to_disable;
937 const ExtensionSet& enabled_set = registry_->enabled_extensions();
938 for (ExtensionSet::const_iterator extension = enabled_set.begin();
939 extension != enabled_set.end(); ++extension) {
940 if (management_policy->UserMayModifySettings(extension->get(), NULL))
941 to_disable.push_back(*extension);
943 const ExtensionSet& terminated_set = registry_->terminated_extensions();
944 for (ExtensionSet::const_iterator extension = terminated_set.begin();
945 extension != terminated_set.end(); ++extension) {
946 if (management_policy->UserMayModifySettings(extension->get(), NULL))
947 to_disable.push_back(*extension);
950 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
951 extension != to_disable.end(); ++extension) {
952 if ((*extension)->was_installed_by_default() &&
953 extension_urls::IsWebstoreUpdateUrl(
954 extensions::ManifestURL::GetUpdateURL(extension->get())))
955 continue;
956 const std::string& id = (*extension)->id();
957 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
958 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
962 // Extensions that are not locked, components or forced by policy should be
963 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
964 // extensions are now considered both blacklisted and locked.
965 void ExtensionService::BlockAllExtensions() {
966 if (block_extensions_)
967 return;
968 block_extensions_ = true;
970 // Blacklisted extensions are already unloaded, need not be blocked.
971 scoped_ptr<ExtensionSet> extensions =
972 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED |
973 ExtensionRegistry::DISABLED |
974 ExtensionRegistry::TERMINATED);
976 for (const scoped_refptr<const Extension>& extension : *extensions) {
977 const std::string& id = extension->id();
979 if (!CanBlockExtension(extension.get()))
980 continue;
982 registry_->RemoveEnabled(id);
983 registry_->RemoveDisabled(id);
984 registry_->RemoveTerminated(id);
986 registry_->AddBlocked(extension.get());
987 UnloadExtension(id, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL);
991 // All locked extensions should revert to being either enabled or disabled
992 // as appropriate.
993 void ExtensionService::UnblockAllExtensions() {
994 block_extensions_ = false;
995 scoped_ptr<ExtensionSet> to_unblock =
996 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED);
998 for (const scoped_refptr<const Extension>& extension : *to_unblock) {
999 registry_->RemoveBlocked(extension->id());
1000 AddExtension(extension.get());
1004 void ExtensionService::GrantPermissionsAndEnableExtension(
1005 const Extension* extension) {
1006 GrantPermissions(extension);
1007 RecordPermissionMessagesHistogram(extension, "ReEnable");
1008 EnableExtension(extension->id());
1011 void ExtensionService::GrantPermissions(const Extension* extension) {
1012 CHECK(extension);
1013 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
1016 // static
1017 void ExtensionService::RecordPermissionMessagesHistogram(
1018 const Extension* extension, const char* histogram) {
1019 // Since this is called from multiple sources, and since the histogram macros
1020 // use statics, we need to manually lookup the histogram ourselves.
1021 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
1022 base::StringPrintf("Extensions.Permissions_%s3", histogram),
1024 APIPermission::kEnumBoundary,
1025 APIPermission::kEnumBoundary + 1,
1026 base::HistogramBase::kUmaTargetedHistogramFlag);
1028 base::HistogramBase* counter_has_any = base::BooleanHistogram::FactoryGet(
1029 base::StringPrintf("Extensions.HasPermissions_%s3", histogram),
1030 base::HistogramBase::kUmaTargetedHistogramFlag);
1032 PermissionIDSet permissions =
1033 extensions::PermissionMessageProvider::Get()->GetAllPermissionIDs(
1034 extension->permissions_data()->active_permissions().get(),
1035 extension->GetType());
1036 counter_has_any->AddBoolean(!permissions.empty());
1037 for (const PermissionID& id : permissions)
1038 counter->Add(id.id());
1041 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1042 // The URLRequestContexts need to be first to know that the extension
1043 // was loaded, otherwise a race can arise where a renderer that is created
1044 // for the extension may try to load an extension URL with an extension id
1045 // that the request context doesn't yet know about. The profile is responsible
1046 // for ensuring its URLRequestContexts appropriately discover the loaded
1047 // extension.
1048 system_->RegisterExtensionWithRequestContexts(extension);
1050 // Tell renderers about the new extension, unless it's a theme (renderers
1051 // don't need to know about themes).
1052 if (!extension->is_theme()) {
1053 for (content::RenderProcessHost::iterator i(
1054 content::RenderProcessHost::AllHostsIterator());
1055 !i.IsAtEnd(); i.Advance()) {
1056 content::RenderProcessHost* host = i.GetCurrentValue();
1057 Profile* host_profile =
1058 Profile::FromBrowserContext(host->GetBrowserContext());
1059 if (host_profile->GetOriginalProfile() ==
1060 profile_->GetOriginalProfile()) {
1061 // We don't need to include tab permisisons here, since the extension
1062 // was just loaded.
1063 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1064 1, ExtensionMsg_Loaded_Params(extension,
1065 false /* no tab permissions */));
1066 host->Send(
1067 new ExtensionMsg_Loaded(loaded_extensions));
1072 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1073 // extension.
1075 // NOTE: It is important that this happen after notifying the renderers about
1076 // the new extensions so that if we navigate to an extension URL in
1077 // ExtensionRegistryObserver::OnLoaded or
1078 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1079 // renderer is guaranteed to know about it.
1080 registry_->TriggerOnLoaded(extension);
1082 content::NotificationService::current()->Notify(
1083 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1084 content::Source<Profile>(profile_),
1085 content::Details<const Extension>(extension));
1087 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1088 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1089 profile_->GetExtensionSpecialStoragePolicy()->
1090 GrantRightsForExtension(extension, profile_);
1092 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1093 // work properly multi-profile. Besides which, it should be using
1094 // ExtensionRegistryObserver. See http://crbug.com/355029.
1095 UpdateActiveExtensionsInCrashReporter();
1097 const extensions::PermissionsData* permissions_data =
1098 extension->permissions_data();
1100 // If the extension has permission to load chrome://favicon/ resources we need
1101 // to make sure that the FaviconSource is registered with the
1102 // ChromeURLDataManager.
1103 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1104 FaviconSource* favicon_source = new FaviconSource(profile_,
1105 FaviconSource::FAVICON);
1106 content::URLDataSource::Add(profile_, favicon_source);
1109 // Same for chrome://theme/ resources.
1110 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1111 ThemeSource* theme_source = new ThemeSource(profile_);
1112 content::URLDataSource::Add(profile_, theme_source);
1115 // Same for chrome://thumb/ resources.
1116 if (permissions_data->HasHostPermission(
1117 GURL(chrome::kChromeUIThumbnailURL))) {
1118 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1119 content::URLDataSource::Add(profile_, thumbnail_source);
1123 void ExtensionService::NotifyExtensionUnloaded(
1124 const Extension* extension,
1125 UnloadedExtensionInfo::Reason reason) {
1126 UnloadedExtensionInfo details(extension, reason);
1128 registry_->TriggerOnUnloaded(extension, reason);
1130 content::NotificationService::current()->Notify(
1131 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1132 content::Source<Profile>(profile_),
1133 content::Details<UnloadedExtensionInfo>(&details));
1135 for (content::RenderProcessHost::iterator i(
1136 content::RenderProcessHost::AllHostsIterator());
1137 !i.IsAtEnd(); i.Advance()) {
1138 content::RenderProcessHost* host = i.GetCurrentValue();
1139 Profile* host_profile =
1140 Profile::FromBrowserContext(host->GetBrowserContext());
1141 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1142 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1145 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1147 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1148 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1149 profile_->GetExtensionSpecialStoragePolicy()->
1150 RevokeRightsForExtension(extension);
1152 #if defined(OS_CHROMEOS)
1153 // Revoke external file access for the extension from its file system context.
1154 // It is safe to access the extension's storage partition at this point. The
1155 // storage partition may get destroyed only after the extension gets unloaded.
1156 GURL site =
1157 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1158 storage::FileSystemContext* filesystem_context =
1159 BrowserContext::GetStoragePartitionForSite(profile_, site)
1160 ->GetFileSystemContext();
1161 if (filesystem_context && filesystem_context->external_backend()) {
1162 filesystem_context->external_backend()->
1163 RevokeAccessForExtension(extension->id());
1165 #endif
1167 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1168 // work properly multi-profile. Besides which, it should be using
1169 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1170 UpdateActiveExtensionsInCrashReporter();
1173 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1174 // Implemented in the .cc file to avoid adding a profile.h dependency to
1175 // extension_service.h.
1176 return profile_;
1179 bool ExtensionService::is_ready() {
1180 return ready_->is_signaled();
1183 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1184 if (file_task_runner_.get())
1185 return file_task_runner_.get();
1187 // We should be able to interrupt any part of extension install process during
1188 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1189 // will be ignored/deleted while we will block on started tasks.
1190 std::string token("ext_install-");
1191 token.append(profile_->GetPath().AsUTF8Unsafe());
1192 file_task_runner_ = BrowserThread::GetBlockingPool()->
1193 GetSequencedTaskRunnerWithShutdownBehavior(
1194 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1195 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1196 return file_task_runner_.get();
1199 void ExtensionService::CheckManagementPolicy() {
1200 std::vector<std::string> to_unload;
1201 std::map<std::string, Extension::DisableReason> to_disable;
1202 std::vector<std::string> to_enable;
1204 // Loop through the extensions list, finding extensions we need to unload or
1205 // disable.
1206 for (scoped_refptr<const Extension> extension :
1207 registry_->enabled_extensions()) {
1208 if (!system_->management_policy()->UserMayLoad(extension.get(), nullptr))
1209 to_unload.push_back(extension->id());
1210 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1211 if (system_->management_policy()->MustRemainDisabled(
1212 extension.get(), &disable_reason, nullptr))
1213 to_disable[extension->id()] = disable_reason;
1216 extensions::ExtensionManagement* management =
1217 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1219 // Loop through the disabled extension list, find extensions to re-enable
1220 // automatically. These extensions are exclusive from the |to_disable| and
1221 // |to_unload| lists constructed above, since disabled_extensions() and
1222 // enabled_extensions() are supposed to be mutually exclusive.
1223 for (scoped_refptr<const Extension> extension :
1224 registry_->disabled_extensions()) {
1225 // Find all disabled extensions disabled due to minimum version requirement,
1226 // but now satisfying it.
1227 if (management->CheckMinimumVersion(extension.get(), nullptr) &&
1228 extension_prefs_->HasDisableReason(
1229 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY)) {
1230 // Is DISABLE_UPDATE_REQUIRED_BY_POLICY the *only* reason?
1231 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1232 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1233 // We need to enable those disabled *only* due to minimum version
1234 // requirement.
1235 to_enable.push_back(extension->id());
1237 extension_prefs_->RemoveDisableReason(
1238 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1242 for (const std::string& id : to_unload)
1243 UnloadExtension(id, UnloadedExtensionInfo::REASON_DISABLE);
1245 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1246 to_disable.begin(); i != to_disable.end(); ++i)
1247 DisableExtension(i->first, i->second);
1249 // No extension is getting re-enabled here after disabling/unloading
1250 // because to_enable is mutually exclusive to to_disable + to_unload.
1251 for (const std::string& id : to_enable)
1252 EnableExtension(id);
1254 if (updater_.get()) {
1255 // Find all extensions disabled due to minimum version requirement from
1256 // policy (including the ones that got disabled just now), and check
1257 // for update.
1258 extensions::ExtensionUpdater::CheckParams to_recheck;
1259 for (scoped_refptr<const Extension> extension :
1260 registry_->disabled_extensions()) {
1261 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1262 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1263 // The minimum version check is the only thing holding this extension
1264 // back, so check if it can be updated to fix that.
1265 to_recheck.ids.push_back(extension->id());
1268 if (!to_recheck.ids.empty())
1269 updater_->CheckNow(to_recheck);
1273 void ExtensionService::CheckForUpdatesSoon() {
1274 // This can legitimately happen in unit tests.
1275 if (!updater_.get())
1276 return;
1278 if (AreAllExternalProvidersReady()) {
1279 updater_->CheckSoon();
1280 } else {
1281 // Sync can start updating before all the external providers are ready
1282 // during startup. Start the update as soon as those providers are ready,
1283 // but not before.
1284 update_once_all_providers_are_ready_ = true;
1288 // Some extensions will autoupdate themselves externally from Chrome. These
1289 // are typically part of some larger client application package. To support
1290 // these, the extension will register its location in the preferences file
1291 // (and also, on Windows, in the registry) and this code will periodically
1292 // check that location for a .crx file, which it will then install locally if
1293 // a new version is available.
1294 // Errors are reported through ExtensionErrorReporter. Success is not
1295 // reported.
1296 void ExtensionService::CheckForExternalUpdates() {
1297 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1298 TRACE_EVENT0("browser,startup", "ExtensionService::CheckForExternalUpdates");
1299 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.CheckForExternalUpdatesTime");
1301 // Note that this installation is intentionally silent (since it didn't
1302 // go through the front-end). Extensions that are registered in this
1303 // way are effectively considered 'pre-bundled', and so implicitly
1304 // trusted. In general, if something has HKLM or filesystem access,
1305 // they could install an extension manually themselves anyway.
1307 // Ask each external extension provider to give us a call back for each
1308 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1309 extensions::ProviderCollection::const_iterator i;
1310 for (i = external_extension_providers_.begin();
1311 i != external_extension_providers_.end(); ++i) {
1312 extensions::ExternalProviderInterface* provider = i->get();
1313 provider->VisitRegisteredExtension();
1316 // Do any required work that we would have done after completion of all
1317 // providers.
1318 if (external_extension_providers_.empty())
1319 OnAllExternalProvidersReady();
1322 void ExtensionService::OnExternalProviderReady(
1323 const extensions::ExternalProviderInterface* provider) {
1324 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1325 CHECK(provider->IsReady());
1327 // An external provider has finished loading. We only take action
1328 // if all of them are finished. So we check them first.
1329 if (AreAllExternalProvidersReady())
1330 OnAllExternalProvidersReady();
1333 bool ExtensionService::AreAllExternalProvidersReady() const {
1334 extensions::ProviderCollection::const_iterator i;
1335 for (i = external_extension_providers_.begin();
1336 i != external_extension_providers_.end(); ++i) {
1337 if (!i->get()->IsReady())
1338 return false;
1340 return true;
1343 void ExtensionService::OnAllExternalProvidersReady() {
1344 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1345 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1346 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1348 // Install any pending extensions.
1349 if (update_once_all_providers_are_ready_ && updater()) {
1350 update_once_all_providers_are_ready_ = false;
1351 extensions::ExtensionUpdater::CheckParams params;
1352 params.callback = external_updates_finished_callback_;
1353 updater()->CheckNow(params);
1356 // Uninstall all the unclaimed extensions.
1357 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1358 extension_prefs_->GetInstalledExtensionsInfo());
1359 for (size_t i = 0; i < extensions_info->size(); ++i) {
1360 ExtensionInfo* info = extensions_info->at(i).get();
1361 if (Manifest::IsExternalLocation(info->extension_location))
1362 CheckExternalUninstall(info->extension_id);
1365 error_controller_->ShowErrorIfNeeded();
1367 external_install_manager_->UpdateExternalExtensionAlert();
1370 void ExtensionService::UnloadExtension(
1371 const std::string& extension_id,
1372 UnloadedExtensionInfo::Reason reason) {
1373 // Make sure the extension gets deleted after we return from this function.
1374 int include_mask =
1375 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1376 scoped_refptr<const Extension> extension(
1377 registry_->GetExtensionById(extension_id, include_mask));
1379 // This method can be called via PostTask, so the extension may have been
1380 // unloaded by the time this runs.
1381 if (!extension.get()) {
1382 // In case the extension may have crashed/uninstalled. Allow the profile to
1383 // clean up its RequestContexts.
1384 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1385 return;
1388 // Keep information about the extension so that we can reload it later
1389 // even if it's not permanently installed.
1390 unloaded_extension_paths_[extension->id()] = extension->path();
1392 // Clean up if the extension is meant to be enabled after a reload.
1393 reloading_extensions_.erase(extension->id());
1395 if (registry_->disabled_extensions().Contains(extension->id())) {
1396 registry_->RemoveDisabled(extension->id());
1397 // Make sure the profile cleans up its RequestContexts when an already
1398 // disabled extension is unloaded (since they are also tracking the disabled
1399 // extensions).
1400 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1401 // Don't send the unloaded notification. It was sent when the extension
1402 // was disabled.
1403 } else {
1404 // Remove the extension from the enabled list.
1405 registry_->RemoveEnabled(extension->id());
1406 NotifyExtensionUnloaded(extension.get(), reason);
1409 content::NotificationService::current()->Notify(
1410 extensions::NOTIFICATION_EXTENSION_REMOVED,
1411 content::Source<Profile>(profile_),
1412 content::Details<const Extension>(extension.get()));
1415 void ExtensionService::RemoveComponentExtension(
1416 const std::string& extension_id) {
1417 scoped_refptr<const Extension> extension(
1418 GetExtensionById(extension_id, false));
1419 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1420 if (extension.get()) {
1421 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1422 extension.get(), extensions::UNINSTALL_REASON_COMPONENT_REMOVED);
1426 void ExtensionService::UnloadAllExtensionsForTest() {
1427 UnloadAllExtensionsInternal();
1430 void ExtensionService::ReloadExtensionsForTest() {
1431 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1432 // warning about calling test code in production.
1433 UnloadAllExtensionsInternal();
1434 component_loader_->LoadAll();
1435 extensions::InstalledLoader(this).LoadAllExtensions();
1436 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1437 // times.
1440 void ExtensionService::SetReadyAndNotifyListeners() {
1441 TRACE_EVENT0("browser,startup",
1442 "ExtensionService::SetReadyAndNotifyListeners");
1443 TRACK_SCOPED_REGION(
1444 "Startup", "ExtensionService::SetReadyAndNotifyListeners");
1445 SCOPED_UMA_HISTOGRAM_TIMER(
1446 "Extensions.ExtensionServiceNotifyReadyListenersTime");
1448 ready_->Signal();
1449 content::NotificationService::current()->Notify(
1450 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1451 content::Source<Profile>(profile_),
1452 content::NotificationService::NoDetails());
1455 void ExtensionService::OnLoadedInstalledExtensions() {
1456 if (updater_)
1457 updater_->Start();
1459 OnBlacklistUpdated();
1462 void ExtensionService::AddExtension(const Extension* extension) {
1463 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1464 // default extension state to DISABLED when the --disable-extensions flag
1465 // is set (http://crbug.com/29067).
1466 if (!extensions_enabled() &&
1467 !extension->is_theme() &&
1468 extension->location() != Manifest::COMPONENT &&
1469 !Manifest::IsExternalLocation(extension->location())) {
1470 return;
1473 bool is_extension_upgrade = false;
1474 bool is_extension_installed = false;
1475 const Extension* old = GetInstalledExtension(extension->id());
1476 if (old) {
1477 is_extension_installed = true;
1478 int version_compare_result =
1479 extension->version()->CompareTo(*(old->version()));
1480 is_extension_upgrade = version_compare_result > 0;
1481 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1482 // that we aren't downgrading.
1483 if (!Manifest::IsUnpackedLocation(extension->location()))
1484 CHECK_GE(version_compare_result, 0);
1486 // If the extension was disabled for a reload, then enable it.
1487 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1489 // Set the upgraded bit; we consider reloads upgrades.
1490 system_->runtime_data()->SetBeingUpgraded(extension->id(),
1491 is_extension_upgrade || reloading);
1493 // The extension is now loaded, remove its data from unloaded extension map.
1494 unloaded_extension_paths_.erase(extension->id());
1496 // If a terminated extension is loaded, remove it from the terminated list.
1497 UntrackTerminatedExtension(extension->id());
1499 // Check if the extension's privileges have changed and mark the
1500 // extension disabled if necessary.
1501 CheckPermissionsIncrease(extension, is_extension_installed);
1503 if (is_extension_installed && !reloading) {
1504 // To upgrade an extension in place, unload the old one and then load the
1505 // new one. ReloadExtension disables the extension, which is sufficient.
1506 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1509 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1510 // Only prefs is checked for the blacklist. We rely on callers to check the
1511 // blacklist before calling into here, e.g. CrxInstaller checks before
1512 // installation then threads through the install and pending install flow
1513 // of this class, and we check when loading installed extensions.
1514 registry_->AddBlacklisted(extension);
1515 } else if (block_extensions_ && CanBlockExtension(extension)) {
1516 registry_->AddBlocked(extension);
1517 } else if (!reloading &&
1518 extension_prefs_->IsExtensionDisabled(extension->id())) {
1519 registry_->AddDisabled(extension);
1520 if (extension_sync_service_)
1521 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1522 content::NotificationService::current()->Notify(
1523 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1524 content::Source<Profile>(profile_),
1525 content::Details<const Extension>(extension));
1527 // Show the extension disabled error if a permissions increase or a remote
1528 // installation is the reason it was disabled, and no other reasons exist.
1529 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1530 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1531 Extension::DISABLE_REMOTE_INSTALL;
1532 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1533 extensions::AddExtensionDisabledError(
1534 this,
1535 extension,
1536 extension_prefs_->HasDisableReason(
1537 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1539 } else if (reloading) {
1540 // Replace the old extension with the new version.
1541 CHECK(!registry_->AddDisabled(extension));
1542 EnableExtension(extension->id());
1543 } else {
1544 // All apps that are displayed in the launcher are ordered by their ordinals
1545 // so we must ensure they have valid ordinals.
1546 if (extension->RequiresSortOrdinal()) {
1547 extension_prefs_->app_sorting()->SetExtensionVisible(
1548 extension->id(),
1549 extension->ShouldDisplayInNewTabPage() &&
1550 !extension_prefs_->IsEphemeralApp(extension->id()));
1551 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1552 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1553 extension->id(), syncer::StringOrdinal());
1557 registry_->AddEnabled(extension);
1558 if (extension_sync_service_)
1559 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1560 NotifyExtensionLoaded(extension);
1562 system_->runtime_data()->SetBeingUpgraded(extension->id(), false);
1565 void ExtensionService::AddComponentExtension(const Extension* extension) {
1566 const std::string old_version_string(
1567 extension_prefs_->GetVersionString(extension->id()));
1568 const Version old_version(old_version_string);
1570 VLOG(1) << "AddComponentExtension " << extension->name();
1571 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1572 VLOG(1) << "Component extension " << extension->name() << " ("
1573 << extension->id() << ") installing/upgrading from '"
1574 << old_version_string << "' to " << extension->version()->GetString();
1576 AddNewOrUpdatedExtension(extension,
1577 Extension::ENABLED,
1578 extensions::kInstallFlagNone,
1579 syncer::StringOrdinal(),
1580 std::string());
1581 return;
1584 AddExtension(extension);
1587 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1588 bool is_extension_installed) {
1589 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1591 // We keep track of all permissions the user has granted each extension.
1592 // This allows extensions to gracefully support backwards compatibility
1593 // by including unknown permissions in their manifests. When the user
1594 // installs the extension, only the recognized permissions are recorded.
1595 // When the unknown permissions become recognized (e.g., through browser
1596 // upgrade), we can prompt the user to accept these new permissions.
1597 // Extensions can also silently upgrade to less permissions, and then
1598 // silently upgrade to a version that adds these permissions back.
1600 // For example, pretend that Chrome 10 includes a permission "omnibox"
1601 // for an API that adds suggestions to the omnibox. An extension can
1602 // maintain backwards compatibility while still having "omnibox" in the
1603 // manifest. If a user installs the extension on Chrome 9, the browser
1604 // will record the permissions it recognized, not including "omnibox."
1605 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1606 // will disable the extension and prompt the user to approve the increase
1607 // in privileges. The extension could then release a new version that
1608 // removes the "omnibox" permission. When the user upgrades, Chrome will
1609 // still remember that "omnibox" had been granted, so that if the
1610 // extension once again includes "omnibox" in an upgrade, the extension
1611 // can upgrade without requiring this user's approval.
1612 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1614 // Silently grant all active permissions to default apps and apps installed
1615 // in kiosk mode.
1616 bool auto_grant_permission =
1617 extension->was_installed_by_default() ||
1618 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1619 if (auto_grant_permission)
1620 GrantPermissions(extension);
1622 bool is_privilege_increase = false;
1623 // We only need to compare the granted permissions to the current permissions
1624 // if the extension has not been auto-granted its permissions above and is
1625 // installed internally.
1626 if (extension->location() == Manifest::INTERNAL && !auto_grant_permission) {
1627 // Add all the recognized permissions if the granted permissions list
1628 // hasn't been initialized yet.
1629 scoped_refptr<PermissionSet> granted_permissions =
1630 extension_prefs_->GetGrantedPermissions(extension->id());
1631 CHECK(granted_permissions.get());
1633 // Here, we check if an extension's privileges have increased in a manner
1634 // that requires the user's approval. This could occur because the browser
1635 // upgraded and recognized additional privileges, or an extension upgrades
1636 // to a version that requires additional privileges.
1637 is_privilege_increase =
1638 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1639 granted_permissions.get(),
1640 extension->permissions_data()->active_permissions().get(),
1641 extension->GetType());
1644 if (is_extension_installed) {
1645 // If the extension was already disabled, suppress any alerts for becoming
1646 // disabled on permissions increase.
1647 bool previously_disabled =
1648 extension_prefs_->IsExtensionDisabled(extension->id());
1649 // Legacy disabled extensions do not have a disable reason. Infer that if
1650 // there was no permission increase, it was likely disabled by the user.
1651 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1652 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1653 disable_reasons |= Extension::DISABLE_USER_ACTION;
1655 // Extensions that came to us disabled from sync need a similar inference,
1656 // except based on the new version's permissions.
1657 if (previously_disabled &&
1658 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1659 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1660 extension_prefs_->ClearDisableReasons(extension->id());
1661 if (!is_privilege_increase)
1662 disable_reasons |= Extension::DISABLE_USER_ACTION;
1664 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1667 // Extension has changed permissions significantly. Disable it. A
1668 // notification should be sent by the caller. If the extension is already
1669 // disabled because it was installed remotely, don't add another disable
1670 // reason.
1671 if (is_privilege_increase &&
1672 disable_reasons != Extension::DISABLE_REMOTE_INSTALL) {
1673 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1674 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1675 RecordPermissionMessagesHistogram(extension, "AutoDisable");
1677 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1679 #if defined(ENABLE_SUPERVISED_USERS)
1680 // If a custodian-installed extension is disabled for a supervised user due
1681 // to a permissions increase, send a request to the custodian, since the
1682 // supervised user themselves can't re-enable the extension.
1683 if (extensions::util::IsExtensionSupervised(extension, profile_)) {
1684 SupervisedUserService* supervised_user_service =
1685 SupervisedUserServiceFactory::GetForProfile(profile_);
1686 supervised_user_service->AddExtensionUpdateRequest(
1687 extension->id(), *extension->version(),
1688 base::Bind(ExtensionUpdateRequestSent, extension->id()));
1690 #endif
1692 if (disable_reasons != Extension::DISABLE_NONE) {
1693 extension_prefs_->AddDisableReason(
1694 extension->id(),
1695 static_cast<Extension::DisableReason>(disable_reasons));
1699 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1700 std::set<std::string> extension_ids;
1701 const ExtensionSet& extensions = registry_->enabled_extensions();
1702 for (ExtensionSet::const_iterator iter = extensions.begin();
1703 iter != extensions.end(); ++iter) {
1704 const Extension* extension = iter->get();
1705 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1706 extension_ids.insert(extension->id());
1709 // TODO(kalman): This is broken. ExtensionService is per-profile.
1710 // crash_keys::SetActiveExtensions is per-process. See
1711 // http://crbug.com/355029.
1712 crash_keys::SetActiveExtensions(extension_ids);
1715 void ExtensionService::OnExtensionInstalled(
1716 const Extension* extension,
1717 const syncer::StringOrdinal& page_ordinal,
1718 int install_flags) {
1719 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1721 const std::string& id = extension->id();
1722 int disable_reasons = GetDisableReasonsOnInstalled(extension);
1723 std::string install_parameter;
1724 const extensions::PendingExtensionInfo* pending_extension_info =
1725 pending_extension_manager()->GetById(id);
1726 if (pending_extension_info) {
1727 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1728 pending_extension_manager()->Remove(id);
1730 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1731 << id << " of type " << extension->GetType()
1732 << " and update URL "
1733 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1734 << "; not installing";
1736 // Delete the extension directory since we're not going to
1737 // load it.
1738 if (!GetFileTaskRunner()->PostTask(
1739 FROM_HERE,
1740 base::Bind(&extensions::file_util::DeleteFile,
1741 extension->path(),
1742 true))) {
1743 NOTREACHED();
1745 return;
1748 install_parameter = pending_extension_info->install_parameter();
1749 pending_extension_manager()->Remove(id);
1750 } else {
1751 // We explicitly want to re-enable an uninstalled external
1752 // extension; if we're here, that means the user is manually
1753 // installing the extension.
1754 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1755 disable_reasons = Extension::DISABLE_NONE;
1759 // Unsupported requirements overrides the management policy.
1760 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1761 disable_reasons |= Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1762 } else {
1763 // Requirement is supported now, remove the corresponding disable reason
1764 // instead.
1765 extension_prefs_->RemoveDisableReason(
1766 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1767 disable_reasons &= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1770 // Check if the extension was disabled because of the minimum version
1771 // requirements from enterprise policy, and satisfies it now.
1772 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1773 ->CheckMinimumVersion(extension, nullptr)) {
1774 // And remove the corresponding disable reason.
1775 extension_prefs_->RemoveDisableReason(
1776 id, Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1777 disable_reasons &= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY;
1780 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1781 // Installation of a blacklisted extension can happen from sync, policy,
1782 // etc, where to maintain consistency we need to install it, just never
1783 // load it (see AddExtension). Usually it should be the job of callers to
1784 // intercept blacklisted extensions earlier (e.g. CrxInstaller, before even
1785 // showing the install dialogue).
1786 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1787 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1788 extension->location(),
1789 Manifest::NUM_LOCATIONS);
1792 if (!GetInstalledExtension(extension->id())) {
1793 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1794 extension->GetType(), 100);
1795 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1796 extension->location(), Manifest::NUM_LOCATIONS);
1797 RecordPermissionMessagesHistogram(extension, "Install");
1798 } else {
1799 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1800 extension->GetType(), 100);
1801 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1802 extension->location(), Manifest::NUM_LOCATIONS);
1804 // A fully installed app cannot be demoted to an ephemeral app.
1805 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1806 !extension_prefs_->IsEphemeralApp(id)) {
1807 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1811 if (disable_reasons)
1812 extension_prefs_->AddDisableReasons(id, disable_reasons);
1814 const Extension::State initial_state =
1815 disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED
1816 : Extension::DISABLED;
1818 if (ShouldDelayExtensionUpdate(
1820 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1821 extension_prefs_->SetDelayedInstallInfo(
1822 extension,
1823 initial_state,
1824 install_flags,
1825 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1826 page_ordinal,
1827 install_parameter);
1829 // Transfer ownership of |extension|.
1830 delayed_installs_.Insert(extension);
1832 // Notify observers that app update is available.
1833 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1834 OnAppUpdateAvailable(extension));
1835 return;
1838 extensions::SharedModuleService::ImportStatus status =
1839 shared_module_service_->SatisfyImports(extension);
1840 if (installs_delayed_for_gc_) {
1841 extension_prefs_->SetDelayedInstallInfo(
1842 extension,
1843 initial_state,
1844 install_flags,
1845 extensions::ExtensionPrefs::DELAY_REASON_GC,
1846 page_ordinal,
1847 install_parameter);
1848 delayed_installs_.Insert(extension);
1849 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1850 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1851 extension_prefs_->SetDelayedInstallInfo(
1852 extension,
1853 initial_state,
1854 install_flags,
1855 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1856 page_ordinal,
1857 install_parameter);
1858 delayed_installs_.Insert(extension);
1860 } else {
1861 AddNewOrUpdatedExtension(extension,
1862 initial_state,
1863 install_flags,
1864 page_ordinal,
1865 install_parameter);
1869 void ExtensionService::OnExtensionManagementSettingsChanged() {
1870 error_controller_->ShowErrorIfNeeded();
1872 // Revokes blocked permissions from active_permissions for all extensions.
1873 extensions::ExtensionManagement* settings =
1874 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1875 CHECK(settings);
1876 scoped_ptr<ExtensionSet> all_extensions(
1877 registry_->GenerateInstalledExtensionsSet());
1878 for (const auto& extension : *all_extensions.get()) {
1879 if (!settings->IsPermissionSetAllowed(
1880 extension.get(),
1881 extension->permissions_data()->active_permissions())) {
1882 extensions::PermissionsUpdater(profile()).RemovePermissions(
1883 extension.get(),
1884 settings->GetBlockedPermissions(extension.get()).get());
1888 CheckManagementPolicy();
1891 void ExtensionService::AddNewOrUpdatedExtension(
1892 const Extension* extension,
1893 Extension::State initial_state,
1894 int install_flags,
1895 const syncer::StringOrdinal& page_ordinal,
1896 const std::string& install_parameter) {
1897 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1898 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1899 extension_prefs_->OnExtensionInstalled(
1900 extension, initial_state, page_ordinal, install_flags, install_parameter);
1901 delayed_installs_.Remove(extension->id());
1902 if (InstallVerifier::NeedsVerification(*extension))
1903 InstallVerifier::Get(GetBrowserContext())->VerifyExtension(extension->id());
1905 const Extension* old = GetInstalledExtension(extension->id());
1906 if (extensions::AppDataMigrator::NeedsMigration(old, extension)) {
1907 app_data_migrator_->DoMigrationAndReply(
1908 old, extension,
1909 base::Bind(&ExtensionService::FinishInstallation, AsWeakPtr(),
1910 make_scoped_refptr(extension), was_ephemeral));
1911 return;
1914 FinishInstallation(extension, was_ephemeral);
1917 void ExtensionService::MaybeFinishDelayedInstallation(
1918 const std::string& extension_id) {
1919 // Check if the extension already got installed.
1920 if (!delayed_installs_.Contains(extension_id))
1921 return;
1922 extensions::ExtensionPrefs::DelayReason reason =
1923 extension_prefs_->GetDelayedInstallReason(extension_id);
1925 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1926 // preferences files that will not have set this field but it was previously
1927 // only used for idle updates.
1928 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1929 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1930 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1931 return;
1933 const Extension* extension = delayed_installs_.GetByID(extension_id);
1934 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1935 extensions::SharedModuleService::ImportStatus status =
1936 shared_module_service_->SatisfyImports(extension);
1937 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1938 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1939 delayed_installs_.Remove(extension_id);
1940 // Make sure no version of the extension is actually installed, (i.e.,
1941 // that this delayed install was not an update).
1942 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1943 extension_prefs_->DeleteExtensionPrefs(extension_id);
1945 return;
1949 FinishDelayedInstallation(extension_id);
1952 void ExtensionService::FinishDelayedInstallation(
1953 const std::string& extension_id) {
1954 scoped_refptr<const Extension> extension(
1955 GetPendingExtensionUpdate(extension_id));
1956 CHECK(extension.get());
1957 delayed_installs_.Remove(extension_id);
1959 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1960 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1961 NOTREACHED();
1963 FinishInstallation(extension.get(), was_ephemeral);
1966 void ExtensionService::FinishInstallation(
1967 const Extension* extension, bool was_ephemeral) {
1968 const extensions::Extension* existing_extension =
1969 GetInstalledExtension(extension->id());
1970 bool is_update = false;
1971 std::string old_name;
1972 if (existing_extension) {
1973 is_update = true;
1974 old_name = existing_extension->name();
1976 bool from_ephemeral =
1977 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1978 extensions::InstalledExtensionInfo details(
1979 extension, is_update, from_ephemeral, old_name);
1980 content::NotificationService::current()->Notify(
1981 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1982 content::Source<Profile>(profile_),
1983 content::Details<const extensions::InstalledExtensionInfo>(&details));
1985 registry_->TriggerOnWillBeInstalled(
1986 extension, is_update, from_ephemeral, old_name);
1988 // Unpacked extensions default to allowing file access, but if that has been
1989 // overridden, don't reset the value.
1990 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1991 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1992 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1995 AddExtension(extension);
1997 // Notify observers that need to know when an installation is complete.
1998 registry_->TriggerOnInstalled(extension, is_update);
2000 // Check extensions that may have been delayed only because this shared module
2001 // was not available.
2002 if (SharedModuleInfo::IsSharedModule(extension))
2003 MaybeFinishDelayedInstallations();
2006 void ExtensionService::PromoteEphemeralApp(
2007 const extensions::Extension* extension, bool is_from_sync) {
2008 DCHECK(GetInstalledExtension(extension->id()) &&
2009 extension_prefs_->IsEphemeralApp(extension->id()));
2011 if (extension->RequiresSortOrdinal()) {
2012 extension_prefs_->app_sorting()->SetExtensionVisible(
2013 extension->id(), extension->ShouldDisplayInNewTabPage());
2015 if (!is_from_sync) {
2016 // Reset the sort ordinals of the app to ensure it is added to the default
2017 // position, like newly installed apps would.
2018 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
2021 extension_prefs_->app_sorting()->EnsureValidOrdinals(
2022 extension->id(), syncer::StringOrdinal());
2025 // Remove the ephemeral flags from the preferences.
2026 extension_prefs_->OnEphemeralAppPromoted(extension->id());
2028 // Fire install-related events to allow observers to handle the promotion
2029 // of the ephemeral app.
2030 extensions::InstalledExtensionInfo details(
2031 extension,
2032 true /* is update */,
2033 true /* from ephemeral */,
2034 extension->name() /* old name */);
2035 content::NotificationService::current()->Notify(
2036 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2037 content::Source<Profile>(profile_),
2038 content::Details<const extensions::InstalledExtensionInfo>(&details));
2040 registry_->TriggerOnWillBeInstalled(
2041 extension,
2042 true /* is update */,
2043 true /* from ephemeral */,
2044 extension->name() /* old name */);
2046 if (registry_->enabled_extensions().Contains(extension->id())) {
2047 // If the app is already enabled and loaded, fire the load events to allow
2048 // observers to handle the promotion of the ephemeral app.
2049 content::NotificationService::current()->Notify(
2050 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
2051 content::Source<Profile>(profile_),
2052 content::Details<const Extension>(extension));
2054 registry_->TriggerOnLoaded(extension);
2055 } else {
2056 // Cached ephemeral apps may be updated and disabled due to permissions
2057 // increase. The app can be enabled (as long as no other disable reasons
2058 // exist) as the install was user-acknowledged.
2059 int disable_mask = Extension::DISABLE_NONE;
2060 if (!is_from_sync)
2061 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
2063 int other_disable_reasons =
2064 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
2065 if (!other_disable_reasons) {
2066 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
2067 GrantPermissionsAndEnableExtension(extension);
2068 else
2069 EnableExtension(extension->id());
2073 registry_->TriggerOnInstalled(extension, true);
2075 if (!is_from_sync && extension_sync_service_)
2076 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
2079 const Extension* ExtensionService::GetPendingExtensionUpdate(
2080 const std::string& id) const {
2081 return delayed_installs_.GetByID(id);
2084 void ExtensionService::RegisterContentSettings(
2085 HostContentSettingsMap* host_content_settings_map) {
2086 TRACE_EVENT0("browser,startup", "ExtensionService::RegisterContentSettings");
2087 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2088 host_content_settings_map->RegisterProvider(
2089 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
2090 scoped_ptr<content_settings::ObservableProvider>(
2091 new content_settings::InternalExtensionProvider(profile_)));
2093 host_content_settings_map->RegisterProvider(
2094 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
2095 scoped_ptr<content_settings::ObservableProvider>(
2096 new content_settings::CustomExtensionProvider(
2097 extensions::ContentSettingsService::Get(
2098 profile_)->content_settings_store(),
2099 profile_->GetOriginalProfile() != profile_)));
2102 void ExtensionService::TrackTerminatedExtension(
2103 const std::string& extension_id) {
2104 extensions_being_terminated_.erase(extension_id);
2106 const Extension* extension = GetInstalledExtension(extension_id);
2107 if (!extension) {
2108 return;
2111 // No need to check for duplicates; inserting a duplicate is a no-op.
2112 registry_->AddTerminated(make_scoped_refptr(extension));
2113 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2116 void ExtensionService::TerminateExtension(const std::string& extension_id) {
2117 TrackTerminatedExtension(extension_id);
2120 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2121 std::string lowercase_id = base::StringToLowerASCII(id);
2122 const Extension* extension =
2123 registry_->terminated_extensions().GetByID(lowercase_id);
2124 registry_->RemoveTerminated(lowercase_id);
2125 if (extension) {
2126 content::NotificationService::current()->Notify(
2127 extensions::NOTIFICATION_EXTENSION_REMOVED,
2128 content::Source<Profile>(profile_),
2129 content::Details<const Extension>(extension));
2133 const Extension* ExtensionService::GetInstalledExtension(
2134 const std::string& id) const {
2135 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2138 bool ExtensionService::OnExternalExtensionFileFound(
2139 const std::string& id,
2140 const Version* version,
2141 const base::FilePath& path,
2142 Manifest::Location location,
2143 int creation_flags,
2144 bool mark_acknowledged,
2145 bool install_immediately) {
2146 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2147 CHECK(crx_file::id_util::IdIsValid(id));
2148 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2149 return false;
2151 // Before even bothering to unpack, check and see if we already have this
2152 // version. This is important because these extensions are going to get
2153 // installed on every startup.
2154 const Extension* existing = GetExtensionById(id, true);
2156 if (existing) {
2157 // The default apps will have the location set as INTERNAL. Since older
2158 // default apps are installed as EXTERNAL, we override them. However, if the
2159 // app is already installed as internal, then do the version check.
2160 // TODO(grv) : Remove after Q1-2013.
2161 bool is_default_apps_migration =
2162 (location == Manifest::INTERNAL &&
2163 Manifest::IsExternalLocation(existing->location()));
2165 if (!is_default_apps_migration) {
2166 DCHECK(version);
2168 switch (existing->version()->CompareTo(*version)) {
2169 case -1: // existing version is older, we should upgrade
2170 break;
2171 case 0: // existing version is same, do nothing
2172 return false;
2173 case 1: // existing version is newer, uh-oh
2174 LOG(WARNING) << "Found external version of extension " << id
2175 << "that is older than current version. Current version "
2176 << "is: " << existing->VersionString() << ". New "
2177 << "version is: " << version->GetString()
2178 << ". Keeping current version.";
2179 return false;
2184 // If the extension is already pending, don't start an install.
2185 if (!pending_extension_manager()->AddFromExternalFile(
2186 id, location, *version, creation_flags, mark_acknowledged)) {
2187 return false;
2190 // no client (silent install)
2191 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2192 installer->set_install_source(location);
2193 installer->set_expected_id(id);
2194 installer->set_expected_version(*version);
2195 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2196 installer->set_install_immediately(install_immediately);
2197 installer->set_creation_flags(creation_flags);
2198 #if defined(OS_CHROMEOS)
2199 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2200 #else
2201 installer->InstallCrx(path);
2202 #endif
2204 // Depending on the source, a new external extension might not need a user
2205 // notification on installation. For such extensions, mark them acknowledged
2206 // now to suppress the notification.
2207 if (mark_acknowledged)
2208 external_install_manager_->AcknowledgeExternalExtension(id);
2210 return true;
2213 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2214 extensions::ExtensionHost* host) {
2215 OrphanedDevTools::iterator iter =
2216 orphaned_dev_tools_.find(host->extension_id());
2217 if (iter == orphaned_dev_tools_.end())
2218 return;
2220 iter->second->ConnectWebContents(host->host_contents());
2221 orphaned_dev_tools_.erase(iter);
2224 void ExtensionService::Observe(int type,
2225 const content::NotificationSource& source,
2226 const content::NotificationDetails& details) {
2227 switch (type) {
2228 case chrome::NOTIFICATION_APP_TERMINATING:
2229 // Shutdown has started. Don't start any more extension installs.
2230 // (We cannot use ExtensionService::Shutdown() for this because it
2231 // happens too late in browser teardown.)
2232 browser_terminating_ = true;
2233 break;
2234 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2235 if (profile_ !=
2236 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2237 break;
2240 extensions::ExtensionHost* host =
2241 content::Details<extensions::ExtensionHost>(details).ptr();
2243 // If the extension is already being terminated, there is nothing left to
2244 // do.
2245 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2246 break;
2248 // Mark the extension as terminated and Unload it. We want it to
2249 // be in a consistent state: either fully working or not loaded
2250 // at all, but never half-crashed. We do it in a PostTask so
2251 // that other handlers of this notification will still have
2252 // access to the Extension and ExtensionHost.
2253 base::ThreadTaskRunnerHandle::Get()->PostTask(
2254 FROM_HERE, base::Bind(&ExtensionService::TrackTerminatedExtension,
2255 AsWeakPtr(), host->extension()->id()));
2256 break;
2258 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2259 content::RenderProcessHost* process =
2260 content::Source<content::RenderProcessHost>(source).ptr();
2261 Profile* host_profile =
2262 Profile::FromBrowserContext(process->GetBrowserContext());
2263 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2264 break;
2266 extensions::ProcessMap* process_map =
2267 extensions::ProcessMap::Get(profile_);
2268 if (process_map->Contains(process->GetID())) {
2269 // An extension process was terminated, this might have resulted in an
2270 // app or extension becoming idle.
2271 std::set<std::string> extension_ids =
2272 process_map->GetExtensionsInProcess(process->GetID());
2273 // In addition to the extensions listed in the process map, one of those
2274 // extensions could be referencing a shared module which is waiting for
2275 // idle to update. Check all imports of these extensions, too.
2276 std::set<std::string> import_ids;
2277 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2278 it != extension_ids.end();
2279 ++it) {
2280 const Extension* extension = GetExtensionById(*it, true);
2281 if (!extension)
2282 continue;
2283 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2284 SharedModuleInfo::GetImports(extension);
2285 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2286 for (import_it = imports.begin(); import_it != imports.end();
2287 import_it++) {
2288 import_ids.insert((*import_it).extension_id);
2291 extension_ids.insert(import_ids.begin(), import_ids.end());
2293 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2294 it != extension_ids.end(); ++it) {
2295 if (delayed_installs_.Contains(*it)) {
2296 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2297 FROM_HERE,
2298 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2299 AsWeakPtr(), *it),
2300 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2305 process_map->RemoveAllFromProcess(process->GetID());
2306 BrowserThread::PostTask(
2307 BrowserThread::IO,
2308 FROM_HERE,
2309 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2310 system_->info_map(),
2311 process->GetID()));
2312 break;
2314 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2315 // Notify observers that chrome update is available.
2316 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2317 OnChromeUpdateAvailable());
2318 break;
2320 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2321 OnProfileDestructionStarted();
2322 break;
2325 default:
2326 NOTREACHED() << "Unexpected notification type.";
2330 int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
2331 Extension::DisableReason disable_reason;
2332 // Extensions disabled by management policy should always be disabled, even
2333 // if it's force-installed.
2334 if (system_->management_policy()->MustRemainDisabled(
2335 extension, &disable_reason, nullptr)) {
2336 // A specified reason is required to disable the extension.
2337 DCHECK(disable_reason != Extension::DISABLE_NONE);
2338 return disable_reason;
2341 // Extensions installed by policy can't be disabled. So even if a previous
2342 // installation disabled the extension, make sure it is now enabled.
2343 if (system_->management_policy()->MustRemainEnabled(extension, nullptr))
2344 return Extension::DISABLE_NONE;
2346 // An already disabled extension should inherit the disable reasons and
2347 // remain disabled.
2348 if (extension_prefs_->IsExtensionDisabled(extension->id())) {
2349 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2350 // If an extension was disabled without specified reason, presume it's
2351 // disabled by user.
2352 return disable_reasons == Extension::DISABLE_NONE
2353 ? Extension::DISABLE_USER_ACTION
2354 : disable_reasons;
2357 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2358 // External extensions are initially disabled. We prompt the user before
2359 // enabling them. Hosted apps are excepted because they are not dangerous
2360 // (they need to be launched by the user anyway).
2361 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2362 Manifest::IsExternalLocation(extension->location()) &&
2363 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2364 return Extension::DISABLE_EXTERNAL_EXTENSION;
2368 return Extension::DISABLE_NONE;
2371 // Helper method to determine if an extension can be blocked.
2372 bool ExtensionService::CanBlockExtension(const Extension* extension) const {
2373 DCHECK(extension);
2374 return extension->location() != Manifest::COMPONENT &&
2375 extension->location() != Manifest::EXTERNAL_COMPONENT &&
2376 !system_->management_policy()->MustRemainEnabled(extension, NULL);
2379 bool ExtensionService::ShouldDelayExtensionUpdate(
2380 const std::string& extension_id,
2381 bool install_immediately) const {
2382 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2384 // If delayed updates are globally disabled, or just for this extension,
2385 // don't delay.
2386 if (!install_updates_when_idle_ || install_immediately)
2387 return false;
2389 const Extension* old = GetInstalledExtension(extension_id);
2390 // If there is no old extension, this is not an update, so don't delay.
2391 if (!old)
2392 return false;
2394 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2395 // Delay installation if the extension listens for the onUpdateAvailable
2396 // event.
2397 return extensions::EventRouter::Get(profile_)
2398 ->ExtensionHasEventListener(extension_id, kOnUpdateAvailableEvent);
2399 } else {
2400 // Delay installation if the extension is not idle.
2401 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2405 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2406 DCHECK(!installs_delayed_for_gc_);
2407 installs_delayed_for_gc_ = true;
2410 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2411 DCHECK(installs_delayed_for_gc_);
2412 installs_delayed_for_gc_ = false;
2413 MaybeFinishDelayedInstallations();
2416 void ExtensionService::MaybeFinishDelayedInstallations() {
2417 std::vector<std::string> to_be_installed;
2418 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2419 it != delayed_installs_.end();
2420 ++it) {
2421 to_be_installed.push_back((*it)->id());
2423 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2424 it != to_be_installed.end();
2425 ++it) {
2426 MaybeFinishDelayedInstallation(*it);
2430 void ExtensionService::OnBlacklistUpdated() {
2431 blacklist_->GetBlacklistedIDs(
2432 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2433 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2436 void ExtensionService::ManageBlacklist(
2437 const extensions::Blacklist::BlacklistStateMap& state_map) {
2438 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2440 std::set<std::string> blacklisted;
2441 ExtensionIdSet greylist;
2442 ExtensionIdSet unchanged;
2443 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2444 state_map.begin();
2445 it != state_map.end();
2446 ++it) {
2447 switch (it->second) {
2448 case extensions::NOT_BLACKLISTED:
2449 break;
2451 case extensions::BLACKLISTED_MALWARE:
2452 blacklisted.insert(it->first);
2453 break;
2455 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2456 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2457 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2458 greylist.insert(it->first);
2459 break;
2461 case extensions::BLACKLISTED_UNKNOWN:
2462 unchanged.insert(it->first);
2463 break;
2467 UpdateBlacklistedExtensions(blacklisted, unchanged);
2468 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2470 error_controller_->ShowErrorIfNeeded();
2473 namespace {
2474 void Partition(const ExtensionIdSet& before,
2475 const ExtensionIdSet& after,
2476 const ExtensionIdSet& unchanged,
2477 ExtensionIdSet* no_longer,
2478 ExtensionIdSet* not_yet) {
2479 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2480 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2481 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2483 } // namespace
2485 void ExtensionService::UpdateBlacklistedExtensions(
2486 const ExtensionIdSet& blacklisted,
2487 const ExtensionIdSet& unchanged) {
2488 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2489 Partition(registry_->blacklisted_extensions().GetIDs(), blacklisted,
2490 unchanged, &no_longer_blocked, &not_yet_blocked);
2492 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2493 it != no_longer_blocked.end(); ++it) {
2494 scoped_refptr<const Extension> extension =
2495 registry_->blacklisted_extensions().GetByID(*it);
2496 if (!extension.get()) {
2497 NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
2498 << "but it was never blacklisted.";
2499 continue;
2501 registry_->RemoveBlacklisted(*it);
2502 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2503 AddExtension(extension.get());
2504 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2505 extension->location(),
2506 Manifest::NUM_LOCATIONS);
2509 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2510 it != not_yet_blocked.end(); ++it) {
2511 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2512 if (!extension.get()) {
2513 NOTREACHED() << "Extension " << *it << " needs to be "
2514 << "blacklisted, but it's not installed.";
2515 continue;
2517 registry_->AddBlacklisted(extension);
2518 extension_prefs_->SetExtensionBlacklistState(
2519 extension->id(), extensions::BLACKLISTED_MALWARE);
2520 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2521 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2522 extension->location(), Manifest::NUM_LOCATIONS);
2526 // TODO(oleg): UMA logging
2527 void ExtensionService::UpdateGreylistedExtensions(
2528 const ExtensionIdSet& greylist,
2529 const ExtensionIdSet& unchanged,
2530 const extensions::Blacklist::BlacklistStateMap& state_map) {
2531 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2532 Partition(greylist_.GetIDs(),
2533 greylist, unchanged,
2534 &no_longer_greylisted, &not_yet_greylisted);
2536 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2537 it != no_longer_greylisted.end(); ++it) {
2538 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2539 if (!extension.get()) {
2540 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2541 << "but it was not marked as greylisted.";
2542 continue;
2545 greylist_.Remove(*it);
2546 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2547 extensions::NOT_BLACKLISTED);
2548 if (extension_prefs_->GetDisableReasons(extension->id()) &
2549 extensions::Extension::DISABLE_GREYLIST)
2550 EnableExtension(*it);
2553 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2554 it != not_yet_greylisted.end(); ++it) {
2555 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2556 if (!extension.get()) {
2557 NOTREACHED() << "Extension " << *it << " needs to be "
2558 << "disabled, but it's not installed.";
2559 continue;
2561 greylist_.Insert(extension);
2562 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2563 state_map.find(*it)->second);
2564 if (registry_->enabled_extensions().Contains(extension->id()))
2565 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2569 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2570 update_observers_.AddObserver(observer);
2573 void ExtensionService::RemoveUpdateObserver(
2574 extensions::UpdateObserver* observer) {
2575 update_observers_.RemoveObserver(observer);
2578 // Used only by test code.
2579 void ExtensionService::UnloadAllExtensionsInternal() {
2580 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2582 registry_->ClearAll();
2583 system_->runtime_data()->ClearAll();
2585 // TODO(erikkay) should there be a notification for this? We can't use
2586 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2587 // or uninstalled.
2590 void ExtensionService::OnProfileDestructionStarted() {
2591 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2592 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2593 it != ids_to_unload.end();
2594 ++it) {
2595 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);