extension_service.cc revision 8bcbed890bc3ce4d7a057a8f32cab53fa534672e
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. 4 5#include "chrome/browser/extensions/extension_service.h" 6 7#include <algorithm> 8#include <iterator> 9#include <set> 10 11#include "base/basictypes.h" 12#include "base/bind.h" 13#include "base/callback.h" 14#include "base/command_line.h" 15#include "base/file_util.h" 16#include "base/logging.h" 17#include "base/metrics/histogram.h" 18#include "base/prefs/pref_service.h" 19#include "base/stl_util.h" 20#include "base/strings/string_number_conversions.h" 21#include "base/strings/string_util.h" 22#include "base/strings/stringprintf.h" 23#include "base/strings/utf_string_conversions.h" 24#include "base/threading/sequenced_worker_pool.h" 25#include "base/threading/thread_restrictions.h" 26#include "base/time/time.h" 27#include "base/values.h" 28#include "base/version.h" 29#include "chrome/browser/app_mode/app_mode_utils.h" 30#include "chrome/browser/browser_process.h" 31#include "chrome/browser/chrome_notification_types.h" 32#include "chrome/browser/extensions/api/app_runtime/app_runtime_api.h" 33#include "chrome/browser/extensions/api/declarative/rules_registry_service.h" 34#include "chrome/browser/extensions/api/extension_action/extension_action_api.h" 35#include "chrome/browser/extensions/api/profile_keyed_api_factory.h" 36#include "chrome/browser/extensions/api/runtime/runtime_api.h" 37#include "chrome/browser/extensions/api/storage/settings_frontend.h" 38#include "chrome/browser/extensions/app_sync_data.h" 39#include "chrome/browser/extensions/component_loader.h" 40#include "chrome/browser/extensions/crx_installer.h" 41#include "chrome/browser/extensions/data_deleter.h" 42#include "chrome/browser/extensions/event_router.h" 43#include "chrome/browser/extensions/extension_disabled_ui.h" 44#include "chrome/browser/extensions/extension_error_reporter.h" 45#include "chrome/browser/extensions/extension_error_ui.h" 46#include "chrome/browser/extensions/extension_host.h" 47#include "chrome/browser/extensions/extension_install_ui.h" 48#include "chrome/browser/extensions/extension_process_manager.h" 49#include "chrome/browser/extensions/extension_sorting.h" 50#include "chrome/browser/extensions/extension_special_storage_policy.h" 51#include "chrome/browser/extensions/extension_sync_data.h" 52#include "chrome/browser/extensions/extension_system.h" 53#include "chrome/browser/extensions/extension_util.h" 54#include "chrome/browser/extensions/external_install_ui.h" 55#include "chrome/browser/extensions/external_provider_impl.h" 56#include "chrome/browser/extensions/external_provider_interface.h" 57#include "chrome/browser/extensions/installed_loader.h" 58#include "chrome/browser/extensions/management_policy.h" 59#include "chrome/browser/extensions/pending_extension_manager.h" 60#include "chrome/browser/extensions/permissions_updater.h" 61#include "chrome/browser/extensions/unpacked_installer.h" 62#include "chrome/browser/extensions/update_observer.h" 63#include "chrome/browser/extensions/updater/extension_updater.h" 64#include "chrome/browser/profiles/profile.h" 65#include "chrome/browser/profiles/profile_manager.h" 66#include "chrome/browser/sync/sync_prefs.h" 67#include "chrome/browser/ui/webui/favicon_source.h" 68#include "chrome/browser/ui/webui/ntp/thumbnail_source.h" 69#include "chrome/browser/ui/webui/theme_source.h" 70#include "chrome/common/chrome_switches.h" 71#include "chrome/common/chrome_version_info.h" 72#include "chrome/common/crash_keys.h" 73#include "chrome/common/extensions/background_info.h" 74#include "chrome/common/extensions/extension.h" 75#include "chrome/common/extensions/extension_constants.h" 76#include "chrome/common/extensions/extension_file_util.h" 77#include "chrome/common/extensions/extension_messages.h" 78#include "chrome/common/extensions/feature_switch.h" 79#include "chrome/common/extensions/features/feature_channel.h" 80#include "chrome/common/extensions/incognito_handler.h" 81#include "chrome/common/extensions/manifest_handlers/app_isolation_info.h" 82#include "chrome/common/extensions/manifest_handlers/app_launch_info.h" 83#include "chrome/common/extensions/manifest_handlers/shared_module_info.h" 84#include "chrome/common/extensions/manifest_url_handler.h" 85#include "chrome/common/extensions/permissions/permissions_data.h" 86#include "chrome/common/extensions/sync_helper.h" 87#include "chrome/common/pref_names.h" 88#include "chrome/common/url_constants.h" 89#include "components/startup_metric_utils/startup_metric_utils.h" 90#include "content/public/browser/browser_thread.h" 91#include "content/public/browser/devtools_agent_host.h" 92#include "content/public/browser/notification_service.h" 93#include "content/public/browser/notification_types.h" 94#include "content/public/browser/render_process_host.h" 95#include "content/public/browser/site_instance.h" 96#include "content/public/browser/storage_partition.h" 97#include "content/public/browser/url_data_source.h" 98#include "extensions/common/constants.h" 99#include "extensions/common/error_utils.h" 100#include "extensions/common/manifest.h" 101#include "extensions/common/manifest_constants.h" 102#include "extensions/common/permissions/permission_message_provider.h" 103#include "grit/generated_resources.h" 104#include "net/base/registry_controlled_domains/registry_controlled_domain.h" 105#include "sync/api/sync_change.h" 106#include "sync/api/sync_error_factory.h" 107#include "ui/base/webui/web_ui_util.h" 108#include "url/gurl.h" 109#include "webkit/browser/database/database_tracker.h" 110#include "webkit/browser/database/database_util.h" 111 112#if defined(OS_CHROMEOS) 113#include "chrome/browser/chromeos/extensions/install_limiter.h" 114#include "webkit/browser/fileapi/file_system_backend.h" 115#include "webkit/browser/fileapi/file_system_context.h" 116#endif 117 118using content::BrowserContext; 119using content::BrowserThread; 120using content::DevToolsAgentHost; 121using extensions::CrxInstaller; 122using extensions::Extension; 123using extensions::ExtensionIdSet; 124using extensions::ExtensionInfo; 125using extensions::FeatureSwitch; 126using extensions::Manifest; 127using extensions::PermissionMessage; 128using extensions::PermissionMessages; 129using extensions::PermissionSet; 130using extensions::SharedModuleInfo; 131using extensions::UnloadedExtensionInfo; 132 133namespace errors = extensions::manifest_errors; 134 135namespace { 136 137// Histogram values for logging events related to externally installed 138// extensions. 139enum ExternalExtensionEvent { 140 EXTERNAL_EXTENSION_INSTALLED = 0, 141 EXTERNAL_EXTENSION_IGNORED, 142 EXTERNAL_EXTENSION_REENABLED, 143 EXTERNAL_EXTENSION_UNINSTALLED, 144 EXTERNAL_EXTENSION_BUCKET_BOUNDARY, 145}; 146 147// Prompt the user this many times before considering an extension acknowledged. 148static const int kMaxExtensionAcknowledgePromptCount = 3; 149 150// Wait this many seconds after an extensions becomes idle before updating it. 151static const int kUpdateIdleDelay = 5; 152 153// Wait this many seconds before trying to garbage collect extensions again. 154static const int kGarbageCollectRetryDelay = 30; 155 156// Wait this many seconds after startup to see if there are any extensions 157// which can be garbage collected. 158static const int kGarbageCollectStartupDelay = 30; 159 160static bool IsSharedModule(const Extension* extension) { 161 return SharedModuleInfo::IsSharedModule(extension); 162} 163 164static bool IsCWSSharedModule(const Extension* extension) { 165 return extension->from_webstore() && IsSharedModule(extension); 166} 167 168class SharedModuleProvider : public extensions::ManagementPolicy::Provider { 169 public: 170 SharedModuleProvider() {} 171 virtual ~SharedModuleProvider() {} 172 173 virtual std::string GetDebugPolicyProviderName() const OVERRIDE { 174 return "SharedModuleProvider"; 175 } 176 177 virtual bool UserMayModifySettings(const Extension* extension, 178 string16* error) const OVERRIDE { 179 return !IsCWSSharedModule(extension); 180 } 181 182 virtual bool MustRemainEnabled(const Extension* extension, 183 string16* error) const OVERRIDE { 184 return IsCWSSharedModule(extension); 185 } 186 187 private: 188 DISALLOW_COPY_AND_ASSIGN(SharedModuleProvider); 189}; 190 191 192} // namespace 193 194ExtensionService::ExtensionRuntimeData::ExtensionRuntimeData() 195 : background_page_ready(false), 196 being_upgraded(false), 197 has_used_webrequest(false) { 198} 199 200ExtensionService::ExtensionRuntimeData::~ExtensionRuntimeData() { 201} 202 203// ExtensionService. 204 205void ExtensionService::CheckExternalUninstall(const std::string& id) { 206 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 207 208 // Check if the providers know about this extension. 209 extensions::ProviderCollection::const_iterator i; 210 for (i = external_extension_providers_.begin(); 211 i != external_extension_providers_.end(); ++i) { 212 DCHECK(i->get()->IsReady()); 213 if (i->get()->HasExtension(id)) 214 return; // Yup, known extension, don't uninstall. 215 } 216 217 // We get the list of external extensions to check from preferences. 218 // It is possible that an extension has preferences but is not loaded. 219 // For example, an extension that requires experimental permissions 220 // will not be loaded if the experimental command line flag is not used. 221 // In this case, do not uninstall. 222 if (!GetInstalledExtension(id)) { 223 // We can't call UninstallExtension with an unloaded/invalid 224 // extension ID. 225 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension " 226 << "with id: " << id; 227 return; 228 } 229 UninstallExtension(id, true, NULL); 230} 231 232void ExtensionService::SetFileTaskRunnerForTesting( 233 base::SequencedTaskRunner* task_runner) { 234 file_task_runner_ = task_runner; 235} 236 237void ExtensionService::ClearProvidersForTesting() { 238 external_extension_providers_.clear(); 239} 240 241void ExtensionService::AddProviderForTesting( 242 extensions::ExternalProviderInterface* test_provider) { 243 CHECK(test_provider); 244 external_extension_providers_.push_back( 245 linked_ptr<extensions::ExternalProviderInterface>(test_provider)); 246} 247 248bool ExtensionService::OnExternalExtensionUpdateUrlFound( 249 const std::string& id, 250 const GURL& update_url, 251 Manifest::Location location, 252 int creation_flags, 253 bool mark_acknowledged) { 254 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 255 CHECK(Extension::IdIsValid(id)); 256 257 const Extension* extension = GetExtensionById(id, true); 258 if (extension) { 259 // Already installed. Skip this install if the current location has 260 // higher priority than |location|. 261 Manifest::Location current = extension->location(); 262 if (current == Manifest::GetHigherPriorityLocation(current, location)) 263 return false; 264 // Otherwise, overwrite the current installation. 265 } 266 267 // Add |id| to the set of pending extensions. If it can not be added, 268 // then there is already a pending record from a higher-priority install 269 // source. In this case, signal that this extension will not be 270 // installed by returning false. 271 if (!pending_extension_manager()->AddFromExternalUpdateUrl( 272 id, update_url, location, creation_flags, mark_acknowledged)) { 273 return false; 274 } 275 276 update_once_all_providers_are_ready_ = true; 277 return true; 278} 279 280const Extension* ExtensionService::GetInstalledApp(const GURL& url) const { 281 const Extension* extension = extensions_.GetExtensionOrAppByURL(url); 282 return (extension && extension->is_app()) ? extension : NULL; 283} 284 285bool ExtensionService::IsInstalledApp(const GURL& url) const { 286 return !!GetInstalledApp(url); 287} 288 289// static 290// This function is used to implement the command-line switch 291// --uninstall-extension, and to uninstall an extension via sync. The LOG 292// statements within this function are used to inform the user if the uninstall 293// cannot be done. 294bool ExtensionService::UninstallExtensionHelper( 295 ExtensionService* extensions_service, 296 const std::string& extension_id) { 297 // We can't call UninstallExtension with an invalid extension ID. 298 if (!extensions_service->GetInstalledExtension(extension_id)) { 299 LOG(WARNING) << "Attempted uninstallation of non-existent extension with " 300 << "id: " << extension_id; 301 return false; 302 } 303 304 // The following call to UninstallExtension will not allow an uninstall of a 305 // policy-controlled extension. 306 string16 error; 307 if (!extensions_service->UninstallExtension(extension_id, false, &error)) { 308 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id 309 << ": " << error; 310 return false; 311 } 312 313 return true; 314} 315 316ExtensionService::ExtensionService(Profile* profile, 317 const CommandLine* command_line, 318 const base::FilePath& install_directory, 319 extensions::ExtensionPrefs* extension_prefs, 320 extensions::Blacklist* blacklist, 321 bool autoupdate_enabled, 322 bool extensions_enabled, 323 extensions::OneShotEvent* ready) 324 : extensions::Blacklist::Observer(blacklist), 325 profile_(profile), 326 system_(extensions::ExtensionSystem::Get(profile)), 327 extension_prefs_(extension_prefs), 328 blacklist_(blacklist), 329 settings_frontend_(extensions::SettingsFrontend::Create(profile)), 330 pending_extension_manager_(*this), 331 install_directory_(install_directory), 332 extensions_enabled_(extensions_enabled), 333 show_extensions_prompts_(true), 334 install_updates_when_idle_(true), 335 ready_(ready), 336 toolbar_model_(this), 337 menu_manager_(profile), 338 update_once_all_providers_are_ready_(false), 339 browser_terminating_(false), 340 installs_delayed_for_gc_(false), 341 is_first_run_(false), 342 app_sync_bundle_(this), 343 extension_sync_bundle_(this), 344 pending_app_enables_( 345 make_scoped_ptr(new browser_sync::SyncPrefs( 346 extension_prefs_->pref_service())), 347 &app_sync_bundle_, 348 syncer::APPS), 349 pending_extension_enables_( 350 make_scoped_ptr(new browser_sync::SyncPrefs( 351 extension_prefs_->pref_service())), 352 &extension_sync_bundle_, 353 syncer::EXTENSIONS) { 354#if defined(OS_CHROMEOS) 355 disable_garbage_collection_ = false; 356#endif 357 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 358 359 // Figure out if extension installation should be enabled. 360 if (command_line->HasSwitch(switches::kDisableExtensions) || 361 profile->GetPrefs()->GetBoolean(prefs::kDisableExtensions)) { 362 extensions_enabled_ = false; 363 } 364 365 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, 366 content::NotificationService::AllBrowserContextsAndSources()); 367 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED, 368 content::NotificationService::AllBrowserContextsAndSources()); 369 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED, 370 content::NotificationService::AllBrowserContextsAndSources()); 371 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, 372 content::NotificationService::AllBrowserContextsAndSources()); 373 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED, 374 content::NotificationService::AllBrowserContextsAndSources()); 375 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED, 376 content::NotificationService::AllBrowserContextsAndSources()); 377 pref_change_registrar_.Init(profile->GetPrefs()); 378 base::Closure callback = 379 base::Bind(&ExtensionService::OnExtensionInstallPrefChanged, 380 base::Unretained(this)); 381 pref_change_registrar_.Add(prefs::kExtensionInstallAllowList, callback); 382 pref_change_registrar_.Add(prefs::kExtensionInstallDenyList, callback); 383 pref_change_registrar_.Add(prefs::kExtensionAllowedTypes, callback); 384 385 // Set up the ExtensionUpdater 386 if (autoupdate_enabled) { 387 int update_frequency = extensions::kDefaultUpdateFrequencySeconds; 388 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) { 389 base::StringToInt(command_line->GetSwitchValueASCII( 390 switches::kExtensionsUpdateFrequency), 391 &update_frequency); 392 } 393 updater_.reset(new extensions::ExtensionUpdater(this, 394 extension_prefs, 395 profile->GetPrefs(), 396 profile, 397 update_frequency)); 398 } 399 400 component_loader_.reset( 401 new extensions::ComponentLoader(this, 402 profile->GetPrefs(), 403 g_browser_process->local_state())); 404 405 if (extensions_enabled_) { 406 extensions::ExternalProviderImpl::CreateExternalProviders( 407 this, profile_, &external_extension_providers_); 408 } 409 410 // Set this as the ExtensionService for extension sorting to ensure it 411 // cause syncs if required. 412 extension_prefs_->extension_sorting()->SetExtensionService(this); 413 414 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun(); 415 416#if defined(ENABLE_EXTENSIONS) 417 extension_action_storage_manager_.reset( 418 new extensions::ExtensionActionStorageManager(profile_)); 419#endif 420 421 shared_module_policy_provider_.reset(new SharedModuleProvider); 422 423 // How long is the path to the Extensions directory? 424 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength", 425 install_directory_.value().length(), 0, 500, 100); 426} 427 428const ExtensionSet* ExtensionService::extensions() const { 429 return &extensions_; 430} 431 432const ExtensionSet* ExtensionService::disabled_extensions() const { 433 return &disabled_extensions_; 434} 435 436const ExtensionSet* ExtensionService::terminated_extensions() const { 437 return &terminated_extensions_; 438} 439 440const ExtensionSet* ExtensionService::blacklisted_extensions() const { 441 return &blacklisted_extensions_; 442} 443 444const ExtensionSet* ExtensionService::delayed_installs() const { 445 return &delayed_installs_; 446} 447 448scoped_ptr<const ExtensionSet> 449 ExtensionService::GenerateInstalledExtensionsSet() const { 450 scoped_ptr<ExtensionSet> installed_extensions(new ExtensionSet()); 451 installed_extensions->InsertAll(extensions_); 452 installed_extensions->InsertAll(disabled_extensions_); 453 installed_extensions->InsertAll(terminated_extensions_); 454 installed_extensions->InsertAll(blacklisted_extensions_); 455 return installed_extensions.PassAs<const ExtensionSet>(); 456} 457 458extensions::PendingExtensionManager* 459 ExtensionService::pending_extension_manager() { 460 return &pending_extension_manager_; 461} 462 463ExtensionService::~ExtensionService() { 464 // No need to unload extensions here because they are profile-scoped, and the 465 // profile is in the process of being deleted. 466 467 extensions::ProviderCollection::const_iterator i; 468 for (i = external_extension_providers_.begin(); 469 i != external_extension_providers_.end(); ++i) { 470 extensions::ExternalProviderInterface* provider = i->get(); 471 provider->ServiceShutdown(); 472 } 473} 474 475void ExtensionService::SetSyncStartFlare( 476 const syncer::SyncableService::StartSyncFlare& flare) { 477 flare_ = flare; 478} 479 480void ExtensionService::Shutdown() { 481 system_->management_policy()->UnregisterProvider( 482 shared_module_policy_provider_.get()); 483} 484 485const Extension* ExtensionService::GetExtensionById( 486 const std::string& id, bool include_disabled) const { 487 int include_mask = INCLUDE_ENABLED; 488 if (include_disabled) { 489 // Include blacklisted extensions here because there are hundreds of 490 // callers of this function, and many might assume that this includes those 491 // that have been disabled due to blacklisting. 492 include_mask |= INCLUDE_DISABLED | INCLUDE_BLACKLISTED; 493 } 494 return GetExtensionById(id, include_mask); 495} 496 497GURL ExtensionService::GetSiteForExtensionId(const std::string& extension_id) { 498 return content::SiteInstance::GetSiteForURL( 499 profile_, 500 Extension::GetBaseURLFromExtensionId(extension_id)); 501} 502 503const Extension* ExtensionService::GetExtensionById( 504 const std::string& id, int include_mask) const { 505 std::string lowercase_id = StringToLowerASCII(id); 506 if (include_mask & INCLUDE_ENABLED) { 507 const Extension* extension = extensions_.GetByID(lowercase_id); 508 if (extension) 509 return extension; 510 } 511 if (include_mask & INCLUDE_DISABLED) { 512 const Extension* extension = disabled_extensions_.GetByID(lowercase_id); 513 if (extension) 514 return extension; 515 } 516 if (include_mask & INCLUDE_TERMINATED) { 517 const Extension* extension = terminated_extensions_.GetByID(lowercase_id); 518 if (extension) 519 return extension; 520 } 521 if (include_mask & INCLUDE_BLACKLISTED) { 522 const Extension* extension = blacklisted_extensions_.GetByID(lowercase_id); 523 if (extension) 524 return extension; 525 } 526 return NULL; 527} 528 529void ExtensionService::Init() { 530 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 531 532 DCHECK(!is_ready()); // Can't redo init. 533 DCHECK_EQ(extensions_.size(), 0u); 534 535 const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); 536 if (cmd_line->HasSwitch(switches::kInstallFromWebstore) || 537 cmd_line->HasSwitch(switches::kLimitedInstallFromWebstore)) { 538 // The sole purpose of this launch is to install a new extension from CWS 539 // and immediately terminate: loading already installed extensions is 540 // unnecessary and may interfere with the inline install dialog (e.g. if an 541 // extension listens to onStartup and opens a window). 542 SetReadyAndNotifyListeners(); 543 } else { 544 // LoadAllExtensions() calls OnLoadedInstalledExtensions(). 545 component_loader_->LoadAll(); 546 extensions::InstalledLoader(this).LoadAllExtensions(); 547 548 ReconcileKnownDisabled(); 549 550 // Attempt to re-enable extensions whose only disable reason is reloading. 551 std::vector<std::string> extensions_to_enable; 552 for (ExtensionSet::const_iterator iter = disabled_extensions_.begin(); 553 iter != disabled_extensions_.end(); ++iter) { 554 const Extension* e = iter->get(); 555 if (extension_prefs_->GetDisableReasons(e->id()) == 556 Extension::DISABLE_RELOAD) { 557 extensions_to_enable.push_back(e->id()); 558 } 559 } 560 for (std::vector<std::string>::iterator it = extensions_to_enable.begin(); 561 it != extensions_to_enable.end(); ++it) { 562 EnableExtension(*it); 563 } 564 565 // Finish install (if possible) of extensions that were still delayed while 566 // the browser was shut down. 567 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info( 568 extension_prefs_->GetAllDelayedInstallInfo()); 569 for (size_t i = 0; i < delayed_info->size(); ++i) { 570 ExtensionInfo* info = delayed_info->at(i).get(); 571 scoped_refptr<const Extension> extension(NULL); 572 if (info->extension_manifest) { 573 std::string error; 574 extension = Extension::Create( 575 info->extension_path, 576 info->extension_location, 577 *info->extension_manifest, 578 extension_prefs_->GetDelayedInstallCreationFlags( 579 info->extension_id), 580 info->extension_id, 581 &error); 582 if (extension.get()) 583 delayed_installs_.Insert(extension); 584 } 585 } 586 MaybeFinishDelayedInstallations(); 587 588 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> delayed_info2( 589 extension_prefs_->GetAllDelayedInstallInfo()); 590 UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateOnLoad", 591 delayed_info2->size() - delayed_info->size()); 592 593 SetReadyAndNotifyListeners(); 594 595 // TODO(erikkay) this should probably be deferred to a future point 596 // rather than running immediately at startup. 597 CheckForExternalUpdates(); 598 599 base::MessageLoop::current()->PostDelayedTask( 600 FROM_HERE, 601 base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()), 602 base::TimeDelta::FromSeconds(kGarbageCollectStartupDelay)); 603 604 if (extension_prefs_->NeedsStorageGarbageCollection()) { 605 GarbageCollectIsolatedStorage(); 606 extension_prefs_->SetNeedsStorageGarbageCollection(false); 607 } 608 system_->management_policy()->RegisterProvider( 609 shared_module_policy_provider_.get()); 610 } 611} 612 613bool ExtensionService::UpdateExtension(const std::string& id, 614 const base::FilePath& extension_path, 615 const GURL& download_url, 616 CrxInstaller** out_crx_installer) { 617 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 618 if (browser_terminating_) { 619 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown"; 620 // Leak the temp file at extension_path. We don't want to add to the disk 621 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and 622 // the file is in the OS temp directory which should be cleaned up for us. 623 return false; 624 } 625 626 const extensions::PendingExtensionInfo* pending_extension_info = 627 pending_extension_manager()->GetById(id); 628 629 const Extension* extension = GetInstalledExtension(id); 630 if (!pending_extension_info && !extension) { 631 LOG(WARNING) << "Will not update extension " << id 632 << " because it is not installed or pending"; 633 // Delete extension_path since we're not creating a CrxInstaller 634 // that would do it for us. 635 if (!GetFileTaskRunner()->PostTask( 636 FROM_HERE, 637 base::Bind( 638 &extension_file_util::DeleteFile, extension_path, false))) 639 NOTREACHED(); 640 641 return false; 642 } 643 644 // We want a silent install only for non-pending extensions and 645 // pending extensions that have install_silently set. 646 scoped_ptr<ExtensionInstallPrompt> client; 647 if (pending_extension_info && !pending_extension_info->install_silently()) 648 client.reset(ExtensionInstallUI::CreateInstallPromptWithProfile(profile_)); 649 650 scoped_refptr<CrxInstaller> installer( 651 CrxInstaller::Create(this, client.Pass())); 652 installer->set_expected_id(id); 653 int creation_flags = Extension::NO_FLAGS; 654 if (pending_extension_info) { 655 installer->set_install_source(pending_extension_info->install_source()); 656 if (pending_extension_info->install_silently()) 657 installer->set_allow_silent_install(true); 658 creation_flags = pending_extension_info->creation_flags(); 659 if (pending_extension_info->mark_acknowledged()) 660 AcknowledgeExternalExtension(id); 661 } else if (extension) { 662 installer->set_install_source(extension->location()); 663 } 664 // If the extension was installed from or has migrated to the webstore, or 665 // its auto-update URL is from the webstore, treat it as a webstore install. 666 // Note that we ignore some older extensions with blank auto-update URLs 667 // because we are mostly concerned with restrictions on NaCl extensions, 668 // which are newer. 669 if ((extension && extension->from_webstore()) || 670 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) || 671 (!extension && extension_urls::IsWebstoreUpdateUrl( 672 pending_extension_info->update_url()))) { 673 creation_flags |= Extension::FROM_WEBSTORE; 674 } 675 676 // Bookmark apps being updated is kind of a contradiction, but that's because 677 // we mark the default apps as bookmark apps, and they're hosted in the web 678 // store, thus they can get updated. See http://crbug.com/101605 for more 679 // details. 680 if (extension && extension->from_bookmark()) 681 creation_flags |= Extension::FROM_BOOKMARK; 682 683 if (extension && extension->was_installed_by_default()) 684 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT; 685 686 if (extension && extension->requires_permissions_consent()) 687 creation_flags |= Extension::REQUIRE_PERMISSIONS_CONSENT; 688 689 installer->set_creation_flags(creation_flags); 690 691 installer->set_delete_source(true); 692 installer->set_download_url(download_url); 693 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE); 694 installer->InstallCrx(extension_path); 695 696 if (out_crx_installer) 697 *out_crx_installer = installer.get(); 698 699 return true; 700} 701 702void ExtensionService::ReloadExtension(const std::string extension_id) { 703 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 704 705 // If the extension is already reloading, don't reload again. 706 if (extension_prefs_->GetDisableReasons(extension_id) & 707 Extension::DISABLE_RELOAD) { 708 return; 709 } 710 711 base::FilePath path; 712 const Extension* current_extension = GetExtensionById(extension_id, false); 713 714 // Disable the extension if it's loaded. It might not be loaded if it crashed. 715 if (current_extension) { 716 // If the extension has an inspector open for its background page, detach 717 // the inspector and hang onto a cookie for it, so that we can reattach 718 // later. 719 // TODO(yoz): this is not incognito-safe! 720 ExtensionProcessManager* manager = system_->process_manager(); 721 extensions::ExtensionHost* host = 722 manager->GetBackgroundHostForExtension(extension_id); 723 if (host && DevToolsAgentHost::HasFor(host->render_view_host())) { 724 // Look for an open inspector for the background page. 725 scoped_refptr<DevToolsAgentHost> agent_host = 726 DevToolsAgentHost::GetOrCreateFor(host->render_view_host()); 727 agent_host->DisconnectRenderViewHost(); 728 orphaned_dev_tools_[extension_id] = agent_host; 729 } 730 731 path = current_extension->path(); 732 // BeingUpgraded is set back to false when the extension is added. 733 SetBeingUpgraded(current_extension, true); 734 DisableExtension(extension_id, Extension::DISABLE_RELOAD); 735 reloading_extensions_.insert(extension_id); 736 } else { 737 path = unloaded_extension_paths_[extension_id]; 738 } 739 740 if (delayed_installs_.Contains(extension_id)) { 741 FinishDelayedInstallation(extension_id); 742 return; 743 } 744 745 // If we're reloading a component extension, use the component extension 746 // loader's reloader. 747 if (component_loader_->Exists(extension_id)) { 748 SetBeingReloaded(extension_id, true); 749 component_loader_->Reload(extension_id); 750 SetBeingReloaded(extension_id, false); 751 return; 752 } 753 754 // Check the installed extensions to see if what we're reloading was already 755 // installed. 756 SetBeingReloaded(extension_id, true); 757 scoped_ptr<ExtensionInfo> installed_extension( 758 extension_prefs_->GetInstalledExtensionInfo(extension_id)); 759 if (installed_extension.get() && 760 installed_extension->extension_manifest.get()) { 761 extensions::InstalledLoader(this).Load(*installed_extension, false); 762 } else { 763 // Otherwise, the extension is unpacked (location LOAD). 764 // We should always be able to remember the extension's path. If it's not in 765 // the map, someone failed to update |unloaded_extension_paths_|. 766 CHECK(!path.empty()); 767 extensions::UnpackedInstaller::Create(this)->Load(path); 768 } 769 // When reloading is done, mark this extension as done reloading. 770 SetBeingReloaded(extension_id, false); 771} 772 773bool ExtensionService::UninstallExtension( 774 std::string extension_id, 775 bool external_uninstall, 776 string16* error) { 777 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 778 779 scoped_refptr<const Extension> extension(GetInstalledExtension(extension_id)); 780 781 // Callers should not send us nonexistent extensions. 782 CHECK(extension.get()); 783 784 // Policy change which triggers an uninstall will always set 785 // |external_uninstall| to true so this is the only way to uninstall 786 // managed extensions. 787 if (!external_uninstall && 788 !system_->management_policy()->UserMayModifySettings( 789 extension.get(), error)) { 790 content::NotificationService::current()->Notify( 791 chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED, 792 content::Source<Profile>(profile_), 793 content::Details<const Extension>(extension.get())); 794 return false; 795 } 796 797 // Extract the data we need for sync now, but don't actually sync until we've 798 // completed the uninstallation. 799 // TODO(tim): If we get here and IsSyncing is false, this will cause 800 // "back from the dead" style bugs, because sync will add-back the extension 801 // that was uninstalled here when MergeDataAndStartSyncing is called. 802 // See crbug.com/256795. 803 syncer::SyncChange sync_change; 804 if (extensions::sync_helper::IsSyncableApp(extension.get())) { 805 if (app_sync_bundle_.IsSyncing()) 806 sync_change = app_sync_bundle_.CreateSyncChangeToDelete(extension.get()); 807 else if (is_ready() && !flare_.is_null()) 808 flare_.Run(syncer::APPS); // Tell sync to start ASAP. 809 } else if (extensions::sync_helper::IsSyncableExtension(extension.get())) { 810 if (extension_sync_bundle_.IsSyncing()) 811 sync_change = extension_sync_bundle_.CreateSyncChangeToDelete(extension); 812 else if (is_ready() && !flare_.is_null()) 813 flare_.Run(syncer::EXTENSIONS); // Tell sync to start ASAP. 814 } 815 816 if (IsUnacknowledgedExternalExtension(extension.get())) { 817 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent", 818 EXTERNAL_EXTENSION_UNINSTALLED, 819 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 820 if (extensions::ManifestURL::UpdatesFromGallery(extension.get())) { 821 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore", 822 EXTERNAL_EXTENSION_UNINSTALLED, 823 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 824 } else { 825 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore", 826 EXTERNAL_EXTENSION_UNINSTALLED, 827 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 828 } 829 } 830 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType", 831 extension->GetType(), 100); 832 RecordPermissionMessagesHistogram(extension.get(), 833 "Extensions.Permissions_Uninstall"); 834 835 // Unload before doing more cleanup to ensure that nothing is hanging on to 836 // any of these resources. 837 UnloadExtension(extension_id, extension_misc::UNLOAD_REASON_UNINSTALL); 838 839 // Tell the backend to start deleting installed extensions on the file thread. 840 if (!Manifest::IsUnpackedLocation(extension->location())) { 841 if (!GetFileTaskRunner()->PostTask( 842 FROM_HERE, 843 base::Bind( 844 &extension_file_util::UninstallExtension, 845 install_directory_, 846 extension_id))) 847 NOTREACHED(); 848 } 849 850 GURL launch_web_url_origin( 851 extensions::AppLaunchInfo::GetLaunchWebURL(extension.get()).GetOrigin()); 852 bool is_storage_isolated = 853 extensions::AppIsolationInfo::HasIsolatedStorage(extension.get()); 854 855 if (is_storage_isolated) { 856 BrowserContext::AsyncObliterateStoragePartition( 857 profile_, 858 GetSiteForExtensionId(extension_id), 859 base::Bind(&ExtensionService::OnNeedsToGarbageCollectIsolatedStorage, 860 AsWeakPtr())); 861 } else { 862 if (extension->is_hosted_app() && 863 !profile_->GetExtensionSpecialStoragePolicy()-> 864 IsStorageProtected(launch_web_url_origin)) { 865 extensions::DataDeleter::StartDeleting( 866 profile_, extension_id, launch_web_url_origin); 867 } 868 extensions::DataDeleter::StartDeleting(profile_, extension_id, 869 extension->url()); 870 } 871 872 UntrackTerminatedExtension(extension_id); 873 874 // Notify interested parties that we've uninstalled this extension. 875 content::NotificationService::current()->Notify( 876 chrome::NOTIFICATION_EXTENSION_UNINSTALLED, 877 content::Source<Profile>(profile_), 878 content::Details<const Extension>(extension.get())); 879 880 if (app_sync_bundle_.HasExtensionId(extension_id) && 881 sync_change.sync_data().GetDataType() == syncer::APPS) { 882 app_sync_bundle_.ProcessDeletion(extension_id, sync_change); 883 } else if (extension_sync_bundle_.HasExtensionId(extension_id) && 884 sync_change.sync_data().GetDataType() == syncer::EXTENSIONS) { 885 extension_sync_bundle_.ProcessDeletion(extension_id, sync_change); 886 } 887 888 delayed_installs_.Remove(extension_id); 889 890 PruneSharedModulesOnUninstall(extension.get()); 891 892 extension_prefs_->OnExtensionUninstalled(extension_id, extension->location(), 893 external_uninstall); 894 895 // Track the uninstallation. 896 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2); 897 898 return true; 899} 900 901bool ExtensionService::IsExtensionEnabled( 902 const std::string& extension_id) const { 903 if (extensions_.Contains(extension_id) || 904 terminated_extensions_.Contains(extension_id)) { 905 return true; 906 } 907 908 if (disabled_extensions_.Contains(extension_id) || 909 blacklisted_extensions_.Contains(extension_id)) { 910 return false; 911 } 912 913 // If the extension hasn't been loaded yet, check the prefs for it. Assume 914 // enabled unless otherwise noted. 915 return !extension_prefs_->IsExtensionDisabled(extension_id) && 916 !extension_prefs_->IsExternalExtensionUninstalled(extension_id); 917} 918 919bool ExtensionService::IsExternalExtensionUninstalled( 920 const std::string& extension_id) const { 921 return extension_prefs_->IsExternalExtensionUninstalled(extension_id); 922} 923 924bool ExtensionService::IsExtensionEnabledForLauncher( 925 const std::string& extension_id) const { 926 return IsExtensionEnabled(extension_id) && 927 !GetTerminatedExtension(extension_id); 928} 929 930bool ExtensionService::DoesExtensionRequirePermissionConsent( 931 const std::string& extension_id) const { 932 return extension_prefs_->IsExtensionDisabled(extension_id) && 933 (extension_prefs_->GetDisableReasons(extension_id) & 934 Extension::DISABLE_PERMISSIONS_CONSENT); 935} 936 937void ExtensionService::EnableExtension(const std::string& extension_id) { 938 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 939 940 if (IsExtensionEnabled(extension_id)) 941 return; 942 943 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED); 944 extension_prefs_->ClearDisableReasons(extension_id); 945 946 const Extension* extension = disabled_extensions_.GetByID(extension_id); 947 // This can happen if sync enables an extension that is not 948 // installed yet. 949 if (!extension) 950 return; 951 952 if (IsUnacknowledgedExternalExtension(extension)) { 953 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent", 954 EXTERNAL_EXTENSION_REENABLED, 955 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 956 if (extensions::ManifestURL::UpdatesFromGallery(extension)) { 957 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore", 958 EXTERNAL_EXTENSION_REENABLED, 959 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 960 } else { 961 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore", 962 EXTERNAL_EXTENSION_REENABLED, 963 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 964 } 965 AcknowledgeExternalExtension(extension->id()); 966 } 967 968 // Move it over to the enabled list. 969 extensions_.Insert(make_scoped_refptr(extension)); 970 if (disabled_extensions_.Remove(extension->id())) 971 extension_prefs_->SetKnownDisabled(disabled_extensions_.GetIDs()); 972 973 NotifyExtensionLoaded(extension); 974 975 // Notify listeners that the extension was enabled. 976 content::NotificationService::current()->Notify( 977 chrome::NOTIFICATION_EXTENSION_ENABLED, 978 content::Source<Profile>(profile_), 979 content::Details<const Extension>(extension)); 980 981 // Syncing may not have started yet, so handle pending enables. 982 if (extensions::sync_helper::IsSyncableApp(extension)) 983 pending_app_enables_.OnExtensionEnabled(extension->id()); 984 985 if (extensions::sync_helper::IsSyncableExtension(extension)) 986 pending_extension_enables_.OnExtensionEnabled(extension->id()); 987 988 SyncExtensionChangeIfNeeded(*extension); 989} 990 991void ExtensionService::DisableExtension( 992 const std::string& extension_id, 993 Extension::DisableReason disable_reason) { 994 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 995 996 // The extension may have been disabled already. 997 if (!IsExtensionEnabled(extension_id)) 998 return; 999 1000 const Extension* extension = GetInstalledExtension(extension_id); 1001 // |extension| can be NULL if sync disables an extension that is not 1002 // installed yet. 1003 if (extension && 1004 disable_reason != Extension::DISABLE_RELOAD && 1005 !system_->management_policy()->UserMayModifySettings(extension, NULL)) { 1006 return; 1007 } 1008 1009 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED); 1010 extension_prefs_->AddDisableReason(extension_id, disable_reason); 1011 1012 int include_mask = INCLUDE_EVERYTHING & ~INCLUDE_DISABLED; 1013 extension = GetExtensionById(extension_id, include_mask); 1014 if (!extension) 1015 return; 1016 1017 // Reset the background_page_ready flag 1018 if (extensions::BackgroundInfo::HasBackgroundPage(extension)) 1019 extension_runtime_data_[extension->id()].background_page_ready = false; 1020 1021 // Move it over to the disabled list. Don't send a second unload notification 1022 // for terminated extensions being disabled. 1023 if (disabled_extensions_.Insert(make_scoped_refptr(extension))) 1024 extension_prefs_->SetKnownDisabled(disabled_extensions_.GetIDs()); 1025 if (extensions_.Contains(extension->id())) { 1026 extensions_.Remove(extension->id()); 1027 NotifyExtensionUnloaded(extension, extension_misc::UNLOAD_REASON_DISABLE); 1028 } else { 1029 terminated_extensions_.Remove(extension->id()); 1030 } 1031 1032 // Syncing may not have started yet, so handle pending enables. 1033 if (extensions::sync_helper::IsSyncableApp(extension)) 1034 pending_app_enables_.OnExtensionDisabled(extension->id()); 1035 1036 if (extensions::sync_helper::IsSyncableExtension(extension)) 1037 pending_extension_enables_.OnExtensionDisabled(extension->id()); 1038 1039 SyncExtensionChangeIfNeeded(*extension); 1040} 1041 1042void ExtensionService::DisableUserExtensions( 1043 const std::vector<std::string>& except_ids) { 1044 extensions::ManagementPolicy* management_policy = 1045 system_->management_policy(); 1046 extensions::ExtensionList to_disable; 1047 1048 for (ExtensionSet::const_iterator extension = extensions_.begin(); 1049 extension != extensions_.end(); ++extension) { 1050 if (management_policy->UserMayModifySettings(extension->get(), NULL)) 1051 to_disable.push_back(*extension); 1052 } 1053 for (ExtensionSet::const_iterator extension = terminated_extensions_.begin(); 1054 extension != terminated_extensions_.end(); ++extension) { 1055 if (management_policy->UserMayModifySettings(extension->get(), NULL)) 1056 to_disable.push_back(*extension); 1057 } 1058 1059 for (extensions::ExtensionList::const_iterator extension = to_disable.begin(); 1060 extension != to_disable.end(); ++extension) { 1061 if ((*extension)->was_installed_by_default() && 1062 extension_urls::IsWebstoreUpdateUrl( 1063 extensions::ManifestURL::GetUpdateURL(*extension))) 1064 continue; 1065 const std::string& id = (*extension)->id(); 1066 if (except_ids.end() == std::find(except_ids.begin(), except_ids.end(), id)) 1067 DisableExtension(id, extensions::Extension::DISABLE_USER_ACTION); 1068 } 1069} 1070 1071void ExtensionService::GrantPermissionsAndEnableExtension( 1072 const Extension* extension) { 1073 GrantPermissions(extension); 1074 RecordPermissionMessagesHistogram( 1075 extension, "Extensions.Permissions_ReEnable"); 1076 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false); 1077 EnableExtension(extension->id()); 1078} 1079 1080void ExtensionService::GrantPermissions(const Extension* extension) { 1081 CHECK(extension); 1082 extensions::PermissionsUpdater perms_updater(profile()); 1083 perms_updater.GrantActivePermissions(extension); 1084} 1085 1086// static 1087void ExtensionService::RecordPermissionMessagesHistogram( 1088 const Extension* extension, const char* histogram) { 1089 // Since this is called from multiple sources, and since the histogram macros 1090 // use statics, we need to manually lookup the histogram ourselves. 1091 base::HistogramBase* counter = base::LinearHistogram::FactoryGet( 1092 histogram, 1093 1, 1094 PermissionMessage::kEnumBoundary, 1095 PermissionMessage::kEnumBoundary + 1, 1096 base::HistogramBase::kUmaTargetedHistogramFlag); 1097 1098 PermissionMessages permissions = 1099 extensions::PermissionsData::GetPermissionMessages(extension); 1100 if (permissions.empty()) { 1101 counter->Add(PermissionMessage::kNone); 1102 } else { 1103 for (PermissionMessages::iterator it = permissions.begin(); 1104 it != permissions.end(); ++it) 1105 counter->Add(it->id()); 1106 } 1107} 1108 1109void ExtensionService::NotifyExtensionLoaded(const Extension* extension) { 1110 // The ChromeURLRequestContexts need to be first to know that the extension 1111 // was loaded, otherwise a race can arise where a renderer that is created 1112 // for the extension may try to load an extension URL with an extension id 1113 // that the request context doesn't yet know about. The profile is responsible 1114 // for ensuring its URLRequestContexts appropriately discover the loaded 1115 // extension. 1116 system_->RegisterExtensionWithRequestContexts(extension); 1117 1118 // Tell renderers about the new extension, unless it's a theme (renderers 1119 // don't need to know about themes). 1120 if (!extension->is_theme()) { 1121 for (content::RenderProcessHost::iterator i( 1122 content::RenderProcessHost::AllHostsIterator()); 1123 !i.IsAtEnd(); i.Advance()) { 1124 content::RenderProcessHost* host = i.GetCurrentValue(); 1125 Profile* host_profile = 1126 Profile::FromBrowserContext(host->GetBrowserContext()); 1127 if (host_profile->GetOriginalProfile() == 1128 profile_->GetOriginalProfile()) { 1129 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions( 1130 1, ExtensionMsg_Loaded_Params(extension)); 1131 host->Send( 1132 new ExtensionMsg_Loaded(loaded_extensions)); 1133 } 1134 } 1135 } 1136 1137 // Tell subsystems that use the EXTENSION_LOADED notification about the new 1138 // extension. 1139 // 1140 // NOTE: It is important that this happen after notifying the renderers about 1141 // the new extensions so that if we navigate to an extension URL in 1142 // NOTIFICATION_EXTENSION_LOADED, the renderer is guaranteed to know about it. 1143 content::NotificationService::current()->Notify( 1144 chrome::NOTIFICATION_EXTENSION_LOADED, 1145 content::Source<Profile>(profile_), 1146 content::Details<const Extension>(extension)); 1147 1148 // Tell a random-ass collection of other subsystems about the new extension. 1149 // TODO(aa): What should we do with all this goop? Can it move into the 1150 // relevant objects via EXTENSION_LOADED? 1151 1152 profile_->GetExtensionSpecialStoragePolicy()-> 1153 GrantRightsForExtension(extension); 1154 1155 UpdateActiveExtensionsInCrashReporter(); 1156 1157 // If the extension has permission to load chrome://favicon/ resources we need 1158 // to make sure that the FaviconSource is registered with the 1159 // ChromeURLDataManager. 1160 if (extensions::PermissionsData::HasHostPermission( 1161 extension, GURL(chrome::kChromeUIFaviconURL))) { 1162 FaviconSource* favicon_source = new FaviconSource(profile_, 1163 FaviconSource::FAVICON); 1164 content::URLDataSource::Add(profile_, favicon_source); 1165 } 1166 1167#if !defined(OS_ANDROID) 1168 // Same for chrome://theme/ resources. 1169 if (extensions::PermissionsData::HasHostPermission( 1170 extension, GURL(chrome::kChromeUIThemeURL))) { 1171 ThemeSource* theme_source = new ThemeSource(profile_); 1172 content::URLDataSource::Add(profile_, theme_source); 1173 } 1174#endif 1175 1176 // Same for chrome://thumb/ resources. 1177 if (extensions::PermissionsData::HasHostPermission( 1178 extension, GURL(chrome::kChromeUIThumbnailURL))) { 1179 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_, false); 1180 content::URLDataSource::Add(profile_, thumbnail_source); 1181 } 1182} 1183 1184void ExtensionService::NotifyExtensionUnloaded( 1185 const Extension* extension, 1186 extension_misc::UnloadedExtensionReason reason) { 1187 UnloadedExtensionInfo details(extension, reason); 1188 content::NotificationService::current()->Notify( 1189 chrome::NOTIFICATION_EXTENSION_UNLOADED, 1190 content::Source<Profile>(profile_), 1191 content::Details<UnloadedExtensionInfo>(&details)); 1192 1193 for (content::RenderProcessHost::iterator i( 1194 content::RenderProcessHost::AllHostsIterator()); 1195 !i.IsAtEnd(); i.Advance()) { 1196 content::RenderProcessHost* host = i.GetCurrentValue(); 1197 Profile* host_profile = 1198 Profile::FromBrowserContext(host->GetBrowserContext()); 1199 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile()) 1200 host->Send(new ExtensionMsg_Unloaded(extension->id())); 1201 } 1202 1203 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason); 1204 profile_->GetExtensionSpecialStoragePolicy()-> 1205 RevokeRightsForExtension(extension); 1206 1207#if defined(OS_CHROMEOS) 1208 // Revoke external file access for the extension from its file system context. 1209 // It is safe to access the extension's storage partition at this point. The 1210 // storage partition may get destroyed only after the extension gets unloaded. 1211 GURL site = extensions::ExtensionSystem::Get(profile_)->extension_service()-> 1212 GetSiteForExtensionId(extension->id()); 1213 fileapi::FileSystemContext* filesystem_context = 1214 BrowserContext::GetStoragePartitionForSite(profile_, site)-> 1215 GetFileSystemContext(); 1216 if (filesystem_context && filesystem_context->external_backend()) { 1217 filesystem_context->external_backend()-> 1218 RevokeAccessForExtension(extension->id()); 1219 } 1220#endif 1221 1222 UpdateActiveExtensionsInCrashReporter(); 1223} 1224 1225Profile* ExtensionService::profile() { 1226 return profile_; 1227} 1228 1229extensions::ExtensionPrefs* ExtensionService::extension_prefs() { 1230 return extension_prefs_; 1231} 1232 1233const extensions::ExtensionPrefs* ExtensionService::extension_prefs() const { 1234 return extension_prefs_; 1235} 1236 1237extensions::SettingsFrontend* ExtensionService::settings_frontend() { 1238 return settings_frontend_.get(); 1239} 1240 1241extensions::ContentSettingsStore* ExtensionService::GetContentSettingsStore() { 1242 return extension_prefs()->content_settings_store(); 1243} 1244 1245bool ExtensionService::is_ready() { 1246 return ready_->is_signaled(); 1247} 1248 1249base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() { 1250 if (file_task_runner_.get()) 1251 return file_task_runner_.get(); 1252 1253 // We should be able to interrupt any part of extension install process during 1254 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks 1255 // will be ignored/deleted while we will block on started tasks. 1256 std::string token("ext_install-"); 1257 token.append(profile_->GetPath().AsUTF8Unsafe()); 1258 file_task_runner_ = BrowserThread::GetBlockingPool()-> 1259 GetSequencedTaskRunnerWithShutdownBehavior( 1260 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token), 1261 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN); 1262 return file_task_runner_.get(); 1263} 1264 1265extensions::ExtensionUpdater* ExtensionService::updater() { 1266 return updater_.get(); 1267} 1268 1269void ExtensionService::CheckManagementPolicy() { 1270 std::vector<std::string> to_be_removed; 1271 1272 // Loop through extensions list, unload installed extensions. 1273 for (ExtensionSet::const_iterator iter = extensions_.begin(); 1274 iter != extensions_.end(); ++iter) { 1275 const Extension* extension = (iter->get()); 1276 if (!system_->management_policy()->UserMayLoad(extension, NULL)) 1277 to_be_removed.push_back(extension->id()); 1278 } 1279 1280 // UnloadExtension will change the extensions_ list. So, we should 1281 // call it outside the iterator loop. 1282 for (size_t i = 0; i < to_be_removed.size(); ++i) 1283 UnloadExtension(to_be_removed[i], extension_misc::UNLOAD_REASON_DISABLE); 1284} 1285 1286void ExtensionService::CheckForUpdatesSoon() { 1287 if (updater()) { 1288 if (AreAllExternalProvidersReady()) { 1289 updater()->CheckSoon(); 1290 } else { 1291 // Sync can start updating before all the external providers are ready 1292 // during startup. Start the update as soon as those providers are ready, 1293 // but not before. 1294 update_once_all_providers_are_ready_ = true; 1295 } 1296 } else { 1297 LOG(WARNING) << "CheckForUpdatesSoon() called with auto-update turned off"; 1298 } 1299} 1300 1301syncer::SyncMergeResult ExtensionService::MergeDataAndStartSyncing( 1302 syncer::ModelType type, 1303 const syncer::SyncDataList& initial_sync_data, 1304 scoped_ptr<syncer::SyncChangeProcessor> sync_processor, 1305 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) { 1306 CHECK(sync_processor.get()); 1307 CHECK(sync_error_factory.get()); 1308 1309 switch (type) { 1310 case syncer::EXTENSIONS: 1311 extension_sync_bundle_.SetupSync(sync_processor.release(), 1312 sync_error_factory.release(), 1313 initial_sync_data); 1314 pending_extension_enables_.OnSyncStarted(this); 1315 break; 1316 1317 case syncer::APPS: 1318 app_sync_bundle_.SetupSync(sync_processor.release(), 1319 sync_error_factory.release(), 1320 initial_sync_data); 1321 pending_app_enables_.OnSyncStarted(this); 1322 break; 1323 1324 default: 1325 LOG(FATAL) << "Got " << type << " ModelType"; 1326 } 1327 1328 // Process local extensions. 1329 // TODO(yoz): Determine whether pending extensions should be considered too. 1330 // See crbug.com/104399. 1331 syncer::SyncDataList sync_data_list = GetAllSyncData(type); 1332 syncer::SyncChangeList sync_change_list; 1333 for (syncer::SyncDataList::const_iterator i = sync_data_list.begin(); 1334 i != sync_data_list.end(); 1335 ++i) { 1336 switch (type) { 1337 case syncer::EXTENSIONS: 1338 sync_change_list.push_back( 1339 extension_sync_bundle_.CreateSyncChange(*i)); 1340 break; 1341 case syncer::APPS: 1342 sync_change_list.push_back(app_sync_bundle_.CreateSyncChange(*i)); 1343 break; 1344 default: 1345 LOG(FATAL) << "Got " << type << " ModelType"; 1346 } 1347 } 1348 1349 1350 if (type == syncer::EXTENSIONS) { 1351 extension_sync_bundle_.ProcessSyncChangeList(sync_change_list); 1352 } else if (type == syncer::APPS) { 1353 app_sync_bundle_.ProcessSyncChangeList(sync_change_list); 1354 } 1355 1356 return syncer::SyncMergeResult(type); 1357} 1358 1359void ExtensionService::StopSyncing(syncer::ModelType type) { 1360 if (type == syncer::APPS) { 1361 app_sync_bundle_.Reset(); 1362 } else if (type == syncer::EXTENSIONS) { 1363 extension_sync_bundle_.Reset(); 1364 } 1365} 1366 1367syncer::SyncDataList ExtensionService::GetAllSyncData( 1368 syncer::ModelType type) const { 1369 if (type == syncer::EXTENSIONS) 1370 return extension_sync_bundle_.GetAllSyncData(); 1371 if (type == syncer::APPS) 1372 return app_sync_bundle_.GetAllSyncData(); 1373 1374 // We should only get sync data for extensions and apps. 1375 NOTREACHED(); 1376 1377 return syncer::SyncDataList(); 1378} 1379 1380syncer::SyncError ExtensionService::ProcessSyncChanges( 1381 const tracked_objects::Location& from_here, 1382 const syncer::SyncChangeList& change_list) { 1383 for (syncer::SyncChangeList::const_iterator i = change_list.begin(); 1384 i != change_list.end(); 1385 ++i) { 1386 syncer::ModelType type = i->sync_data().GetDataType(); 1387 if (type == syncer::EXTENSIONS) { 1388 extension_sync_bundle_.ProcessSyncChange( 1389 extensions::ExtensionSyncData(*i)); 1390 } else if (type == syncer::APPS) { 1391 app_sync_bundle_.ProcessSyncChange(extensions::AppSyncData(*i)); 1392 } 1393 } 1394 1395 extension_prefs()->extension_sorting()->FixNTPOrdinalCollisions(); 1396 1397 return syncer::SyncError(); 1398} 1399 1400extensions::ExtensionSyncData ExtensionService::GetExtensionSyncData( 1401 const Extension& extension) const { 1402 return extensions::ExtensionSyncData( 1403 extension, 1404 IsExtensionEnabled(extension.id()), 1405 extension_util::IsIncognitoEnabled(extension.id(), this)); 1406} 1407 1408extensions::AppSyncData ExtensionService::GetAppSyncData( 1409 const Extension& extension) const { 1410 return extensions::AppSyncData( 1411 extension, 1412 IsExtensionEnabled(extension.id()), 1413 extension_util::IsIncognitoEnabled(extension.id(), this), 1414 extension_prefs_->extension_sorting()->GetAppLaunchOrdinal( 1415 extension.id()), 1416 extension_prefs_->extension_sorting()->GetPageOrdinal(extension.id())); 1417} 1418 1419std::vector<extensions::ExtensionSyncData> 1420 ExtensionService::GetExtensionSyncDataList() const { 1421 std::vector<extensions::ExtensionSyncData> extension_sync_list; 1422 extension_sync_bundle_.GetExtensionSyncDataListHelper(extensions_, 1423 &extension_sync_list); 1424 extension_sync_bundle_.GetExtensionSyncDataListHelper(disabled_extensions_, 1425 &extension_sync_list); 1426 extension_sync_bundle_.GetExtensionSyncDataListHelper(terminated_extensions_, 1427 &extension_sync_list); 1428 1429 std::vector<extensions::ExtensionSyncData> pending_extensions = 1430 extension_sync_bundle_.GetPendingData(); 1431 extension_sync_list.insert(extension_sync_list.begin(), 1432 pending_extensions.begin(), 1433 pending_extensions.end()); 1434 1435 return extension_sync_list; 1436} 1437 1438std::vector<extensions::AppSyncData> ExtensionService::GetAppSyncDataList() 1439 const { 1440 std::vector<extensions::AppSyncData> app_sync_list; 1441 app_sync_bundle_.GetAppSyncDataListHelper(extensions_, &app_sync_list); 1442 app_sync_bundle_.GetAppSyncDataListHelper(disabled_extensions_, 1443 &app_sync_list); 1444 app_sync_bundle_.GetAppSyncDataListHelper(terminated_extensions_, 1445 &app_sync_list); 1446 1447 std::vector<extensions::AppSyncData> pending_apps = 1448 app_sync_bundle_.GetPendingData(); 1449 app_sync_list.insert(app_sync_list.begin(), 1450 pending_apps.begin(), 1451 pending_apps.end()); 1452 1453 return app_sync_list; 1454} 1455 1456bool ExtensionService::ProcessExtensionSyncData( 1457 const extensions::ExtensionSyncData& extension_sync_data) { 1458 if (!ProcessExtensionSyncDataHelper(extension_sync_data, 1459 syncer::EXTENSIONS)) { 1460 extension_sync_bundle_.AddPendingExtension(extension_sync_data.id(), 1461 extension_sync_data); 1462 CheckForUpdatesSoon(); 1463 return false; 1464 } 1465 1466 return true; 1467} 1468 1469bool ExtensionService::ProcessAppSyncData( 1470 const extensions::AppSyncData& app_sync_data) { 1471 const std::string& id = app_sync_data.id(); 1472 1473 if (app_sync_data.app_launch_ordinal().IsValid() && 1474 app_sync_data.page_ordinal().IsValid()) { 1475 extension_prefs_->extension_sorting()->SetAppLaunchOrdinal( 1476 id, 1477 app_sync_data.app_launch_ordinal()); 1478 extension_prefs_->extension_sorting()->SetPageOrdinal( 1479 id, 1480 app_sync_data.page_ordinal()); 1481 } 1482 1483 if (!ProcessExtensionSyncDataHelper(app_sync_data.extension_sync_data(), 1484 syncer::APPS)) { 1485 app_sync_bundle_.AddPendingApp(id, app_sync_data); 1486 CheckForUpdatesSoon(); 1487 return false; 1488 } 1489 1490 return true; 1491} 1492 1493bool ExtensionService::IsCorrectSyncType(const Extension& extension, 1494 syncer::ModelType type) const { 1495 if (type == syncer::EXTENSIONS && 1496 extensions::sync_helper::IsSyncableExtension(&extension)) { 1497 return true; 1498 } 1499 1500 if (type == syncer::APPS && 1501 extensions::sync_helper::IsSyncableApp(&extension)) { 1502 return true; 1503 } 1504 1505 return false; 1506} 1507 1508bool ExtensionService::IsPendingEnable(const std::string& extension_id) const { 1509 return pending_app_enables_.Contains(extension_id) || 1510 pending_extension_enables_.Contains(extension_id); 1511} 1512 1513bool ExtensionService::ProcessExtensionSyncDataHelper( 1514 const extensions::ExtensionSyncData& extension_sync_data, 1515 syncer::ModelType type) { 1516 const std::string& id = extension_sync_data.id(); 1517 const Extension* extension = GetInstalledExtension(id); 1518 1519 // TODO(bolms): we should really handle this better. The particularly bad 1520 // case is where an app becomes an extension or vice versa, and we end up with 1521 // a zombie extension that won't go away. 1522 if (extension && !IsCorrectSyncType(*extension, type)) 1523 return true; 1524 1525 // Handle uninstalls first. 1526 if (extension_sync_data.uninstalled()) { 1527 if (!UninstallExtensionHelper(this, id)) { 1528 LOG(WARNING) << "Could not uninstall extension " << id 1529 << " for sync"; 1530 } 1531 return true; 1532 } 1533 1534 // Extension from sync was uninstalled by the user as external extensions. 1535 // Honor user choice and skip installation/enabling. 1536 if (IsExternalExtensionUninstalled(id)) { 1537 LOG(WARNING) << "Extension with id " << id 1538 << " from sync was uninstalled as external extension"; 1539 return true; 1540 } 1541 1542 // Set user settings. 1543 // If the extension has been disabled from sync, it may not have 1544 // been installed yet, so we don't know if the disable reason was a 1545 // permissions increase. That will be updated once CheckPermissionsIncrease 1546 // is called for it. 1547 if (extension_sync_data.enabled()) 1548 EnableExtension(id); 1549 else if (!IsPendingEnable(id)) 1550 DisableExtension(id, Extension::DISABLE_UNKNOWN_FROM_SYNC); 1551 1552 // We need to cache some version information here because setting the 1553 // incognito flag invalidates the |extension| pointer (it reloads the 1554 // extension). 1555 bool extension_installed = (extension != NULL); 1556 int result = extension ? 1557 extension->version()->CompareTo(extension_sync_data.version()) : 0; 1558 extension_util::SetIsIncognitoEnabled( 1559 id, this, extension_sync_data.incognito_enabled()); 1560 extension = NULL; // No longer safe to use. 1561 1562 if (extension_installed) { 1563 // If the extension is already installed, check if it's outdated. 1564 if (result < 0) { 1565 // Extension is outdated. 1566 return false; 1567 } 1568 } else { 1569 // TODO(akalin): Replace silent update with a list of enabled 1570 // permissions. 1571 const bool kInstallSilently = true; 1572 1573 CHECK(type == syncer::EXTENSIONS || type == syncer::APPS); 1574 extensions::PendingExtensionInfo::ShouldAllowInstallPredicate filter = 1575 (type == syncer::APPS) ? extensions::sync_helper::IsSyncableApp : 1576 extensions::sync_helper::IsSyncableExtension; 1577 1578 if (!pending_extension_manager()->AddFromSync( 1579 id, 1580 extension_sync_data.update_url(), 1581 filter, 1582 kInstallSilently)) { 1583 LOG(WARNING) << "Could not add pending extension for " << id; 1584 // This means that the extension is already pending installation, with a 1585 // non-INTERNAL location. Add to pending_sync_data, even though it will 1586 // never be removed (we'll never install a syncable version of the 1587 // extension), so that GetAllSyncData() continues to send it. 1588 } 1589 // Track pending extensions so that we can return them in GetAllSyncData(). 1590 return false; 1591 } 1592 1593 return true; 1594} 1595 1596void ExtensionService::OnExtensionMoved( 1597 const std::string& moved_extension_id, 1598 const std::string& predecessor_extension_id, 1599 const std::string& successor_extension_id) { 1600 extension_prefs_->extension_sorting()->OnExtensionMoved( 1601 moved_extension_id, 1602 predecessor_extension_id, 1603 successor_extension_id); 1604 1605 const Extension* extension = GetInstalledExtension(moved_extension_id); 1606 if (extension) 1607 SyncExtensionChangeIfNeeded(*extension); 1608} 1609 1610// Some extensions will autoupdate themselves externally from Chrome. These 1611// are typically part of some larger client application package. To support 1612// these, the extension will register its location in the the preferences file 1613// (and also, on Windows, in the registry) and this code will periodically 1614// check that location for a .crx file, which it will then install locally if 1615// a new version is available. 1616// Errors are reported through ExtensionErrorReporter. Succcess is not 1617// reported. 1618void ExtensionService::CheckForExternalUpdates() { 1619 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1620 1621 // Note that this installation is intentionally silent (since it didn't 1622 // go through the front-end). Extensions that are registered in this 1623 // way are effectively considered 'pre-bundled', and so implicitly 1624 // trusted. In general, if something has HKLM or filesystem access, 1625 // they could install an extension manually themselves anyway. 1626 1627 // Ask each external extension provider to give us a call back for each 1628 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found. 1629 extensions::ProviderCollection::const_iterator i; 1630 for (i = external_extension_providers_.begin(); 1631 i != external_extension_providers_.end(); ++i) { 1632 extensions::ExternalProviderInterface* provider = i->get(); 1633 provider->VisitRegisteredExtension(); 1634 } 1635 1636 // Do any required work that we would have done after completion of all 1637 // providers. 1638 if (external_extension_providers_.empty()) { 1639 OnAllExternalProvidersReady(); 1640 } 1641} 1642 1643void ExtensionService::OnExternalProviderReady( 1644 const extensions::ExternalProviderInterface* provider) { 1645 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1646 CHECK(provider->IsReady()); 1647 1648 // An external provider has finished loading. We only take action 1649 // if all of them are finished. So we check them first. 1650 if (AreAllExternalProvidersReady()) 1651 OnAllExternalProvidersReady(); 1652} 1653 1654bool ExtensionService::AreAllExternalProvidersReady() const { 1655 extensions::ProviderCollection::const_iterator i; 1656 for (i = external_extension_providers_.begin(); 1657 i != external_extension_providers_.end(); ++i) { 1658 if (!i->get()->IsReady()) 1659 return false; 1660 } 1661 return true; 1662} 1663 1664void ExtensionService::OnAllExternalProvidersReady() { 1665 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1666 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime(); 1667 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed); 1668 1669 // Install any pending extensions. 1670 if (update_once_all_providers_are_ready_ && updater()) { 1671 update_once_all_providers_are_ready_ = false; 1672 updater()->CheckNow(extensions::ExtensionUpdater::CheckParams()); 1673 } 1674 1675 // Uninstall all the unclaimed extensions. 1676 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info( 1677 extension_prefs_->GetInstalledExtensionsInfo()); 1678 for (size_t i = 0; i < extensions_info->size(); ++i) { 1679 ExtensionInfo* info = extensions_info->at(i).get(); 1680 if (Manifest::IsExternalLocation(info->extension_location)) 1681 CheckExternalUninstall(info->extension_id); 1682 } 1683 IdentifyAlertableExtensions(); 1684} 1685 1686void ExtensionService::IdentifyAlertableExtensions() { 1687 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1688 1689 // Build up the lists of extensions that require acknowledgment. If this is 1690 // the first time, grandfather extensions that would have caused 1691 // notification. 1692 extension_error_ui_.reset(ExtensionErrorUI::Create(this)); 1693 1694 bool did_show_alert = false; 1695 if (PopulateExtensionErrorUI(extension_error_ui_.get())) { 1696 if (!is_first_run_) { 1697 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 1698 did_show_alert = extension_error_ui_->ShowErrorInBubbleView(); 1699 } else { 1700 // First run. Just acknowledge all the extensions, silently, by 1701 // shortcutting the display of the UI and going straight to the 1702 // callback for pressing the Accept button. 1703 HandleExtensionAlertAccept(); 1704 } 1705 } 1706 1707 UpdateExternalExtensionAlert(); 1708 1709 if (!did_show_alert) 1710 extension_error_ui_.reset(); 1711} 1712 1713bool ExtensionService::PopulateExtensionErrorUI( 1714 ExtensionErrorUI* extension_error_ui) { 1715 bool needs_alert = false; 1716 1717 // Extensions that are blacklisted. 1718 for (ExtensionSet::const_iterator it = blacklisted_extensions_.begin(); 1719 it != blacklisted_extensions_.end(); ++it) { 1720 std::string id = (*it)->id(); 1721 if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(id)) { 1722 extension_error_ui->AddBlacklistedExtension(id); 1723 needs_alert = true; 1724 } 1725 } 1726 1727 for (ExtensionSet::const_iterator iter = extensions_.begin(); 1728 iter != extensions_.end(); ++iter) { 1729 const Extension* e = iter->get(); 1730 1731 // Extensions disabled by policy. Note: this no longer includes blacklisted 1732 // extensions, though we still show the same UI. 1733 if (!system_->management_policy()->UserMayLoad(e, NULL)) { 1734 if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(e->id())) { 1735 extension_error_ui->AddBlacklistedExtension(e->id()); 1736 needs_alert = true; 1737 } 1738 } 1739 } 1740 1741 return needs_alert; 1742} 1743 1744void ExtensionService::HandleExtensionAlertClosed() { 1745 const ExtensionIdSet* extension_ids = 1746 extension_error_ui_->get_blacklisted_extension_ids(); 1747 for (ExtensionIdSet::const_iterator iter = extension_ids->begin(); 1748 iter != extension_ids->end(); ++iter) { 1749 extension_prefs_->AcknowledgeBlacklistedExtension(*iter); 1750 } 1751 extension_error_ui_.reset(); 1752} 1753 1754void ExtensionService::HandleExtensionAlertAccept() { 1755 extension_error_ui_->Close(); 1756} 1757 1758void ExtensionService::AcknowledgeExternalExtension(const std::string& id) { 1759 extension_prefs_->AcknowledgeExternalExtension(id); 1760 UpdateExternalExtensionAlert(); 1761} 1762 1763bool ExtensionService::IsUnacknowledgedExternalExtension( 1764 const Extension* extension) { 1765 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) 1766 return false; 1767 1768 return (Manifest::IsExternalLocation(extension->location()) && 1769 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id()) && 1770 !(extension_prefs_->GetDisableReasons(extension->id()) & 1771 Extension::DISABLE_SIDELOAD_WIPEOUT)); 1772} 1773 1774void ExtensionService::ReconcileKnownDisabled() { 1775 ExtensionIdSet known_disabled_ids = extension_prefs_->GetKnownDisabled(); 1776 if (known_disabled_ids.empty()) { 1777 if (!disabled_extensions_.is_empty()) { 1778 extension_prefs_->SetKnownDisabled(disabled_extensions_.GetIDs()); 1779 UMA_HISTOGRAM_BOOLEAN("Extensions.KnownDisabledInitialized", true); 1780 } 1781 } else { 1782 // Both |known_disabled_ids| and |extensions_| are ordered (by definition 1783 // of std::map and std::set). Iterate forward over both sets in parallel 1784 // to find matching IDs and disable the corresponding extensions. 1785 ExtensionSet::const_iterator extensions_it = extensions_.begin(); 1786 ExtensionIdSet::const_iterator known_disabled_ids_it = 1787 known_disabled_ids.begin(); 1788 int known_disabled_count = 0; 1789 while (extensions_it != extensions_.end() && 1790 known_disabled_ids_it != known_disabled_ids.end()) { 1791 const std::string& extension_id = extensions_it->get()->id(); 1792 const int comparison = extension_id.compare(*known_disabled_ids_it); 1793 if (comparison < 0) { 1794 ++extensions_it; 1795 } else if (comparison > 0) { 1796 ++known_disabled_ids_it; 1797 } else { 1798 ++known_disabled_count; 1799 // Advance |extensions_it| immediately as it will be invalidated upon 1800 // disabling the extension it points to. 1801 ++extensions_it; 1802 ++known_disabled_ids_it; 1803 DisableExtension(extension_id, Extension::DISABLE_KNOWN_DISABLED); 1804 } 1805 } 1806 UMA_HISTOGRAM_COUNTS_100("Extensions.KnownDisabledReDisabled", 1807 known_disabled_count); 1808 } 1809} 1810 1811void ExtensionService::HandleExtensionAlertDetails() { 1812 extension_error_ui_->ShowExtensions(); 1813 // ShowExtensions may cause the error UI to close synchronously, e.g. if it 1814 // causes a navigation. 1815 if (extension_error_ui_) 1816 extension_error_ui_->Close(); 1817} 1818 1819void ExtensionService::UpdateExternalExtensionAlert() { 1820 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) 1821 return; 1822 1823 const Extension* extension = NULL; 1824 for (ExtensionSet::const_iterator iter = disabled_extensions_.begin(); 1825 iter != disabled_extensions_.end(); ++iter) { 1826 const Extension* e = iter->get(); 1827 if (IsUnacknowledgedExternalExtension(e)) { 1828 extension = e; 1829 break; 1830 } 1831 } 1832 1833 if (extension) { 1834 if (!extensions::HasExternalInstallError(this)) { 1835 if (extension_prefs_->IncrementAcknowledgePromptCount(extension->id()) > 1836 kMaxExtensionAcknowledgePromptCount) { 1837 // Stop prompting for this extension, and check if there's another 1838 // one that needs prompting. 1839 extension_prefs_->AcknowledgeExternalExtension(extension->id()); 1840 UpdateExternalExtensionAlert(); 1841 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent", 1842 EXTERNAL_EXTENSION_IGNORED, 1843 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 1844 if (extensions::ManifestURL::UpdatesFromGallery(extension)) { 1845 UMA_HISTOGRAM_ENUMERATION( 1846 "Extensions.ExternalExtensionEventWebstore", 1847 EXTERNAL_EXTENSION_IGNORED, 1848 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 1849 } else { 1850 UMA_HISTOGRAM_ENUMERATION( 1851 "Extensions.ExternalExtensionEventNonWebstore", 1852 EXTERNAL_EXTENSION_IGNORED, 1853 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 1854 } 1855 return; 1856 } 1857 if (is_first_run_) 1858 extension_prefs_->SetExternalInstallFirstRun(extension->id()); 1859 // first_run is true if the extension was installed during a first run 1860 // (even if it's post-first run now). 1861 bool first_run = extension_prefs_->IsExternalInstallFirstRun( 1862 extension->id()); 1863 extensions::AddExternalInstallError(this, extension, first_run); 1864 } 1865 } else { 1866 extensions::RemoveExternalInstallError(this); 1867 } 1868} 1869 1870void ExtensionService::UnloadExtension( 1871 const std::string& extension_id, 1872 extension_misc::UnloadedExtensionReason reason) { 1873 // Make sure the extension gets deleted after we return from this function. 1874 int include_mask = INCLUDE_EVERYTHING & ~INCLUDE_TERMINATED; 1875 scoped_refptr<const Extension> extension( 1876 GetExtensionById(extension_id, include_mask)); 1877 1878 // This method can be called via PostTask, so the extension may have been 1879 // unloaded by the time this runs. 1880 if (!extension.get()) { 1881 // In case the extension may have crashed/uninstalled. Allow the profile to 1882 // clean up its RequestContexts. 1883 system_->UnregisterExtensionWithRequestContexts(extension_id, reason); 1884 return; 1885 } 1886 1887 // If uninstalling let RuntimeEventRouter know. 1888 if (reason == extension_misc::UNLOAD_REASON_UNINSTALL) 1889 extensions::RuntimeEventRouter::OnExtensionUninstalled( 1890 profile_, extension_id); 1891 1892 // Keep information about the extension so that we can reload it later 1893 // even if it's not permanently installed. 1894 unloaded_extension_paths_[extension->id()] = extension->path(); 1895 1896 // Clean up if the extension is meant to be enabled after a reload. 1897 reloading_extensions_.erase(extension->id()); 1898 1899 // Clean up runtime data. 1900 extension_runtime_data_.erase(extension_id); 1901 1902 if (disabled_extensions_.Contains(extension->id())) { 1903 disabled_extensions_.Remove(extension->id()); 1904 // Make sure the profile cleans up its RequestContexts when an already 1905 // disabled extension is unloaded (since they are also tracking the disabled 1906 // extensions). 1907 system_->UnregisterExtensionWithRequestContexts(extension_id, reason); 1908 } else { 1909 // Remove the extension from our list. 1910 extensions_.Remove(extension->id()); 1911 NotifyExtensionUnloaded(extension.get(), reason); 1912 } 1913 1914 content::NotificationService::current()->Notify( 1915 chrome::NOTIFICATION_EXTENSION_REMOVED, 1916 content::Source<Profile>(profile_), 1917 content::Details<const Extension>(extension.get())); 1918} 1919 1920void ExtensionService::RemoveComponentExtension( 1921 const std::string& extension_id) { 1922 scoped_refptr<const Extension> extension( 1923 GetExtensionById(extension_id, false)); 1924 UnloadExtension(extension_id, extension_misc::UNLOAD_REASON_UNINSTALL); 1925 content::NotificationService::current()->Notify( 1926 chrome::NOTIFICATION_EXTENSION_UNINSTALLED, 1927 content::Source<Profile>(profile_), 1928 content::Details<const Extension>(extension.get())); 1929} 1930 1931void ExtensionService::UnloadAllExtensions() { 1932 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions(); 1933 1934 extensions_.Clear(); 1935 disabled_extensions_.Clear(); 1936 terminated_extensions_.Clear(); 1937 extension_runtime_data_.clear(); 1938 1939 // TODO(erikkay) should there be a notification for this? We can't use 1940 // EXTENSION_UNLOADED since that implies that the extension has been disabled 1941 // or uninstalled, and UnloadAll is just part of shutdown. 1942} 1943 1944void ExtensionService::ReloadExtensions() { 1945 UnloadAllExtensions(); 1946 component_loader_->LoadAll(); 1947 extensions::InstalledLoader(this).LoadAllExtensions(); 1948 // Don't call SetReadyAndNotifyListeners() since tests call this multiple 1949 // times. 1950} 1951 1952void ExtensionService::GarbageCollectExtensions() { 1953#if defined(OS_CHROMEOS) 1954 if (disable_garbage_collection_) 1955 return; 1956#endif 1957 1958 if (extension_prefs_->pref_service()->ReadOnly()) 1959 return; 1960 1961 if (pending_extension_manager()->HasPendingExtensions()) { 1962 // Don't garbage collect while there are pending installations, which may 1963 // be using the temporary installation directory. Try to garbage collect 1964 // again later. 1965 base::MessageLoop::current()->PostDelayedTask( 1966 FROM_HERE, 1967 base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()), 1968 base::TimeDelta::FromSeconds(kGarbageCollectRetryDelay)); 1969 return; 1970 } 1971 1972 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> info( 1973 extension_prefs_->GetInstalledExtensionsInfo()); 1974 1975 std::multimap<std::string, base::FilePath> extension_paths; 1976 for (size_t i = 0; i < info->size(); ++i) 1977 extension_paths.insert(std::make_pair(info->at(i)->extension_id, 1978 info->at(i)->extension_path)); 1979 1980 info = extension_prefs_->GetAllDelayedInstallInfo(); 1981 for (size_t i = 0; i < info->size(); ++i) 1982 extension_paths.insert(std::make_pair(info->at(i)->extension_id, 1983 info->at(i)->extension_path)); 1984 1985 if (!GetFileTaskRunner()->PostTask( 1986 FROM_HERE, 1987 base::Bind( 1988 &extension_file_util::GarbageCollectExtensions, 1989 install_directory_, 1990 extension_paths))) { 1991 NOTREACHED(); 1992 } 1993} 1994 1995void ExtensionService::SyncExtensionChangeIfNeeded(const Extension& extension) { 1996 if (extensions::sync_helper::IsSyncableApp(&extension)) { 1997 if (app_sync_bundle_.IsSyncing()) 1998 app_sync_bundle_.SyncChangeIfNeeded(extension); 1999 else if (is_ready() && !flare_.is_null()) 2000 flare_.Run(syncer::APPS); 2001 } else if (extensions::sync_helper::IsSyncableExtension(&extension)) { 2002 if (extension_sync_bundle_.IsSyncing()) 2003 extension_sync_bundle_.SyncChangeIfNeeded(extension); 2004 else if (is_ready() && !flare_.is_null()) 2005 flare_.Run(syncer::EXTENSIONS); 2006 } 2007} 2008 2009void ExtensionService::SetReadyAndNotifyListeners() { 2010 ready_->Signal(); 2011 content::NotificationService::current()->Notify( 2012 chrome::NOTIFICATION_EXTENSIONS_READY, 2013 content::Source<Profile>(profile_), 2014 content::NotificationService::NoDetails()); 2015} 2016 2017void ExtensionService::OnLoadedInstalledExtensions() { 2018 if (updater_) 2019 updater_->Start(); 2020 2021 OnBlacklistUpdated(); 2022} 2023 2024void ExtensionService::AddExtension(const Extension* extension) { 2025 // TODO(jstritar): We may be able to get rid of this branch by overriding the 2026 // default extension state to DISABLED when the --disable-extensions flag 2027 // is set (http://crbug.com/29067). 2028 if (!extensions_enabled() && 2029 !extension->is_theme() && 2030 extension->location() != Manifest::COMPONENT && 2031 !Manifest::IsExternalLocation(extension->location())) { 2032 return; 2033 } 2034 2035 bool is_extension_upgrade = false; 2036 bool is_extension_installed = false; 2037 const Extension* old = GetInstalledExtension(extension->id()); 2038 if (old) { 2039 is_extension_installed = true; 2040 int version_compare_result = 2041 extension->version()->CompareTo(*(old->version())); 2042 is_extension_upgrade = version_compare_result > 0; 2043 // Other than for unpacked extensions, CrxInstaller should have guaranteed 2044 // that we aren't downgrading. 2045 if (!Manifest::IsUnpackedLocation(extension->location())) 2046 CHECK_GE(version_compare_result, 0); 2047 } 2048 SetBeingUpgraded(extension, is_extension_upgrade); 2049 2050 // The extension is now loaded, remove its data from unloaded extension map. 2051 unloaded_extension_paths_.erase(extension->id()); 2052 2053 // If a terminated extension is loaded, remove it from the terminated list. 2054 UntrackTerminatedExtension(extension->id()); 2055 2056 // If the extension was disabled for a reload, then enable it. 2057 bool reloading = reloading_extensions_.erase(extension->id()) > 0; 2058 2059 // Check if the extension's privileges have changed and mark the 2060 // extension disabled if necessary. 2061 CheckPermissionsIncrease(extension, is_extension_installed); 2062 2063 if (is_extension_installed && !reloading) { 2064 // To upgrade an extension in place, unload the old one and then load the 2065 // new one. ReloadExtension disables the extension, which is sufficient. 2066 UnloadExtension(extension->id(), extension_misc::UNLOAD_REASON_UPDATE); 2067 } 2068 2069 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) { 2070 // Only prefs is checked for the blacklist. We rely on callers to check the 2071 // blacklist before calling into here, e.g. CrxInstaller checks before 2072 // installation then threads through the install and pending install flow 2073 // of this class, and we check when loading installed extensions. 2074 blacklisted_extensions_.Insert(extension); 2075 } else if (!reloading && 2076 extension_prefs_->IsExtensionDisabled(extension->id())) { 2077 disabled_extensions_.Insert(extension); 2078 SyncExtensionChangeIfNeeded(*extension); 2079 content::NotificationService::current()->Notify( 2080 chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED, 2081 content::Source<Profile>(profile_), 2082 content::Details<const Extension>(extension)); 2083 2084 // Show the extension disabled error if a permissions increase was the 2085 // only reason it was disabled. 2086 if (extension_prefs_->GetDisableReasons(extension->id()) == 2087 Extension::DISABLE_PERMISSIONS_INCREASE) { 2088 extensions::AddExtensionDisabledError(this, extension); 2089 } 2090 } else if (reloading) { 2091 // Replace the old extension with the new version. 2092 CHECK(!disabled_extensions_.Insert(extension)); 2093 EnableExtension(extension->id()); 2094 } else { 2095 // All apps that are displayed in the launcher are ordered by their ordinals 2096 // so we must ensure they have valid ordinals. 2097 if (extension->RequiresSortOrdinal()) { 2098 if (!extension->ShouldDisplayInNewTabPage()) { 2099 extension_prefs_->extension_sorting()->MarkExtensionAsHidden( 2100 extension->id()); 2101 } 2102 extension_prefs_->extension_sorting()->EnsureValidOrdinals( 2103 extension->id(), syncer::StringOrdinal()); 2104 } 2105 2106 extensions_.Insert(extension); 2107 SyncExtensionChangeIfNeeded(*extension); 2108 NotifyExtensionLoaded(extension); 2109 } 2110 SetBeingUpgraded(extension, false); 2111} 2112 2113void ExtensionService::AddComponentExtension(const Extension* extension) { 2114 const std::string old_version_string( 2115 extension_prefs_->GetVersionString(extension->id())); 2116 const Version old_version(old_version_string); 2117 2118 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) { 2119 VLOG(1) << "Component extension " << extension->name() << " (" 2120 << extension->id() << ") installing/upgrading from '" 2121 << old_version_string << "' to " << extension->version()->GetString(); 2122 2123 AddNewOrUpdatedExtension(extension, 2124 Extension::ENABLED_COMPONENT, 2125 extensions::Blacklist::NOT_BLACKLISTED, 2126 syncer::StringOrdinal()); 2127 return; 2128 } 2129 2130 AddExtension(extension); 2131} 2132 2133void ExtensionService::UpdateActivePermissions(const Extension* extension) { 2134 // If the extension has used the optional permissions API, it will have a 2135 // custom set of active permissions defined in the extension prefs. Here, 2136 // we update the extension's active permissions based on the prefs. 2137 scoped_refptr<PermissionSet> active_permissions = 2138 extension_prefs()->GetActivePermissions(extension->id()); 2139 2140 if (active_permissions.get()) { 2141 // We restrict the active permissions to be within the bounds defined in the 2142 // extension's manifest. 2143 // a) active permissions must be a subset of optional + default permissions 2144 // b) active permissions must contains all default permissions 2145 scoped_refptr<PermissionSet> total_permissions = 2146 PermissionSet::CreateUnion( 2147 extensions::PermissionsData::GetRequiredPermissions(extension), 2148 extensions::PermissionsData::GetOptionalPermissions(extension)); 2149 2150 // Make sure the active permissions contain no more than optional + default. 2151 scoped_refptr<PermissionSet> adjusted_active = 2152 PermissionSet::CreateIntersection( 2153 total_permissions.get(), active_permissions.get()); 2154 2155 // Make sure the active permissions contain the default permissions. 2156 adjusted_active = PermissionSet::CreateUnion( 2157 extensions::PermissionsData::GetRequiredPermissions(extension), 2158 adjusted_active.get()); 2159 2160 extensions::PermissionsUpdater perms_updater(profile()); 2161 perms_updater.UpdateActivePermissions(extension, adjusted_active.get()); 2162 } 2163} 2164 2165void ExtensionService::CheckPermissionsIncrease(const Extension* extension, 2166 bool is_extension_installed) { 2167 UpdateActivePermissions(extension); 2168 2169 // We keep track of all permissions the user has granted each extension. 2170 // This allows extensions to gracefully support backwards compatibility 2171 // by including unknown permissions in their manifests. When the user 2172 // installs the extension, only the recognized permissions are recorded. 2173 // When the unknown permissions become recognized (e.g., through browser 2174 // upgrade), we can prompt the user to accept these new permissions. 2175 // Extensions can also silently upgrade to less permissions, and then 2176 // silently upgrade to a version that adds these permissions back. 2177 // 2178 // For example, pretend that Chrome 10 includes a permission "omnibox" 2179 // for an API that adds suggestions to the omnibox. An extension can 2180 // maintain backwards compatibility while still having "omnibox" in the 2181 // manifest. If a user installs the extension on Chrome 9, the browser 2182 // will record the permissions it recognized, not including "omnibox." 2183 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome 2184 // will disable the extension and prompt the user to approve the increase 2185 // in privileges. The extension could then release a new version that 2186 // removes the "omnibox" permission. When the user upgrades, Chrome will 2187 // still remember that "omnibox" had been granted, so that if the 2188 // extension once again includes "omnibox" in an upgrade, the extension 2189 // can upgrade without requiring this user's approval. 2190 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id()); 2191 2192 bool auto_grant_permission = 2193 (!is_extension_installed && extension->was_installed_by_default() && 2194 !extension->requires_permissions_consent()) || 2195 chrome::IsRunningInForcedAppMode(); 2196 // Silently grant all active permissions to default apps only on install. 2197 // After install they should behave like other apps. 2198 // Silently grant all active permissions to apps install in kiosk mode on both 2199 // install and update. 2200 if (auto_grant_permission) 2201 GrantPermissions(extension); 2202 2203 bool is_privilege_increase = false; 2204 // We only need to compare the granted permissions to the current permissions 2205 // if the extension is not allowed to silently increase its permissions. 2206 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) && 2207 !auto_grant_permission) { 2208 // Add all the recognized permissions if the granted permissions list 2209 // hasn't been initialized yet. 2210 scoped_refptr<PermissionSet> granted_permissions = 2211 extension_prefs_->GetGrantedPermissions(extension->id()); 2212 CHECK(granted_permissions.get()); 2213 2214 // Here, we check if an extension's privileges have increased in a manner 2215 // that requires the user's approval. This could occur because the browser 2216 // upgraded and recognized additional privileges, or an extension upgrades 2217 // to a version that requires additional privileges. 2218 is_privilege_increase = 2219 extensions::PermissionMessageProvider::Get()->IsPrivilegeIncrease( 2220 granted_permissions, 2221 extension->GetActivePermissions().get(), 2222 extension->GetType()); 2223 } 2224 2225 if (is_extension_installed) { 2226 // If the extension was already disabled, suppress any alerts for becoming 2227 // disabled on permissions increase. 2228 bool previously_disabled = 2229 extension_prefs_->IsExtensionDisabled(extension->id()); 2230 // Legacy disabled extensions do not have a disable reason. Infer that if 2231 // there was no permission increase, it was likely disabled by the user. 2232 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE && 2233 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) { 2234 disable_reasons |= Extension::DISABLE_USER_ACTION; 2235 } 2236 // Extensions that came to us disabled from sync need a similar inference, 2237 // except based on the new version's permissions. 2238 if (previously_disabled && 2239 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) { 2240 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason. 2241 extension_prefs_->ClearDisableReasons(extension->id()); 2242 if (!is_privilege_increase) 2243 disable_reasons |= Extension::DISABLE_USER_ACTION; 2244 } 2245 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC; 2246 } else if (extension->requires_permissions_consent()) { 2247 disable_reasons |= Extension::DISABLE_PERMISSIONS_CONSENT; 2248 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED); 2249 } 2250 2251 // Extension has changed permissions significantly. Disable it. A 2252 // notification should be sent by the caller. 2253 if (is_privilege_increase) { 2254 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE; 2255 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) { 2256 RecordPermissionMessagesHistogram( 2257 extension, "Extensions.Permissions_AutoDisable"); 2258 } 2259 DisableExtension(extension->id(), 2260 static_cast<Extension::DisableReason>(disable_reasons)); 2261 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true); 2262 } 2263 if (disable_reasons != Extension::DISABLE_NONE) { 2264 extension_prefs_->AddDisableReason( 2265 extension->id(), 2266 static_cast<Extension::DisableReason>(disable_reasons)); 2267 } 2268} 2269 2270void ExtensionService::UpdateActiveExtensionsInCrashReporter() { 2271 std::set<std::string> extension_ids; 2272 for (ExtensionSet::const_iterator iter = extensions_.begin(); 2273 iter != extensions_.end(); ++iter) { 2274 const Extension* extension = iter->get(); 2275 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT) 2276 extension_ids.insert(extension->id()); 2277 } 2278 2279 crash_keys::SetActiveExtensions(extension_ids); 2280} 2281 2282ExtensionService::ImportStatus ExtensionService::CheckImports( 2283 const extensions::Extension* extension, 2284 std::list<SharedModuleInfo::ImportInfo>* missing_modules, 2285 std::list<SharedModuleInfo::ImportInfo>* outdated_modules) { 2286 DCHECK(extension); 2287 DCHECK(missing_modules && missing_modules->empty()); 2288 DCHECK(outdated_modules && outdated_modules->empty()); 2289 ImportStatus status = IMPORT_STATUS_OK; 2290 if (SharedModuleInfo::ImportsModules(extension)) { 2291 const std::vector<SharedModuleInfo::ImportInfo>& imports = 2292 SharedModuleInfo::GetImports(extension); 2293 std::vector<SharedModuleInfo::ImportInfo>::const_iterator i; 2294 for (i = imports.begin(); i != imports.end(); ++i) { 2295 Version version_required(i->minimum_version); 2296 const Extension* imported_module = 2297 GetExtensionById(i->extension_id, true); 2298 if (!imported_module) { 2299 if (extension->from_webstore()) { 2300 status = IMPORT_STATUS_UNSATISFIED; 2301 missing_modules->push_back(*i); 2302 } else { 2303 return IMPORT_STATUS_UNRECOVERABLE; 2304 } 2305 } else if (!SharedModuleInfo::IsSharedModule(imported_module)) { 2306 return IMPORT_STATUS_UNRECOVERABLE; 2307 } else if (version_required.IsValid() && 2308 imported_module->version()->CompareTo(version_required) < 0) { 2309 if (imported_module->from_webstore()) { 2310 outdated_modules->push_back(*i); 2311 status = IMPORT_STATUS_UNSATISFIED; 2312 } else { 2313 return IMPORT_STATUS_UNRECOVERABLE; 2314 } 2315 } 2316 } 2317 } 2318 return status; 2319} 2320 2321ExtensionService::ImportStatus ExtensionService::SatisfyImports( 2322 const Extension* extension) { 2323 std::list<SharedModuleInfo::ImportInfo> noinstalled; 2324 std::list<SharedModuleInfo::ImportInfo> outdated; 2325 ImportStatus status = CheckImports(extension, &noinstalled, &outdated); 2326 if (status == IMPORT_STATUS_UNRECOVERABLE) 2327 return status; 2328 if (status == IMPORT_STATUS_UNSATISFIED) { 2329 std::list<SharedModuleInfo::ImportInfo>::const_iterator iter; 2330 for (iter = noinstalled.begin(); iter != noinstalled.end(); ++iter) { 2331 pending_extension_manager()->AddFromExtensionImport( 2332 iter->extension_id, 2333 extension_urls::GetWebstoreUpdateUrl(), 2334 IsSharedModule); 2335 } 2336 CheckForUpdatesSoon(); 2337 } 2338 return status; 2339} 2340 2341scoped_ptr<const ExtensionSet> 2342 ExtensionService::GetDependentExtensions(const Extension* extension) { 2343 scoped_ptr<ExtensionSet> dependents(new ExtensionSet()); 2344 scoped_ptr<ExtensionSet> set_to_check(new ExtensionSet()); 2345 if (SharedModuleInfo::IsSharedModule(extension)) { 2346 set_to_check->InsertAll(disabled_extensions_); 2347 set_to_check->InsertAll(delayed_installs_); 2348 set_to_check->InsertAll(extensions_); 2349 for (ExtensionSet::const_iterator iter = set_to_check->begin(); 2350 iter != set_to_check->end(); ++iter) { 2351 if (SharedModuleInfo::ImportsExtensionById(iter->get(), 2352 extension->id())) { 2353 dependents->Insert(*iter); 2354 } 2355 } 2356 } 2357 return dependents.PassAs<const ExtensionSet>(); 2358} 2359 2360void ExtensionService::PruneSharedModulesOnUninstall( 2361 const Extension* extension) { 2362 if (SharedModuleInfo::ImportsModules(extension)) { 2363 const std::vector<SharedModuleInfo::ImportInfo>& imports = 2364 SharedModuleInfo::GetImports(extension); 2365 std::vector<SharedModuleInfo::ImportInfo>::const_iterator i; 2366 for (i = imports.begin(); i != imports.end(); ++i) { 2367 const Extension* imported_module = 2368 GetExtensionById(i->extension_id, true); 2369 if (imported_module && imported_module->from_webstore()) { 2370 scoped_ptr<const ExtensionSet> dependents = 2371 GetDependentExtensions(imported_module); 2372 if (dependents->size() == 0) { 2373 UninstallExtension(i->extension_id, true, NULL); 2374 } 2375 } 2376 } 2377 } 2378} 2379 2380void ExtensionService::OnExtensionInstalled( 2381 const Extension* extension, 2382 const syncer::StringOrdinal& page_ordinal, 2383 bool has_requirement_errors, 2384 extensions::Blacklist::BlacklistState blacklist_state, 2385 bool wait_for_idle) { 2386 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 2387 2388 const std::string& id = extension->id(); 2389 bool initial_enable = ShouldEnableOnInstall(extension); 2390 const extensions::PendingExtensionInfo* pending_extension_info = NULL; 2391 if ((pending_extension_info = pending_extension_manager()->GetById(id))) { 2392 if (!pending_extension_info->ShouldAllowInstall(extension)) { 2393 pending_extension_manager()->Remove(id); 2394 2395 LOG(WARNING) << "ShouldAllowInstall() returned false for " 2396 << id << " of type " << extension->GetType() 2397 << " and update URL " 2398 << extensions::ManifestURL::GetUpdateURL(extension).spec() 2399 << "; not installing"; 2400 2401 // Delete the extension directory since we're not going to 2402 // load it. 2403 if (!GetFileTaskRunner()->PostTask( 2404 FROM_HERE, 2405 base::Bind(&extension_file_util::DeleteFile, 2406 extension->path(), true))) { 2407 NOTREACHED(); 2408 } 2409 return; 2410 } 2411 2412 pending_extension_manager()->Remove(id); 2413 } else { 2414 // We explicitly want to re-enable an uninstalled external 2415 // extension; if we're here, that means the user is manually 2416 // installing the extension. 2417 if (IsExternalExtensionUninstalled(id)) { 2418 initial_enable = true; 2419 } 2420 } 2421 2422 // Unsupported requirements overrides the management policy. 2423 if (has_requirement_errors) { 2424 initial_enable = false; 2425 extension_prefs_->AddDisableReason( 2426 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT); 2427 // If the extension was disabled because of unsupported requirements but 2428 // now supports all requirements after an update and there are not other 2429 // disable reasons, enable it. 2430 } else if (extension_prefs_->GetDisableReasons(id) == 2431 Extension::DISABLE_UNSUPPORTED_REQUIREMENT) { 2432 initial_enable = true; 2433 extension_prefs_->ClearDisableReasons(id); 2434 } 2435 2436 if (blacklist_state == extensions::Blacklist::BLACKLISTED) { 2437 // Installation of a blacklisted extension can happen from sync, policy, 2438 // etc, where to maintain consistency we need to install it, just never 2439 // load it (see AddExtension). Usually it should be the job of callers to 2440 // incercept blacklisted extension earlier (e.g. CrxInstaller, before even 2441 // showing the install dialogue). 2442 extension_prefs()->AcknowledgeBlacklistedExtension(id); 2443 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.SilentInstall", 2444 extension->location(), 2445 Manifest::NUM_LOCATIONS); 2446 } 2447 2448 if (!GetInstalledExtension(extension->id())) { 2449 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType", 2450 extension->GetType(), 100); 2451 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource", 2452 extension->location(), Manifest::NUM_LOCATIONS); 2453 RecordPermissionMessagesHistogram( 2454 extension, "Extensions.Permissions_Install"); 2455 } else { 2456 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType", 2457 extension->GetType(), 100); 2458 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource", 2459 extension->location(), Manifest::NUM_LOCATIONS); 2460 } 2461 2462 // Certain extension locations are specific enough that we can 2463 // auto-acknowledge any extension that came from one of them. 2464 if (Manifest::IsPolicyLocation(extension->location())) 2465 AcknowledgeExternalExtension(extension->id()); 2466 const Extension::State initial_state = 2467 initial_enable ? Extension::ENABLED : Extension::DISABLED; 2468 if (ShouldDelayExtensionUpdate(id, wait_for_idle)) { 2469 extension_prefs_->SetDelayedInstallInfo( 2470 extension, 2471 initial_state, 2472 blacklist_state, 2473 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE, 2474 page_ordinal); 2475 2476 // Transfer ownership of |extension|. 2477 delayed_installs_.Insert(extension); 2478 2479 // Notify extension of available update. 2480 extensions::RuntimeEventRouter::DispatchOnUpdateAvailableEvent( 2481 profile_, id, extension->manifest()->value()); 2482 2483 // Notify observers that app update is available. 2484 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_, 2485 OnAppUpdateAvailable(extension->id())); 2486 return; 2487 } 2488 2489 ImportStatus status = SatisfyImports(extension); 2490 if (installs_delayed_for_gc()) { 2491 extension_prefs_->SetDelayedInstallInfo( 2492 extension, 2493 initial_state, 2494 blacklist_state, 2495 extensions::ExtensionPrefs::DELAY_REASON_GC, 2496 page_ordinal); 2497 delayed_installs_.Insert(extension); 2498 } else if (status != IMPORT_STATUS_OK) { 2499 if (status == IMPORT_STATUS_UNSATISFIED) { 2500 extension_prefs_->SetDelayedInstallInfo( 2501 extension, 2502 initial_state, 2503 blacklist_state, 2504 extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS, 2505 page_ordinal); 2506 delayed_installs_.Insert(extension); 2507 } 2508 } else { 2509 AddNewOrUpdatedExtension(extension, 2510 initial_state, 2511 blacklist_state, 2512 page_ordinal); 2513 } 2514} 2515 2516void ExtensionService::AddNewOrUpdatedExtension( 2517 const Extension* extension, 2518 Extension::State initial_state, 2519 extensions::Blacklist::BlacklistState blacklist_state, 2520 const syncer::StringOrdinal& page_ordinal) { 2521 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 2522 extension_prefs_->OnExtensionInstalled(extension, 2523 initial_state, 2524 blacklist_state, 2525 page_ordinal); 2526 delayed_installs_.Remove(extension->id()); 2527 FinishInstallation(extension); 2528} 2529 2530void ExtensionService::MaybeFinishDelayedInstallation( 2531 const std::string& extension_id) { 2532 // Check if the extension already got installed. 2533 if (!delayed_installs_.Contains(extension_id)) 2534 return; 2535 extensions::ExtensionPrefs::DelayReason reason = 2536 extension_prefs_->GetDelayedInstallReason(extension_id); 2537 2538 // Check if the extension is idle. DELAY_REASON_NONE is used for older 2539 // preferences files that will not have set this field but it was previously 2540 // only used for idle updates. 2541 if ((reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IDLE || 2542 reason == extensions::ExtensionPrefs::DELAY_REASON_NONE) && 2543 is_ready() && !IsExtensionIdle(extension_id)) 2544 return; 2545 2546 const Extension* extension = delayed_installs_.GetByID(extension_id); 2547 if (reason == extensions::ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS) { 2548 ImportStatus status = SatisfyImports(extension); 2549 if (status != IMPORT_STATUS_OK) { 2550 if (status == IMPORT_STATUS_UNRECOVERABLE) { 2551 delayed_installs_.Remove(extension_id); 2552 // Make sure no version of the extension is actually installed, (i.e., 2553 // that this delayed install was not an update). 2554 CHECK(!extension_prefs_->GetInstalledExtensionInfo(extension_id).get()); 2555 extension_prefs_->DeleteExtensionPrefs(extension_id); 2556 } 2557 return; 2558 } 2559 } 2560 2561 FinishDelayedInstallation(extension_id); 2562} 2563 2564void ExtensionService::FinishDelayedInstallation( 2565 const std::string& extension_id) { 2566 scoped_refptr<const Extension> extension( 2567 GetPendingExtensionUpdate(extension_id)); 2568 CHECK(extension.get()); 2569 delayed_installs_.Remove(extension_id); 2570 2571 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id)) 2572 NOTREACHED(); 2573 2574 FinishInstallation(extension.get()); 2575} 2576 2577void ExtensionService::FinishInstallation(const Extension* extension) { 2578 const extensions::Extension* existing_extension = 2579 GetInstalledExtension(extension->id()); 2580 bool is_update = false; 2581 std::string old_name; 2582 if (existing_extension) { 2583 is_update = true; 2584 old_name = existing_extension->name(); 2585 } 2586 extensions::InstalledExtensionInfo details(extension, is_update, old_name); 2587 content::NotificationService::current()->Notify( 2588 chrome::NOTIFICATION_EXTENSION_INSTALLED, 2589 content::Source<Profile>(profile_), 2590 content::Details<const extensions::InstalledExtensionInfo>(&details)); 2591 2592 bool unacknowledged_external = IsUnacknowledgedExternalExtension(extension); 2593 2594 // Unpacked extensions default to allowing file access, but if that has been 2595 // overridden, don't reset the value. 2596 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) && 2597 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) { 2598 extension_prefs_->SetAllowFileAccess(extension->id(), true); 2599 } 2600 2601 AddExtension(extension); 2602 2603 // If this is a new external extension that was disabled, alert the user 2604 // so he can reenable it. We do this last so that it has already been 2605 // added to our list of extensions. 2606 if (unacknowledged_external && !is_update) { 2607 UpdateExternalExtensionAlert(); 2608 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent", 2609 EXTERNAL_EXTENSION_INSTALLED, 2610 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 2611 if (extensions::ManifestURL::UpdatesFromGallery(extension)) { 2612 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventWebstore", 2613 EXTERNAL_EXTENSION_INSTALLED, 2614 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 2615 } else { 2616 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEventNonWebstore", 2617 EXTERNAL_EXTENSION_INSTALLED, 2618 EXTERNAL_EXTENSION_BUCKET_BOUNDARY); 2619 } 2620 } 2621 2622 // Check extensions that may have been delayed only because this shared module 2623 // was not available. 2624 if (SharedModuleInfo::IsSharedModule(extension)) { 2625 MaybeFinishDelayedInstallations(); 2626 } 2627} 2628 2629const Extension* ExtensionService::GetPendingExtensionUpdate( 2630 const std::string& id) const { 2631 return delayed_installs_.GetByID(id); 2632} 2633 2634void ExtensionService::TrackTerminatedExtension(const Extension* extension) { 2635 if (!terminated_extensions_.Contains(extension->id())) 2636 terminated_extensions_.Insert(make_scoped_refptr(extension)); 2637 2638 UnloadExtension(extension->id(), extension_misc::UNLOAD_REASON_TERMINATE); 2639} 2640 2641void ExtensionService::UntrackTerminatedExtension(const std::string& id) { 2642 std::string lowercase_id = StringToLowerASCII(id); 2643 const Extension* extension = terminated_extensions_.GetByID(lowercase_id); 2644 terminated_extensions_.Remove(lowercase_id); 2645 if (extension) { 2646 content::NotificationService::current()->Notify( 2647 chrome::NOTIFICATION_EXTENSION_REMOVED, 2648 content::Source<Profile>(profile_), 2649 content::Details<const Extension>(extension)); 2650 } 2651} 2652 2653const Extension* ExtensionService::GetTerminatedExtension( 2654 const std::string& id) const { 2655 return GetExtensionById(id, INCLUDE_TERMINATED); 2656} 2657 2658const Extension* ExtensionService::GetInstalledExtension( 2659 const std::string& id) const { 2660 int include_mask = INCLUDE_ENABLED | 2661 INCLUDE_DISABLED | 2662 INCLUDE_TERMINATED | 2663 INCLUDE_BLACKLISTED; 2664 return GetExtensionById(id, include_mask); 2665} 2666 2667bool ExtensionService::ExtensionBindingsAllowed(const GURL& url) { 2668 // Allow bindings for all packaged extensions and component hosted apps. 2669 const Extension* extension = extensions_.GetExtensionOrAppByURL(url); 2670 return extension && (!extension->is_hosted_app() || 2671 extension->location() == Manifest::COMPONENT); 2672} 2673 2674bool ExtensionService::ShouldBlockUrlInBrowserTab(GURL* url) { 2675 const Extension* extension = extensions_.GetExtensionOrAppByURL(*url); 2676 if (extension && extension->is_platform_app()) { 2677 *url = GURL(chrome::kExtensionInvalidRequestURL); 2678 return true; 2679 } 2680 2681 return false; 2682} 2683 2684bool ExtensionService::OnExternalExtensionFileFound( 2685 const std::string& id, 2686 const Version* version, 2687 const base::FilePath& path, 2688 Manifest::Location location, 2689 int creation_flags, 2690 bool mark_acknowledged) { 2691 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 2692 CHECK(Extension::IdIsValid(id)); 2693 if (extension_prefs_->IsExternalExtensionUninstalled(id)) 2694 return false; 2695 2696 // Before even bothering to unpack, check and see if we already have this 2697 // version. This is important because these extensions are going to get 2698 // installed on every startup. 2699 const Extension* existing = GetExtensionById(id, true); 2700 2701 if (existing) { 2702 // The default apps will have the location set as INTERNAL. Since older 2703 // default apps are installed as EXTERNAL, we override them. However, if the 2704 // app is already installed as internal, then do the version check. 2705 // TODO(grv) : Remove after Q1-2013. 2706 bool is_default_apps_migration = 2707 (location == Manifest::INTERNAL && 2708 Manifest::IsExternalLocation(existing->location())); 2709 2710 if (!is_default_apps_migration) { 2711 DCHECK(version); 2712 2713 switch (existing->version()->CompareTo(*version)) { 2714 case -1: // existing version is older, we should upgrade 2715 break; 2716 case 0: // existing version is same, do nothing 2717 return false; 2718 case 1: // existing version is newer, uh-oh 2719 LOG(WARNING) << "Found external version of extension " << id 2720 << "that is older than current version. Current version " 2721 << "is: " << existing->VersionString() << ". New " 2722 << "version is: " << version->GetString() 2723 << ". Keeping current version."; 2724 return false; 2725 } 2726 } 2727 } 2728 2729 // If the extension is already pending, don't start an install. 2730 if (!pending_extension_manager()->AddFromExternalFile( 2731 id, location, *version, creation_flags, mark_acknowledged)) { 2732 return false; 2733 } 2734 2735 // no client (silent install) 2736 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(this)); 2737 installer->set_install_source(location); 2738 installer->set_expected_id(id); 2739 installer->set_expected_version(*version); 2740 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE); 2741 installer->set_creation_flags(creation_flags); 2742#if defined(OS_CHROMEOS) 2743 extensions::InstallLimiter::Get(profile_)->Add(installer, path); 2744#else 2745 installer->InstallCrx(path); 2746#endif 2747 2748 // Depending on the source, a new external extension might not need a user 2749 // notification on installation. For such extensions, mark them acknowledged 2750 // now to suppress the notification. 2751 if (mark_acknowledged) 2752 AcknowledgeExternalExtension(id); 2753 2754 return true; 2755} 2756 2757void ExtensionService::ReportExtensionLoadError( 2758 const base::FilePath& extension_path, 2759 const std::string &error, 2760 bool be_noisy) { 2761 content::NotificationService::current()->Notify( 2762 chrome::NOTIFICATION_EXTENSION_LOAD_ERROR, 2763 content::Source<Profile>(profile_), 2764 content::Details<const std::string>(&error)); 2765 2766 std::string path_str = UTF16ToUTF8(extension_path.LossyDisplayName()); 2767 string16 message = UTF8ToUTF16(base::StringPrintf( 2768 "Could not load extension from '%s'. %s", 2769 path_str.c_str(), error.c_str())); 2770 ExtensionErrorReporter::GetInstance()->ReportError(message, be_noisy); 2771} 2772 2773void ExtensionService::DidCreateRenderViewForBackgroundPage( 2774 extensions::ExtensionHost* host) { 2775 OrphanedDevTools::iterator iter = 2776 orphaned_dev_tools_.find(host->extension_id()); 2777 if (iter == orphaned_dev_tools_.end()) 2778 return; 2779 2780 iter->second->ConnectRenderViewHost(host->render_view_host()); 2781 orphaned_dev_tools_.erase(iter); 2782} 2783 2784void ExtensionService::Observe(int type, 2785 const content::NotificationSource& source, 2786 const content::NotificationDetails& details) { 2787 switch (type) { 2788 case chrome::NOTIFICATION_APP_TERMINATING: 2789 // Shutdown has started. Don't start any more extension installs. 2790 // (We cannot use ExtensionService::Shutdown() for this because it 2791 // happens too late in browser teardown.) 2792 browser_terminating_ = true; 2793 break; 2794 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: { 2795 if (profile_ != 2796 content::Source<Profile>(source).ptr()->GetOriginalProfile()) { 2797 break; 2798 } 2799 2800 extensions::ExtensionHost* host = 2801 content::Details<extensions::ExtensionHost>(details).ptr(); 2802 2803 // Mark the extension as terminated and Unload it. We want it to 2804 // be in a consistent state: either fully working or not loaded 2805 // at all, but never half-crashed. We do it in a PostTask so 2806 // that other handlers of this notification will still have 2807 // access to the Extension and ExtensionHost. 2808 base::MessageLoop::current()->PostTask( 2809 FROM_HERE, 2810 base::Bind( 2811 &ExtensionService::TrackTerminatedExtension, 2812 AsWeakPtr(), 2813 host->extension())); 2814 break; 2815 } 2816 case content::NOTIFICATION_RENDERER_PROCESS_CREATED: { 2817 content::RenderProcessHost* process = 2818 content::Source<content::RenderProcessHost>(source).ptr(); 2819 Profile* host_profile = 2820 Profile::FromBrowserContext(process->GetBrowserContext()); 2821 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile())) 2822 break; 2823 2824 // Extensions need to know the channel for API restrictions. 2825 process->Send(new ExtensionMsg_SetChannel( 2826 extensions::GetCurrentChannel())); 2827 2828 // Platform apps need to know the system font. 2829 scoped_ptr<base::DictionaryValue> fonts(new base::DictionaryValue); 2830 webui::SetFontAndTextDirection(fonts.get()); 2831 std::string font_family, font_size; 2832 fonts->GetString("fontfamily", &font_family); 2833 fonts->GetString("fontsize", &font_size); 2834 process->Send(new ExtensionMsg_SetSystemFont( 2835 font_family, font_size)); 2836 2837 // Valid extension function names, used to setup bindings in renderer. 2838 std::vector<std::string> function_names; 2839 ExtensionFunctionDispatcher::GetAllFunctionNames(&function_names); 2840 process->Send(new ExtensionMsg_SetFunctionNames(function_names)); 2841 2842 // Scripting whitelist. This is modified by tests and must be communicated 2843 // to renderers. 2844 process->Send(new ExtensionMsg_SetScriptingWhitelist( 2845 *Extension::GetScriptingWhitelist())); 2846 2847 // Loaded extensions. 2848 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions; 2849 for (ExtensionSet::const_iterator iter = extensions_.begin(); 2850 iter != extensions_.end(); ++iter) { 2851 // Renderers don't need to know about themes. 2852 if (!(*iter)->is_theme()) 2853 loaded_extensions.push_back(ExtensionMsg_Loaded_Params(iter->get())); 2854 } 2855 process->Send(new ExtensionMsg_Loaded(loaded_extensions)); 2856 break; 2857 } 2858 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: { 2859 content::RenderProcessHost* process = 2860 content::Source<content::RenderProcessHost>(source).ptr(); 2861 Profile* host_profile = 2862 Profile::FromBrowserContext(process->GetBrowserContext()); 2863 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile())) 2864 break; 2865 2866 process_map_.RemoveAllFromProcess(process->GetID()); 2867 BrowserThread::PostTask( 2868 BrowserThread::IO, FROM_HERE, 2869 base::Bind(&ExtensionInfoMap::UnregisterAllExtensionsInProcess, 2870 system_->info_map(), 2871 process->GetID())); 2872 break; 2873 } 2874 case chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED: { 2875 extensions::ExtensionHost* host = 2876 content::Details<extensions::ExtensionHost>(details).ptr(); 2877 std::string extension_id = host->extension_id(); 2878 if (delayed_installs_.Contains(extension_id)) { 2879 // We were waiting for this extension to become idle, it now might have, 2880 // so maybe finish installation. 2881 base::MessageLoop::current()->PostDelayedTask( 2882 FROM_HERE, 2883 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation, 2884 AsWeakPtr(), extension_id), 2885 base::TimeDelta::FromSeconds(kUpdateIdleDelay)); 2886 } 2887 break; 2888 } 2889 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: { 2890 // Notify extensions that chrome update is available. 2891 extensions::RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent( 2892 profile_); 2893 2894 // Notify observers that chrome update is available. 2895 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_, 2896 OnChromeUpdateAvailable()); 2897 break; 2898 } 2899 2900 default: 2901 NOTREACHED() << "Unexpected notification type."; 2902 } 2903} 2904 2905void ExtensionService::OnExtensionInstallPrefChanged() { 2906 IdentifyAlertableExtensions(); 2907 CheckManagementPolicy(); 2908} 2909 2910bool ExtensionService::HasApps() const { 2911 return !GetAppIds().empty(); 2912} 2913 2914ExtensionIdSet ExtensionService::GetAppIds() const { 2915 ExtensionIdSet result; 2916 for (ExtensionSet::const_iterator it = extensions_.begin(); 2917 it != extensions_.end(); ++it) { 2918 if ((*it)->is_app() && (*it)->location() != Manifest::COMPONENT) 2919 result.insert((*it)->id()); 2920 } 2921 2922 return result; 2923} 2924 2925bool ExtensionService::IsBackgroundPageReady(const Extension* extension) const { 2926 if (!extensions::BackgroundInfo::HasPersistentBackgroundPage(extension)) 2927 return true; 2928 ExtensionRuntimeDataMap::const_iterator it = 2929 extension_runtime_data_.find(extension->id()); 2930 return it == extension_runtime_data_.end() ? false : 2931 it->second.background_page_ready; 2932} 2933 2934void ExtensionService::SetBackgroundPageReady(const Extension* extension) { 2935 DCHECK(extensions::BackgroundInfo::HasBackgroundPage(extension)); 2936 extension_runtime_data_[extension->id()].background_page_ready = true; 2937 content::NotificationService::current()->Notify( 2938 chrome::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY, 2939 content::Source<const Extension>(extension), 2940 content::NotificationService::NoDetails()); 2941} 2942 2943bool ExtensionService::IsBeingUpgraded(const Extension* extension) const { 2944 ExtensionRuntimeDataMap::const_iterator it = 2945 extension_runtime_data_.find(extension->id()); 2946 return it == extension_runtime_data_.end() ? false : 2947 it->second.being_upgraded; 2948} 2949 2950void ExtensionService::SetBeingUpgraded(const Extension* extension, 2951 bool value) { 2952 extension_runtime_data_[extension->id()].being_upgraded = value; 2953} 2954 2955bool ExtensionService::IsBeingReloaded( 2956 const std::string& extension_id) const { 2957 return ContainsKey(extensions_being_reloaded_, extension_id); 2958} 2959 2960void ExtensionService::SetBeingReloaded(const std::string& extension_id, 2961 bool isBeingReloaded) { 2962 if (isBeingReloaded) 2963 extensions_being_reloaded_.insert(extension_id); 2964 else 2965 extensions_being_reloaded_.erase(extension_id); 2966} 2967 2968bool ExtensionService::HasUsedWebRequest(const Extension* extension) const { 2969 ExtensionRuntimeDataMap::const_iterator it = 2970 extension_runtime_data_.find(extension->id()); 2971 return it == extension_runtime_data_.end() ? false : 2972 it->second.has_used_webrequest; 2973} 2974 2975void ExtensionService::SetHasUsedWebRequest(const Extension* extension, 2976 bool value) { 2977 extension_runtime_data_[extension->id()].has_used_webrequest = value; 2978} 2979 2980bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) { 2981 // Extensions installed by policy can't be disabled. So even if a previous 2982 // installation disabled the extension, make sure it is now enabled. 2983 if (system_->management_policy()->MustRemainEnabled(extension, NULL)) 2984 return true; 2985 2986 if (extension_prefs_->IsExtensionDisabled(extension->id())) 2987 return false; 2988 2989 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) { 2990 // External extensions are initially disabled. We prompt the user before 2991 // enabling them. Hosted apps are excepted because they are not dangerous 2992 // (they need to be launched by the user anyway). 2993 if (extension->GetType() != Manifest::TYPE_HOSTED_APP && 2994 Manifest::IsExternalLocation(extension->location()) && 2995 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) { 2996 return false; 2997 } 2998 } 2999 3000 return true; 3001} 3002 3003bool ExtensionService::IsExtensionIdle(const std::string& extension_id) const { 3004 ExtensionProcessManager* process_manager = system_->process_manager(); 3005 DCHECK(process_manager); 3006 extensions::ExtensionHost* host = 3007 process_manager->GetBackgroundHostForExtension(extension_id); 3008 if (host) 3009 return false; 3010 return process_manager->GetRenderViewHostsForExtension(extension_id).empty(); 3011} 3012 3013bool ExtensionService::ShouldDelayExtensionUpdate( 3014 const std::string& extension_id, 3015 bool wait_for_idle) const { 3016 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable"; 3017 3018 // If delayed updates are globally disabled, or just for this extension, 3019 // don't delay. 3020 if (!install_updates_when_idle_ || !wait_for_idle) 3021 return false; 3022 3023 const Extension* old = GetInstalledExtension(extension_id); 3024 // If there is no old extension, this is not an update, so don't delay. 3025 if (!old) 3026 return false; 3027 3028 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) { 3029 // Delay installation if the extension listens for the onUpdateAvailable 3030 // event. 3031 return system_->event_router()->ExtensionHasEventListener( 3032 extension_id, kOnUpdateAvailableEvent); 3033 } else { 3034 // Delay installation if the extension is not idle. 3035 return !IsExtensionIdle(extension_id); 3036 } 3037} 3038 3039void ExtensionService::GarbageCollectIsolatedStorage() { 3040 scoped_ptr<base::hash_set<base::FilePath> > active_paths( 3041 new base::hash_set<base::FilePath>()); 3042 for (ExtensionSet::const_iterator it = extensions_.begin(); 3043 it != extensions_.end(); ++it) { 3044 if (extensions::AppIsolationInfo::HasIsolatedStorage(it->get())) { 3045 active_paths->insert(BrowserContext::GetStoragePartitionForSite( 3046 profile_, GetSiteForExtensionId((*it)->id()))->GetPath()); 3047 } 3048 } 3049 3050 DCHECK(!installs_delayed_for_gc()); 3051 set_installs_delayed_for_gc(true); 3052 BrowserContext::GarbageCollectStoragePartitions( 3053 profile_, active_paths.Pass(), 3054 base::Bind(&ExtensionService::OnGarbageCollectIsolatedStorageFinished, 3055 AsWeakPtr())); 3056} 3057 3058void ExtensionService::OnGarbageCollectIsolatedStorageFinished() { 3059 set_installs_delayed_for_gc(false); 3060 MaybeFinishDelayedInstallations(); 3061} 3062 3063void ExtensionService::MaybeFinishDelayedInstallations() { 3064 std::vector<std::string> to_be_installed; 3065 for (ExtensionSet::const_iterator it = delayed_installs_.begin(); 3066 it != delayed_installs_.end(); 3067 ++it) { 3068 to_be_installed.push_back((*it)->id()); 3069 } 3070 for (std::vector<std::string>::const_iterator it = to_be_installed.begin(); 3071 it != to_be_installed.end(); 3072 ++it) { 3073 MaybeFinishDelayedInstallation(*it); 3074 } 3075} 3076 3077void ExtensionService::OnNeedsToGarbageCollectIsolatedStorage() { 3078 extension_prefs_->SetNeedsStorageGarbageCollection(true); 3079} 3080 3081void ExtensionService::OnBlacklistUpdated() { 3082 blacklist_->GetBlacklistedIDs( 3083 GenerateInstalledExtensionsSet()->GetIDs(), 3084 base::Bind(&ExtensionService::ManageBlacklist, AsWeakPtr())); 3085} 3086 3087void ExtensionService::ManageBlacklist(const std::set<std::string>& updated) { 3088 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); 3089 3090 std::set<std::string> before = blacklisted_extensions_.GetIDs(); 3091 std::set<std::string> no_longer_blacklisted = 3092 base::STLSetDifference<std::set<std::string> >(before, updated); 3093 std::set<std::string> not_yet_blacklisted = 3094 base::STLSetDifference<std::set<std::string> >(updated, before); 3095 3096 for (std::set<std::string>::iterator it = no_longer_blacklisted.begin(); 3097 it != no_longer_blacklisted.end(); ++it) { 3098 scoped_refptr<const Extension> extension = 3099 blacklisted_extensions_.GetByID(*it); 3100 if (!extension.get()) { 3101 NOTREACHED() << "Extension " << *it << " no longer blacklisted, " 3102 << "but it was never blacklisted."; 3103 continue; 3104 } 3105 blacklisted_extensions_.Remove(*it); 3106 extension_prefs_->SetExtensionBlacklisted(extension->id(), false); 3107 AddExtension(extension.get()); 3108 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled", 3109 extension->location(), 3110 Manifest::NUM_LOCATIONS); 3111 } 3112 3113 for (std::set<std::string>::iterator it = not_yet_blacklisted.begin(); 3114 it != not_yet_blacklisted.end(); ++it) { 3115 scoped_refptr<const Extension> extension = GetInstalledExtension(*it); 3116 if (!extension.get()) { 3117 NOTREACHED() << "Extension " << *it << " needs to be " 3118 << "blacklisted, but it's not installed."; 3119 continue; 3120 } 3121 blacklisted_extensions_.Insert(extension); 3122 extension_prefs_->SetExtensionBlacklisted(extension->id(), true); 3123 UnloadExtension(*it, extension_misc::UNLOAD_REASON_BLACKLIST); 3124 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled", 3125 extension->location(), Manifest::NUM_LOCATIONS); 3126 } 3127 3128 IdentifyAlertableExtensions(); 3129} 3130 3131void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) { 3132 update_observers_.AddObserver(observer); 3133} 3134 3135void ExtensionService::RemoveUpdateObserver( 3136 extensions::UpdateObserver* observer) { 3137 update_observers_.RemoveObserver(observer); 3138} 3139