Allow only one bookmark to be added for multiple fast starring
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blob1b1ca1f2debb55cd0816d481ccb1dc2a6af4ea4d
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::PermissionSet;
120 using extensions::SharedModuleInfo;
121 using extensions::SharedModuleService;
122 using extensions::UnloadedExtensionInfo;
124 namespace {
126 // Wait this many seconds after an extensions becomes idle before updating it.
127 const int kUpdateIdleDelay = 5;
129 #if defined(ENABLE_SUPERVISED_USERS)
130 // Callback for SupervisedUserService::AddExtensionUpdateRequest.
131 void ExtensionUpdateRequestSent(const std::string& id, bool success) {
132 LOG_IF(WARNING, !success) << "Failed sending update request for " << id;
134 #endif
136 } // namespace
138 // ExtensionService.
140 void ExtensionService::CheckExternalUninstall(const std::string& id) {
141 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
143 // Check if the providers know about this extension.
144 extensions::ProviderCollection::const_iterator i;
145 for (i = external_extension_providers_.begin();
146 i != external_extension_providers_.end(); ++i) {
147 DCHECK(i->get()->IsReady());
148 if (i->get()->HasExtension(id))
149 return; // Yup, known extension, don't uninstall.
152 // We get the list of external extensions to check from preferences.
153 // It is possible that an extension has preferences but is not loaded.
154 // For example, an extension that requires experimental permissions
155 // will not be loaded if the experimental command line flag is not used.
156 // In this case, do not uninstall.
157 if (!GetInstalledExtension(id)) {
158 // We can't call UninstallExtension with an unloaded/invalid
159 // extension ID.
160 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
161 << "with id: " << id;
162 return;
164 UninstallExtension(id,
165 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
166 base::Bind(&base::DoNothing),
167 NULL);
170 void ExtensionService::SetFileTaskRunnerForTesting(
171 const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
172 file_task_runner_ = task_runner;
175 void ExtensionService::ClearProvidersForTesting() {
176 external_extension_providers_.clear();
179 void ExtensionService::AddProviderForTesting(
180 extensions::ExternalProviderInterface* test_provider) {
181 CHECK(test_provider);
182 external_extension_providers_.push_back(
183 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
186 void ExtensionService::BlacklistExtensionForTest(
187 const std::string& extension_id) {
188 ExtensionIdSet blacklisted;
189 ExtensionIdSet unchanged;
190 blacklisted.insert(extension_id);
191 UpdateBlacklistedExtensions(blacklisted, unchanged);
194 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
195 const std::string& id,
196 const std::string& install_parameter,
197 const GURL& update_url,
198 Manifest::Location location,
199 int creation_flags,
200 bool mark_acknowledged) {
201 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
202 CHECK(crx_file::id_util::IdIsValid(id));
204 if (Manifest::IsExternalLocation(location)) {
205 // All extensions that are not user specific can be cached.
206 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
207 ->AllowCaching(id);
210 const Extension* extension = GetExtensionById(id, true);
211 if (extension) {
212 // Already installed. Skip this install if the current location has
213 // higher priority than |location|.
214 Manifest::Location current = extension->location();
215 if (current == Manifest::GetHigherPriorityLocation(current, location))
216 return false;
217 // Otherwise, overwrite the current installation.
220 // Add |id| to the set of pending extensions. If it can not be added,
221 // then there is already a pending record from a higher-priority install
222 // source. In this case, signal that this extension will not be
223 // installed by returning false.
224 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
226 install_parameter,
227 update_url,
228 location,
229 creation_flags,
230 mark_acknowledged)) {
231 return false;
234 update_once_all_providers_are_ready_ = true;
235 return true;
238 // static
239 // This function is used to uninstall an extension via sync. The LOG statements
240 // within this function are used to inform the user if the uninstall cannot be
241 // done.
242 bool ExtensionService::UninstallExtensionHelper(
243 ExtensionService* extensions_service,
244 const std::string& extension_id,
245 extensions::UninstallReason reason) {
246 // We can't call UninstallExtension with an invalid extension ID.
247 if (!extensions_service->GetInstalledExtension(extension_id)) {
248 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
249 << "id: " << extension_id;
250 return false;
253 // The following call to UninstallExtension will not allow an uninstall of a
254 // policy-controlled extension.
255 base::string16 error;
256 if (!extensions_service->UninstallExtension(
257 extension_id, reason, base::Bind(&base::DoNothing), &error)) {
258 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
259 << ": " << error;
260 return false;
263 return true;
266 ExtensionService::ExtensionService(Profile* profile,
267 const base::CommandLine* command_line,
268 const base::FilePath& install_directory,
269 extensions::ExtensionPrefs* extension_prefs,
270 extensions::Blacklist* blacklist,
271 bool autoupdate_enabled,
272 bool extensions_enabled,
273 extensions::OneShotEvent* ready)
274 : extensions::Blacklist::Observer(blacklist),
275 profile_(profile),
276 system_(extensions::ExtensionSystem::Get(profile)),
277 extension_prefs_(extension_prefs),
278 blacklist_(blacklist),
279 registry_(extensions::ExtensionRegistry::Get(profile)),
280 pending_extension_manager_(profile),
281 install_directory_(install_directory),
282 extensions_enabled_(extensions_enabled),
283 show_extensions_prompts_(true),
284 install_updates_when_idle_(true),
285 ready_(ready),
286 update_once_all_providers_are_ready_(false),
287 browser_terminating_(false),
288 installs_delayed_for_gc_(false),
289 is_first_run_(false),
290 block_extensions_(false),
291 shared_module_service_(new extensions::SharedModuleService(profile_)),
292 app_data_migrator_(new extensions::AppDataMigrator(profile_, registry_)) {
293 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
294 TRACE_EVENT0("browser,startup", "ExtensionService::ExtensionService::ctor");
296 // Figure out if extension installation should be enabled.
297 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
298 *command_line, profile))
299 extensions_enabled_ = false;
301 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
302 content::NotificationService::AllBrowserContextsAndSources());
303 registrar_.Add(this,
304 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
305 content::NotificationService::AllBrowserContextsAndSources());
306 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
307 content::NotificationService::AllBrowserContextsAndSources());
308 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
309 content::NotificationService::AllBrowserContextsAndSources());
310 registrar_.Add(this,
311 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
312 content::Source<Profile>(profile_));
314 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
315 ->AddObserver(this);
317 // Set up the ExtensionUpdater.
318 if (autoupdate_enabled) {
319 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
320 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
321 base::StringToInt(command_line->GetSwitchValueASCII(
322 switches::kExtensionsUpdateFrequency),
323 &update_frequency);
325 updater_.reset(new extensions::ExtensionUpdater(
326 this,
327 extension_prefs,
328 profile->GetPrefs(),
329 profile,
330 update_frequency,
331 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
332 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
333 profile)));
336 component_loader_.reset(
337 new extensions::ComponentLoader(this,
338 profile->GetPrefs(),
339 g_browser_process->local_state(),
340 profile));
342 if (extensions_enabled_) {
343 extensions::ExternalProviderImpl::CreateExternalProviders(
344 this, profile_, &external_extension_providers_);
347 // Set this as the ExtensionService for app sorting to ensure it causes syncs
348 // if required.
349 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
351 error_controller_.reset(
352 new extensions::ExtensionErrorController(profile_, is_first_run_));
353 external_install_manager_.reset(
354 new extensions::ExternalInstallManager(profile_, is_first_run_));
356 extension_action_storage_manager_.reset(
357 new extensions::ExtensionActionStorageManager(profile_));
359 // How long is the path to the Extensions directory?
360 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
361 install_directory_.value().length(), 0, 500, 100);
364 extensions::PendingExtensionManager*
365 ExtensionService::pending_extension_manager() {
366 return &pending_extension_manager_;
369 ExtensionService::~ExtensionService() {
370 // No need to unload extensions here because they are profile-scoped, and the
371 // profile is in the process of being deleted.
373 extensions::ProviderCollection::const_iterator i;
374 for (i = external_extension_providers_.begin();
375 i != external_extension_providers_.end(); ++i) {
376 extensions::ExternalProviderInterface* provider = i->get();
377 provider->ServiceShutdown();
381 void ExtensionService::Shutdown() {
382 extensions::ExtensionManagementFactory::GetInstance()
383 ->GetForBrowserContext(profile())
384 ->RemoveObserver(this);
385 system_->management_policy()->UnregisterProvider(
386 shared_module_policy_provider_.get());
389 const Extension* ExtensionService::GetExtensionById(
390 const std::string& id, bool include_disabled) const {
391 int include_mask = ExtensionRegistry::ENABLED;
392 if (include_disabled) {
393 // Include blacklisted and blocked extensions here because there are
394 // hundreds of callers of this function, and many might assume that this
395 // includes those that have been disabled due to blacklisting or blocking.
396 include_mask |= ExtensionRegistry::DISABLED |
397 ExtensionRegistry::BLACKLISTED | ExtensionRegistry::BLOCKED;
399 return registry_->GetExtensionById(id, include_mask);
402 void ExtensionService::Init() {
403 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
404 TRACE_EVENT0("browser,startup", "ExtensionService::Init");
405 TRACK_SCOPED_REGION("Startup", "ExtensionService::Init");
406 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.ExtensionServiceInitTime");
408 DCHECK(!is_ready()); // Can't redo init.
409 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
411 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
412 if (cmd_line->HasSwitch(switches::kInstallEphemeralAppFromWebstore)) {
413 // The sole purpose of this launch is to install a new extension from CWS
414 // and immediately terminate: loading already installed extensions is
415 // unnecessary and may interfere with the inline install dialog (e.g. if an
416 // extension listens to onStartup and opens a window).
417 SetReadyAndNotifyListeners();
418 } else {
419 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
420 component_loader_->LoadAll();
421 extensions::InstalledLoader(this).LoadAllExtensions();
423 EnabledReloadableExtensions();
424 MaybeFinishShutdownDelayed();
425 SetReadyAndNotifyListeners();
427 // TODO(erikkay): this should probably be deferred to a future point
428 // rather than running immediately at startup.
429 CheckForExternalUpdates();
431 LoadGreylistFromPrefs();
435 void ExtensionService::EnabledReloadableExtensions() {
436 TRACE_EVENT0("browser,startup",
437 "ExtensionService::EnabledReloadableExtensions");
439 std::vector<std::string> extensions_to_enable;
440 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
441 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
442 iter != disabled_extensions.end(); ++iter) {
443 const Extension* e = iter->get();
444 if (extension_prefs_->GetDisableReasons(e->id()) ==
445 Extension::DISABLE_RELOAD) {
446 extensions_to_enable.push_back(e->id());
449 for (const std::string& extension : extensions_to_enable) {
450 EnableExtension(extension);
454 void ExtensionService::MaybeFinishShutdownDelayed() {
455 TRACE_EVENT0("browser,startup",
456 "ExtensionService::MaybeFinishShutdownDelayed");
458 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
459 extension_prefs_->GetAllDelayedInstallInfo());
460 for (size_t i = 0; i < delayed_info->size(); ++i) {
461 ExtensionInfo* info = delayed_info->at(i).get();
462 scoped_refptr<const Extension> extension(NULL);
463 if (info->extension_manifest) {
464 std::string error;
465 extension = Extension::Create(
466 info->extension_path, info->extension_location,
467 *info->extension_manifest,
468 extension_prefs_->GetDelayedInstallCreationFlags(info->extension_id),
469 info->extension_id, &error);
470 if (extension.get())
471 delayed_installs_.Insert(extension);
474 MaybeFinishDelayedInstallations();
475 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
476 extension_prefs_->GetAllDelayedInstallInfo());
477 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
478 delayed_info2->size() - delayed_info->size());
481 void ExtensionService::LoadGreylistFromPrefs() {
482 TRACE_EVENT0("browser,startup", "ExtensionService::LoadGreylistFromPrefs");
484 scoped_ptr<ExtensionSet> all_extensions =
485 registry_->GenerateInstalledExtensionsSet();
487 for (ExtensionSet::const_iterator it = all_extensions->begin();
488 it != all_extensions->end(); ++it) {
489 extensions::BlacklistState state =
490 extension_prefs_->GetExtensionBlacklistState((*it)->id());
491 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
492 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
493 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
494 greylist_.Insert(*it);
498 bool ExtensionService::UpdateExtension(const extensions::CRXFileInfo& file,
499 bool file_ownership_passed,
500 CrxInstaller** out_crx_installer) {
501 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
502 if (browser_terminating_) {
503 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
504 // Leak the temp file at extension_path. We don't want to add to the disk
505 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
506 // the file is in the OS temp directory which should be cleaned up for us.
507 return false;
510 const std::string& id = file.extension_id;
512 const extensions::PendingExtensionInfo* pending_extension_info =
513 pending_extension_manager()->GetById(id);
515 const Extension* extension = GetInstalledExtension(id);
516 if (!pending_extension_info && !extension) {
517 LOG(WARNING) << "Will not update extension " << id
518 << " because it is not installed or pending";
519 // Delete extension_path since we're not creating a CrxInstaller
520 // that would do it for us.
521 if (!GetFileTaskRunner()->PostTask(
522 FROM_HERE,
523 base::Bind(&extensions::file_util::DeleteFile, file.path, false)))
524 NOTREACHED();
526 return false;
529 scoped_refptr<CrxInstaller> installer(
530 CrxInstaller::Create(this, scoped_ptr<ExtensionInstallPrompt>()));
531 installer->set_expected_id(id);
532 installer->set_expected_hash(file.expected_hash);
533 int creation_flags = Extension::NO_FLAGS;
534 if (pending_extension_info) {
535 installer->set_install_source(pending_extension_info->install_source());
536 installer->set_allow_silent_install(true);
537 if (pending_extension_info->remote_install())
538 installer->set_grant_permissions(false);
539 creation_flags = pending_extension_info->creation_flags();
540 if (pending_extension_info->mark_acknowledged())
541 external_install_manager_->AcknowledgeExternalExtension(id);
543 // If the extension came in disabled due to a permission increase, then
544 // don't grant it all the permissions. crbug.com/484214
545 if (extensions::ExtensionPrefs::Get(profile_)->HasDisableReason(
546 id, Extension::DISABLE_PERMISSIONS_INCREASE)) {
547 installer->set_grant_permissions(false);
549 } else if (extension) {
550 installer->set_install_source(extension->location());
552 // If the extension was installed from or has migrated to the webstore, or
553 // its auto-update URL is from the webstore, treat it as a webstore install.
554 // Note that we ignore some older extensions with blank auto-update URLs
555 // because we are mostly concerned with restrictions on NaCl extensions,
556 // which are newer.
557 if ((extension && extension->from_webstore()) ||
558 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
559 (!extension && extension_urls::IsWebstoreUpdateUrl(
560 pending_extension_info->update_url()))) {
561 creation_flags |= Extension::FROM_WEBSTORE;
564 // Bookmark apps being updated is kind of a contradiction, but that's because
565 // we mark the default apps as bookmark apps, and they're hosted in the web
566 // store, thus they can get updated. See http://crbug.com/101605 for more
567 // details.
568 if (extension && extension->from_bookmark())
569 creation_flags |= Extension::FROM_BOOKMARK;
571 if (extension && extension->was_installed_by_default())
572 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
574 if (extension && extension->was_installed_by_oem())
575 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
577 if (extension && extension->was_installed_by_custodian())
578 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
580 if (extension) {
581 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
582 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
585 installer->set_creation_flags(creation_flags);
587 installer->set_delete_source(file_ownership_passed);
588 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
589 installer->InstallCrxFile(file);
591 if (out_crx_installer)
592 *out_crx_installer = installer.get();
594 return true;
597 void ExtensionService::ReloadExtensionImpl(
598 // "transient" because the process of reloading may cause the reference
599 // to become invalid. Instead, use |extension_id|, a copy.
600 const std::string& transient_extension_id,
601 bool be_noisy) {
602 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
604 // If the extension is already reloading, don't reload again.
605 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
606 Extension::DISABLE_RELOAD) {
607 return;
610 // Ignore attempts to reload a blacklisted or blocked extension. Sometimes
611 // this can happen in a convoluted reload sequence triggered by the
612 // termination of a blacklisted or blocked extension and a naive attempt to
613 // reload it. For an example see http://crbug.com/373842.
614 if (registry_->blacklisted_extensions().Contains(transient_extension_id) ||
615 registry_->blocked_extensions().Contains(transient_extension_id)) {
616 return;
619 base::FilePath path;
621 std::string extension_id = transient_extension_id;
622 const Extension* transient_current_extension =
623 GetExtensionById(extension_id, false);
625 // Disable the extension if it's loaded. It might not be loaded if it crashed.
626 if (transient_current_extension) {
627 // If the extension has an inspector open for its background page, detach
628 // the inspector and hang onto a cookie for it, so that we can reattach
629 // later.
630 // TODO(yoz): this is not incognito-safe!
631 extensions::ProcessManager* manager =
632 extensions::ProcessManager::Get(profile_);
633 extensions::ExtensionHost* host =
634 manager->GetBackgroundHostForExtension(extension_id);
635 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
636 // Look for an open inspector for the background page.
637 scoped_refptr<DevToolsAgentHost> agent_host =
638 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
639 agent_host->DisconnectWebContents();
640 orphaned_dev_tools_[extension_id] = agent_host;
643 path = transient_current_extension->path();
644 // BeingUpgraded is set back to false when the extension is added.
645 system_->runtime_data()->SetBeingUpgraded(transient_current_extension->id(),
646 true);
647 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
648 reloading_extensions_.insert(extension_id);
649 } else {
650 std::map<std::string, base::FilePath>::const_iterator iter =
651 unloaded_extension_paths_.find(extension_id);
652 if (iter == unloaded_extension_paths_.end()) {
653 return;
655 path = unloaded_extension_paths_[extension_id];
658 transient_current_extension = NULL;
660 if (delayed_installs_.Contains(extension_id)) {
661 FinishDelayedInstallation(extension_id);
662 return;
665 // If we're reloading a component extension, use the component extension
666 // loader's reloader.
667 if (component_loader_->Exists(extension_id)) {
668 component_loader_->Reload(extension_id);
669 return;
672 // Check the installed extensions to see if what we're reloading was already
673 // installed.
674 scoped_ptr<ExtensionInfo> installed_extension(
675 extension_prefs_->GetInstalledExtensionInfo(extension_id));
676 if (installed_extension.get() &&
677 installed_extension->extension_manifest.get()) {
678 extensions::InstalledLoader(this).Load(*installed_extension, false);
679 } else {
680 // Otherwise, the extension is unpacked (location LOAD).
681 // We should always be able to remember the extension's path. If it's not in
682 // the map, someone failed to update |unloaded_extension_paths_|.
683 CHECK(!path.empty());
684 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
685 extensions::UnpackedInstaller::Create(this);
686 unpacked_installer->set_be_noisy_on_failure(be_noisy);
687 unpacked_installer->Load(path);
691 void ExtensionService::ReloadExtension(const std::string& extension_id) {
692 ReloadExtensionImpl(extension_id, true); // be_noisy
695 void ExtensionService::ReloadExtensionWithQuietFailure(
696 const std::string& extension_id) {
697 ReloadExtensionImpl(extension_id, false); // be_noisy
700 bool ExtensionService::UninstallExtension(
701 // "transient" because the process of uninstalling may cause the reference
702 // to become invalid. Instead, use |extenson->id()|.
703 const std::string& transient_extension_id,
704 extensions::UninstallReason reason,
705 const base::Closure& deletion_done_callback,
706 base::string16* error) {
707 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
709 scoped_refptr<const Extension> extension =
710 GetInstalledExtension(transient_extension_id);
712 // Callers should not send us nonexistent extensions.
713 CHECK(extension.get());
715 ManagementPolicy* by_policy = system_->management_policy();
716 // Policy change which triggers an uninstall will always set
717 // |external_uninstall| to true so this is the only way to uninstall
718 // managed extensions.
719 // Shared modules being uninstalled will also set |external_uninstall| to true
720 // so that we can guarantee users don't uninstall a shared module.
721 // (crbug.com/273300)
722 // TODO(rdevlin.cronin): This is probably not right. We should do something
723 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
724 // we don't do this.
725 bool external_uninstall =
726 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
727 (reason == extensions::UNINSTALL_REASON_COMPONENT_REMOVED) ||
728 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
729 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
730 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
731 (reason == extensions::UNINSTALL_REASON_SYNC &&
732 extension->was_installed_by_custodian());
733 if (!external_uninstall &&
734 (!by_policy->UserMayModifySettings(extension.get(), error) ||
735 by_policy->MustRemainInstalled(extension.get(), error))) {
736 content::NotificationService::current()->Notify(
737 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
738 content::Source<Profile>(profile_),
739 content::Details<const Extension>(extension.get()));
740 return false;
743 InstallVerifier::Get(GetBrowserContext())->Remove(extension->id());
745 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
746 extension->GetType(), 100);
747 RecordPermissionMessagesHistogram(extension.get(), "Uninstall");
749 // Unload before doing more cleanup to ensure that nothing is hanging on to
750 // any of these resources.
751 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
753 // Tell the backend to start deleting installed extensions on the file thread.
754 if (!Manifest::IsUnpackedLocation(extension->location())) {
755 if (!GetFileTaskRunner()->PostTask(
756 FROM_HERE,
757 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
758 extension->id(),
759 profile_,
760 install_directory_,
761 extension->path())))
762 NOTREACHED();
765 extensions::DataDeleter::StartDeleting(
766 profile_, extension.get(), deletion_done_callback);
768 UntrackTerminatedExtension(extension->id());
770 // Notify interested parties that we've uninstalled this extension.
771 ExtensionRegistry::Get(profile_)
772 ->TriggerOnUninstalled(extension.get(), reason);
774 // Don't sync the uninstall if we're going to reinstall the extension
775 // momentarily.
776 if (reason != extensions::UNINSTALL_REASON_REINSTALL) {
777 ExtensionSyncService::Get(profile_)->SyncUninstallExtension(*extension);
780 delayed_installs_.Remove(extension->id());
782 extension_prefs_->OnExtensionUninstalled(
783 extension->id(), extension->location(), external_uninstall);
785 // Track the uninstallation.
786 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
788 return true;
791 // static
792 void ExtensionService::UninstallExtensionOnFileThread(
793 const std::string& id,
794 Profile* profile,
795 const base::FilePath& install_dir,
796 const base::FilePath& extension_path) {
797 extensions::ExtensionAssetsManager* assets_manager =
798 extensions::ExtensionAssetsManager::GetInstance();
799 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
802 bool ExtensionService::IsExtensionEnabled(
803 const std::string& extension_id) const {
804 if (registry_->enabled_extensions().Contains(extension_id) ||
805 registry_->terminated_extensions().Contains(extension_id)) {
806 return true;
809 if (registry_->disabled_extensions().Contains(extension_id) ||
810 registry_->blacklisted_extensions().Contains(extension_id) ||
811 registry_->blocked_extensions().Contains(extension_id)) {
812 return false;
815 // Blocked extensions aren't marked as such in prefs, thus if
816 // |block_extensions_| is true then CanBlockExtension() must be called with an
817 // Extension object. If the |extension_id| is not loaded, assume not enabled.
818 if (block_extensions_) {
819 const Extension* extension = GetInstalledExtension(extension_id);
820 if (!extension || CanBlockExtension(extension))
821 return false;
824 // If the extension hasn't been loaded yet, check the prefs for it. Assume
825 // enabled unless otherwise noted.
826 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
827 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
828 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
831 void ExtensionService::EnableExtension(const std::string& extension_id) {
832 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
834 if (IsExtensionEnabled(extension_id))
835 return;
836 const Extension* extension =
837 registry_->disabled_extensions().GetByID(extension_id);
839 ManagementPolicy* policy = system_->management_policy();
840 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
841 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
842 return;
845 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
846 extension_prefs_->ClearDisableReasons(extension_id);
848 // This can happen if sync enables an extension that is not
849 // installed yet.
850 if (!extension)
851 return;
853 // Move it over to the enabled list.
854 registry_->AddEnabled(make_scoped_refptr(extension));
855 registry_->RemoveDisabled(extension->id());
857 NotifyExtensionLoaded(extension);
859 // Notify listeners that the extension was enabled.
860 content::NotificationService::current()->Notify(
861 extensions::NOTIFICATION_EXTENSION_ENABLED,
862 content::Source<Profile>(profile_),
863 content::Details<const Extension>(extension));
865 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(*extension);
868 void ExtensionService::DisableExtension(const std::string& extension_id,
869 int disable_reasons) {
870 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
872 // The extension may have been disabled already. Just add a disable reason.
873 if (!IsExtensionEnabled(extension_id)) {
874 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
875 return;
878 const Extension* extension = GetInstalledExtension(extension_id);
879 // |extension| can be NULL if sync disables an extension that is not
880 // installed yet.
881 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
882 // can be uninstalled by the browser if the user sets extension-specific
883 // preferences.
884 if (extension &&
885 !(disable_reasons & Extension::DISABLE_RELOAD) &&
886 !(disable_reasons & Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) &&
887 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
888 extension->location() != Manifest::EXTERNAL_COMPONENT) {
889 return;
892 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
893 extension_prefs_->AddDisableReasons(extension_id, disable_reasons);
895 int include_mask =
896 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
897 extension = registry_->GetExtensionById(extension_id, include_mask);
898 if (!extension)
899 return;
901 // The extension is either enabled or terminated.
902 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
903 registry_->terminated_extensions().Contains(extension->id()));
905 // Move it over to the disabled list. Don't send a second unload notification
906 // for terminated extensions being disabled.
907 registry_->AddDisabled(make_scoped_refptr(extension));
908 if (registry_->enabled_extensions().Contains(extension->id())) {
909 registry_->RemoveEnabled(extension->id());
910 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
911 } else {
912 registry_->RemoveTerminated(extension->id());
915 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(*extension);
918 void ExtensionService::DisableUserExtensions(
919 const std::vector<std::string>& except_ids) {
920 extensions::ManagementPolicy* management_policy =
921 system_->management_policy();
922 extensions::ExtensionList to_disable;
924 const ExtensionSet& enabled_set = registry_->enabled_extensions();
925 for (ExtensionSet::const_iterator extension = enabled_set.begin();
926 extension != enabled_set.end(); ++extension) {
927 if (management_policy->UserMayModifySettings(extension->get(), NULL))
928 to_disable.push_back(*extension);
930 const ExtensionSet& terminated_set = registry_->terminated_extensions();
931 for (ExtensionSet::const_iterator extension = terminated_set.begin();
932 extension != terminated_set.end(); ++extension) {
933 if (management_policy->UserMayModifySettings(extension->get(), NULL))
934 to_disable.push_back(*extension);
937 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
938 extension != to_disable.end(); ++extension) {
939 if ((*extension)->was_installed_by_default() &&
940 extension_urls::IsWebstoreUpdateUrl(
941 extensions::ManifestURL::GetUpdateURL(extension->get())))
942 continue;
943 const std::string& id = (*extension)->id();
944 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
945 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
949 // Extensions that are not locked, components or forced by policy should be
950 // locked. Extensions are no longer considered enabled or disabled. Blacklisted
951 // extensions are now considered both blacklisted and locked.
952 void ExtensionService::BlockAllExtensions() {
953 if (block_extensions_)
954 return;
955 block_extensions_ = true;
957 // Blacklisted extensions are already unloaded, need not be blocked.
958 scoped_ptr<ExtensionSet> extensions =
959 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::ENABLED |
960 ExtensionRegistry::DISABLED |
961 ExtensionRegistry::TERMINATED);
963 for (const scoped_refptr<const Extension>& extension : *extensions) {
964 const std::string& id = extension->id();
966 if (!CanBlockExtension(extension.get()))
967 continue;
969 registry_->RemoveEnabled(id);
970 registry_->RemoveDisabled(id);
971 registry_->RemoveTerminated(id);
973 registry_->AddBlocked(extension.get());
974 UnloadExtension(id, extensions::UnloadedExtensionInfo::REASON_LOCK_ALL);
978 // All locked extensions should revert to being either enabled or disabled
979 // as appropriate.
980 void ExtensionService::UnblockAllExtensions() {
981 block_extensions_ = false;
982 scoped_ptr<ExtensionSet> to_unblock =
983 registry_->GenerateInstalledExtensionsSet(ExtensionRegistry::BLOCKED);
985 for (const scoped_refptr<const Extension>& extension : *to_unblock) {
986 registry_->RemoveBlocked(extension->id());
987 AddExtension(extension.get());
991 void ExtensionService::GrantPermissionsAndEnableExtension(
992 const Extension* extension) {
993 GrantPermissions(extension);
994 RecordPermissionMessagesHistogram(extension, "ReEnable");
995 EnableExtension(extension->id());
998 void ExtensionService::GrantPermissions(const Extension* extension) {
999 CHECK(extension);
1000 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
1003 // static
1004 void ExtensionService::RecordPermissionMessagesHistogram(
1005 const Extension* extension, const char* histogram) {
1006 // Since this is called from multiple sources, and since the histogram macros
1007 // use statics, we need to manually lookup the histogram ourselves.
1008 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
1009 base::StringPrintf("Extensions.Permissions_%s3", histogram),
1011 APIPermission::kEnumBoundary,
1012 APIPermission::kEnumBoundary + 1,
1013 base::HistogramBase::kUmaTargetedHistogramFlag);
1015 base::HistogramBase* counter_has_any = base::BooleanHistogram::FactoryGet(
1016 base::StringPrintf("Extensions.HasPermissions_%s3", histogram),
1017 base::HistogramBase::kUmaTargetedHistogramFlag);
1019 PermissionIDSet permissions =
1020 extensions::PermissionMessageProvider::Get()->GetAllPermissionIDs(
1021 extension->permissions_data()->active_permissions().get(),
1022 extension->GetType());
1023 counter_has_any->AddBoolean(!permissions.empty());
1024 for (const PermissionID& id : permissions)
1025 counter->Add(id.id());
1028 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1029 // The URLRequestContexts need to be first to know that the extension
1030 // was loaded, otherwise a race can arise where a renderer that is created
1031 // for the extension may try to load an extension URL with an extension id
1032 // that the request context doesn't yet know about. The profile is responsible
1033 // for ensuring its URLRequestContexts appropriately discover the loaded
1034 // extension.
1035 system_->RegisterExtensionWithRequestContexts(
1036 extension,
1037 base::Bind(&ExtensionService::OnExtensionRegisteredWithRequestContexts,
1038 AsWeakPtr(), make_scoped_refptr(extension)));
1040 // Tell renderers about the new extension, unless it's a theme (renderers
1041 // don't need to know about themes).
1042 if (!extension->is_theme()) {
1043 for (content::RenderProcessHost::iterator i(
1044 content::RenderProcessHost::AllHostsIterator());
1045 !i.IsAtEnd(); i.Advance()) {
1046 content::RenderProcessHost* host = i.GetCurrentValue();
1047 Profile* host_profile =
1048 Profile::FromBrowserContext(host->GetBrowserContext());
1049 if (host_profile->GetOriginalProfile() ==
1050 profile_->GetOriginalProfile()) {
1051 // We don't need to include tab permisisons here, since the extension
1052 // was just loaded.
1053 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1054 1, ExtensionMsg_Loaded_Params(extension,
1055 false /* no tab permissions */));
1056 host->Send(
1057 new ExtensionMsg_Loaded(loaded_extensions));
1062 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1063 // extension.
1065 // NOTE: It is important that this happen after notifying the renderers about
1066 // the new extensions so that if we navigate to an extension URL in
1067 // ExtensionRegistryObserver::OnLoaded or
1068 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
1069 // renderer is guaranteed to know about it.
1070 registry_->TriggerOnLoaded(extension);
1072 content::NotificationService::current()->Notify(
1073 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1074 content::Source<Profile>(profile_),
1075 content::Details<const Extension>(extension));
1077 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1078 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1079 profile_->GetExtensionSpecialStoragePolicy()->
1080 GrantRightsForExtension(extension, profile_);
1082 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1083 // work properly multi-profile. Besides which, it should be using
1084 // ExtensionRegistryObserver. See http://crbug.com/355029.
1085 UpdateActiveExtensionsInCrashReporter();
1087 const extensions::PermissionsData* permissions_data =
1088 extension->permissions_data();
1090 // If the extension has permission to load chrome://favicon/ resources we need
1091 // to make sure that the FaviconSource is registered with the
1092 // ChromeURLDataManager.
1093 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1094 FaviconSource* favicon_source = new FaviconSource(profile_,
1095 FaviconSource::FAVICON);
1096 content::URLDataSource::Add(profile_, favicon_source);
1099 // Same for chrome://theme/ resources.
1100 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1101 ThemeSource* theme_source = new ThemeSource(profile_);
1102 content::URLDataSource::Add(profile_, theme_source);
1105 // Same for chrome://thumb/ resources.
1106 if (permissions_data->HasHostPermission(
1107 GURL(chrome::kChromeUIThumbnailURL))) {
1108 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1109 content::URLDataSource::Add(profile_, thumbnail_source);
1113 void ExtensionService::OnExtensionRegisteredWithRequestContexts(
1114 scoped_refptr<const extensions::Extension> extension) {
1115 registry_->AddReady(extension);
1116 if (registry_->enabled_extensions().Contains(extension->id()))
1117 registry_->TriggerOnReady(extension.get());
1120 void ExtensionService::NotifyExtensionUnloaded(
1121 const Extension* extension,
1122 UnloadedExtensionInfo::Reason reason) {
1123 UnloadedExtensionInfo details(extension, reason);
1125 registry_->TriggerOnUnloaded(extension, reason);
1127 content::NotificationService::current()->Notify(
1128 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1129 content::Source<Profile>(profile_),
1130 content::Details<UnloadedExtensionInfo>(&details));
1132 for (content::RenderProcessHost::iterator i(
1133 content::RenderProcessHost::AllHostsIterator());
1134 !i.IsAtEnd(); i.Advance()) {
1135 content::RenderProcessHost* host = i.GetCurrentValue();
1136 Profile* host_profile =
1137 Profile::FromBrowserContext(host->GetBrowserContext());
1138 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1139 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1142 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1144 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1145 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1146 profile_->GetExtensionSpecialStoragePolicy()->
1147 RevokeRightsForExtension(extension);
1149 #if defined(OS_CHROMEOS)
1150 // Revoke external file access for the extension from its file system context.
1151 // It is safe to access the extension's storage partition at this point. The
1152 // storage partition may get destroyed only after the extension gets unloaded.
1153 GURL site =
1154 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1155 storage::FileSystemContext* filesystem_context =
1156 BrowserContext::GetStoragePartitionForSite(profile_, site)
1157 ->GetFileSystemContext();
1158 if (filesystem_context && filesystem_context->external_backend()) {
1159 filesystem_context->external_backend()->
1160 RevokeAccessForExtension(extension->id());
1162 #endif
1164 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1165 // work properly multi-profile. Besides which, it should be using
1166 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1167 UpdateActiveExtensionsInCrashReporter();
1170 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1171 // Implemented in the .cc file to avoid adding a profile.h dependency to
1172 // extension_service.h.
1173 return profile_;
1176 bool ExtensionService::is_ready() {
1177 return ready_->is_signaled();
1180 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1181 if (file_task_runner_.get())
1182 return file_task_runner_.get();
1184 // We should be able to interrupt any part of extension install process during
1185 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1186 // will be ignored/deleted while we will block on started tasks.
1187 std::string token("ext_install-");
1188 token.append(profile_->GetPath().AsUTF8Unsafe());
1189 file_task_runner_ = BrowserThread::GetBlockingPool()->
1190 GetSequencedTaskRunnerWithShutdownBehavior(
1191 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1192 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1193 return file_task_runner_.get();
1196 void ExtensionService::CheckManagementPolicy() {
1197 std::vector<std::string> to_unload;
1198 std::map<std::string, Extension::DisableReason> to_disable;
1199 std::vector<std::string> to_enable;
1201 // Loop through the extensions list, finding extensions we need to unload or
1202 // disable.
1203 for (scoped_refptr<const Extension> extension :
1204 registry_->enabled_extensions()) {
1205 if (!system_->management_policy()->UserMayLoad(extension.get(), nullptr))
1206 to_unload.push_back(extension->id());
1207 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1208 if (system_->management_policy()->MustRemainDisabled(
1209 extension.get(), &disable_reason, nullptr))
1210 to_disable[extension->id()] = disable_reason;
1213 extensions::ExtensionManagement* management =
1214 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1216 // Loop through the disabled extension list, find extensions to re-enable
1217 // automatically. These extensions are exclusive from the |to_disable| and
1218 // |to_unload| lists constructed above, since disabled_extensions() and
1219 // enabled_extensions() are supposed to be mutually exclusive.
1220 for (scoped_refptr<const Extension> extension :
1221 registry_->disabled_extensions()) {
1222 // Find all disabled extensions disabled due to minimum version requirement,
1223 // but now satisfying it.
1224 if (management->CheckMinimumVersion(extension.get(), nullptr) &&
1225 extension_prefs_->HasDisableReason(
1226 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY)) {
1227 // Is DISABLE_UPDATE_REQUIRED_BY_POLICY the *only* reason?
1228 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1229 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1230 // We need to enable those disabled *only* due to minimum version
1231 // requirement.
1232 to_enable.push_back(extension->id());
1234 extension_prefs_->RemoveDisableReason(
1235 extension->id(), Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1239 for (const std::string& id : to_unload)
1240 UnloadExtension(id, UnloadedExtensionInfo::REASON_DISABLE);
1242 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1243 to_disable.begin(); i != to_disable.end(); ++i)
1244 DisableExtension(i->first, i->second);
1246 // No extension is getting re-enabled here after disabling/unloading
1247 // because to_enable is mutually exclusive to to_disable + to_unload.
1248 for (const std::string& id : to_enable)
1249 EnableExtension(id);
1251 if (updater_.get()) {
1252 // Find all extensions disabled due to minimum version requirement from
1253 // policy (including the ones that got disabled just now), and check
1254 // for update.
1255 extensions::ExtensionUpdater::CheckParams to_recheck;
1256 for (scoped_refptr<const Extension> extension :
1257 registry_->disabled_extensions()) {
1258 if (extension_prefs_->GetDisableReasons(extension->id()) ==
1259 Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY) {
1260 // The minimum version check is the only thing holding this extension
1261 // back, so check if it can be updated to fix that.
1262 to_recheck.ids.push_back(extension->id());
1265 if (!to_recheck.ids.empty())
1266 updater_->CheckNow(to_recheck);
1270 void ExtensionService::CheckForUpdatesSoon() {
1271 // This can legitimately happen in unit tests.
1272 if (!updater_.get())
1273 return;
1275 if (AreAllExternalProvidersReady()) {
1276 updater_->CheckSoon();
1277 } else {
1278 // Sync can start updating before all the external providers are ready
1279 // during startup. Start the update as soon as those providers are ready,
1280 // but not before.
1281 update_once_all_providers_are_ready_ = true;
1285 // Some extensions will autoupdate themselves externally from Chrome. These
1286 // are typically part of some larger client application package. To support
1287 // these, the extension will register its location in the preferences file
1288 // (and also, on Windows, in the registry) and this code will periodically
1289 // check that location for a .crx file, which it will then install locally if
1290 // a new version is available.
1291 // Errors are reported through ExtensionErrorReporter. Success is not
1292 // reported.
1293 void ExtensionService::CheckForExternalUpdates() {
1294 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1295 TRACE_EVENT0("browser,startup", "ExtensionService::CheckForExternalUpdates");
1296 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.CheckForExternalUpdatesTime");
1298 // Note that this installation is intentionally silent (since it didn't
1299 // go through the front-end). Extensions that are registered in this
1300 // way are effectively considered 'pre-bundled', and so implicitly
1301 // trusted. In general, if something has HKLM or filesystem access,
1302 // they could install an extension manually themselves anyway.
1304 // Ask each external extension provider to give us a call back for each
1305 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1306 extensions::ProviderCollection::const_iterator i;
1307 for (i = external_extension_providers_.begin();
1308 i != external_extension_providers_.end(); ++i) {
1309 extensions::ExternalProviderInterface* provider = i->get();
1310 provider->VisitRegisteredExtension();
1313 // Do any required work that we would have done after completion of all
1314 // providers.
1315 if (external_extension_providers_.empty())
1316 OnAllExternalProvidersReady();
1319 void ExtensionService::OnExternalProviderReady(
1320 const extensions::ExternalProviderInterface* provider) {
1321 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1322 CHECK(provider->IsReady());
1324 // An external provider has finished loading. We only take action
1325 // if all of them are finished. So we check them first.
1326 if (AreAllExternalProvidersReady())
1327 OnAllExternalProvidersReady();
1330 bool ExtensionService::AreAllExternalProvidersReady() const {
1331 extensions::ProviderCollection::const_iterator i;
1332 for (i = external_extension_providers_.begin();
1333 i != external_extension_providers_.end(); ++i) {
1334 if (!i->get()->IsReady())
1335 return false;
1337 return true;
1340 void ExtensionService::OnAllExternalProvidersReady() {
1341 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1342 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1343 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1345 // Install any pending extensions.
1346 if (update_once_all_providers_are_ready_ && updater()) {
1347 update_once_all_providers_are_ready_ = false;
1348 extensions::ExtensionUpdater::CheckParams params;
1349 params.callback = external_updates_finished_callback_;
1350 updater()->CheckNow(params);
1353 // Uninstall all the unclaimed extensions.
1354 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1355 extension_prefs_->GetInstalledExtensionsInfo());
1356 for (size_t i = 0; i < extensions_info->size(); ++i) {
1357 ExtensionInfo* info = extensions_info->at(i).get();
1358 if (Manifest::IsExternalLocation(info->extension_location))
1359 CheckExternalUninstall(info->extension_id);
1362 error_controller_->ShowErrorIfNeeded();
1364 external_install_manager_->UpdateExternalExtensionAlert();
1367 void ExtensionService::UnloadExtension(
1368 const std::string& extension_id,
1369 UnloadedExtensionInfo::Reason reason) {
1370 // Make sure the extension gets deleted after we return from this function.
1371 int include_mask =
1372 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1373 scoped_refptr<const Extension> extension(
1374 registry_->GetExtensionById(extension_id, include_mask));
1376 // This method can be called via PostTask, so the extension may have been
1377 // unloaded by the time this runs.
1378 if (!extension.get()) {
1379 // In case the extension may have crashed/uninstalled. Allow the profile to
1380 // clean up its RequestContexts.
1381 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1382 return;
1385 // Keep information about the extension so that we can reload it later
1386 // even if it's not permanently installed.
1387 unloaded_extension_paths_[extension->id()] = extension->path();
1389 // Clean up if the extension is meant to be enabled after a reload.
1390 reloading_extensions_.erase(extension->id());
1392 if (registry_->disabled_extensions().Contains(extension->id())) {
1393 registry_->RemoveDisabled(extension->id());
1394 // Make sure the profile cleans up its RequestContexts when an already
1395 // disabled extension is unloaded (since they are also tracking the disabled
1396 // extensions).
1397 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1398 // Don't send the unloaded notification. It was sent when the extension
1399 // was disabled.
1400 } else {
1401 // Remove the extension from the enabled list.
1402 registry_->RemoveEnabled(extension->id());
1403 NotifyExtensionUnloaded(extension.get(), reason);
1406 content::NotificationService::current()->Notify(
1407 extensions::NOTIFICATION_EXTENSION_REMOVED,
1408 content::Source<Profile>(profile_),
1409 content::Details<const Extension>(extension.get()));
1412 void ExtensionService::RemoveComponentExtension(
1413 const std::string& extension_id) {
1414 scoped_refptr<const Extension> extension(
1415 GetExtensionById(extension_id, false));
1416 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1417 if (extension.get()) {
1418 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1419 extension.get(), extensions::UNINSTALL_REASON_COMPONENT_REMOVED);
1423 void ExtensionService::UnloadAllExtensionsForTest() {
1424 UnloadAllExtensionsInternal();
1427 void ExtensionService::ReloadExtensionsForTest() {
1428 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1429 // warning about calling test code in production.
1430 UnloadAllExtensionsInternal();
1431 component_loader_->LoadAll();
1432 extensions::InstalledLoader(this).LoadAllExtensions();
1433 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1434 // times.
1437 void ExtensionService::SetReadyAndNotifyListeners() {
1438 TRACE_EVENT0("browser,startup",
1439 "ExtensionService::SetReadyAndNotifyListeners");
1440 TRACK_SCOPED_REGION(
1441 "Startup", "ExtensionService::SetReadyAndNotifyListeners");
1442 SCOPED_UMA_HISTOGRAM_TIMER(
1443 "Extensions.ExtensionServiceNotifyReadyListenersTime");
1445 ready_->Signal();
1446 content::NotificationService::current()->Notify(
1447 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1448 content::Source<Profile>(profile_),
1449 content::NotificationService::NoDetails());
1452 void ExtensionService::OnLoadedInstalledExtensions() {
1453 if (updater_)
1454 updater_->Start();
1456 OnBlacklistUpdated();
1459 void ExtensionService::AddExtension(const Extension* extension) {
1460 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1461 // default extension state to DISABLED when the --disable-extensions flag
1462 // is set (http://crbug.com/29067).
1463 if (!extensions_enabled() &&
1464 !extension->is_theme() &&
1465 extension->location() != Manifest::COMPONENT &&
1466 !Manifest::IsExternalLocation(extension->location())) {
1467 return;
1470 bool is_extension_upgrade = false;
1471 bool is_extension_installed = false;
1472 const Extension* old = GetInstalledExtension(extension->id());
1473 if (old) {
1474 is_extension_installed = true;
1475 int version_compare_result =
1476 extension->version()->CompareTo(*(old->version()));
1477 is_extension_upgrade = version_compare_result > 0;
1478 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1479 // that we aren't downgrading.
1480 if (!Manifest::IsUnpackedLocation(extension->location()))
1481 CHECK_GE(version_compare_result, 0);
1483 // If the extension was disabled for a reload, then enable it.
1484 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1486 // Set the upgraded bit; we consider reloads upgrades.
1487 system_->runtime_data()->SetBeingUpgraded(extension->id(),
1488 is_extension_upgrade || reloading);
1490 // The extension is now loaded, remove its data from unloaded extension map.
1491 unloaded_extension_paths_.erase(extension->id());
1493 // If a terminated extension is loaded, remove it from the terminated list.
1494 UntrackTerminatedExtension(extension->id());
1496 // Check if the extension's privileges have changed and mark the
1497 // extension disabled if necessary.
1498 CheckPermissionsIncrease(extension, is_extension_installed);
1500 if (is_extension_installed && !reloading) {
1501 // To upgrade an extension in place, unload the old one and then load the
1502 // new one. ReloadExtension disables the extension, which is sufficient.
1503 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1506 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1507 // Only prefs is checked for the blacklist. We rely on callers to check the
1508 // blacklist before calling into here, e.g. CrxInstaller checks before
1509 // installation then threads through the install and pending install flow
1510 // of this class, and we check when loading installed extensions.
1511 registry_->AddBlacklisted(extension);
1512 } else if (block_extensions_ && CanBlockExtension(extension)) {
1513 registry_->AddBlocked(extension);
1514 } else if (!reloading &&
1515 extension_prefs_->IsExtensionDisabled(extension->id())) {
1516 registry_->AddDisabled(extension);
1517 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(
1518 *extension);
1519 content::NotificationService::current()->Notify(
1520 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1521 content::Source<Profile>(profile_),
1522 content::Details<const Extension>(extension));
1524 // Show the extension disabled error if a permissions increase or a remote
1525 // installation is the reason it was disabled, and no other reasons exist.
1526 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1527 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1528 Extension::DISABLE_REMOTE_INSTALL;
1529 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1530 extensions::AddExtensionDisabledError(
1531 this,
1532 extension,
1533 extension_prefs_->HasDisableReason(
1534 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1536 } else if (reloading) {
1537 // Replace the old extension with the new version.
1538 CHECK(!registry_->AddDisabled(extension));
1539 EnableExtension(extension->id());
1540 } else {
1541 // All apps that are displayed in the launcher are ordered by their ordinals
1542 // so we must ensure they have valid ordinals.
1543 if (extension->RequiresSortOrdinal()) {
1544 extension_prefs_->app_sorting()->SetExtensionVisible(
1545 extension->id(),
1546 extension->ShouldDisplayInNewTabPage() &&
1547 !extension_prefs_->IsEphemeralApp(extension->id()));
1548 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1549 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1550 extension->id(), syncer::StringOrdinal());
1554 registry_->AddEnabled(extension);
1555 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(
1556 *extension);
1557 NotifyExtensionLoaded(extension);
1559 system_->runtime_data()->SetBeingUpgraded(extension->id(), false);
1562 void ExtensionService::AddComponentExtension(const Extension* extension) {
1563 const std::string old_version_string(
1564 extension_prefs_->GetVersionString(extension->id()));
1565 const Version old_version(old_version_string);
1567 VLOG(1) << "AddComponentExtension " << extension->name();
1568 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1569 VLOG(1) << "Component extension " << extension->name() << " ("
1570 << extension->id() << ") installing/upgrading from '"
1571 << old_version_string << "' to " << extension->version()->GetString();
1573 AddNewOrUpdatedExtension(extension,
1574 Extension::ENABLED,
1575 extensions::kInstallFlagNone,
1576 syncer::StringOrdinal(),
1577 std::string());
1578 return;
1581 AddExtension(extension);
1584 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1585 bool is_extension_installed) {
1586 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1588 // We keep track of all permissions the user has granted each extension.
1589 // This allows extensions to gracefully support backwards compatibility
1590 // by including unknown permissions in their manifests. When the user
1591 // installs the extension, only the recognized permissions are recorded.
1592 // When the unknown permissions become recognized (e.g., through browser
1593 // upgrade), we can prompt the user to accept these new permissions.
1594 // Extensions can also silently upgrade to less permissions, and then
1595 // silently upgrade to a version that adds these permissions back.
1597 // For example, pretend that Chrome 10 includes a permission "omnibox"
1598 // for an API that adds suggestions to the omnibox. An extension can
1599 // maintain backwards compatibility while still having "omnibox" in the
1600 // manifest. If a user installs the extension on Chrome 9, the browser
1601 // will record the permissions it recognized, not including "omnibox."
1602 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1603 // will disable the extension and prompt the user to approve the increase
1604 // in privileges. The extension could then release a new version that
1605 // removes the "omnibox" permission. When the user upgrades, Chrome will
1606 // still remember that "omnibox" had been granted, so that if the
1607 // extension once again includes "omnibox" in an upgrade, the extension
1608 // can upgrade without requiring this user's approval.
1609 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1611 // Silently grant all active permissions to default apps and apps installed
1612 // in kiosk mode.
1613 bool auto_grant_permission =
1614 extension->was_installed_by_default() ||
1615 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1616 if (auto_grant_permission)
1617 GrantPermissions(extension);
1619 bool is_privilege_increase = false;
1620 // We only need to compare the granted permissions to the current permissions
1621 // if the extension has not been auto-granted its permissions above and is
1622 // installed internally.
1623 if (extension->location() == Manifest::INTERNAL && !auto_grant_permission) {
1624 // Add all the recognized permissions if the granted permissions list
1625 // hasn't been initialized yet.
1626 scoped_refptr<PermissionSet> granted_permissions =
1627 extension_prefs_->GetGrantedPermissions(extension->id());
1628 CHECK(granted_permissions.get());
1630 // Here, we check if an extension's privileges have increased in a manner
1631 // that requires the user's approval. This could occur because the browser
1632 // upgraded and recognized additional privileges, or an extension upgrades
1633 // to a version that requires additional privileges.
1634 is_privilege_increase =
1635 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1636 granted_permissions.get(),
1637 extension->permissions_data()->active_permissions().get(),
1638 extension->GetType());
1641 if (is_extension_installed) {
1642 // If the extension was already disabled, suppress any alerts for becoming
1643 // disabled on permissions increase.
1644 bool previously_disabled =
1645 extension_prefs_->IsExtensionDisabled(extension->id());
1646 // Legacy disabled extensions do not have a disable reason. Infer that if
1647 // there was no permission increase, it was likely disabled by the user.
1648 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1649 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1650 disable_reasons |= Extension::DISABLE_USER_ACTION;
1652 // Extensions that came to us disabled from sync need a similar inference,
1653 // except based on the new version's permissions.
1654 if (previously_disabled &&
1655 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1656 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1657 extension_prefs_->ClearDisableReasons(extension->id());
1658 if (!is_privilege_increase)
1659 disable_reasons |= Extension::DISABLE_USER_ACTION;
1661 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1664 // Extension has changed permissions significantly. Disable it. A
1665 // notification should be sent by the caller. If the extension is already
1666 // disabled because it was installed remotely, don't add another disable
1667 // reason.
1668 if (is_privilege_increase &&
1669 disable_reasons != Extension::DISABLE_REMOTE_INSTALL) {
1670 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1671 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1672 RecordPermissionMessagesHistogram(extension, "AutoDisable");
1674 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1676 #if defined(ENABLE_SUPERVISED_USERS)
1677 // If a custodian-installed extension is disabled for a supervised user due
1678 // to a permissions increase, send a request to the custodian if the
1679 // supervised user themselves can't re-enable the extension.
1680 if (extensions::util::IsExtensionSupervised(extension, profile_) &&
1681 extensions::util::NeedCustodianApprovalForPermissionIncrease()) {
1682 SupervisedUserService* supervised_user_service =
1683 SupervisedUserServiceFactory::GetForProfile(profile_);
1684 supervised_user_service->AddExtensionUpdateRequest(
1685 extension->id(), *extension->version(),
1686 base::Bind(ExtensionUpdateRequestSent, extension->id()));
1688 #endif
1690 if (disable_reasons != Extension::DISABLE_NONE)
1691 extension_prefs_->AddDisableReasons(extension->id(), disable_reasons);
1694 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1695 std::set<std::string> extension_ids;
1696 const ExtensionSet& extensions = registry_->enabled_extensions();
1697 for (ExtensionSet::const_iterator iter = extensions.begin();
1698 iter != extensions.end(); ++iter) {
1699 const Extension* extension = iter->get();
1700 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1701 extension_ids.insert(extension->id());
1704 // TODO(kalman): This is broken. ExtensionService is per-profile.
1705 // crash_keys::SetActiveExtensions is per-process. See
1706 // http://crbug.com/355029.
1707 crash_keys::SetActiveExtensions(extension_ids);
1710 void ExtensionService::OnExtensionInstalled(
1711 const Extension* extension,
1712 const syncer::StringOrdinal& page_ordinal,
1713 int install_flags) {
1714 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1716 const std::string& id = extension->id();
1717 int disable_reasons = GetDisableReasonsOnInstalled(extension);
1718 std::string install_parameter;
1719 const extensions::PendingExtensionInfo* pending_extension_info =
1720 pending_extension_manager()->GetById(id);
1721 if (pending_extension_info) {
1722 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1723 pending_extension_manager()->Remove(id);
1725 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1726 << id << " of type " << extension->GetType()
1727 << " and update URL "
1728 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1729 << "; not installing";
1731 // Delete the extension directory since we're not going to
1732 // load it.
1733 if (!GetFileTaskRunner()->PostTask(
1734 FROM_HERE,
1735 base::Bind(&extensions::file_util::DeleteFile,
1736 extension->path(),
1737 true))) {
1738 NOTREACHED();
1740 return;
1743 install_parameter = pending_extension_info->install_parameter();
1744 pending_extension_manager()->Remove(id);
1745 } else {
1746 // We explicitly want to re-enable an uninstalled external
1747 // extension; if we're here, that means the user is manually
1748 // installing the extension.
1749 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1750 disable_reasons = Extension::DISABLE_NONE;
1754 // Unsupported requirements overrides the management policy.
1755 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1756 disable_reasons |= Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1757 } else {
1758 // Requirement is supported now, remove the corresponding disable reason
1759 // instead.
1760 extension_prefs_->RemoveDisableReason(
1761 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1762 disable_reasons &= ~Extension::DISABLE_UNSUPPORTED_REQUIREMENT;
1765 // Check if the extension was disabled because of the minimum version
1766 // requirements from enterprise policy, and satisfies it now.
1767 if (extensions::ExtensionManagementFactory::GetForBrowserContext(profile())
1768 ->CheckMinimumVersion(extension, nullptr)) {
1769 // And remove the corresponding disable reason.
1770 extension_prefs_->RemoveDisableReason(
1771 id, Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY);
1772 disable_reasons &= ~Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY;
1775 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1776 // Installation of a blacklisted extension can happen from sync, policy,
1777 // etc, where to maintain consistency we need to install it, just never
1778 // load it (see AddExtension). Usually it should be the job of callers to
1779 // intercept blacklisted extensions earlier (e.g. CrxInstaller, before even
1780 // showing the install dialogue).
1781 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1782 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1783 extension->location(),
1784 Manifest::NUM_LOCATIONS);
1787 if (!GetInstalledExtension(extension->id())) {
1788 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1789 extension->GetType(), 100);
1790 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1791 extension->location(), Manifest::NUM_LOCATIONS);
1792 RecordPermissionMessagesHistogram(extension, "Install");
1793 } else {
1794 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1795 extension->GetType(), 100);
1796 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1797 extension->location(), Manifest::NUM_LOCATIONS);
1799 // A fully installed app cannot be demoted to an ephemeral app.
1800 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1801 !extension_prefs_->IsEphemeralApp(id)) {
1802 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1806 if (disable_reasons)
1807 extension_prefs_->AddDisableReasons(id, disable_reasons);
1809 const Extension::State initial_state =
1810 disable_reasons == Extension::DISABLE_NONE ? Extension::ENABLED
1811 : Extension::DISABLED;
1813 if (ShouldDelayExtensionUpdate(
1815 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1816 extension_prefs_->SetDelayedInstallInfo(
1817 extension,
1818 initial_state,
1819 install_flags,
1820 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1821 page_ordinal,
1822 install_parameter);
1824 // Transfer ownership of |extension|.
1825 delayed_installs_.Insert(extension);
1827 // Notify observers that app update is available.
1828 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1829 OnAppUpdateAvailable(extension));
1830 return;
1833 extensions::SharedModuleService::ImportStatus status =
1834 shared_module_service_->SatisfyImports(extension);
1835 if (installs_delayed_for_gc_) {
1836 extension_prefs_->SetDelayedInstallInfo(
1837 extension,
1838 initial_state,
1839 install_flags,
1840 extensions::ExtensionPrefs::DELAY_REASON_GC,
1841 page_ordinal,
1842 install_parameter);
1843 delayed_installs_.Insert(extension);
1844 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1845 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1846 extension_prefs_->SetDelayedInstallInfo(
1847 extension,
1848 initial_state,
1849 install_flags,
1850 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1851 page_ordinal,
1852 install_parameter);
1853 delayed_installs_.Insert(extension);
1855 } else {
1856 AddNewOrUpdatedExtension(extension,
1857 initial_state,
1858 install_flags,
1859 page_ordinal,
1860 install_parameter);
1864 void ExtensionService::OnExtensionManagementSettingsChanged() {
1865 error_controller_->ShowErrorIfNeeded();
1867 // Revokes blocked permissions from active_permissions for all extensions.
1868 extensions::ExtensionManagement* settings =
1869 extensions::ExtensionManagementFactory::GetForBrowserContext(profile());
1870 CHECK(settings);
1871 scoped_ptr<ExtensionSet> all_extensions(
1872 registry_->GenerateInstalledExtensionsSet());
1873 for (const auto& extension : *all_extensions.get()) {
1874 if (!settings->IsPermissionSetAllowed(
1875 extension.get(),
1876 extension->permissions_data()->active_permissions())) {
1877 extensions::PermissionsUpdater(profile()).RemovePermissions(
1878 extension.get(),
1879 settings->GetBlockedPermissions(extension.get()).get());
1883 CheckManagementPolicy();
1886 void ExtensionService::AddNewOrUpdatedExtension(
1887 const Extension* extension,
1888 Extension::State initial_state,
1889 int install_flags,
1890 const syncer::StringOrdinal& page_ordinal,
1891 const std::string& install_parameter) {
1892 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1893 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1894 extension_prefs_->OnExtensionInstalled(
1895 extension, initial_state, page_ordinal, install_flags, install_parameter);
1896 delayed_installs_.Remove(extension->id());
1897 if (InstallVerifier::NeedsVerification(*extension))
1898 InstallVerifier::Get(GetBrowserContext())->VerifyExtension(extension->id());
1900 const Extension* old = GetInstalledExtension(extension->id());
1901 if (extensions::AppDataMigrator::NeedsMigration(old, extension)) {
1902 app_data_migrator_->DoMigrationAndReply(
1903 old, extension,
1904 base::Bind(&ExtensionService::FinishInstallation, AsWeakPtr(),
1905 make_scoped_refptr(extension), was_ephemeral));
1906 return;
1909 FinishInstallation(extension, was_ephemeral);
1912 void ExtensionService::MaybeFinishDelayedInstallation(
1913 const std::string& extension_id) {
1914 // Check if the extension already got installed.
1915 if (!delayed_installs_.Contains(extension_id))
1916 return;
1917 extensions::ExtensionPrefs::DelayReason reason =
1918 extension_prefs_->GetDelayedInstallReason(extension_id);
1920 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1921 // preferences files that will not have set this field but it was previously
1922 // only used for idle updates.
1923 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1924 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1925 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1926 return;
1928 const Extension* extension = delayed_installs_.GetByID(extension_id);
1929 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1930 extensions::SharedModuleService::ImportStatus status =
1931 shared_module_service_->SatisfyImports(extension);
1932 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1933 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1934 delayed_installs_.Remove(extension_id);
1935 // Make sure no version of the extension is actually installed, (i.e.,
1936 // that this delayed install was not an update).
1937 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1938 extension_prefs_->DeleteExtensionPrefs(extension_id);
1940 return;
1944 FinishDelayedInstallation(extension_id);
1947 void ExtensionService::FinishDelayedInstallation(
1948 const std::string& extension_id) {
1949 scoped_refptr<const Extension> extension(
1950 GetPendingExtensionUpdate(extension_id));
1951 CHECK(extension.get());
1952 delayed_installs_.Remove(extension_id);
1954 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1955 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1956 NOTREACHED();
1958 FinishInstallation(extension.get(), was_ephemeral);
1961 void ExtensionService::FinishInstallation(
1962 const Extension* extension, bool was_ephemeral) {
1963 const extensions::Extension* existing_extension =
1964 GetInstalledExtension(extension->id());
1965 bool is_update = false;
1966 std::string old_name;
1967 if (existing_extension) {
1968 is_update = true;
1969 old_name = existing_extension->name();
1971 bool from_ephemeral =
1972 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1973 extensions::InstalledExtensionInfo details(
1974 extension, is_update, from_ephemeral, old_name);
1975 content::NotificationService::current()->Notify(
1976 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1977 content::Source<Profile>(profile_),
1978 content::Details<const extensions::InstalledExtensionInfo>(&details));
1980 registry_->TriggerOnWillBeInstalled(
1981 extension, is_update, from_ephemeral, old_name);
1983 // Unpacked extensions default to allowing file access, but if that has been
1984 // overridden, don't reset the value.
1985 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1986 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1987 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1990 AddExtension(extension);
1992 // Notify observers that need to know when an installation is complete.
1993 registry_->TriggerOnInstalled(extension, is_update);
1995 // Check extensions that may have been delayed only because this shared module
1996 // was not available.
1997 if (SharedModuleInfo::IsSharedModule(extension))
1998 MaybeFinishDelayedInstallations();
2001 void ExtensionService::PromoteEphemeralApp(
2002 const extensions::Extension* extension, bool is_from_sync) {
2003 DCHECK(GetInstalledExtension(extension->id()) &&
2004 extension_prefs_->IsEphemeralApp(extension->id()));
2006 if (extension->RequiresSortOrdinal()) {
2007 extension_prefs_->app_sorting()->SetExtensionVisible(
2008 extension->id(), extension->ShouldDisplayInNewTabPage());
2010 if (!is_from_sync) {
2011 // Reset the sort ordinals of the app to ensure it is added to the default
2012 // position, like newly installed apps would.
2013 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
2016 extension_prefs_->app_sorting()->EnsureValidOrdinals(
2017 extension->id(), syncer::StringOrdinal());
2020 // Remove the ephemeral flags from the preferences.
2021 extension_prefs_->OnEphemeralAppPromoted(extension->id());
2023 // Fire install-related events to allow observers to handle the promotion
2024 // of the ephemeral app.
2025 extensions::InstalledExtensionInfo details(
2026 extension,
2027 true /* is update */,
2028 true /* from ephemeral */,
2029 extension->name() /* old name */);
2030 content::NotificationService::current()->Notify(
2031 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2032 content::Source<Profile>(profile_),
2033 content::Details<const extensions::InstalledExtensionInfo>(&details));
2035 registry_->TriggerOnWillBeInstalled(
2036 extension,
2037 true /* is update */,
2038 true /* from ephemeral */,
2039 extension->name() /* old name */);
2041 if (registry_->enabled_extensions().Contains(extension->id())) {
2042 // If the app is already enabled and loaded, fire the load events to allow
2043 // observers to handle the promotion of the ephemeral app.
2044 content::NotificationService::current()->Notify(
2045 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
2046 content::Source<Profile>(profile_),
2047 content::Details<const Extension>(extension));
2049 registry_->TriggerOnLoaded(extension);
2050 } else {
2051 // Cached ephemeral apps may be updated and disabled due to permissions
2052 // increase. The app can be enabled (as long as no other disable reasons
2053 // exist) as the install was user-acknowledged.
2054 int disable_mask = Extension::DISABLE_NONE;
2055 if (!is_from_sync)
2056 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
2058 int other_disable_reasons =
2059 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
2060 if (!other_disable_reasons) {
2061 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
2062 GrantPermissionsAndEnableExtension(extension);
2063 else
2064 EnableExtension(extension->id());
2068 registry_->TriggerOnInstalled(extension, true);
2070 if (!is_from_sync) {
2071 ExtensionSyncService::Get(profile_)->SyncExtensionChangeIfNeeded(
2072 *extension);
2076 const Extension* ExtensionService::GetPendingExtensionUpdate(
2077 const std::string& id) const {
2078 return delayed_installs_.GetByID(id);
2081 void ExtensionService::RegisterContentSettings(
2082 HostContentSettingsMap* host_content_settings_map) {
2083 TRACE_EVENT0("browser,startup", "ExtensionService::RegisterContentSettings");
2084 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2085 host_content_settings_map->RegisterProvider(
2086 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
2087 scoped_ptr<content_settings::ObservableProvider>(
2088 new content_settings::InternalExtensionProvider(profile_)));
2090 host_content_settings_map->RegisterProvider(
2091 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
2092 scoped_ptr<content_settings::ObservableProvider>(
2093 new content_settings::CustomExtensionProvider(
2094 extensions::ContentSettingsService::Get(
2095 profile_)->content_settings_store(),
2096 profile_->GetOriginalProfile() != profile_)));
2099 void ExtensionService::TrackTerminatedExtension(
2100 const std::string& extension_id) {
2101 extensions_being_terminated_.erase(extension_id);
2103 const Extension* extension = GetInstalledExtension(extension_id);
2104 if (!extension) {
2105 return;
2108 // No need to check for duplicates; inserting a duplicate is a no-op.
2109 registry_->AddTerminated(make_scoped_refptr(extension));
2110 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
2113 void ExtensionService::TerminateExtension(const std::string& extension_id) {
2114 TrackTerminatedExtension(extension_id);
2117 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2118 std::string lowercase_id = base::StringToLowerASCII(id);
2119 const Extension* extension =
2120 registry_->terminated_extensions().GetByID(lowercase_id);
2121 registry_->RemoveTerminated(lowercase_id);
2122 if (extension) {
2123 content::NotificationService::current()->Notify(
2124 extensions::NOTIFICATION_EXTENSION_REMOVED,
2125 content::Source<Profile>(profile_),
2126 content::Details<const Extension>(extension));
2130 const Extension* ExtensionService::GetInstalledExtension(
2131 const std::string& id) const {
2132 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
2135 bool ExtensionService::OnExternalExtensionFileFound(
2136 const std::string& id,
2137 const Version* version,
2138 const base::FilePath& path,
2139 Manifest::Location location,
2140 int creation_flags,
2141 bool mark_acknowledged,
2142 bool install_immediately) {
2143 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2144 CHECK(crx_file::id_util::IdIsValid(id));
2145 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2146 return false;
2148 // Before even bothering to unpack, check and see if we already have this
2149 // version. This is important because these extensions are going to get
2150 // installed on every startup.
2151 const Extension* existing = GetExtensionById(id, true);
2153 if (existing) {
2154 // The default apps will have the location set as INTERNAL. Since older
2155 // default apps are installed as EXTERNAL, we override them. However, if the
2156 // app is already installed as internal, then do the version check.
2157 // TODO(grv) : Remove after Q1-2013.
2158 bool is_default_apps_migration =
2159 (location == Manifest::INTERNAL &&
2160 Manifest::IsExternalLocation(existing->location()));
2162 if (!is_default_apps_migration) {
2163 DCHECK(version);
2165 switch (existing->version()->CompareTo(*version)) {
2166 case -1: // existing version is older, we should upgrade
2167 break;
2168 case 0: // existing version is same, do nothing
2169 return false;
2170 case 1: // existing version is newer, uh-oh
2171 LOG(WARNING) << "Found external version of extension " << id
2172 << "that is older than current version. Current version "
2173 << "is: " << existing->VersionString() << ". New "
2174 << "version is: " << version->GetString()
2175 << ". Keeping current version.";
2176 return false;
2181 // If the extension is already pending, don't start an install.
2182 if (!pending_extension_manager()->AddFromExternalFile(
2183 id, location, *version, creation_flags, mark_acknowledged)) {
2184 return false;
2187 // no client (silent install)
2188 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
2189 installer->set_install_source(location);
2190 installer->set_expected_id(id);
2191 installer->set_expected_version(*version);
2192 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2193 installer->set_install_immediately(install_immediately);
2194 installer->set_creation_flags(creation_flags);
2195 #if defined(OS_CHROMEOS)
2196 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2197 #else
2198 installer->InstallCrx(path);
2199 #endif
2201 // Depending on the source, a new external extension might not need a user
2202 // notification on installation. For such extensions, mark them acknowledged
2203 // now to suppress the notification.
2204 if (mark_acknowledged)
2205 external_install_manager_->AcknowledgeExternalExtension(id);
2207 return true;
2210 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2211 extensions::ExtensionHost* host) {
2212 OrphanedDevTools::iterator iter =
2213 orphaned_dev_tools_.find(host->extension_id());
2214 if (iter == orphaned_dev_tools_.end())
2215 return;
2217 iter->second->ConnectWebContents(host->host_contents());
2218 orphaned_dev_tools_.erase(iter);
2221 void ExtensionService::Observe(int type,
2222 const content::NotificationSource& source,
2223 const content::NotificationDetails& details) {
2224 switch (type) {
2225 case chrome::NOTIFICATION_APP_TERMINATING:
2226 // Shutdown has started. Don't start any more extension installs.
2227 // (We cannot use ExtensionService::Shutdown() for this because it
2228 // happens too late in browser teardown.)
2229 browser_terminating_ = true;
2230 break;
2231 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2232 if (profile_ !=
2233 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2234 break;
2237 extensions::ExtensionHost* host =
2238 content::Details<extensions::ExtensionHost>(details).ptr();
2240 // If the extension is already being terminated, there is nothing left to
2241 // do.
2242 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2243 break;
2245 // Mark the extension as terminated and Unload it. We want it to
2246 // be in a consistent state: either fully working or not loaded
2247 // at all, but never half-crashed. We do it in a PostTask so
2248 // that other handlers of this notification will still have
2249 // access to the Extension and ExtensionHost.
2250 base::ThreadTaskRunnerHandle::Get()->PostTask(
2251 FROM_HERE, base::Bind(&ExtensionService::TrackTerminatedExtension,
2252 AsWeakPtr(), host->extension()->id()));
2253 break;
2255 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2256 content::RenderProcessHost* process =
2257 content::Source<content::RenderProcessHost>(source).ptr();
2258 Profile* host_profile =
2259 Profile::FromBrowserContext(process->GetBrowserContext());
2260 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2261 break;
2263 extensions::ProcessMap* process_map =
2264 extensions::ProcessMap::Get(profile_);
2265 if (process_map->Contains(process->GetID())) {
2266 // An extension process was terminated, this might have resulted in an
2267 // app or extension becoming idle.
2268 std::set<std::string> extension_ids =
2269 process_map->GetExtensionsInProcess(process->GetID());
2270 // In addition to the extensions listed in the process map, one of those
2271 // extensions could be referencing a shared module which is waiting for
2272 // idle to update. Check all imports of these extensions, too.
2273 std::set<std::string> import_ids;
2274 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2275 it != extension_ids.end();
2276 ++it) {
2277 const Extension* extension = GetExtensionById(*it, true);
2278 if (!extension)
2279 continue;
2280 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2281 SharedModuleInfo::GetImports(extension);
2282 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2283 for (import_it = imports.begin(); import_it != imports.end();
2284 import_it++) {
2285 import_ids.insert((*import_it).extension_id);
2288 extension_ids.insert(import_ids.begin(), import_ids.end());
2290 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2291 it != extension_ids.end(); ++it) {
2292 if (delayed_installs_.Contains(*it)) {
2293 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
2294 FROM_HERE,
2295 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2296 AsWeakPtr(), *it),
2297 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2302 process_map->RemoveAllFromProcess(process->GetID());
2303 BrowserThread::PostTask(
2304 BrowserThread::IO,
2305 FROM_HERE,
2306 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2307 system_->info_map(),
2308 process->GetID()));
2309 break;
2311 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2312 // Notify observers that chrome update is available.
2313 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2314 OnChromeUpdateAvailable());
2315 break;
2317 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2318 OnProfileDestructionStarted();
2319 break;
2322 default:
2323 NOTREACHED() << "Unexpected notification type.";
2327 int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
2328 Extension::DisableReason disable_reason;
2329 // Extensions disabled by management policy should always be disabled, even
2330 // if it's force-installed.
2331 if (system_->management_policy()->MustRemainDisabled(
2332 extension, &disable_reason, nullptr)) {
2333 // A specified reason is required to disable the extension.
2334 DCHECK(disable_reason != Extension::DISABLE_NONE);
2335 return disable_reason;
2338 // Extensions installed by policy can't be disabled. So even if a previous
2339 // installation disabled the extension, make sure it is now enabled.
2340 if (system_->management_policy()->MustRemainEnabled(extension, nullptr))
2341 return Extension::DISABLE_NONE;
2343 // An already disabled extension should inherit the disable reasons and
2344 // remain disabled.
2345 if (extension_prefs_->IsExtensionDisabled(extension->id())) {
2346 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2347 // If an extension was disabled without specified reason, presume it's
2348 // disabled by user.
2349 return disable_reasons == Extension::DISABLE_NONE
2350 ? Extension::DISABLE_USER_ACTION
2351 : disable_reasons;
2354 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2355 // External extensions are initially disabled. We prompt the user before
2356 // enabling them. Hosted apps are excepted because they are not dangerous
2357 // (they need to be launched by the user anyway).
2358 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2359 Manifest::IsExternalLocation(extension->location()) &&
2360 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2361 return Extension::DISABLE_EXTERNAL_EXTENSION;
2365 return Extension::DISABLE_NONE;
2368 // Helper method to determine if an extension can be blocked.
2369 bool ExtensionService::CanBlockExtension(const Extension* extension) const {
2370 DCHECK(extension);
2371 return extension->location() != Manifest::COMPONENT &&
2372 extension->location() != Manifest::EXTERNAL_COMPONENT &&
2373 !system_->management_policy()->MustRemainEnabled(extension, NULL);
2376 bool ExtensionService::ShouldDelayExtensionUpdate(
2377 const std::string& extension_id,
2378 bool install_immediately) const {
2379 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2381 // If delayed updates are globally disabled, or just for this extension,
2382 // don't delay.
2383 if (!install_updates_when_idle_ || install_immediately)
2384 return false;
2386 const Extension* old = GetInstalledExtension(extension_id);
2387 // If there is no old extension, this is not an update, so don't delay.
2388 if (!old)
2389 return false;
2391 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2392 // Delay installation if the extension listens for the onUpdateAvailable
2393 // event.
2394 return extensions::EventRouter::Get(profile_)
2395 ->ExtensionHasEventListener(extension_id, kOnUpdateAvailableEvent);
2396 } else {
2397 // Delay installation if the extension is not idle.
2398 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2402 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2403 DCHECK(!installs_delayed_for_gc_);
2404 installs_delayed_for_gc_ = true;
2407 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2408 DCHECK(installs_delayed_for_gc_);
2409 installs_delayed_for_gc_ = false;
2410 MaybeFinishDelayedInstallations();
2413 void ExtensionService::MaybeFinishDelayedInstallations() {
2414 std::vector<std::string> to_be_installed;
2415 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2416 it != delayed_installs_.end();
2417 ++it) {
2418 to_be_installed.push_back((*it)->id());
2420 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2421 it != to_be_installed.end();
2422 ++it) {
2423 MaybeFinishDelayedInstallation(*it);
2427 void ExtensionService::OnBlacklistUpdated() {
2428 blacklist_->GetBlacklistedIDs(
2429 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2430 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2433 void ExtensionService::ManageBlacklist(
2434 const extensions::Blacklist::BlacklistStateMap& state_map) {
2435 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2437 std::set<std::string> blacklisted;
2438 ExtensionIdSet greylist;
2439 ExtensionIdSet unchanged;
2440 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2441 state_map.begin();
2442 it != state_map.end();
2443 ++it) {
2444 switch (it->second) {
2445 case extensions::NOT_BLACKLISTED:
2446 break;
2448 case extensions::BLACKLISTED_MALWARE:
2449 blacklisted.insert(it->first);
2450 break;
2452 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2453 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2454 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2455 greylist.insert(it->first);
2456 break;
2458 case extensions::BLACKLISTED_UNKNOWN:
2459 unchanged.insert(it->first);
2460 break;
2464 UpdateBlacklistedExtensions(blacklisted, unchanged);
2465 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2467 error_controller_->ShowErrorIfNeeded();
2470 namespace {
2471 void Partition(const ExtensionIdSet& before,
2472 const ExtensionIdSet& after,
2473 const ExtensionIdSet& unchanged,
2474 ExtensionIdSet* no_longer,
2475 ExtensionIdSet* not_yet) {
2476 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2477 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2478 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2480 } // namespace
2482 void ExtensionService::UpdateBlacklistedExtensions(
2483 const ExtensionIdSet& blacklisted,
2484 const ExtensionIdSet& unchanged) {
2485 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2486 Partition(registry_->blacklisted_extensions().GetIDs(), blacklisted,
2487 unchanged, &no_longer_blocked, &not_yet_blocked);
2489 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2490 it != no_longer_blocked.end(); ++it) {
2491 scoped_refptr<const Extension> extension =
2492 registry_->blacklisted_extensions().GetByID(*it);
2493 if (!extension.get()) {
2494 NOTREACHED() << "Extension " << *it << " no longer blacklisted, "
2495 << "but it was never blacklisted.";
2496 continue;
2498 registry_->RemoveBlacklisted(*it);
2499 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2500 AddExtension(extension.get());
2501 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2502 extension->location(),
2503 Manifest::NUM_LOCATIONS);
2506 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2507 it != not_yet_blocked.end(); ++it) {
2508 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2509 if (!extension.get()) {
2510 NOTREACHED() << "Extension " << *it << " needs to be "
2511 << "blacklisted, but it's not installed.";
2512 continue;
2514 registry_->AddBlacklisted(extension);
2515 extension_prefs_->SetExtensionBlacklistState(
2516 extension->id(), extensions::BLACKLISTED_MALWARE);
2517 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2518 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2519 extension->location(), Manifest::NUM_LOCATIONS);
2523 // TODO(oleg): UMA logging
2524 void ExtensionService::UpdateGreylistedExtensions(
2525 const ExtensionIdSet& greylist,
2526 const ExtensionIdSet& unchanged,
2527 const extensions::Blacklist::BlacklistStateMap& state_map) {
2528 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2529 Partition(greylist_.GetIDs(),
2530 greylist, unchanged,
2531 &no_longer_greylisted, &not_yet_greylisted);
2533 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2534 it != no_longer_greylisted.end(); ++it) {
2535 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2536 if (!extension.get()) {
2537 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2538 << "but it was not marked as greylisted.";
2539 continue;
2542 greylist_.Remove(*it);
2543 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2544 extensions::NOT_BLACKLISTED);
2545 if (extension_prefs_->GetDisableReasons(extension->id()) &
2546 extensions::Extension::DISABLE_GREYLIST)
2547 EnableExtension(*it);
2550 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2551 it != not_yet_greylisted.end(); ++it) {
2552 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2553 if (!extension.get()) {
2554 NOTREACHED() << "Extension " << *it << " needs to be "
2555 << "disabled, but it's not installed.";
2556 continue;
2558 greylist_.Insert(extension);
2559 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2560 state_map.find(*it)->second);
2561 if (registry_->enabled_extensions().Contains(extension->id()))
2562 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2566 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2567 update_observers_.AddObserver(observer);
2570 void ExtensionService::RemoveUpdateObserver(
2571 extensions::UpdateObserver* observer) {
2572 update_observers_.RemoveObserver(observer);
2575 // Used only by test code.
2576 void ExtensionService::UnloadAllExtensionsInternal() {
2577 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2579 registry_->ClearAll();
2580 system_->runtime_data()->ClearAll();
2582 // TODO(erikkay) should there be a notification for this? We can't use
2583 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2584 // or uninstalled.
2587 void ExtensionService::OnProfileDestructionStarted() {
2588 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2589 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2590 it != ids_to_unload.end();
2591 ++it) {
2592 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);