Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blob7afdf07b305a1dfd66906bf1b74eee1e3b65d03a
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/metrics/histogram.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/stringprintf.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/sequenced_worker_pool.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/browser_process.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/content_settings/content_settings_custom_extension_provider.h"
22 #include "chrome/browser/content_settings/content_settings_internal_extension_provider.h"
23 #include "chrome/browser/content_settings/host_content_settings_map.h"
24 #include "chrome/browser/extensions/api/content_settings/content_settings_service.h"
25 #include "chrome/browser/extensions/component_loader.h"
26 #include "chrome/browser/extensions/crx_installer.h"
27 #include "chrome/browser/extensions/data_deleter.h"
28 #include "chrome/browser/extensions/extension_action_storage_manager.h"
29 #include "chrome/browser/extensions/extension_assets_manager.h"
30 #include "chrome/browser/extensions/extension_disabled_ui.h"
31 #include "chrome/browser/extensions/extension_error_controller.h"
32 #include "chrome/browser/extensions/extension_install_ui.h"
33 #include "chrome/browser/extensions/extension_special_storage_policy.h"
34 #include "chrome/browser/extensions/extension_sync_service.h"
35 #include "chrome/browser/extensions/extension_util.h"
36 #include "chrome/browser/extensions/external_install_manager.h"
37 #include "chrome/browser/extensions/external_provider_impl.h"
38 #include "chrome/browser/extensions/install_verifier.h"
39 #include "chrome/browser/extensions/installed_loader.h"
40 #include "chrome/browser/extensions/pending_extension_manager.h"
41 #include "chrome/browser/extensions/permissions_updater.h"
42 #include "chrome/browser/extensions/shared_module_service.h"
43 #include "chrome/browser/extensions/unpacked_installer.h"
44 #include "chrome/browser/extensions/updater/chrome_extension_downloader_factory.h"
45 #include "chrome/browser/extensions/updater/extension_updater.h"
46 #include "chrome/browser/google/google_brand.h"
47 #include "chrome/browser/profiles/profile.h"
48 #include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
49 #include "chrome/browser/ui/webui/favicon_source.h"
50 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
51 #include "chrome/browser/ui/webui/theme_source.h"
52 #include "chrome/common/chrome_switches.h"
53 #include "chrome/common/crash_keys.h"
54 #include "chrome/common/extensions/extension_constants.h"
55 #include "chrome/common/extensions/features/feature_channel.h"
56 #include "chrome/common/url_constants.h"
57 #include "components/crx_file/id_util.h"
58 #include "components/startup_metric_utils/startup_metric_utils.h"
59 #include "content/public/browser/devtools_agent_host.h"
60 #include "content/public/browser/notification_service.h"
61 #include "content/public/browser/render_process_host.h"
62 #include "content/public/browser/storage_partition.h"
63 #include "extensions/browser/event_router.h"
64 #include "extensions/browser/extension_host.h"
65 #include "extensions/browser/extension_prefs.h"
66 #include "extensions/browser/extension_registry.h"
67 #include "extensions/browser/extension_system.h"
68 #include "extensions/browser/extensions_browser_client.h"
69 #include "extensions/browser/install_flag.h"
70 #include "extensions/browser/runtime_data.h"
71 #include "extensions/browser/uninstall_reason.h"
72 #include "extensions/browser/update_observer.h"
73 #include "extensions/browser/updater/extension_cache.h"
74 #include "extensions/browser/updater/extension_downloader.h"
75 #include "extensions/common/extension_messages.h"
76 #include "extensions/common/extension_urls.h"
77 #include "extensions/common/feature_switch.h"
78 #include "extensions/common/file_util.h"
79 #include "extensions/common/manifest_constants.h"
80 #include "extensions/common/manifest_handlers/background_info.h"
81 #include "extensions/common/manifest_url_handlers.h"
82 #include "extensions/common/one_shot_event.h"
83 #include "extensions/common/permissions/permission_message_provider.h"
84 #include "extensions/common/permissions/permissions_data.h"
86 #if defined(OS_CHROMEOS)
87 #include "chrome/browser/chromeos/extensions/install_limiter.h"
88 #include "storage/browser/fileapi/file_system_backend.h"
89 #include "storage/browser/fileapi/file_system_context.h"
90 #endif
92 using content::BrowserContext;
93 using content::BrowserThread;
94 using content::DevToolsAgentHost;
95 using extensions::CrxInstaller;
96 using extensions::Extension;
97 using extensions::ExtensionIdSet;
98 using extensions::ExtensionInfo;
99 using extensions::ExtensionRegistry;
100 using extensions::ExtensionSet;
101 using extensions::FeatureSwitch;
102 using extensions::InstallVerifier;
103 using extensions::ManagementPolicy;
104 using extensions::Manifest;
105 using extensions::PermissionMessage;
106 using extensions::PermissionMessages;
107 using extensions::PermissionSet;
108 using extensions::SharedModuleInfo;
109 using extensions::SharedModuleService;
110 using extensions::UnloadedExtensionInfo;
112 namespace errors = extensions::manifest_errors;
114 namespace {
116 // Wait this many seconds after an extensions becomes idle before updating it.
117 const int kUpdateIdleDelay = 5;
119 } // namespace
121 // ExtensionService.
123 void ExtensionService::CheckExternalUninstall(const std::string& id) {
124 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
126 // Check if the providers know about this extension.
127 extensions::ProviderCollection::const_iterator i;
128 for (i = external_extension_providers_.begin();
129 i != external_extension_providers_.end(); ++i) {
130 DCHECK(i->get()->IsReady());
131 if (i->get()->HasExtension(id))
132 return; // Yup, known extension, don't uninstall.
135 // We get the list of external extensions to check from preferences.
136 // It is possible that an extension has preferences but is not loaded.
137 // For example, an extension that requires experimental permissions
138 // will not be loaded if the experimental command line flag is not used.
139 // In this case, do not uninstall.
140 if (!GetInstalledExtension(id)) {
141 // We can't call UninstallExtension with an unloaded/invalid
142 // extension ID.
143 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
144 << "with id: " << id;
145 return;
147 UninstallExtension(id,
148 extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION,
149 base::Bind(&base::DoNothing),
150 NULL);
153 void ExtensionService::SetFileTaskRunnerForTesting(
154 const scoped_refptr<base::SequencedTaskRunner>& task_runner) {
155 file_task_runner_ = task_runner;
158 void ExtensionService::ClearProvidersForTesting() {
159 external_extension_providers_.clear();
162 void ExtensionService::AddProviderForTesting(
163 extensions::ExternalProviderInterface* test_provider) {
164 CHECK(test_provider);
165 external_extension_providers_.push_back(
166 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
169 void ExtensionService::BlacklistExtensionForTest(
170 const std::string& extension_id) {
171 ExtensionIdSet blocked;
172 ExtensionIdSet unchanged;
173 blocked.insert(extension_id);
174 UpdateBlockedExtensions(blocked, unchanged);
177 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
178 const std::string& id,
179 const std::string& install_parameter,
180 const GURL& update_url,
181 Manifest::Location location,
182 int creation_flags,
183 bool mark_acknowledged) {
184 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
185 CHECK(crx_file::id_util::IdIsValid(id));
187 if (Manifest::IsExternalLocation(location)) {
188 // All extensions that are not user specific can be cached.
189 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache()
190 ->AllowCaching(id);
193 const Extension* extension = GetExtensionById(id, true);
194 if (extension) {
195 // Already installed. Skip this install if the current location has
196 // higher priority than |location|.
197 Manifest::Location current = extension->location();
198 if (current == Manifest::GetHigherPriorityLocation(current, location))
199 return false;
200 // Otherwise, overwrite the current installation.
203 // Add |id| to the set of pending extensions. If it can not be added,
204 // then there is already a pending record from a higher-priority install
205 // source. In this case, signal that this extension will not be
206 // installed by returning false.
207 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
209 install_parameter,
210 update_url,
211 location,
212 creation_flags,
213 mark_acknowledged)) {
214 return false;
217 update_once_all_providers_are_ready_ = true;
218 return true;
221 // static
222 // This function is used to uninstall an extension via sync. The LOG statements
223 // within this function are used to inform the user if the uninstall cannot be
224 // done.
225 bool ExtensionService::UninstallExtensionHelper(
226 ExtensionService* extensions_service,
227 const std::string& extension_id,
228 extensions::UninstallReason reason) {
229 // We can't call UninstallExtension with an invalid extension ID.
230 if (!extensions_service->GetInstalledExtension(extension_id)) {
231 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
232 << "id: " << extension_id;
233 return false;
236 // The following call to UninstallExtension will not allow an uninstall of a
237 // policy-controlled extension.
238 base::string16 error;
239 if (!extensions_service->UninstallExtension(
240 extension_id, reason, base::Bind(&base::DoNothing), &error)) {
241 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
242 << ": " << error;
243 return false;
246 return true;
249 ExtensionService::ExtensionService(Profile* profile,
250 const CommandLine* command_line,
251 const base::FilePath& install_directory,
252 extensions::ExtensionPrefs* extension_prefs,
253 extensions::Blacklist* blacklist,
254 bool autoupdate_enabled,
255 bool extensions_enabled,
256 extensions::OneShotEvent* ready)
257 : extensions::Blacklist::Observer(blacklist),
258 profile_(profile),
259 system_(extensions::ExtensionSystem::Get(profile)),
260 extension_prefs_(extension_prefs),
261 blacklist_(blacklist),
262 extension_sync_service_(NULL),
263 registry_(extensions::ExtensionRegistry::Get(profile)),
264 pending_extension_manager_(profile),
265 install_directory_(install_directory),
266 extensions_enabled_(extensions_enabled),
267 show_extensions_prompts_(true),
268 install_updates_when_idle_(true),
269 ready_(ready),
270 update_once_all_providers_are_ready_(false),
271 browser_terminating_(false),
272 installs_delayed_for_gc_(false),
273 is_first_run_(false),
274 shared_module_service_(new extensions::SharedModuleService(profile_)) {
275 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
277 // Figure out if extension installation should be enabled.
278 if (extensions::ExtensionsBrowserClient::Get()->AreExtensionsDisabled(
279 *command_line, profile))
280 extensions_enabled_ = false;
282 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
283 content::NotificationService::AllBrowserContextsAndSources());
284 registrar_.Add(this,
285 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
286 content::NotificationService::AllBrowserContextsAndSources());
287 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
288 content::NotificationService::AllBrowserContextsAndSources());
289 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
290 content::NotificationService::AllBrowserContextsAndSources());
291 registrar_.Add(this,
292 chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
293 content::Source<Profile>(profile_));
295 extensions::ExtensionManagementFactory::GetForBrowserContext(profile_)
296 ->AddObserver(this);
298 // Set up the ExtensionUpdater
299 if (autoupdate_enabled) {
300 int update_frequency = extensions::kDefaultUpdateFrequencySeconds;
301 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
302 base::StringToInt(command_line->GetSwitchValueASCII(
303 switches::kExtensionsUpdateFrequency),
304 &update_frequency);
306 updater_.reset(new extensions::ExtensionUpdater(
307 this,
308 extension_prefs,
309 profile->GetPrefs(),
310 profile,
311 update_frequency,
312 extensions::ExtensionsBrowserClient::Get()->GetExtensionCache(),
313 base::Bind(ChromeExtensionDownloaderFactory::CreateForProfile,
314 profile)));
317 component_loader_.reset(
318 new extensions::ComponentLoader(this,
319 profile->GetPrefs(),
320 g_browser_process->local_state(),
321 profile));
323 if (extensions_enabled_) {
324 extensions::ExternalProviderImpl::CreateExternalProviders(
325 this, profile_, &external_extension_providers_);
328 // Set this as the ExtensionService for app sorting to ensure it causes syncs
329 // if required.
330 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
332 error_controller_.reset(
333 new extensions::ExtensionErrorController(profile_, is_first_run_));
334 external_install_manager_.reset(
335 new extensions::ExternalInstallManager(profile_, is_first_run_));
337 extension_action_storage_manager_.reset(
338 new extensions::ExtensionActionStorageManager(profile_));
340 // How long is the path to the Extensions directory?
341 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
342 install_directory_.value().length(), 0, 500, 100);
345 const ExtensionSet* ExtensionService::extensions() const {
346 return &registry_->enabled_extensions();
349 extensions::PendingExtensionManager*
350 ExtensionService::pending_extension_manager() {
351 return &pending_extension_manager_;
354 ExtensionService::~ExtensionService() {
355 // No need to unload extensions here because they are profile-scoped, and the
356 // profile is in the process of being deleted.
358 extensions::ProviderCollection::const_iterator i;
359 for (i = external_extension_providers_.begin();
360 i != external_extension_providers_.end(); ++i) {
361 extensions::ExternalProviderInterface* provider = i->get();
362 provider->ServiceShutdown();
366 void ExtensionService::Shutdown() {
367 extensions::ExtensionManagementFactory::GetInstance()
368 ->GetForBrowserContext(profile())
369 ->RemoveObserver(this);
370 system_->management_policy()->UnregisterProvider(
371 shared_module_policy_provider_.get());
374 const Extension* ExtensionService::GetExtensionById(
375 const std::string& id, bool include_disabled) const {
376 int include_mask = ExtensionRegistry::ENABLED;
377 if (include_disabled) {
378 // Include blacklisted extensions here because there are hundreds of
379 // callers of this function, and many might assume that this includes those
380 // that have been disabled due to blacklisting.
381 include_mask |= ExtensionRegistry::DISABLED |
382 ExtensionRegistry::BLACKLISTED;
384 return registry_->GetExtensionById(id, include_mask);
387 void ExtensionService::Init() {
388 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
390 base::Time begin_time = base::Time::Now();
392 DCHECK(!is_ready()); // Can't redo init.
393 DCHECK_EQ(registry_->enabled_extensions().size(), 0u);
395 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
396 if (cmd_line->HasSwitch(switches::kInstallEphemeralAppFromWebstore)) {
397 // The sole purpose of this launch is to install a new extension from CWS
398 // and immediately terminate: loading already installed extensions is
399 // unnecessary and may interfere with the inline install dialog (e.g. if an
400 // extension listens to onStartup and opens a window).
401 SetReadyAndNotifyListeners();
402 } else {
403 // LoadAllExtensions() calls OnLoadedInstalledExtensions().
404 component_loader_->LoadAll();
405 extensions::InstalledLoader(this).LoadAllExtensions();
407 // Attempt to re-enable extensions whose only disable reason is reloading.
408 std::vector<std::string> extensions_to_enable;
409 const ExtensionSet& disabled_extensions = registry_->disabled_extensions();
410 for (ExtensionSet::const_iterator iter = disabled_extensions.begin();
411 iter != disabled_extensions.end(); ++iter) {
412 const Extension* e = iter->get();
413 if (extension_prefs_->GetDisableReasons(e->id()) ==
414 Extension::DISABLE_RELOAD) {
415 extensions_to_enable.push_back(e->id());
418 for (std::vector<std::string>::iterator it = extensions_to_enable.begin();
419 it != extensions_to_enable.end(); ++it) {
420 EnableExtension(*it);
423 // Finish install (if possible) of extensions that were still delayed while
424 // the browser was shut down.
425 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info(
426 extension_prefs_->GetAllDelayedInstallInfo());
427 for (size_t i = 0; i < delayed_info->size(); ++i) {
428 ExtensionInfo* info = delayed_info->at(i).get();
429 scoped_refptr<const Extension> extension(NULL);
430 if (info->extension_manifest) {
431 std::string error;
432 extension = Extension::Create(
433 info->extension_path,
434 info->extension_location,
435 *info->extension_manifest,
436 extension_prefs_->GetDelayedInstallCreationFlags(
437 info->extension_id),
438 info->extension_id,
439 &error);
440 if (extension.get())
441 delayed_installs_.Insert(extension);
444 MaybeFinishDelayedInstallations();
446 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2(
447 extension_prefs_->GetAllDelayedInstallInfo());
448 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad",
449 delayed_info2->size() - delayed_info->size());
451 SetReadyAndNotifyListeners();
453 // TODO(erikkay) this should probably be deferred to a future point
454 // rather than running immediately at startup.
455 CheckForExternalUpdates();
457 LoadGreylistFromPrefs();
460 UMA_HISTOGRAM_TIMES("Extensions.ExtensionServiceInitTime",
461 base::Time::Now() - begin_time);
464 void ExtensionService::LoadGreylistFromPrefs() {
465 scoped_ptr<ExtensionSet> all_extensions =
466 registry_->GenerateInstalledExtensionsSet();
468 for (ExtensionSet::const_iterator it = all_extensions->begin();
469 it != all_extensions->end(); ++it) {
470 extensions::BlacklistState state =
471 extension_prefs_->GetExtensionBlacklistState((*it)->id());
472 if (state == extensions::BLACKLISTED_SECURITY_VULNERABILITY ||
473 state == extensions::BLACKLISTED_POTENTIALLY_UNWANTED ||
474 state == extensions::BLACKLISTED_CWS_POLICY_VIOLATION)
475 greylist_.Insert(*it);
479 bool ExtensionService::UpdateExtension(const std::string& id,
480 const base::FilePath& extension_path,
481 bool file_ownership_passed,
482 CrxInstaller** out_crx_installer) {
483 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
484 if (browser_terminating_) {
485 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
486 // Leak the temp file at extension_path. We don't want to add to the disk
487 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
488 // the file is in the OS temp directory which should be cleaned up for us.
489 return false;
492 const extensions::PendingExtensionInfo* pending_extension_info =
493 pending_extension_manager()->GetById(id);
495 const Extension* extension = GetInstalledExtension(id);
496 if (!pending_extension_info && !extension) {
497 LOG(WARNING) << "Will not update extension " << id
498 << " because it is not installed or pending";
499 // Delete extension_path since we're not creating a CrxInstaller
500 // that would do it for us.
501 if (!GetFileTaskRunner()->PostTask(
502 FROM_HERE,
503 base::Bind(
504 &extensions::file_util::DeleteFile, extension_path, false)))
505 NOTREACHED();
507 return false;
510 scoped_refptr<CrxInstaller> installer(
511 CrxInstaller::Create(this, scoped_ptr<ExtensionInstallPrompt>()));
512 installer->set_expected_id(id);
513 int creation_flags = Extension::NO_FLAGS;
514 if (pending_extension_info) {
515 installer->set_install_source(pending_extension_info->install_source());
516 installer->set_allow_silent_install(true);
517 if (pending_extension_info->remote_install())
518 installer->set_grant_permissions(false);
519 creation_flags = pending_extension_info->creation_flags();
520 if (pending_extension_info->mark_acknowledged())
521 external_install_manager_->AcknowledgeExternalExtension(id);
522 } else if (extension) {
523 installer->set_install_source(extension->location());
525 // If the extension was installed from or has migrated to the webstore, or
526 // its auto-update URL is from the webstore, treat it as a webstore install.
527 // Note that we ignore some older extensions with blank auto-update URLs
528 // because we are mostly concerned with restrictions on NaCl extensions,
529 // which are newer.
530 if ((extension && extension->from_webstore()) ||
531 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
532 (!extension && extension_urls::IsWebstoreUpdateUrl(
533 pending_extension_info->update_url()))) {
534 creation_flags |= Extension::FROM_WEBSTORE;
537 // Bookmark apps being updated is kind of a contradiction, but that's because
538 // we mark the default apps as bookmark apps, and they're hosted in the web
539 // store, thus they can get updated. See http://crbug.com/101605 for more
540 // details.
541 if (extension && extension->from_bookmark())
542 creation_flags |= Extension::FROM_BOOKMARK;
544 if (extension && extension->was_installed_by_default())
545 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
547 if (extension && extension->was_installed_by_oem())
548 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
550 if (extension && extension->was_installed_by_custodian())
551 creation_flags |= Extension::WAS_INSTALLED_BY_CUSTODIAN;
553 if (extension) {
554 installer->set_is_ephemeral(extension_prefs_->IsEphemeralApp(id));
555 installer->set_do_not_sync(extension_prefs_->DoNotSync(id));
558 installer->set_creation_flags(creation_flags);
560 installer->set_delete_source(file_ownership_passed);
561 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
562 installer->InstallCrx(extension_path);
564 if (out_crx_installer)
565 *out_crx_installer = installer.get();
567 return true;
570 void ExtensionService::ReloadExtensionImpl(
571 // "transient" because the process of reloading may cause the reference
572 // to become invalid. Instead, use |extension_id|, a copy.
573 const std::string& transient_extension_id,
574 bool be_noisy) {
575 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
577 // If the extension is already reloading, don't reload again.
578 if (extension_prefs_->GetDisableReasons(transient_extension_id) &
579 Extension::DISABLE_RELOAD) {
580 return;
583 // Ignore attempts to reload a blacklisted extension. Sometimes this can
584 // happen in a convoluted reload sequence triggered by the termination of a
585 // blacklisted extension and a naive attempt to reload it. For an example see
586 // http://crbug.com/373842.
587 if (registry_->blacklisted_extensions().Contains(transient_extension_id))
588 return;
590 base::FilePath path;
592 std::string extension_id = transient_extension_id;
593 const Extension* transient_current_extension =
594 GetExtensionById(extension_id, false);
596 // Disable the extension if it's loaded. It might not be loaded if it crashed.
597 if (transient_current_extension) {
598 // If the extension has an inspector open for its background page, detach
599 // the inspector and hang onto a cookie for it, so that we can reattach
600 // later.
601 // TODO(yoz): this is not incognito-safe!
602 extensions::ProcessManager* manager = system_->process_manager();
603 extensions::ExtensionHost* host =
604 manager->GetBackgroundHostForExtension(extension_id);
605 if (host && DevToolsAgentHost::HasFor(host->host_contents())) {
606 // Look for an open inspector for the background page.
607 scoped_refptr<DevToolsAgentHost> agent_host =
608 DevToolsAgentHost::GetOrCreateFor(host->host_contents());
609 agent_host->DisconnectWebContents();
610 orphaned_dev_tools_[extension_id] = agent_host;
613 path = transient_current_extension->path();
614 // BeingUpgraded is set back to false when the extension is added.
615 system_->runtime_data()->SetBeingUpgraded(transient_current_extension,
616 true);
617 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
618 reloading_extensions_.insert(extension_id);
619 } else {
620 std::map<std::string, base::FilePath>::const_iterator iter =
621 unloaded_extension_paths_.find(extension_id);
622 if (iter == unloaded_extension_paths_.end()) {
623 return;
625 path = unloaded_extension_paths_[extension_id];
628 transient_current_extension = NULL;
630 if (delayed_installs_.Contains(extension_id)) {
631 FinishDelayedInstallation(extension_id);
632 return;
635 // If we're reloading a component extension, use the component extension
636 // loader's reloader.
637 if (component_loader_->Exists(extension_id)) {
638 component_loader_->Reload(extension_id);
639 return;
642 // Check the installed extensions to see if what we're reloading was already
643 // installed.
644 scoped_ptr<ExtensionInfo> installed_extension(
645 extension_prefs_->GetInstalledExtensionInfo(extension_id));
646 if (installed_extension.get() &&
647 installed_extension->extension_manifest.get()) {
648 extensions::InstalledLoader(this).Load(*installed_extension, false);
649 } else {
650 // Otherwise, the extension is unpacked (location LOAD).
651 // We should always be able to remember the extension's path. If it's not in
652 // the map, someone failed to update |unloaded_extension_paths_|.
653 CHECK(!path.empty());
654 scoped_refptr<extensions::UnpackedInstaller> unpacked_installer =
655 extensions::UnpackedInstaller::Create(this);
656 unpacked_installer->set_be_noisy_on_failure(be_noisy);
657 unpacked_installer->Load(path);
661 void ExtensionService::ReloadExtension(const std::string& extension_id) {
662 ReloadExtensionImpl(extension_id, true); // be_noisy
665 void ExtensionService::ReloadExtensionWithQuietFailure(
666 const std::string& extension_id) {
667 ReloadExtensionImpl(extension_id, false); // be_noisy
670 bool ExtensionService::UninstallExtension(
671 // "transient" because the process of uninstalling may cause the reference
672 // to become invalid. Instead, use |extenson->id()|.
673 const std::string& transient_extension_id,
674 extensions::UninstallReason reason,
675 const base::Closure& deletion_done_callback,
676 base::string16* error) {
677 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
679 scoped_refptr<const Extension> extension =
680 GetInstalledExtension(transient_extension_id);
682 // Callers should not send us nonexistent extensions.
683 CHECK(extension.get());
685 ManagementPolicy* by_policy = system_->management_policy();
686 // Policy change which triggers an uninstall will always set
687 // |external_uninstall| to true so this is the only way to uninstall
688 // managed extensions.
689 // Shared modules being uninstalled will also set |external_uninstall| to true
690 // so that we can guarantee users don't uninstall a shared module.
691 // (crbug.com/273300)
692 // TODO(rdevlin.cronin): This is probably not right. We should do something
693 // else, like include an enum IS_INTERNAL_UNINSTALL or IS_USER_UNINSTALL so
694 // we don't do this.
695 bool external_uninstall =
696 (reason == extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT) ||
697 (reason == extensions::UNINSTALL_REASON_REINSTALL) ||
698 (reason == extensions::UNINSTALL_REASON_ORPHANED_EXTERNAL_EXTENSION) ||
699 (reason == extensions::UNINSTALL_REASON_ORPHANED_SHARED_MODULE) ||
700 (reason == extensions::UNINSTALL_REASON_SYNC &&
701 extension->was_installed_by_custodian());
702 if (!external_uninstall &&
703 (!by_policy->UserMayModifySettings(extension.get(), error) ||
704 by_policy->MustRemainInstalled(extension.get(), error))) {
705 content::NotificationService::current()->Notify(
706 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
707 content::Source<Profile>(profile_),
708 content::Details<const Extension>(extension.get()));
709 return false;
712 syncer::SyncChange sync_change;
713 // Don't sync the uninstall if we're going to reinstall the extension
714 // momentarily.
715 if (extension_sync_service_ &&
716 reason != extensions::UNINSTALL_REASON_REINSTALL) {
717 sync_change = extension_sync_service_->PrepareToSyncUninstallExtension(
718 extension.get(), is_ready());
721 system_->install_verifier()->Remove(extension->id());
723 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
724 extension->GetType(), 100);
725 RecordPermissionMessagesHistogram(extension.get(),
726 "Extensions.Permissions_Uninstall2");
728 // Unload before doing more cleanup to ensure that nothing is hanging on to
729 // any of these resources.
730 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UNINSTALL);
732 // Tell the backend to start deleting installed extensions on the file thread.
733 if (!Manifest::IsUnpackedLocation(extension->location())) {
734 if (!GetFileTaskRunner()->PostTask(
735 FROM_HERE,
736 base::Bind(&ExtensionService::UninstallExtensionOnFileThread,
737 extension->id(),
738 profile_,
739 install_directory_,
740 extension->path())))
741 NOTREACHED();
744 extensions::DataDeleter::StartDeleting(
745 profile_, extension.get(), deletion_done_callback);
747 UntrackTerminatedExtension(extension->id());
749 // Notify interested parties that we've uninstalled this extension.
750 content::NotificationService::current()->Notify(
751 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
752 content::Source<Profile>(profile_),
753 content::Details<const Extension>(extension.get()));
754 ExtensionRegistry::Get(profile_)
755 ->TriggerOnUninstalled(extension.get(), reason);
757 if (sync_change.IsValid()) {
758 extension_sync_service_->ProcessSyncUninstallExtension(extension->id(),
759 sync_change);
762 delayed_installs_.Remove(extension->id());
764 extension_prefs_->OnExtensionUninstalled(
765 extension->id(), extension->location(), external_uninstall);
767 // Track the uninstallation.
768 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
770 return true;
773 // static
774 void ExtensionService::UninstallExtensionOnFileThread(
775 const std::string& id,
776 Profile* profile,
777 const base::FilePath& install_dir,
778 const base::FilePath& extension_path) {
779 extensions::ExtensionAssetsManager* assets_manager =
780 extensions::ExtensionAssetsManager::GetInstance();
781 assets_manager->UninstallExtension(id, profile, install_dir, extension_path);
784 bool ExtensionService::IsExtensionEnabled(
785 const std::string& extension_id) const {
786 if (registry_->enabled_extensions().Contains(extension_id) ||
787 registry_->terminated_extensions().Contains(extension_id)) {
788 return true;
791 if (registry_->disabled_extensions().Contains(extension_id) ||
792 registry_->blacklisted_extensions().Contains(extension_id)) {
793 return false;
796 // If the extension hasn't been loaded yet, check the prefs for it. Assume
797 // enabled unless otherwise noted.
798 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
799 !extension_prefs_->IsExtensionBlacklisted(extension_id) &&
800 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
803 void ExtensionService::EnableExtension(const std::string& extension_id) {
804 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
806 if (IsExtensionEnabled(extension_id))
807 return;
808 const Extension* extension =
809 registry_->disabled_extensions().GetByID(extension_id);
811 ManagementPolicy* policy = system_->management_policy();
812 if (extension && policy->MustRemainDisabled(extension, NULL, NULL)) {
813 UMA_HISTOGRAM_COUNTS_100("Extensions.EnableDeniedByPolicy", 1);
814 return;
817 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
818 extension_prefs_->ClearDisableReasons(extension_id);
820 // This can happen if sync enables an extension that is not
821 // installed yet.
822 if (!extension)
823 return;
825 // Move it over to the enabled list.
826 registry_->AddEnabled(make_scoped_refptr(extension));
827 registry_->RemoveDisabled(extension->id());
829 NotifyExtensionLoaded(extension);
831 // Notify listeners that the extension was enabled.
832 content::NotificationService::current()->Notify(
833 extensions::NOTIFICATION_EXTENSION_ENABLED,
834 content::Source<Profile>(profile_),
835 content::Details<const Extension>(extension));
837 if (extension_sync_service_)
838 extension_sync_service_->SyncEnableExtension(*extension);
841 void ExtensionService::DisableExtension(
842 const std::string& extension_id,
843 Extension::DisableReason disable_reason) {
844 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
846 // The extension may have been disabled already. Just add a disable reason.
847 if (!IsExtensionEnabled(extension_id)) {
848 extension_prefs_->AddDisableReason(extension_id, disable_reason);
849 return;
852 const Extension* extension = GetInstalledExtension(extension_id);
853 // |extension| can be NULL if sync disables an extension that is not
854 // installed yet.
855 // EXTERNAL_COMPONENT extensions are not generally modifiable by users, but
856 // can be uninstalled by the browser if the user sets extension-specific
857 // preferences.
858 if (extension &&
859 disable_reason != Extension::DISABLE_RELOAD &&
860 !system_->management_policy()->UserMayModifySettings(extension, NULL) &&
861 extension->location() != Manifest::EXTERNAL_COMPONENT) {
862 return;
865 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
866 extension_prefs_->AddDisableReason(extension_id, disable_reason);
868 int include_mask =
869 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::DISABLED;
870 extension = registry_->GetExtensionById(extension_id, include_mask);
871 if (!extension)
872 return;
874 // The extension is either enabled or terminated.
875 DCHECK(registry_->enabled_extensions().Contains(extension->id()) ||
876 registry_->terminated_extensions().Contains(extension->id()));
878 // Move it over to the disabled list. Don't send a second unload notification
879 // for terminated extensions being disabled.
880 registry_->AddDisabled(make_scoped_refptr(extension));
881 if (registry_->enabled_extensions().Contains(extension->id())) {
882 registry_->RemoveEnabled(extension->id());
883 NotifyExtensionUnloaded(extension, UnloadedExtensionInfo::REASON_DISABLE);
884 } else {
885 registry_->RemoveTerminated(extension->id());
888 if (extension_sync_service_)
889 extension_sync_service_->SyncDisableExtension(*extension);
892 void ExtensionService::DisableUserExtensions(
893 const std::vector<std::string>& except_ids) {
894 extensions::ManagementPolicy* management_policy =
895 system_->management_policy();
896 extensions::ExtensionList to_disable;
898 const ExtensionSet& enabled_set = registry_->enabled_extensions();
899 for (ExtensionSet::const_iterator extension = enabled_set.begin();
900 extension != enabled_set.end(); ++extension) {
901 if (management_policy->UserMayModifySettings(extension->get(), NULL))
902 to_disable.push_back(*extension);
904 const ExtensionSet& terminated_set = registry_->terminated_extensions();
905 for (ExtensionSet::const_iterator extension = terminated_set.begin();
906 extension != terminated_set.end(); ++extension) {
907 if (management_policy->UserMayModifySettings(extension->get(), NULL))
908 to_disable.push_back(*extension);
911 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
912 extension != to_disable.end(); ++extension) {
913 if ((*extension)->was_installed_by_default() &&
914 extension_urls::IsWebstoreUpdateUrl(
915 extensions::ManifestURL::GetUpdateURL(extension->get())))
916 continue;
917 const std::string& id = (*extension)->id();
918 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id))
919 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION);
923 void ExtensionService::GrantPermissionsAndEnableExtension(
924 const Extension* extension) {
925 GrantPermissions(extension);
926 RecordPermissionMessagesHistogram(extension,
927 "Extensions.Permissions_ReEnable2");
928 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
929 EnableExtension(extension->id());
932 void ExtensionService::GrantPermissions(const Extension* extension) {
933 CHECK(extension);
934 extensions::PermissionsUpdater(profile()).GrantActivePermissions(extension);
937 // static
938 void ExtensionService::RecordPermissionMessagesHistogram(
939 const Extension* extension, const char* histogram) {
940 // Since this is called from multiple sources, and since the histogram macros
941 // use statics, we need to manually lookup the histogram ourselves.
942 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
943 histogram,
945 PermissionMessage::kEnumBoundary,
946 PermissionMessage::kEnumBoundary + 1,
947 base::HistogramBase::kUmaTargetedHistogramFlag);
949 PermissionMessages permissions =
950 extension->permissions_data()->GetPermissionMessages();
951 if (permissions.empty()) {
952 counter->Add(PermissionMessage::kNone);
953 } else {
954 for (PermissionMessages::iterator it = permissions.begin();
955 it != permissions.end(); ++it)
956 counter->Add(it->id());
960 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
961 // The URLRequestContexts need to be first to know that the extension
962 // was loaded, otherwise a race can arise where a renderer that is created
963 // for the extension may try to load an extension URL with an extension id
964 // that the request context doesn't yet know about. The profile is responsible
965 // for ensuring its URLRequestContexts appropriately discover the loaded
966 // extension.
967 system_->RegisterExtensionWithRequestContexts(extension);
969 // Tell renderers about the new extension, unless it's a theme (renderers
970 // don't need to know about themes).
971 if (!extension->is_theme()) {
972 for (content::RenderProcessHost::iterator i(
973 content::RenderProcessHost::AllHostsIterator());
974 !i.IsAtEnd(); i.Advance()) {
975 content::RenderProcessHost* host = i.GetCurrentValue();
976 Profile* host_profile =
977 Profile::FromBrowserContext(host->GetBrowserContext());
978 if (host_profile->GetOriginalProfile() ==
979 profile_->GetOriginalProfile()) {
980 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
981 1, ExtensionMsg_Loaded_Params(extension));
982 host->Send(
983 new ExtensionMsg_Loaded(loaded_extensions));
988 // Tell subsystems that use the EXTENSION_LOADED notification about the new
989 // extension.
991 // NOTE: It is important that this happen after notifying the renderers about
992 // the new extensions so that if we navigate to an extension URL in
993 // ExtensionRegistryObserver::OnLoaded or
994 // NOTIFICATION_EXTENSION_LOADED_DEPRECATED, the
995 // renderer is guaranteed to know about it.
996 registry_->TriggerOnLoaded(extension);
998 content::NotificationService::current()->Notify(
999 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1000 content::Source<Profile>(profile_),
1001 content::Details<const Extension>(extension));
1003 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1004 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1005 profile_->GetExtensionSpecialStoragePolicy()->
1006 GrantRightsForExtension(extension, profile_);
1008 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1009 // work properly multi-profile. Besides which, it should be using
1010 // ExtensionRegistryObserver. See http://crbug.com/355029.
1011 UpdateActiveExtensionsInCrashReporter();
1013 const extensions::PermissionsData* permissions_data =
1014 extension->permissions_data();
1016 // If the extension has permission to load chrome://favicon/ resources we need
1017 // to make sure that the FaviconSource is registered with the
1018 // ChromeURLDataManager.
1019 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIFaviconURL))) {
1020 FaviconSource* favicon_source = new FaviconSource(profile_,
1021 FaviconSource::FAVICON);
1022 content::URLDataSource::Add(profile_, favicon_source);
1025 // Same for chrome://theme/ resources.
1026 if (permissions_data->HasHostPermission(GURL(chrome::kChromeUIThemeURL))) {
1027 ThemeSource* theme_source = new ThemeSource(profile_);
1028 content::URLDataSource::Add(profile_, theme_source);
1031 // Same for chrome://thumb/ resources.
1032 if (permissions_data->HasHostPermission(
1033 GURL(chrome::kChromeUIThumbnailURL))) {
1034 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false);
1035 content::URLDataSource::Add(profile_, thumbnail_source);
1039 void ExtensionService::NotifyExtensionUnloaded(
1040 const Extension* extension,
1041 UnloadedExtensionInfo::Reason reason) {
1042 UnloadedExtensionInfo details(extension, reason);
1044 registry_->TriggerOnUnloaded(extension, reason);
1046 content::NotificationService::current()->Notify(
1047 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
1048 content::Source<Profile>(profile_),
1049 content::Details<UnloadedExtensionInfo>(&details));
1051 for (content::RenderProcessHost::iterator i(
1052 content::RenderProcessHost::AllHostsIterator());
1053 !i.IsAtEnd(); i.Advance()) {
1054 content::RenderProcessHost* host = i.GetCurrentValue();
1055 Profile* host_profile =
1056 Profile::FromBrowserContext(host->GetBrowserContext());
1057 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1058 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1061 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1063 // TODO(kalman): Convert ExtensionSpecialStoragePolicy to a
1064 // BrowserContextKeyedService and use ExtensionRegistryObserver.
1065 profile_->GetExtensionSpecialStoragePolicy()->
1066 RevokeRightsForExtension(extension);
1068 #if defined(OS_CHROMEOS)
1069 // Revoke external file access for the extension from its file system context.
1070 // It is safe to access the extension's storage partition at this point. The
1071 // storage partition may get destroyed only after the extension gets unloaded.
1072 GURL site =
1073 extensions::util::GetSiteForExtensionId(extension->id(), profile_);
1074 storage::FileSystemContext* filesystem_context =
1075 BrowserContext::GetStoragePartitionForSite(profile_, site)
1076 ->GetFileSystemContext();
1077 if (filesystem_context && filesystem_context->external_backend()) {
1078 filesystem_context->external_backend()->
1079 RevokeAccessForExtension(extension->id());
1081 #endif
1083 // TODO(kalman): This is broken. The crash reporter is process-wide so doesn't
1084 // work properly multi-profile. Besides which, it should be using
1085 // ExtensionRegistryObserver::OnExtensionLoaded. See http://crbug.com/355029.
1086 UpdateActiveExtensionsInCrashReporter();
1089 content::BrowserContext* ExtensionService::GetBrowserContext() const {
1090 // Implemented in the .cc file to avoid adding a profile.h dependency to
1091 // extension_service.h.
1092 return profile_;
1095 bool ExtensionService::is_ready() {
1096 return ready_->is_signaled();
1099 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1100 if (file_task_runner_.get())
1101 return file_task_runner_.get();
1103 // We should be able to interrupt any part of extension install process during
1104 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1105 // will be ignored/deleted while we will block on started tasks.
1106 std::string token("ext_install-");
1107 token.append(profile_->GetPath().AsUTF8Unsafe());
1108 file_task_runner_ = BrowserThread::GetBlockingPool()->
1109 GetSequencedTaskRunnerWithShutdownBehavior(
1110 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1111 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1112 return file_task_runner_.get();
1115 void ExtensionService::CheckManagementPolicy() {
1116 std::vector<std::string> to_unload;
1117 std::map<std::string, Extension::DisableReason> to_disable;
1119 // Loop through the extensions list, finding extensions we need to unload or
1120 // disable.
1121 const ExtensionSet& extensions = registry_->enabled_extensions();
1122 for (ExtensionSet::const_iterator iter = extensions.begin();
1123 iter != extensions.end(); ++iter) {
1124 const Extension* extension = (iter->get());
1125 if (!system_->management_policy()->UserMayLoad(extension, NULL))
1126 to_unload.push_back(extension->id());
1127 Extension::DisableReason disable_reason = Extension::DISABLE_NONE;
1128 if (system_->management_policy()->MustRemainDisabled(
1129 extension, &disable_reason, NULL))
1130 to_disable[extension->id()] = disable_reason;
1133 for (size_t i = 0; i < to_unload.size(); ++i)
1134 UnloadExtension(to_unload[i], UnloadedExtensionInfo::REASON_DISABLE);
1136 for (std::map<std::string, Extension::DisableReason>::const_iterator i =
1137 to_disable.begin(); i != to_disable.end(); ++i)
1138 DisableExtension(i->first, i->second);
1141 void ExtensionService::CheckForUpdatesSoon() {
1142 // This can legitimately happen in unit tests.
1143 if (!updater_.get())
1144 return;
1146 if (AreAllExternalProvidersReady()) {
1147 updater_->CheckSoon();
1148 } else {
1149 // Sync can start updating before all the external providers are ready
1150 // during startup. Start the update as soon as those providers are ready,
1151 // but not before.
1152 update_once_all_providers_are_ready_ = true;
1156 // Some extensions will autoupdate themselves externally from Chrome. These
1157 // are typically part of some larger client application package. To support
1158 // these, the extension will register its location in the the preferences file
1159 // (and also, on Windows, in the registry) and this code will periodically
1160 // check that location for a .crx file, which it will then install locally if
1161 // a new version is available.
1162 // Errors are reported through ExtensionErrorReporter. Succcess is not
1163 // reported.
1164 void ExtensionService::CheckForExternalUpdates() {
1165 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1167 // Note that this installation is intentionally silent (since it didn't
1168 // go through the front-end). Extensions that are registered in this
1169 // way are effectively considered 'pre-bundled', and so implicitly
1170 // trusted. In general, if something has HKLM or filesystem access,
1171 // they could install an extension manually themselves anyway.
1173 // Ask each external extension provider to give us a call back for each
1174 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1175 extensions::ProviderCollection::const_iterator i;
1176 for (i = external_extension_providers_.begin();
1177 i != external_extension_providers_.end(); ++i) {
1178 extensions::ExternalProviderInterface* provider = i->get();
1179 provider->VisitRegisteredExtension();
1182 // Do any required work that we would have done after completion of all
1183 // providers.
1184 if (external_extension_providers_.empty())
1185 OnAllExternalProvidersReady();
1188 void ExtensionService::OnExternalProviderReady(
1189 const extensions::ExternalProviderInterface* provider) {
1190 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1191 CHECK(provider->IsReady());
1193 // An external provider has finished loading. We only take action
1194 // if all of them are finished. So we check them first.
1195 if (AreAllExternalProvidersReady())
1196 OnAllExternalProvidersReady();
1199 bool ExtensionService::AreAllExternalProvidersReady() const {
1200 extensions::ProviderCollection::const_iterator i;
1201 for (i = external_extension_providers_.begin();
1202 i != external_extension_providers_.end(); ++i) {
1203 if (!i->get()->IsReady())
1204 return false;
1206 return true;
1209 void ExtensionService::OnAllExternalProvidersReady() {
1210 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1211 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1212 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1214 // Install any pending extensions.
1215 if (update_once_all_providers_are_ready_ && updater()) {
1216 update_once_all_providers_are_ready_ = false;
1217 extensions::ExtensionUpdater::CheckParams params;
1218 params.callback = external_updates_finished_callback_;
1219 updater()->CheckNow(params);
1222 // Uninstall all the unclaimed extensions.
1223 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1224 extension_prefs_->GetInstalledExtensionsInfo());
1225 for (size_t i = 0; i < extensions_info->size(); ++i) {
1226 ExtensionInfo* info = extensions_info->at(i).get();
1227 if (Manifest::IsExternalLocation(info->extension_location))
1228 CheckExternalUninstall(info->extension_id);
1231 error_controller_->ShowErrorIfNeeded();
1233 external_install_manager_->UpdateExternalExtensionAlert();
1236 void ExtensionService::UnloadExtension(
1237 const std::string& extension_id,
1238 UnloadedExtensionInfo::Reason reason) {
1239 // Make sure the extension gets deleted after we return from this function.
1240 int include_mask =
1241 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
1242 scoped_refptr<const Extension> extension(
1243 registry_->GetExtensionById(extension_id, include_mask));
1245 // This method can be called via PostTask, so the extension may have been
1246 // unloaded by the time this runs.
1247 if (!extension.get()) {
1248 // In case the extension may have crashed/uninstalled. Allow the profile to
1249 // clean up its RequestContexts.
1250 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1251 return;
1254 // Keep information about the extension so that we can reload it later
1255 // even if it's not permanently installed.
1256 unloaded_extension_paths_[extension->id()] = extension->path();
1258 // Clean up if the extension is meant to be enabled after a reload.
1259 reloading_extensions_.erase(extension->id());
1261 if (registry_->disabled_extensions().Contains(extension->id())) {
1262 registry_->RemoveDisabled(extension->id());
1263 // Make sure the profile cleans up its RequestContexts when an already
1264 // disabled extension is unloaded (since they are also tracking the disabled
1265 // extensions).
1266 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1267 // Don't send the unloaded notification. It was sent when the extension
1268 // was disabled.
1269 } else {
1270 // Remove the extension from the enabled list.
1271 registry_->RemoveEnabled(extension->id());
1272 NotifyExtensionUnloaded(extension.get(), reason);
1275 content::NotificationService::current()->Notify(
1276 extensions::NOTIFICATION_EXTENSION_REMOVED,
1277 content::Source<Profile>(profile_),
1278 content::Details<const Extension>(extension.get()));
1281 void ExtensionService::RemoveComponentExtension(
1282 const std::string& extension_id) {
1283 scoped_refptr<const Extension> extension(
1284 GetExtensionById(extension_id, false));
1285 UnloadExtension(extension_id, UnloadedExtensionInfo::REASON_UNINSTALL);
1286 if (extension.get()) {
1287 content::NotificationService::current()->Notify(
1288 extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
1289 content::Source<Profile>(profile_),
1290 content::Details<const Extension>(extension.get()));
1291 ExtensionRegistry::Get(profile_)->TriggerOnUninstalled(
1292 extension.get(), extensions::UNINSTALL_REASON_INTERNAL_MANAGEMENT);
1296 void ExtensionService::UnloadAllExtensionsForTest() {
1297 UnloadAllExtensionsInternal();
1300 void ExtensionService::ReloadExtensionsForTest() {
1301 // Calling UnloadAllExtensionsForTest here triggers a false-positive presubmit
1302 // warning about calling test code in production.
1303 UnloadAllExtensionsInternal();
1304 component_loader_->LoadAll();
1305 extensions::InstalledLoader(this).LoadAllExtensions();
1306 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1307 // times.
1310 void ExtensionService::SetReadyAndNotifyListeners() {
1311 ready_->Signal();
1312 content::NotificationService::current()->Notify(
1313 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
1314 content::Source<Profile>(profile_),
1315 content::NotificationService::NoDetails());
1318 void ExtensionService::OnLoadedInstalledExtensions() {
1319 if (updater_)
1320 updater_->Start();
1322 OnBlacklistUpdated();
1325 void ExtensionService::AddExtension(const Extension* extension) {
1326 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1327 // default extension state to DISABLED when the --disable-extensions flag
1328 // is set (http://crbug.com/29067).
1329 if (!extensions_enabled() &&
1330 !extension->is_theme() &&
1331 extension->location() != Manifest::COMPONENT &&
1332 !Manifest::IsExternalLocation(extension->location())) {
1333 return;
1336 bool is_extension_upgrade = false;
1337 bool is_extension_installed = false;
1338 const Extension* old = GetInstalledExtension(extension->id());
1339 if (old) {
1340 is_extension_installed = true;
1341 int version_compare_result =
1342 extension->version()->CompareTo(*(old->version()));
1343 is_extension_upgrade = version_compare_result > 0;
1344 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1345 // that we aren't downgrading.
1346 if (!Manifest::IsUnpackedLocation(extension->location()))
1347 CHECK_GE(version_compare_result, 0);
1349 system_->runtime_data()->SetBeingUpgraded(extension, is_extension_upgrade);
1351 // The extension is now loaded, remove its data from unloaded extension map.
1352 unloaded_extension_paths_.erase(extension->id());
1354 // If a terminated extension is loaded, remove it from the terminated list.
1355 UntrackTerminatedExtension(extension->id());
1357 // If the extension was disabled for a reload, then enable it.
1358 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1360 // Check if the extension's privileges have changed and mark the
1361 // extension disabled if necessary.
1362 CheckPermissionsIncrease(extension, is_extension_installed);
1364 if (is_extension_installed && !reloading) {
1365 // To upgrade an extension in place, unload the old one and then load the
1366 // new one. ReloadExtension disables the extension, which is sufficient.
1367 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_UPDATE);
1370 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
1371 // Only prefs is checked for the blacklist. We rely on callers to check the
1372 // blacklist before calling into here, e.g. CrxInstaller checks before
1373 // installation then threads through the install and pending install flow
1374 // of this class, and we check when loading installed extensions.
1375 registry_->AddBlacklisted(extension);
1376 } else if (!reloading &&
1377 extension_prefs_->IsExtensionDisabled(extension->id())) {
1378 registry_->AddDisabled(extension);
1379 if (extension_sync_service_)
1380 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1381 content::NotificationService::current()->Notify(
1382 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
1383 content::Source<Profile>(profile_),
1384 content::Details<const Extension>(extension));
1386 // Show the extension disabled error if a permissions increase or a remote
1387 // installation is the reason it was disabled, and no other reasons exist.
1388 int reasons = extension_prefs_->GetDisableReasons(extension->id());
1389 const int kReasonMask = Extension::DISABLE_PERMISSIONS_INCREASE |
1390 Extension::DISABLE_REMOTE_INSTALL;
1391 if (reasons & kReasonMask && !(reasons & ~kReasonMask)) {
1392 extensions::AddExtensionDisabledError(
1393 this,
1394 extension,
1395 extension_prefs_->HasDisableReason(
1396 extension->id(), Extension::DISABLE_REMOTE_INSTALL));
1398 } else if (reloading) {
1399 // Replace the old extension with the new version.
1400 CHECK(!registry_->AddDisabled(extension));
1401 EnableExtension(extension->id());
1402 } else {
1403 // All apps that are displayed in the launcher are ordered by their ordinals
1404 // so we must ensure they have valid ordinals.
1405 if (extension->RequiresSortOrdinal()) {
1406 extension_prefs_->app_sorting()->SetExtensionVisible(
1407 extension->id(),
1408 extension->ShouldDisplayInNewTabPage() &&
1409 !extension_prefs_->IsEphemeralApp(extension->id()));
1410 if (!extension_prefs_->IsEphemeralApp(extension->id())) {
1411 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1412 extension->id(), syncer::StringOrdinal());
1416 registry_->AddEnabled(extension);
1417 if (extension_sync_service_)
1418 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1419 NotifyExtensionLoaded(extension);
1421 system_->runtime_data()->SetBeingUpgraded(extension, false);
1424 void ExtensionService::AddComponentExtension(const Extension* extension) {
1425 const std::string old_version_string(
1426 extension_prefs_->GetVersionString(extension->id()));
1427 const Version old_version(old_version_string);
1429 VLOG(1) << "AddComponentExtension " << extension->name();
1430 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
1431 VLOG(1) << "Component extension " << extension->name() << " ("
1432 << extension->id() << ") installing/upgrading from '"
1433 << old_version_string << "' to " << extension->version()->GetString();
1435 AddNewOrUpdatedExtension(extension,
1436 Extension::ENABLED,
1437 extensions::kInstallFlagNone,
1438 syncer::StringOrdinal(),
1439 std::string());
1440 return;
1443 AddExtension(extension);
1446 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
1447 bool is_extension_installed) {
1448 extensions::PermissionsUpdater(profile_).InitializePermissions(extension);
1450 // We keep track of all permissions the user has granted each extension.
1451 // This allows extensions to gracefully support backwards compatibility
1452 // by including unknown permissions in their manifests. When the user
1453 // installs the extension, only the recognized permissions are recorded.
1454 // When the unknown permissions become recognized (e.g., through browser
1455 // upgrade), we can prompt the user to accept these new permissions.
1456 // Extensions can also silently upgrade to less permissions, and then
1457 // silently upgrade to a version that adds these permissions back.
1459 // For example, pretend that Chrome 10 includes a permission "omnibox"
1460 // for an API that adds suggestions to the omnibox. An extension can
1461 // maintain backwards compatibility while still having "omnibox" in the
1462 // manifest. If a user installs the extension on Chrome 9, the browser
1463 // will record the permissions it recognized, not including "omnibox."
1464 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
1465 // will disable the extension and prompt the user to approve the increase
1466 // in privileges. The extension could then release a new version that
1467 // removes the "omnibox" permission. When the user upgrades, Chrome will
1468 // still remember that "omnibox" had been granted, so that if the
1469 // extension once again includes "omnibox" in an upgrade, the extension
1470 // can upgrade without requiring this user's approval.
1471 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
1473 bool auto_grant_permission =
1474 (!is_extension_installed && extension->was_installed_by_default()) ||
1475 extensions::ExtensionsBrowserClient::Get()->IsRunningInForcedAppMode();
1476 // Silently grant all active permissions to default apps only on install.
1477 // After install they should behave like other apps.
1478 // Silently grant all active permissions to apps install in kiosk mode on both
1479 // install and update.
1480 if (auto_grant_permission)
1481 GrantPermissions(extension);
1483 bool is_privilege_increase = false;
1484 // We only need to compare the granted permissions to the current permissions
1485 // if the extension is not allowed to silently increase its permissions.
1486 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) &&
1487 !auto_grant_permission) {
1488 // Add all the recognized permissions if the granted permissions list
1489 // hasn't been initialized yet.
1490 scoped_refptr<PermissionSet> granted_permissions =
1491 extension_prefs_->GetGrantedPermissions(extension->id());
1492 CHECK(granted_permissions.get());
1494 // Here, we check if an extension's privileges have increased in a manner
1495 // that requires the user's approval. This could occur because the browser
1496 // upgraded and recognized additional privileges, or an extension upgrades
1497 // to a version that requires additional privileges.
1498 is_privilege_increase =
1499 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease(
1500 granted_permissions.get(),
1501 extension->permissions_data()->active_permissions().get(),
1502 extension->GetType());
1505 if (is_extension_installed) {
1506 // If the extension was already disabled, suppress any alerts for becoming
1507 // disabled on permissions increase.
1508 bool previously_disabled =
1509 extension_prefs_->IsExtensionDisabled(extension->id());
1510 // Legacy disabled extensions do not have a disable reason. Infer that if
1511 // there was no permission increase, it was likely disabled by the user.
1512 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
1513 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1514 disable_reasons |= Extension::DISABLE_USER_ACTION;
1516 // Extensions that came to us disabled from sync need a similar inference,
1517 // except based on the new version's permissions.
1518 if (previously_disabled &&
1519 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
1520 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
1521 extension_prefs_->ClearDisableReasons(extension->id());
1522 if (!is_privilege_increase)
1523 disable_reasons |= Extension::DISABLE_USER_ACTION;
1525 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
1528 // Extension has changed permissions significantly. Disable it. A
1529 // notification should be sent by the caller. If the extension is already
1530 // disabled because it was installed remotely, don't add another disable
1531 // reason, but instead always set the "did escalate permissions" flag, to
1532 // ensure enabling it will always show a warning.
1533 if (disable_reasons == Extension::DISABLE_REMOTE_INSTALL) {
1534 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1535 } else if (is_privilege_increase) {
1536 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
1537 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
1538 RecordPermissionMessagesHistogram(extension,
1539 "Extensions.Permissions_AutoDisable2");
1541 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
1542 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
1544 if (disable_reasons != Extension::DISABLE_NONE) {
1545 extension_prefs_->AddDisableReason(
1546 extension->id(),
1547 static_cast<Extension::DisableReason>(disable_reasons));
1551 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
1552 std::set<std::string> extension_ids;
1553 const ExtensionSet& extensions = registry_->enabled_extensions();
1554 for (ExtensionSet::const_iterator iter = extensions.begin();
1555 iter != extensions.end(); ++iter) {
1556 const Extension* extension = iter->get();
1557 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
1558 extension_ids.insert(extension->id());
1561 // TODO(kalman): This is broken. ExtensionService is per-profile.
1562 // crash_keys::SetActiveExtensions is per-process. See
1563 // http://crbug.com/355029.
1564 crash_keys::SetActiveExtensions(extension_ids);
1567 void ExtensionService::OnExtensionInstalled(
1568 const Extension* extension,
1569 const syncer::StringOrdinal& page_ordinal,
1570 int install_flags) {
1571 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1573 const std::string& id = extension->id();
1574 bool initial_enable = ShouldEnableOnInstall(extension);
1575 std::string install_parameter;
1576 const extensions::PendingExtensionInfo* pending_extension_info =
1577 pending_extension_manager()->GetById(id);
1578 if (pending_extension_info) {
1579 if (!pending_extension_info->ShouldAllowInstall(extension)) {
1580 pending_extension_manager()->Remove(id);
1582 LOG(WARNING) << "ShouldAllowInstall() returned false for "
1583 << id << " of type " << extension->GetType()
1584 << " and update URL "
1585 << extensions::ManifestURL::GetUpdateURL(extension).spec()
1586 << "; not installing";
1588 // Delete the extension directory since we're not going to
1589 // load it.
1590 if (!GetFileTaskRunner()->PostTask(
1591 FROM_HERE,
1592 base::Bind(&extensions::file_util::DeleteFile,
1593 extension->path(),
1594 true))) {
1595 NOTREACHED();
1597 return;
1600 install_parameter = pending_extension_info->install_parameter();
1601 pending_extension_manager()->Remove(id);
1602 } else {
1603 // We explicitly want to re-enable an uninstalled external
1604 // extension; if we're here, that means the user is manually
1605 // installing the extension.
1606 if (extension_prefs_->IsExternalExtensionUninstalled(id)) {
1607 initial_enable = true;
1611 // Unsupported requirements overrides the management policy.
1612 if (install_flags & extensions::kInstallFlagHasRequirementErrors) {
1613 initial_enable = false;
1614 extension_prefs_->AddDisableReason(
1615 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
1616 // If the extension was disabled because of unsupported requirements but
1617 // now supports all requirements after an update and there are not other
1618 // disable reasons, enable it.
1619 } else if (extension_prefs_->GetDisableReasons(id) ==
1620 Extension::DISABLE_UNSUPPORTED_REQUIREMENT) {
1621 initial_enable = true;
1622 extension_prefs_->ClearDisableReasons(id);
1625 if (install_flags & extensions::kInstallFlagIsBlacklistedForMalware) {
1626 // Installation of a blacklisted extension can happen from sync, policy,
1627 // etc, where to maintain consistency we need to install it, just never
1628 // load it (see AddExtension). Usually it should be the job of callers to
1629 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even
1630 // showing the install dialogue).
1631 extension_prefs_->AcknowledgeBlacklistedExtension(id);
1632 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall",
1633 extension->location(),
1634 Manifest::NUM_LOCATIONS);
1637 if (!GetInstalledExtension(extension->id())) {
1638 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
1639 extension->GetType(), 100);
1640 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
1641 extension->location(), Manifest::NUM_LOCATIONS);
1642 RecordPermissionMessagesHistogram(extension,
1643 "Extensions.Permissions_Install2");
1644 } else {
1645 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
1646 extension->GetType(), 100);
1647 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
1648 extension->location(), Manifest::NUM_LOCATIONS);
1650 // A fully installed app cannot be demoted to an ephemeral app.
1651 if ((install_flags & extensions::kInstallFlagIsEphemeral) &&
1652 !extension_prefs_->IsEphemeralApp(id)) {
1653 install_flags &= ~static_cast<int>(extensions::kInstallFlagIsEphemeral);
1657 const Extension::State initial_state =
1658 initial_enable ? Extension::ENABLED : Extension::DISABLED;
1659 if (ShouldDelayExtensionUpdate(
1661 !!(install_flags & extensions::kInstallFlagInstallImmediately))) {
1662 extension_prefs_->SetDelayedInstallInfo(
1663 extension,
1664 initial_state,
1665 install_flags,
1666 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE,
1667 page_ordinal,
1668 install_parameter);
1670 // Transfer ownership of |extension|.
1671 delayed_installs_.Insert(extension);
1673 // Notify observers that app update is available.
1674 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
1675 OnAppUpdateAvailable(extension));
1676 return;
1679 extensions::SharedModuleService::ImportStatus status =
1680 shared_module_service_->SatisfyImports(extension);
1681 if (installs_delayed_for_gc_) {
1682 extension_prefs_->SetDelayedInstallInfo(
1683 extension,
1684 initial_state,
1685 install_flags,
1686 extensions::ExtensionPrefs::DELAY_REASON_GC,
1687 page_ordinal,
1688 install_parameter);
1689 delayed_installs_.Insert(extension);
1690 } else if (status != SharedModuleService::IMPORT_STATUS_OK) {
1691 if (status == SharedModuleService::IMPORT_STATUS_UNSATISFIED) {
1692 extension_prefs_->SetDelayedInstallInfo(
1693 extension,
1694 initial_state,
1695 install_flags,
1696 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1697 page_ordinal,
1698 install_parameter);
1699 delayed_installs_.Insert(extension);
1701 } else {
1702 AddNewOrUpdatedExtension(extension,
1703 initial_state,
1704 install_flags,
1705 page_ordinal,
1706 install_parameter);
1710 void ExtensionService::OnExtensionManagementSettingsChanged() {
1711 error_controller_->ShowErrorIfNeeded();
1712 CheckManagementPolicy();
1715 void ExtensionService::AddNewOrUpdatedExtension(
1716 const Extension* extension,
1717 Extension::State initial_state,
1718 int install_flags,
1719 const syncer::StringOrdinal& page_ordinal,
1720 const std::string& install_parameter) {
1721 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1722 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1723 extension_prefs_->OnExtensionInstalled(
1724 extension, initial_state, page_ordinal, install_flags, install_parameter);
1725 delayed_installs_.Remove(extension->id());
1726 if (InstallVerifier::NeedsVerification(*extension))
1727 system_->install_verifier()->VerifyExtension(extension->id());
1728 FinishInstallation(extension, was_ephemeral);
1731 void ExtensionService::MaybeFinishDelayedInstallation(
1732 const std::string& extension_id) {
1733 // Check if the extension already got installed.
1734 if (!delayed_installs_.Contains(extension_id))
1735 return;
1736 extensions::ExtensionPrefs::DelayReason reason =
1737 extension_prefs_->GetDelayedInstallReason(extension_id);
1739 // Check if the extension is idle. DELAY_REASON_NONE is used for older
1740 // preferences files that will not have set this field but it was previously
1741 // only used for idle updates.
1742 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE ||
1743 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) &&
1744 is_ready() && !extensions::util::IsExtensionIdle(extension_id, profile_))
1745 return;
1747 const Extension* extension = delayed_installs_.GetByID(extension_id);
1748 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) {
1749 extensions::SharedModuleService::ImportStatus status =
1750 shared_module_service_->SatisfyImports(extension);
1751 if (status != SharedModuleService::IMPORT_STATUS_OK) {
1752 if (status == SharedModuleService::IMPORT_STATUS_UNRECOVERABLE) {
1753 delayed_installs_.Remove(extension_id);
1754 // Make sure no version of the extension is actually installed, (i.e.,
1755 // that this delayed install was not an update).
1756 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get());
1757 extension_prefs_->DeleteExtensionPrefs(extension_id);
1759 return;
1763 FinishDelayedInstallation(extension_id);
1766 void ExtensionService::FinishDelayedInstallation(
1767 const std::string& extension_id) {
1768 scoped_refptr<const Extension> extension(
1769 GetPendingExtensionUpdate(extension_id));
1770 CHECK(extension.get());
1771 delayed_installs_.Remove(extension_id);
1773 bool was_ephemeral = extension_prefs_->IsEphemeralApp(extension->id());
1774 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
1775 NOTREACHED();
1777 FinishInstallation(extension.get(), was_ephemeral);
1780 void ExtensionService::FinishInstallation(
1781 const Extension* extension, bool was_ephemeral) {
1782 const extensions::Extension* existing_extension =
1783 GetInstalledExtension(extension->id());
1784 bool is_update = false;
1785 std::string old_name;
1786 if (existing_extension) {
1787 is_update = true;
1788 old_name = existing_extension->name();
1790 bool from_ephemeral =
1791 was_ephemeral && !extension_prefs_->IsEphemeralApp(extension->id());
1792 extensions::InstalledExtensionInfo details(
1793 extension, is_update, from_ephemeral, old_name);
1794 content::NotificationService::current()->Notify(
1795 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1796 content::Source<Profile>(profile_),
1797 content::Details<const extensions::InstalledExtensionInfo>(&details));
1799 registry_->TriggerOnWillBeInstalled(
1800 extension, is_update, from_ephemeral, old_name);
1802 // Unpacked extensions default to allowing file access, but if that has been
1803 // overridden, don't reset the value.
1804 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
1805 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
1806 extension_prefs_->SetAllowFileAccess(extension->id(), true);
1809 AddExtension(extension);
1811 // Notify observers that need to know when an installation is complete.
1812 registry_->TriggerOnInstalled(extension, is_update);
1814 // Check extensions that may have been delayed only because this shared module
1815 // was not available.
1816 if (SharedModuleInfo::IsSharedModule(extension))
1817 MaybeFinishDelayedInstallations();
1820 void ExtensionService::PromoteEphemeralApp(
1821 const extensions::Extension* extension, bool is_from_sync) {
1822 DCHECK(GetInstalledExtension(extension->id()) &&
1823 extension_prefs_->IsEphemeralApp(extension->id()));
1825 if (extension->RequiresSortOrdinal()) {
1826 extension_prefs_->app_sorting()->SetExtensionVisible(
1827 extension->id(), extension->ShouldDisplayInNewTabPage());
1829 if (!is_from_sync) {
1830 // Reset the sort ordinals of the app to ensure it is added to the default
1831 // position, like newly installed apps would.
1832 extension_prefs_->app_sorting()->ClearOrdinals(extension->id());
1835 extension_prefs_->app_sorting()->EnsureValidOrdinals(
1836 extension->id(), syncer::StringOrdinal());
1839 // Remove the ephemeral flags from the preferences.
1840 extension_prefs_->OnEphemeralAppPromoted(extension->id());
1842 // Fire install-related events to allow observers to handle the promotion
1843 // of the ephemeral app.
1844 extensions::InstalledExtensionInfo details(
1845 extension,
1846 true /* is update */,
1847 true /* from ephemeral */,
1848 extension->name() /* old name */);
1849 content::NotificationService::current()->Notify(
1850 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1851 content::Source<Profile>(profile_),
1852 content::Details<const extensions::InstalledExtensionInfo>(&details));
1854 registry_->TriggerOnWillBeInstalled(
1855 extension,
1856 true /* is update */,
1857 true /* from ephemeral */,
1858 extension->name() /* old name */);
1860 if (registry_->enabled_extensions().Contains(extension->id())) {
1861 // If the app is already enabled and loaded, fire the load events to allow
1862 // observers to handle the promotion of the ephemeral app.
1863 content::NotificationService::current()->Notify(
1864 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1865 content::Source<Profile>(profile_),
1866 content::Details<const Extension>(extension));
1868 registry_->TriggerOnLoaded(extension);
1869 } else {
1870 // Cached ephemeral apps may be updated and disabled due to permissions
1871 // increase. The app can be enabled (as long as no other disable reasons
1872 // exist) as the install was user-acknowledged.
1873 int disable_mask = Extension::DISABLE_NONE;
1874 if (!is_from_sync)
1875 disable_mask |= Extension::DISABLE_PERMISSIONS_INCREASE;
1877 int other_disable_reasons =
1878 extension_prefs_->GetDisableReasons(extension->id()) & ~disable_mask;
1879 if (!other_disable_reasons) {
1880 if (extension_prefs_->DidExtensionEscalatePermissions(extension->id()))
1881 GrantPermissionsAndEnableExtension(extension);
1882 else
1883 EnableExtension(extension->id());
1887 registry_->TriggerOnInstalled(extension, true);
1889 if (!is_from_sync && extension_sync_service_)
1890 extension_sync_service_->SyncExtensionChangeIfNeeded(*extension);
1893 const Extension* ExtensionService::GetPendingExtensionUpdate(
1894 const std::string& id) const {
1895 return delayed_installs_.GetByID(id);
1898 void ExtensionService::RegisterContentSettings(
1899 HostContentSettingsMap* host_content_settings_map) {
1900 host_content_settings_map->RegisterProvider(
1901 HostContentSettingsMap::INTERNAL_EXTENSION_PROVIDER,
1902 scoped_ptr<content_settings::ObservableProvider>(
1903 new content_settings::InternalExtensionProvider(this)));
1905 host_content_settings_map->RegisterProvider(
1906 HostContentSettingsMap::CUSTOM_EXTENSION_PROVIDER,
1907 scoped_ptr<content_settings::ObservableProvider>(
1908 new content_settings::CustomExtensionProvider(
1909 extensions::ContentSettingsService::Get(
1910 profile_)->content_settings_store(),
1911 profile_->GetOriginalProfile() != profile_)));
1914 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
1915 // No need to check for duplicates; inserting a duplicate is a no-op.
1916 registry_->AddTerminated(make_scoped_refptr(extension));
1917 extensions_being_terminated_.erase(extension->id());
1918 UnloadExtension(extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
1921 void ExtensionService::TerminateExtension(const std::string& extension_id) {
1922 const Extension* extension = GetInstalledExtension(extension_id);
1923 TrackTerminatedExtension(extension);
1926 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
1927 std::string lowercase_id = base::StringToLowerASCII(id);
1928 const Extension* extension =
1929 registry_->terminated_extensions().GetByID(lowercase_id);
1930 registry_->RemoveTerminated(lowercase_id);
1931 if (extension) {
1932 content::NotificationService::current()->Notify(
1933 extensions::NOTIFICATION_EXTENSION_REMOVED,
1934 content::Source<Profile>(profile_),
1935 content::Details<const Extension>(extension));
1939 const Extension* ExtensionService::GetInstalledExtension(
1940 const std::string& id) const {
1941 return registry_->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
1944 bool ExtensionService::OnExternalExtensionFileFound(
1945 const std::string& id,
1946 const Version* version,
1947 const base::FilePath& path,
1948 Manifest::Location location,
1949 int creation_flags,
1950 bool mark_acknowledged) {
1951 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1952 CHECK(crx_file::id_util::IdIsValid(id));
1953 if (extension_prefs_->IsExternalExtensionUninstalled(id))
1954 return false;
1956 // Before even bothering to unpack, check and see if we already have this
1957 // version. This is important because these extensions are going to get
1958 // installed on every startup.
1959 const Extension* existing = GetExtensionById(id, true);
1961 if (existing) {
1962 // The default apps will have the location set as INTERNAL. Since older
1963 // default apps are installed as EXTERNAL, we override them. However, if the
1964 // app is already installed as internal, then do the version check.
1965 // TODO(grv) : Remove after Q1-2013.
1966 bool is_default_apps_migration =
1967 (location == Manifest::INTERNAL &&
1968 Manifest::IsExternalLocation(existing->location()));
1970 if (!is_default_apps_migration) {
1971 DCHECK(version);
1973 switch (existing->version()->CompareTo(*version)) {
1974 case -1: // existing version is older, we should upgrade
1975 break;
1976 case 0: // existing version is same, do nothing
1977 return false;
1978 case 1: // existing version is newer, uh-oh
1979 LOG(WARNING) << "Found external version of extension " << id
1980 << "that is older than current version. Current version "
1981 << "is: " << existing->VersionString() << ". New "
1982 << "version is: " << version->GetString()
1983 << ". Keeping current version.";
1984 return false;
1989 // If the extension is already pending, don't start an install.
1990 if (!pending_extension_manager()->AddFromExternalFile(
1991 id, location, *version, creation_flags, mark_acknowledged)) {
1992 return false;
1995 // no client (silent install)
1996 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this));
1997 installer->set_install_source(location);
1998 installer->set_expected_id(id);
1999 installer->set_expected_version(*version);
2000 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2001 installer->set_creation_flags(creation_flags);
2002 #if defined(OS_CHROMEOS)
2003 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2004 #else
2005 installer->InstallCrx(path);
2006 #endif
2008 // Depending on the source, a new external extension might not need a user
2009 // notification on installation. For such extensions, mark them acknowledged
2010 // now to suppress the notification.
2011 if (mark_acknowledged)
2012 external_install_manager_->AcknowledgeExternalExtension(id);
2014 return true;
2017 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2018 extensions::ExtensionHost* host) {
2019 OrphanedDevTools::iterator iter =
2020 orphaned_dev_tools_.find(host->extension_id());
2021 if (iter == orphaned_dev_tools_.end())
2022 return;
2024 iter->second->ConnectWebContents(host->host_contents());
2025 orphaned_dev_tools_.erase(iter);
2028 void ExtensionService::Observe(int type,
2029 const content::NotificationSource& source,
2030 const content::NotificationDetails& details) {
2031 switch (type) {
2032 case chrome::NOTIFICATION_APP_TERMINATING:
2033 // Shutdown has started. Don't start any more extension installs.
2034 // (We cannot use ExtensionService::Shutdown() for this because it
2035 // happens too late in browser teardown.)
2036 browser_terminating_ = true;
2037 break;
2038 case extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2039 if (profile_ !=
2040 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2041 break;
2044 extensions::ExtensionHost* host =
2045 content::Details<extensions::ExtensionHost>(details).ptr();
2047 // If the extension is already being terminated, there is nothing left to
2048 // do.
2049 if (!extensions_being_terminated_.insert(host->extension_id()).second)
2050 break;
2052 // Mark the extension as terminated and Unload it. We want it to
2053 // be in a consistent state: either fully working or not loaded
2054 // at all, but never half-crashed. We do it in a PostTask so
2055 // that other handlers of this notification will still have
2056 // access to the Extension and ExtensionHost.
2057 base::MessageLoop::current()->PostTask(
2058 FROM_HERE,
2059 base::Bind(
2060 &ExtensionService::TrackTerminatedExtension,
2061 AsWeakPtr(),
2062 host->extension()));
2063 break;
2065 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2066 content::RenderProcessHost* process =
2067 content::Source<content::RenderProcessHost>(source).ptr();
2068 Profile* host_profile =
2069 Profile::FromBrowserContext(process->GetBrowserContext());
2070 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2071 break;
2073 extensions::ProcessMap* process_map =
2074 extensions::ProcessMap::Get(profile_);
2075 if (process_map->Contains(process->GetID())) {
2076 // An extension process was terminated, this might have resulted in an
2077 // app or extension becoming idle.
2078 std::set<std::string> extension_ids =
2079 process_map->GetExtensionsInProcess(process->GetID());
2080 // In addition to the extensions listed in the process map, one of those
2081 // extensions could be referencing a shared module which is waiting for
2082 // idle to update. Check all imports of these extensions, too.
2083 std::set<std::string> import_ids;
2084 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2085 it != extension_ids.end();
2086 ++it) {
2087 const Extension* extension = GetExtensionById(*it, true);
2088 if (!extension)
2089 continue;
2090 const std::vector<SharedModuleInfo::ImportInfo>& imports =
2091 SharedModuleInfo::GetImports(extension);
2092 std::vector<SharedModuleInfo::ImportInfo>::const_iterator import_it;
2093 for (import_it = imports.begin(); import_it != imports.end();
2094 import_it++) {
2095 import_ids.insert((*import_it).extension_id);
2098 extension_ids.insert(import_ids.begin(), import_ids.end());
2100 for (std::set<std::string>::const_iterator it = extension_ids.begin();
2101 it != extension_ids.end(); ++it) {
2102 if (delayed_installs_.Contains(*it)) {
2103 base::MessageLoop::current()->PostDelayedTask(
2104 FROM_HERE,
2105 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2106 AsWeakPtr(), *it),
2107 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2112 process_map->RemoveAllFromProcess(process->GetID());
2113 BrowserThread::PostTask(
2114 BrowserThread::IO,
2115 FROM_HERE,
2116 base::Bind(&extensions::InfoMap::UnregisterAllExtensionsInProcess,
2117 system_->info_map(),
2118 process->GetID()));
2119 break;
2121 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2122 // Notify observers that chrome update is available.
2123 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2124 OnChromeUpdateAvailable());
2125 break;
2127 case chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED: {
2128 OnProfileDestructionStarted();
2129 break;
2132 default:
2133 NOTREACHED() << "Unexpected notification type.";
2137 bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) {
2138 // Extensions installed by policy can't be disabled. So even if a previous
2139 // installation disabled the extension, make sure it is now enabled.
2140 if (system_->management_policy()->MustRemainEnabled(extension, NULL))
2141 return true;
2143 if (extension_prefs_->IsExtensionDisabled(extension->id()))
2144 return false;
2146 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2147 // External extensions are initially disabled. We prompt the user before
2148 // enabling them. Hosted apps are excepted because they are not dangerous
2149 // (they need to be launched by the user anyway).
2150 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2151 Manifest::IsExternalLocation(extension->location()) &&
2152 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2153 return false;
2157 return true;
2160 bool ExtensionService::ShouldDelayExtensionUpdate(
2161 const std::string& extension_id,
2162 bool install_immediately) const {
2163 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2165 // If delayed updates are globally disabled, or just for this extension,
2166 // don't delay.
2167 if (!install_updates_when_idle_ || install_immediately)
2168 return false;
2170 const Extension* old = GetInstalledExtension(extension_id);
2171 // If there is no old extension, this is not an update, so don't delay.
2172 if (!old)
2173 return false;
2175 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2176 // Delay installation if the extension listens for the onUpdateAvailable
2177 // event.
2178 return system_->event_router()->ExtensionHasEventListener(
2179 extension_id, kOnUpdateAvailableEvent);
2180 } else {
2181 // Delay installation if the extension is not idle.
2182 return !extensions::util::IsExtensionIdle(extension_id, profile_);
2186 void ExtensionService::OnGarbageCollectIsolatedStorageStart() {
2187 DCHECK(!installs_delayed_for_gc_);
2188 installs_delayed_for_gc_ = true;
2191 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2192 DCHECK(installs_delayed_for_gc_);
2193 installs_delayed_for_gc_ = false;
2194 MaybeFinishDelayedInstallations();
2197 void ExtensionService::MaybeFinishDelayedInstallations() {
2198 std::vector<std::string> to_be_installed;
2199 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2200 it != delayed_installs_.end();
2201 ++it) {
2202 to_be_installed.push_back((*it)->id());
2204 for (std::vector<std::string>::const_iterator it = to_be_installed.begin();
2205 it != to_be_installed.end();
2206 ++it) {
2207 MaybeFinishDelayedInstallation(*it);
2211 void ExtensionService::OnBlacklistUpdated() {
2212 blacklist_->GetBlacklistedIDs(
2213 registry_->GenerateInstalledExtensionsSet()->GetIDs(),
2214 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr()));
2217 void ExtensionService::ManageBlacklist(
2218 const extensions::Blacklist::BlacklistStateMap& state_map) {
2219 DCHECK_CURRENTLY_ON(BrowserThread::UI);
2221 std::set<std::string> blocked;
2222 ExtensionIdSet greylist;
2223 ExtensionIdSet unchanged;
2224 for (extensions::Blacklist::BlacklistStateMap::const_iterator it =
2225 state_map.begin();
2226 it != state_map.end();
2227 ++it) {
2228 switch (it->second) {
2229 case extensions::NOT_BLACKLISTED:
2230 break;
2232 case extensions::BLACKLISTED_MALWARE:
2233 blocked.insert(it->first);
2234 break;
2236 case extensions::BLACKLISTED_SECURITY_VULNERABILITY:
2237 case extensions::BLACKLISTED_CWS_POLICY_VIOLATION:
2238 case extensions::BLACKLISTED_POTENTIALLY_UNWANTED:
2239 greylist.insert(it->first);
2240 break;
2242 case extensions::BLACKLISTED_UNKNOWN:
2243 unchanged.insert(it->first);
2244 break;
2248 UpdateBlockedExtensions(blocked, unchanged);
2249 UpdateGreylistedExtensions(greylist, unchanged, state_map);
2251 error_controller_->ShowErrorIfNeeded();
2254 namespace {
2255 void Partition(const ExtensionIdSet& before,
2256 const ExtensionIdSet& after,
2257 const ExtensionIdSet& unchanged,
2258 ExtensionIdSet* no_longer,
2259 ExtensionIdSet* not_yet) {
2260 *not_yet = base::STLSetDifference<ExtensionIdSet>(after, before);
2261 *no_longer = base::STLSetDifference<ExtensionIdSet>(before, after);
2262 *no_longer = base::STLSetDifference<ExtensionIdSet>(*no_longer, unchanged);
2264 } // namespace
2266 void ExtensionService::UpdateBlockedExtensions(
2267 const ExtensionIdSet& blocked,
2268 const ExtensionIdSet& unchanged) {
2269 ExtensionIdSet not_yet_blocked, no_longer_blocked;
2270 Partition(registry_->blacklisted_extensions().GetIDs(),
2271 blocked, unchanged,
2272 &no_longer_blocked, &not_yet_blocked);
2274 for (ExtensionIdSet::iterator it = no_longer_blocked.begin();
2275 it != no_longer_blocked.end(); ++it) {
2276 scoped_refptr<const Extension> extension =
2277 registry_->blacklisted_extensions().GetByID(*it);
2278 if (!extension.get()) {
2279 NOTREACHED() << "Extension " << *it << " no longer blocked, "
2280 << "but it was never blocked.";
2281 continue;
2283 registry_->RemoveBlacklisted(*it);
2284 extension_prefs_->SetExtensionBlacklisted(extension->id(), false);
2285 AddExtension(extension.get());
2286 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2287 extension->location(),
2288 Manifest::NUM_LOCATIONS);
2291 for (ExtensionIdSet::iterator it = not_yet_blocked.begin();
2292 it != not_yet_blocked.end(); ++it) {
2293 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2294 if (!extension.get()) {
2295 NOTREACHED() << "Extension " << *it << " needs to be "
2296 << "blacklisted, but it's not installed.";
2297 continue;
2299 registry_->AddBlacklisted(extension);
2300 extension_prefs_->SetExtensionBlacklistState(
2301 extension->id(), extensions::BLACKLISTED_MALWARE);
2302 UnloadExtension(*it, UnloadedExtensionInfo::REASON_BLACKLIST);
2303 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2304 extension->location(), Manifest::NUM_LOCATIONS);
2308 // TODO(oleg): UMA logging
2309 void ExtensionService::UpdateGreylistedExtensions(
2310 const ExtensionIdSet& greylist,
2311 const ExtensionIdSet& unchanged,
2312 const extensions::Blacklist::BlacklistStateMap& state_map) {
2313 ExtensionIdSet not_yet_greylisted, no_longer_greylisted;
2314 Partition(greylist_.GetIDs(),
2315 greylist, unchanged,
2316 &no_longer_greylisted, &not_yet_greylisted);
2318 for (ExtensionIdSet::iterator it = no_longer_greylisted.begin();
2319 it != no_longer_greylisted.end(); ++it) {
2320 scoped_refptr<const Extension> extension = greylist_.GetByID(*it);
2321 if (!extension.get()) {
2322 NOTREACHED() << "Extension " << *it << " no longer greylisted, "
2323 << "but it was not marked as greylisted.";
2324 continue;
2327 greylist_.Remove(*it);
2328 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2329 extensions::NOT_BLACKLISTED);
2330 if (extension_prefs_->GetDisableReasons(extension->id()) &
2331 extensions::Extension::DISABLE_GREYLIST)
2332 EnableExtension(*it);
2335 for (ExtensionIdSet::iterator it = not_yet_greylisted.begin();
2336 it != not_yet_greylisted.end(); ++it) {
2337 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2338 if (!extension.get()) {
2339 NOTREACHED() << "Extension " << *it << " needs to be "
2340 << "disabled, but it's not installed.";
2341 continue;
2343 greylist_.Insert(extension);
2344 extension_prefs_->SetExtensionBlacklistState(extension->id(),
2345 state_map.find(*it)->second);
2346 if (registry_->enabled_extensions().Contains(extension->id()))
2347 DisableExtension(*it, extensions::Extension::DISABLE_GREYLIST);
2351 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2352 update_observers_.AddObserver(observer);
2355 void ExtensionService::RemoveUpdateObserver(
2356 extensions::UpdateObserver* observer) {
2357 update_observers_.RemoveObserver(observer);
2360 // Used only by test code.
2361 void ExtensionService::UnloadAllExtensionsInternal() {
2362 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
2364 registry_->ClearAll();
2365 system_->runtime_data()->ClearAll();
2367 // TODO(erikkay) should there be a notification for this? We can't use
2368 // EXTENSION_UNLOADED since that implies that the extension has been disabled
2369 // or uninstalled.
2372 void ExtensionService::OnProfileDestructionStarted() {
2373 ExtensionIdSet ids_to_unload = registry_->enabled_extensions().GetIDs();
2374 for (ExtensionIdSet::iterator it = ids_to_unload.begin();
2375 it != ids_to_unload.end();
2376 ++it) {
2377 UnloadExtension(*it, UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN);