Remove unused field from extension_sorting.cc
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service.cc
blobc08866d6bcc7749963cd65fe9a1f1fedde5f80d1
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/extension_service.h"
7 #include <algorithm>
8 #include <iterator>
9 #include <set>
11 #include "base/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.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/devtools/devtools_window.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/browser_event_router.h"
40 #include "chrome/browser/extensions/component_loader.h"
41 #include "chrome/browser/extensions/crx_installer.h"
42 #include "chrome/browser/extensions/data_deleter.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/external_install_ui.h"
54 #include "chrome/browser/extensions/external_provider_impl.h"
55 #include "chrome/browser/extensions/external_provider_interface.h"
56 #include "chrome/browser/extensions/installed_loader.h"
57 #include "chrome/browser/extensions/lazy_background_task_queue.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/platform_app_launcher.h"
62 #include "chrome/browser/extensions/shell_window_registry.h"
63 #include "chrome/browser/extensions/unpacked_installer.h"
64 #include "chrome/browser/extensions/update_observer.h"
65 #include "chrome/browser/extensions/updater/extension_updater.h"
66 #include "chrome/browser/profiles/profile.h"
67 #include "chrome/browser/profiles/profile_manager.h"
68 #include "chrome/browser/themes/theme_service.h"
69 #include "chrome/browser/themes/theme_service_factory.h"
70 #include "chrome/browser/ui/webui/favicon_source.h"
71 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
72 #include "chrome/browser/ui/webui/theme_source.h"
73 #include "chrome/common/child_process_logging.h"
74 #include "chrome/common/chrome_notification_types.h"
75 #include "chrome/common/chrome_switches.h"
76 #include "chrome/common/chrome_version_info.h"
77 #include "chrome/common/extensions/background_info.h"
78 #include "chrome/common/extensions/extension.h"
79 #include "chrome/common/extensions/extension_file_util.h"
80 #include "chrome/common/extensions/extension_manifest_constants.h"
81 #include "chrome/common/extensions/extension_messages.h"
82 #include "chrome/common/extensions/feature_switch.h"
83 #include "chrome/common/extensions/features/feature.h"
84 #include "chrome/common/extensions/incognito_handler.h"
85 #include "chrome/common/extensions/manifest.h"
86 #include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
87 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
88 #include "chrome/common/extensions/manifest_url_handler.h"
89 #include "chrome/common/extensions/permissions/permissions_data.h"
90 #include "chrome/common/extensions/sync_helper.h"
91 #include "chrome/common/pref_names.h"
92 #include "chrome/common/startup_metric_utils.h"
93 #include "chrome/common/url_constants.h"
94 #include "content/public/browser/browser_thread.h"
95 #include "content/public/browser/devtools_agent_host.h"
96 #include "content/public/browser/notification_service.h"
97 #include "content/public/browser/notification_types.h"
98 #include "content/public/browser/render_process_host.h"
99 #include "content/public/browser/site_instance.h"
100 #include "content/public/browser/storage_partition.h"
101 #include "content/public/browser/url_data_source.h"
102 #include "extensions/common/constants.h"
103 #include "extensions/common/error_utils.h"
104 #include "googleurl/src/gurl.h"
105 #include "grit/generated_resources.h"
106 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
107 #include "sync/api/sync_change.h"
108 #include "sync/api/sync_error_factory.h"
109 #include "ui/webui/web_ui_util.h"
110 #include "webkit/browser/database/database_tracker.h"
111 #include "webkit/browser/database/database_util.h"
113 #if defined(OS_CHROMEOS)
114 #include "chrome/browser/chromeos/extensions/install_limiter.h"
115 #include "webkit/browser/fileapi/file_system_context.h"
116 #include "webkit/browser/fileapi/file_system_mount_point_provider.h"
117 #endif
119 using content::BrowserContext;
120 using content::BrowserThread;
121 using content::DevToolsAgentHost;
122 using extensions::CrxInstaller;
123 using extensions::Extension;
124 using extensions::ExtensionIdSet;
125 using extensions::ExtensionInfo;
126 using extensions::FeatureSwitch;
127 using extensions::Manifest;
128 using extensions::PermissionMessage;
129 using extensions::PermissionMessages;
130 using extensions::PermissionSet;
131 using extensions::UnloadedExtensionInfo;
133 namespace errors = extension_manifest_errors;
135 namespace {
137 // Histogram values for logging events related to externally installed
138 // extensions.
139 enum ExternalExtensionEvent {
140 EXTERNAL_EXTENSION_INSTALLED = 0,
141 EXTERNAL_EXTENSION_IGNORED,
142 EXTERNAL_EXTENSION_REENABLED,
143 EXTERNAL_EXTENSION_UNINSTALLED,
144 EXTERNAL_EXTENSION_BUCKET_BOUNDARY,
147 // Prompt the user this many times before considering an extension acknowledged.
148 static const int kMaxExtensionAcknowledgePromptCount = 3;
150 // Wait this many seconds after an extensions becomes idle before updating it.
151 static const int kUpdateIdleDelay = 5;
153 // Wait this many seconds before trying to garbage collect extensions again.
154 static const int kGarbageCollectRetryDelay = 30;
156 // Wait this many seconds after startup to see if there are any extensions
157 // which can be garbage collected.
158 static const int kGarbageCollectStartupDelay = 30;
160 } // namespace
162 ExtensionService::ExtensionRuntimeData::ExtensionRuntimeData()
163 : background_page_ready(false),
164 being_upgraded(false),
165 has_used_webrequest(false) {
168 ExtensionService::ExtensionRuntimeData::~ExtensionRuntimeData() {
171 // ExtensionService.
173 const char ExtensionService::kLocalAppSettingsDirectoryName[] =
174 "Local App Settings";
175 const char ExtensionService::kLocalExtensionSettingsDirectoryName[] =
176 "Local Extension Settings";
177 const char ExtensionService::kSyncAppSettingsDirectoryName[] =
178 "Sync App Settings";
179 const char ExtensionService::kSyncExtensionSettingsDirectoryName[] =
180 "Sync Extension Settings";
181 const char ExtensionService::kManagedSettingsDirectoryName[] =
182 "Managed Extension Settings";
183 const char ExtensionService::kStateStoreName[] = "Extension State";
184 const char ExtensionService::kRulesStoreName[] = "Extension Rules";
186 void ExtensionService::CheckExternalUninstall(const std::string& id) {
187 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
189 // Check if the providers know about this extension.
190 extensions::ProviderCollection::const_iterator i;
191 for (i = external_extension_providers_.begin();
192 i != external_extension_providers_.end(); ++i) {
193 DCHECK(i->get()->IsReady());
194 if (i->get()->HasExtension(id))
195 return; // Yup, known extension, don't uninstall.
198 // We get the list of external extensions to check from preferences.
199 // It is possible that an extension has preferences but is not loaded.
200 // For example, an extension that requires experimental permissions
201 // will not be loaded if the experimental command line flag is not used.
202 // In this case, do not uninstall.
203 if (!GetInstalledExtension(id)) {
204 // We can't call UninstallExtension with an unloaded/invalid
205 // extension ID.
206 LOG(WARNING) << "Attempted uninstallation of unloaded/invalid extension "
207 << "with id: " << id;
208 return;
210 UninstallExtension(id, true, NULL);
213 void ExtensionService::SetFileTaskRunnerForTesting(
214 base::SequencedTaskRunner* task_runner) {
215 file_task_runner_ = task_runner;
218 void ExtensionService::ClearProvidersForTesting() {
219 external_extension_providers_.clear();
222 void ExtensionService::AddProviderForTesting(
223 extensions::ExternalProviderInterface* test_provider) {
224 CHECK(test_provider);
225 external_extension_providers_.push_back(
226 linked_ptr<extensions::ExternalProviderInterface>(test_provider));
229 bool ExtensionService::OnExternalExtensionUpdateUrlFound(
230 const std::string& id,
231 const GURL& update_url,
232 Manifest::Location location) {
233 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
234 CHECK(Extension::IdIsValid(id));
236 const Extension* extension = GetExtensionById(id, true);
237 if (extension) {
238 // Already installed. Skip this install if the current location has
239 // higher priority than |location|.
240 Manifest::Location current = extension->location();
241 if (current == Manifest::GetHigherPriorityLocation(current, location))
242 return false;
243 // Otherwise, overwrite the current installation.
246 // Add |id| to the set of pending extensions. If it can not be added,
247 // then there is already a pending record from a higher-priority install
248 // source. In this case, signal that this extension will not be
249 // installed by returning false.
250 if (!pending_extension_manager()->AddFromExternalUpdateUrl(
251 id, update_url, location)) {
252 return false;
255 update_once_all_providers_are_ready_ = true;
256 return true;
259 const Extension* ExtensionService::GetInstalledApp(const GURL& url) const {
260 const Extension* extension = extensions_.GetExtensionOrAppByURL(
261 ExtensionURLInfo(url));
262 return (extension && extension->is_app()) ? extension : NULL;
265 bool ExtensionService::IsInstalledApp(const GURL& url) const {
266 return !!GetInstalledApp(url);
269 const Extension* ExtensionService::GetIsolatedAppForRenderer(
270 int renderer_child_id) const {
271 std::set<std::string> extension_ids =
272 process_map_.GetExtensionsInProcess(renderer_child_id);
273 // All apps in one process share the same partition.
274 // It is only possible for the app to have isolated storage
275 // if there is only 1 app in the process.
276 if (extension_ids.size() != 1)
277 return NULL;
279 const extensions::Extension* extension =
280 extensions_.GetByID(*(extension_ids.begin()));
281 // We still need to check if the extension has isolated storage,
282 // because it's common for there to be one extension in a process
283 // without isolated storage.
284 if (extension &&
285 extensions::AppIsolationInfo::HasIsolatedStorage(extension))
286 return extension;
288 return NULL;
291 // static
292 // This function is used to implement the command-line switch
293 // --uninstall-extension, and to uninstall an extension via sync. The LOG
294 // statements within this function are used to inform the user if the uninstall
295 // cannot be done.
296 bool ExtensionService::UninstallExtensionHelper(
297 ExtensionService* extensions_service,
298 const std::string& extension_id) {
299 // We can't call UninstallExtension with an invalid extension ID.
300 if (!extensions_service->GetInstalledExtension(extension_id)) {
301 LOG(WARNING) << "Attempted uninstallation of non-existent extension with "
302 << "id: " << extension_id;
303 return false;
306 // The following call to UninstallExtension will not allow an uninstall of a
307 // policy-controlled extension.
308 string16 error;
309 if (!extensions_service->UninstallExtension(extension_id, false, &error)) {
310 LOG(WARNING) << "Cannot uninstall extension with id " << extension_id
311 << ": " << error;
312 return false;
315 return true;
318 ExtensionService::ExtensionService(Profile* profile,
319 const CommandLine* command_line,
320 const base::FilePath& install_directory,
321 extensions::ExtensionPrefs* extension_prefs,
322 extensions::Blacklist* blacklist,
323 bool autoupdate_enabled,
324 bool extensions_enabled,
325 extensions::OneShotEvent* ready)
326 : extensions::Blacklist::Observer(blacklist),
327 profile_(profile),
328 system_(extensions::ExtensionSystem::Get(profile)),
329 extension_prefs_(extension_prefs),
330 blacklist_(blacklist),
331 settings_frontend_(extensions::SettingsFrontend::Create(profile)),
332 pending_extension_manager_(*this),
333 install_directory_(install_directory),
334 extensions_enabled_(extensions_enabled),
335 show_extensions_prompts_(true),
336 install_updates_when_idle_(true),
337 ready_(ready),
338 toolbar_model_(this),
339 menu_manager_(profile),
340 event_routers_initialized_(false),
341 update_once_all_providers_are_ready_(false),
342 browser_terminating_(false),
343 installs_delayed_(false),
344 is_first_run_(false),
345 app_sync_bundle_(this),
346 extension_sync_bundle_(this) {
347 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
349 // Figure out if extension installation should be enabled.
350 if (command_line->HasSwitch(switches::kDisableExtensions) ||
351 profile->GetPrefs()->GetBoolean(prefs::kDisableExtensions)) {
352 extensions_enabled_ = false;
355 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
356 content::NotificationService::AllBrowserContextsAndSources());
357 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
358 content::NotificationService::AllBrowserContextsAndSources());
359 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED,
360 content::NotificationService::AllBrowserContextsAndSources());
361 registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
362 content::NotificationService::AllBrowserContextsAndSources());
363 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED,
364 content::NotificationService::AllBrowserContextsAndSources());
365 registrar_.Add(this, chrome::NOTIFICATION_UPGRADE_RECOMMENDED,
366 content::NotificationService::AllBrowserContextsAndSources());
367 pref_change_registrar_.Init(profile->GetPrefs());
368 base::Closure callback =
369 base::Bind(&ExtensionService::OnExtensionInstallPrefChanged,
370 base::Unretained(this));
371 pref_change_registrar_.Add(prefs::kExtensionInstallAllowList, callback);
372 pref_change_registrar_.Add(prefs::kExtensionInstallDenyList, callback);
373 pref_change_registrar_.Add(prefs::kExtensionAllowedTypes, callback);
375 // Set up the ExtensionUpdater
376 if (autoupdate_enabled) {
377 int update_frequency = kDefaultUpdateFrequencySeconds;
378 if (command_line->HasSwitch(switches::kExtensionsUpdateFrequency)) {
379 base::StringToInt(command_line->GetSwitchValueASCII(
380 switches::kExtensionsUpdateFrequency),
381 &update_frequency);
383 updater_.reset(new extensions::ExtensionUpdater(this,
384 extension_prefs,
385 profile->GetPrefs(),
386 profile,
387 blacklist,
388 update_frequency));
391 component_loader_.reset(
392 new extensions::ComponentLoader(this,
393 profile->GetPrefs(),
394 g_browser_process->local_state()));
396 if (extensions_enabled_) {
397 extensions::ExternalProviderImpl::CreateExternalProviders(
398 this, profile_, &external_extension_providers_);
401 // Set this as the ExtensionService for extension sorting to ensure it
402 // cause syncs if required.
403 extension_prefs_->extension_sorting()->SetExtensionService(this);
405 is_first_run_ = !extension_prefs_->SetAlertSystemFirstRun();
407 #if defined(ENABLE_EXTENSIONS)
408 extension_action_storage_manager_.reset(
409 new extensions::ExtensionActionStorageManager(profile_));
410 #endif
412 // How long is the path to the Extensions directory?
413 UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions.ExtensionRootPathLength",
414 install_directory_.value().length(), 0, 500, 100);
417 const ExtensionSet* ExtensionService::extensions() const {
418 return &extensions_;
421 const ExtensionSet* ExtensionService::disabled_extensions() const {
422 return &disabled_extensions_;
425 const ExtensionSet* ExtensionService::terminated_extensions() const {
426 return &terminated_extensions_;
429 const ExtensionSet* ExtensionService::blacklisted_extensions() const {
430 return &blacklisted_extensions_;
433 scoped_ptr<const ExtensionSet>
434 ExtensionService::GenerateInstalledExtensionsSet() const {
435 scoped_ptr<ExtensionSet> installed_extensions(new ExtensionSet());
436 installed_extensions->InsertAll(extensions_);
437 installed_extensions->InsertAll(disabled_extensions_);
438 installed_extensions->InsertAll(terminated_extensions_);
439 installed_extensions->InsertAll(blacklisted_extensions_);
440 return installed_extensions.PassAs<const ExtensionSet>();
443 extensions::PendingExtensionManager*
444 ExtensionService::pending_extension_manager() {
445 return &pending_extension_manager_;
448 ExtensionService::~ExtensionService() {
449 // No need to unload extensions here because they are profile-scoped, and the
450 // profile is in the process of being deleted.
452 extensions::ProviderCollection::const_iterator i;
453 for (i = external_extension_providers_.begin();
454 i != external_extension_providers_.end(); ++i) {
455 extensions::ExternalProviderInterface* provider = i->get();
456 provider->ServiceShutdown();
460 void ExtensionService::InitEventRoutersAfterImport() {
461 RegisterForImportFinished();
464 void ExtensionService::RegisterForImportFinished() {
465 if (!registrar_.IsRegistered(this, chrome::NOTIFICATION_IMPORT_FINISHED,
466 content::Source<Profile>(profile_))) {
467 registrar_.Add(this, chrome::NOTIFICATION_IMPORT_FINISHED,
468 content::Source<Profile>(profile_));
472 void ExtensionService::InitAfterImport() {
473 startup_metric_utils::ScopedSlowStartupUMA
474 scoped_timer("Startup.SlowStartupExtensionServiceInitAfterImport");
475 component_loader_->LoadAll();
477 CheckForExternalUpdates();
479 GarbageCollectExtensions();
481 // Idempotent, so although there is a possible race if the import
482 // process finished sometime in the middle of ProfileImpl::InitExtensions,
483 // it cannot happen twice.
484 InitEventRouters();
487 void ExtensionService::InitEventRouters() {
488 if (event_routers_initialized_)
489 return;
491 #if defined(ENABLE_EXTENSIONS)
492 browser_event_router_.reset(new extensions::BrowserEventRouter(profile_));
493 #endif // defined(ENABLE_EXTENSIONS)
494 event_routers_initialized_ = true;
497 void ExtensionService::Shutdown() {
498 // Do nothing for now.
501 const Extension* ExtensionService::GetExtensionById(
502 const std::string& id, bool include_disabled) const {
503 int include_mask = INCLUDE_ENABLED;
504 if (include_disabled) {
505 // Include blacklisted extensions here because there are hundreds of
506 // callers of this function, and many might assume that this includes those
507 // that have been disabled due to blacklisting.
508 include_mask |= INCLUDE_DISABLED | INCLUDE_BLACKLISTED;
510 return GetExtensionById(id, include_mask);
513 GURL ExtensionService::GetSiteForExtensionId(const std::string& extension_id) {
514 return content::SiteInstance::GetSiteForURL(
515 profile_,
516 Extension::GetBaseURLFromExtensionId(extension_id));
519 const Extension* ExtensionService::GetExtensionById(
520 const std::string& id, int include_mask) const {
521 std::string lowercase_id = StringToLowerASCII(id);
522 if (include_mask & INCLUDE_ENABLED) {
523 const Extension* extension = extensions_.GetByID(lowercase_id);
524 if (extension)
525 return extension;
527 if (include_mask & INCLUDE_DISABLED) {
528 const Extension* extension = disabled_extensions_.GetByID(lowercase_id);
529 if (extension)
530 return extension;
532 if (include_mask & INCLUDE_TERMINATED) {
533 const Extension* extension = terminated_extensions_.GetByID(lowercase_id);
534 if (extension)
535 return extension;
537 if (include_mask & INCLUDE_BLACKLISTED) {
538 const Extension* extension = blacklisted_extensions_.GetByID(lowercase_id);
539 if (extension)
540 return extension;
542 return NULL;
545 void ExtensionService::Init() {
546 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
548 DCHECK(!is_ready()); // Can't redo init.
549 DCHECK_EQ(extensions_.size(), 0u);
551 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
552 if (cmd_line->HasSwitch(switches::kInstallFromWebstore) ||
553 cmd_line->HasSwitch(switches::kLimitedInstallFromWebstore)) {
554 // The sole purpose of this launch is to install a new extension from CWS
555 // and immediately terminate: loading already installed extensions is
556 // unnecessary and may interfere with the inline install dialog (e.g. if an
557 // extension listens to onStartup and opens a window).
558 SetReadyAndNotifyListeners();
559 } else {
560 // TODO(mek): It might be cleaner to do the FinishDelayedInstallInfo stuff
561 // here instead of in installedloader.
562 if (g_browser_process->profile_manager() &&
563 g_browser_process->profile_manager()->will_import()) {
564 // Do not load any component extensions, since they may conflict with the
565 // import process.
567 extensions::InstalledLoader(this).LoadAllExtensions();
568 SetReadyAndNotifyListeners();
569 RegisterForImportFinished();
570 } else {
571 // In this case, LoadAllExtensions() calls OnLoadedInstalledExtensions().
572 component_loader_->LoadAll();
573 extensions::InstalledLoader(this).LoadAllExtensions();
574 SetReadyAndNotifyListeners();
576 // TODO(erikkay) this should probably be deferred to a future point
577 // rather than running immediately at startup.
578 CheckForExternalUpdates();
580 base::MessageLoop::current()->PostDelayedTask(
581 FROM_HERE,
582 base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
583 base::TimeDelta::FromSeconds(kGarbageCollectStartupDelay));
586 if (extension_prefs_->NeedsStorageGarbageCollection()) {
587 GarbageCollectIsolatedStorage();
588 extension_prefs_->SetNeedsStorageGarbageCollection(false);
593 bool ExtensionService::UpdateExtension(const std::string& id,
594 const base::FilePath& extension_path,
595 const GURL& download_url,
596 CrxInstaller** out_crx_installer) {
597 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
598 if (browser_terminating_) {
599 LOG(WARNING) << "Skipping UpdateExtension due to browser shutdown";
600 // Leak the temp file at extension_path. We don't want to add to the disk
601 // I/O burden at shutdown, we can't rely on the I/O completing anyway, and
602 // the file is in the OS temp directory which should be cleaned up for us.
603 return false;
606 const extensions::PendingExtensionInfo* pending_extension_info =
607 pending_extension_manager()->GetById(id);
609 const Extension* extension = GetInstalledExtension(id);
610 if (!pending_extension_info && !extension) {
611 LOG(WARNING) << "Will not update extension " << id
612 << " because it is not installed or pending";
613 // Delete extension_path since we're not creating a CrxInstaller
614 // that would do it for us.
615 if (!GetFileTaskRunner()->PostTask(
616 FROM_HERE,
617 base::Bind(
618 &extension_file_util::DeleteFile, extension_path, false)))
619 NOTREACHED();
621 return false;
624 // We want a silent install only for non-pending extensions and
625 // pending extensions that have install_silently set.
626 ExtensionInstallPrompt* client = NULL;
627 if (pending_extension_info && !pending_extension_info->install_silently())
628 client = ExtensionInstallUI::CreateInstallPromptWithProfile(profile_);
630 scoped_refptr<CrxInstaller> installer(CrxInstaller::Create(this, client));
631 installer->set_expected_id(id);
632 if (pending_extension_info) {
633 installer->set_install_source(pending_extension_info->install_source());
634 if (pending_extension_info->install_silently())
635 installer->set_allow_silent_install(true);
636 } else if (extension) {
637 installer->set_install_source(extension->location());
639 // If the extension was installed from or has migrated to the webstore, or
640 // its auto-update URL is from the webstore, treat it as a webstore install.
641 // Note that we ignore some older extensions with blank auto-update URLs
642 // because we are mostly concerned with restrictions on NaCl extensions,
643 // which are newer.
644 int creation_flags = Extension::NO_FLAGS;
645 if ((extension && extension->from_webstore()) ||
646 (extension && extensions::ManifestURL::UpdatesFromGallery(extension)) ||
647 (!extension && extension_urls::IsWebstoreUpdateUrl(
648 pending_extension_info->update_url()))) {
649 creation_flags |= Extension::FROM_WEBSTORE;
652 // Bookmark apps being updated is kind of a contradiction, but that's because
653 // we mark the default apps as bookmark apps, and they're hosted in the web
654 // store, thus they can get updated. See http://crbug.com/101605 for more
655 // details.
656 if (extension && extension->from_bookmark())
657 creation_flags |= Extension::FROM_BOOKMARK;
659 if (extension && extension->was_installed_by_default())
660 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
662 installer->set_creation_flags(creation_flags);
664 installer->set_delete_source(true);
665 installer->set_download_url(download_url);
666 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
667 installer->InstallCrx(extension_path);
669 if (out_crx_installer)
670 *out_crx_installer = installer.get();
672 return true;
675 void ExtensionService::ReloadExtension(const std::string& extension_id) {
676 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
678 // If the extension is already reloading, don't reload again.
679 if (extension_prefs_->GetDisableReasons(extension_id) &
680 Extension::DISABLE_RELOAD) {
681 return;
684 base::FilePath path;
685 const Extension* current_extension = GetExtensionById(extension_id, false);
687 // Disable the extension if it's loaded. It might not be loaded if it crashed.
688 if (current_extension) {
689 // If the extension has an inspector open for its background page, detach
690 // the inspector and hang onto a cookie for it, so that we can reattach
691 // later.
692 // TODO(yoz): this is not incognito-safe!
693 ExtensionProcessManager* manager = system_->process_manager();
694 extensions::ExtensionHost* host =
695 manager->GetBackgroundHostForExtension(extension_id);
696 if (host && DevToolsAgentHost::HasFor(host->render_view_host())) {
697 // Look for an open inspector for the background page.
698 std::string devtools_cookie = DevToolsAgentHost::DisconnectRenderViewHost(
699 host->render_view_host());
700 if (devtools_cookie != std::string())
701 orphaned_dev_tools_[extension_id] = devtools_cookie;
704 path = current_extension->path();
705 DisableExtension(extension_id, Extension::DISABLE_RELOAD);
706 reloading_extensions_.insert(extension_id);
707 } else {
708 path = unloaded_extension_paths_[extension_id];
711 if (delayed_updates_for_idle_.Contains(extension_id)) {
712 FinishDelayedInstallation(extension_id);
713 return;
716 // If we're reloading a component extension, use the component extension
717 // loader's reloader.
718 if (component_loader_->Exists(extension_id)) {
719 component_loader_->Reload(extension_id);
720 return;
723 // Check the installed extensions to see if what we're reloading was already
724 // installed.
725 scoped_ptr<ExtensionInfo> installed_extension(
726 extension_prefs_->GetInstalledExtensionInfo(extension_id));
727 if (installed_extension.get() &&
728 installed_extension->extension_manifest.get()) {
729 extensions::InstalledLoader(this).Load(*installed_extension, false);
730 } else {
731 // Otherwise, the extension is unpacked (location LOAD).
732 // We should always be able to remember the extension's path. If it's not in
733 // the map, someone failed to update |unloaded_extension_paths_|.
734 CHECK(!path.empty());
735 extensions::UnpackedInstaller::Create(this)->Load(path);
739 bool ExtensionService::UninstallExtension(
740 std::string extension_id,
741 bool external_uninstall,
742 string16* error) {
743 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
745 scoped_refptr<const Extension> extension(GetInstalledExtension(extension_id));
747 // Callers should not send us nonexistent extensions.
748 CHECK(extension.get());
750 // Policy change which triggers an uninstall will always set
751 // |external_uninstall| to true so this is the only way to uninstall
752 // managed extensions.
753 if (!external_uninstall &&
754 !system_->management_policy()->UserMayModifySettings(
755 extension.get(), error)) {
756 content::NotificationService::current()->Notify(
757 chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
758 content::Source<Profile>(profile_),
759 content::Details<const Extension>(extension.get()));
760 return false;
763 // Extract the data we need for sync now, but don't actually sync until we've
764 // completed the uninstallation.
765 syncer::SyncChange sync_change;
766 if (app_sync_bundle_.HandlesApp(*extension.get())) {
767 sync_change = app_sync_bundle_.CreateSyncChangeToDelete(extension.get());
768 } else if (extension_sync_bundle_.HandlesExtension(*extension.get())) {
769 sync_change =
770 extension_sync_bundle_.CreateSyncChangeToDelete(extension.get());
773 if (IsUnacknowledgedExternalExtension(extension.get())) {
774 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
775 EXTERNAL_EXTENSION_UNINSTALLED,
776 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
778 UMA_HISTOGRAM_ENUMERATION("Extensions.UninstallType",
779 extension->GetType(), 100);
780 RecordPermissionMessagesHistogram(extension.get(),
781 "Extensions.Permissions_Uninstall");
783 // Unload before doing more cleanup to ensure that nothing is hanging on to
784 // any of these resources.
785 UnloadExtension(extension_id, extension_misc::UNLOAD_REASON_UNINSTALL);
787 extension_prefs_->OnExtensionUninstalled(extension_id, extension->location(),
788 external_uninstall);
790 // Tell the backend to start deleting installed extensions on the file thread.
791 if (!Manifest::IsUnpackedLocation(extension->location())) {
792 if (!GetFileTaskRunner()->PostTask(
793 FROM_HERE,
794 base::Bind(
795 &extension_file_util::UninstallExtension,
796 install_directory_,
797 extension_id)))
798 NOTREACHED();
801 GURL launch_web_url_origin(
802 extensions::AppLaunchInfo::GetLaunchWebURL(extension.get()).GetOrigin());
803 bool is_storage_isolated =
804 extensions::AppIsolationInfo::HasIsolatedStorage(extension.get());
806 if (is_storage_isolated) {
807 BrowserContext::AsyncObliterateStoragePartition(
808 profile_,
809 GetSiteForExtensionId(extension_id),
810 base::Bind(&ExtensionService::OnNeedsToGarbageCollectIsolatedStorage,
811 AsWeakPtr()));
812 } else {
813 if (extension->is_hosted_app() &&
814 !profile_->GetExtensionSpecialStoragePolicy()->
815 IsStorageProtected(launch_web_url_origin)) {
816 extensions::DataDeleter::StartDeleting(
817 profile_, extension_id, launch_web_url_origin);
819 extensions::DataDeleter::StartDeleting(profile_, extension_id,
820 extension->url());
823 UntrackTerminatedExtension(extension_id);
825 // Notify interested parties that we've uninstalled this extension.
826 content::NotificationService::current()->Notify(
827 chrome::NOTIFICATION_EXTENSION_UNINSTALLED,
828 content::Source<Profile>(profile_),
829 content::Details<const Extension>(extension.get()));
831 if (app_sync_bundle_.HasExtensionId(extension_id) &&
832 sync_change.sync_data().GetDataType() == syncer::APPS) {
833 app_sync_bundle_.ProcessDeletion(extension_id, sync_change);
834 } else if (extension_sync_bundle_.HasExtensionId(extension_id) &&
835 sync_change.sync_data().GetDataType() == syncer::EXTENSIONS) {
836 extension_sync_bundle_.ProcessDeletion(extension_id, sync_change);
839 delayed_updates_for_idle_.Remove(extension_id);
840 delayed_installs_.Remove(extension_id);
842 // Track the uninstallation.
843 UMA_HISTOGRAM_ENUMERATION("Extensions.ExtensionUninstalled", 1, 2);
845 return true;
848 bool ExtensionService::IsExtensionEnabled(
849 const std::string& extension_id) const {
850 if (extensions_.Contains(extension_id) ||
851 terminated_extensions_.Contains(extension_id)) {
852 return true;
855 if (disabled_extensions_.Contains(extension_id) ||
856 blacklisted_extensions_.Contains(extension_id)) {
857 return false;
860 // If the extension hasn't been loaded yet, check the prefs for it. Assume
861 // enabled unless otherwise noted.
862 return !extension_prefs_->IsExtensionDisabled(extension_id) &&
863 !extension_prefs_->IsExternalExtensionUninstalled(extension_id);
866 bool ExtensionService::IsExternalExtensionUninstalled(
867 const std::string& extension_id) const {
868 return extension_prefs_->IsExternalExtensionUninstalled(extension_id);
871 bool ExtensionService::IsExtensionEnabledForLauncher(
872 const std::string& extension_id) const {
873 return IsExtensionEnabled(extension_id) &&
874 !GetTerminatedExtension(extension_id);
877 void ExtensionService::EnableExtension(const std::string& extension_id) {
878 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
880 if (IsExtensionEnabled(extension_id))
881 return;
883 extension_prefs_->SetExtensionState(extension_id, Extension::ENABLED);
884 extension_prefs_->ClearDisableReasons(extension_id);
886 const Extension* extension = disabled_extensions_.GetByID(extension_id);
887 // This can happen if sync enables an extension that is not
888 // installed yet.
889 if (!extension)
890 return;
892 if (IsUnacknowledgedExternalExtension(extension)) {
893 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
894 EXTERNAL_EXTENSION_REENABLED,
895 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
896 AcknowledgeExternalExtension(extension->id());
899 // Move it over to the enabled list.
900 extensions_.Insert(make_scoped_refptr(extension));
901 disabled_extensions_.Remove(extension->id());
903 NotifyExtensionLoaded(extension);
905 // Notify listeners that the extension was enabled.
906 content::NotificationService::current()->Notify(
907 chrome::NOTIFICATION_EXTENSION_ENABLED,
908 content::Source<Profile>(profile_),
909 content::Details<const Extension>(extension));
911 SyncExtensionChangeIfNeeded(*extension);
914 void ExtensionService::DisableExtension(
915 const std::string& extension_id,
916 Extension::DisableReason disable_reason) {
917 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
919 // The extension may have been disabled already.
920 if (!IsExtensionEnabled(extension_id))
921 return;
923 const Extension* extension = GetInstalledExtension(extension_id);
924 // |extension| can be NULL if sync disables an extension that is not
925 // installed yet.
926 if (extension &&
927 !system_->management_policy()->UserMayModifySettings(extension, NULL)) {
928 return;
931 extension_prefs_->SetExtensionState(extension_id, Extension::DISABLED);
932 extension_prefs_->AddDisableReason(extension_id, disable_reason);
934 int include_mask = INCLUDE_EVERYTHING & ~INCLUDE_DISABLED;
935 extension = GetExtensionById(extension_id, include_mask);
936 if (!extension)
937 return;
939 // Reset the background_page_ready flag
940 if (extensions::BackgroundInfo::HasBackgroundPage(extension))
941 extension_runtime_data_[extension->id()].background_page_ready = false;
943 // Move it over to the disabled list. Don't send a second unload notification
944 // for terminated extensions being disabled.
945 disabled_extensions_.Insert(make_scoped_refptr(extension));
946 if (extensions_.Contains(extension->id())) {
947 extensions_.Remove(extension->id());
948 NotifyExtensionUnloaded(extension, extension_misc::UNLOAD_REASON_DISABLE);
949 } else {
950 terminated_extensions_.Remove(extension->id());
953 SyncExtensionChangeIfNeeded(*extension);
956 void ExtensionService::DisableUserExtensions() {
957 extensions::ManagementPolicy* management_policy =
958 system_->management_policy();
959 extensions::ExtensionList to_disable;
961 for (ExtensionSet::const_iterator extension = extensions_.begin();
962 extension != extensions_.end(); ++extension) {
963 if (management_policy->UserMayModifySettings(*extension, NULL))
964 to_disable.push_back(*extension);
966 for (ExtensionSet::const_iterator extension = terminated_extensions_.begin();
967 extension != terminated_extensions_.end(); ++extension) {
968 if (management_policy->UserMayModifySettings(*extension, NULL))
969 to_disable.push_back(*extension);
972 for (extensions::ExtensionList::const_iterator extension = to_disable.begin();
973 extension != to_disable.end(); ++extension) {
974 DisableExtension((*extension)->id(),
975 extensions::Extension::DISABLE_USER_ACTION);
979 void ExtensionService::GrantPermissionsAndEnableExtension(
980 const Extension* extension) {
981 GrantPermissions(extension);
982 RecordPermissionMessagesHistogram(
983 extension, "Extensions.Permissions_ReEnable");
984 extension_prefs_->SetDidExtensionEscalatePermissions(extension, false);
985 EnableExtension(extension->id());
988 void ExtensionService::GrantPermissions(const Extension* extension) {
989 CHECK(extension);
990 extensions::PermissionsUpdater perms_updater(profile());
991 perms_updater.GrantActivePermissions(extension);
994 // static
995 void ExtensionService::RecordPermissionMessagesHistogram(
996 const Extension* extension, const char* histogram) {
997 // Since this is called from multiple sources, and since the histogram macros
998 // use statics, we need to manually lookup the histogram ourselves.
999 base::HistogramBase* counter = base::LinearHistogram::FactoryGet(
1000 histogram,
1002 PermissionMessage::kEnumBoundary,
1003 PermissionMessage::kEnumBoundary + 1,
1004 base::HistogramBase::kUmaTargetedHistogramFlag);
1006 PermissionMessages permissions =
1007 extensions::PermissionsData::GetPermissionMessages(extension);
1008 if (permissions.empty()) {
1009 counter->Add(PermissionMessage::kNone);
1010 } else {
1011 for (PermissionMessages::iterator it = permissions.begin();
1012 it != permissions.end(); ++it)
1013 counter->Add(it->id());
1017 void ExtensionService::NotifyExtensionLoaded(const Extension* extension) {
1018 // The ChromeURLRequestContexts need to be first to know that the extension
1019 // was loaded, otherwise a race can arise where a renderer that is created
1020 // for the extension may try to load an extension URL with an extension id
1021 // that the request context doesn't yet know about. The profile is responsible
1022 // for ensuring its URLRequestContexts appropriately discover the loaded
1023 // extension.
1024 system_->RegisterExtensionWithRequestContexts(extension);
1026 // Tell renderers about the new extension, unless it's a theme (renderers
1027 // don't need to know about themes).
1028 if (!extension->is_theme()) {
1029 for (content::RenderProcessHost::iterator i(
1030 content::RenderProcessHost::AllHostsIterator());
1031 !i.IsAtEnd(); i.Advance()) {
1032 content::RenderProcessHost* host = i.GetCurrentValue();
1033 Profile* host_profile =
1034 Profile::FromBrowserContext(host->GetBrowserContext());
1035 if (host_profile->GetOriginalProfile() ==
1036 profile_->GetOriginalProfile()) {
1037 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions(
1038 1, ExtensionMsg_Loaded_Params(extension));
1039 host->Send(
1040 new ExtensionMsg_Loaded(loaded_extensions));
1045 // Tell subsystems that use the EXTENSION_LOADED notification about the new
1046 // extension.
1048 // NOTE: It is important that this happen after notifying the renderers about
1049 // the new extensions so that if we navigate to an extension URL in
1050 // NOTIFICATION_EXTENSION_LOADED, the renderer is guaranteed to know about it.
1051 content::NotificationService::current()->Notify(
1052 chrome::NOTIFICATION_EXTENSION_LOADED,
1053 content::Source<Profile>(profile_),
1054 content::Details<const Extension>(extension));
1056 // Tell a random-ass collection of other subsystems about the new extension.
1057 // TODO(aa): What should we do with all this goop? Can it move into the
1058 // relevant objects via EXTENSION_LOADED?
1060 profile_->GetExtensionSpecialStoragePolicy()->
1061 GrantRightsForExtension(extension);
1063 UpdateActiveExtensionsInCrashReporter();
1065 // If the extension has permission to load chrome://favicon/ resources we need
1066 // to make sure that the FaviconSource is registered with the
1067 // ChromeURLDataManager.
1068 if (extensions::PermissionsData::HasHostPermission(
1069 extension, GURL(chrome::kChromeUIFaviconURL))) {
1070 FaviconSource* favicon_source = new FaviconSource(profile_,
1071 FaviconSource::FAVICON);
1072 content::URLDataSource::Add(profile_, favicon_source);
1075 #if !defined(OS_ANDROID)
1076 // Same for chrome://theme/ resources.
1077 if (extensions::PermissionsData::HasHostPermission(
1078 extension, GURL(chrome::kChromeUIThemeURL))) {
1079 ThemeSource* theme_source = new ThemeSource(profile_);
1080 content::URLDataSource::Add(profile_, theme_source);
1082 #endif
1084 // Same for chrome://thumb/ resources.
1085 if (extensions::PermissionsData::HasHostPermission(
1086 extension, GURL(chrome::kChromeUIThumbnailURL))) {
1087 ThumbnailSource* thumbnail_source = new ThumbnailSource(profile_);
1088 content::URLDataSource::Add(profile_, thumbnail_source);
1092 void ExtensionService::NotifyExtensionUnloaded(
1093 const Extension* extension,
1094 extension_misc::UnloadedExtensionReason reason) {
1095 UnloadedExtensionInfo details(extension, reason);
1096 content::NotificationService::current()->Notify(
1097 chrome::NOTIFICATION_EXTENSION_UNLOADED,
1098 content::Source<Profile>(profile_),
1099 content::Details<UnloadedExtensionInfo>(&details));
1101 #if defined(ENABLE_THEMES)
1102 // If the current theme is being unloaded, tell ThemeService to revert back
1103 // to the default theme.
1104 if (reason != extension_misc::UNLOAD_REASON_UPDATE && extension->is_theme()) {
1105 ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_);
1106 if (extension->id() == theme_service->GetThemeID())
1107 theme_service->UseDefaultTheme();
1109 #endif
1111 for (content::RenderProcessHost::iterator i(
1112 content::RenderProcessHost::AllHostsIterator());
1113 !i.IsAtEnd(); i.Advance()) {
1114 content::RenderProcessHost* host = i.GetCurrentValue();
1115 Profile* host_profile =
1116 Profile::FromBrowserContext(host->GetBrowserContext());
1117 if (host_profile->GetOriginalProfile() == profile_->GetOriginalProfile())
1118 host->Send(new ExtensionMsg_Unloaded(extension->id()));
1121 system_->UnregisterExtensionWithRequestContexts(extension->id(), reason);
1122 profile_->GetExtensionSpecialStoragePolicy()->
1123 RevokeRightsForExtension(extension);
1125 #if defined(OS_CHROMEOS)
1126 // Revoke external file access for the extension from its file system context.
1127 // It is safe to access the extension's storage partition at this point. The
1128 // storage partition may get destroyed only after the extension gets unloaded.
1129 GURL site = extensions::ExtensionSystem::Get(profile_)->extension_service()->
1130 GetSiteForExtensionId(extension->id());
1131 fileapi::FileSystemContext* filesystem_context =
1132 BrowserContext::GetStoragePartitionForSite(profile_, site)->
1133 GetFileSystemContext();
1134 if (filesystem_context && filesystem_context->external_provider()) {
1135 filesystem_context->external_provider()->
1136 RevokeAccessForExtension(extension->id());
1138 #endif
1140 UpdateActiveExtensionsInCrashReporter();
1143 Profile* ExtensionService::profile() {
1144 return profile_;
1147 extensions::ExtensionPrefs* ExtensionService::extension_prefs() {
1148 return extension_prefs_;
1151 extensions::SettingsFrontend* ExtensionService::settings_frontend() {
1152 return settings_frontend_.get();
1155 extensions::ContentSettingsStore* ExtensionService::GetContentSettingsStore() {
1156 return extension_prefs()->content_settings_store();
1159 bool ExtensionService::is_ready() {
1160 return ready_->is_signaled();
1163 base::SequencedTaskRunner* ExtensionService::GetFileTaskRunner() {
1164 if (file_task_runner_.get())
1165 return file_task_runner_.get();
1167 // We should be able to interrupt any part of extension install process during
1168 // shutdown. SKIP_ON_SHUTDOWN ensures that not started extension install tasks
1169 // will be ignored/deleted while we will block on started tasks.
1170 std::string token("ext_install-");
1171 token.append(profile_->GetPath().AsUTF8Unsafe());
1172 file_task_runner_ = BrowserThread::GetBlockingPool()->
1173 GetSequencedTaskRunnerWithShutdownBehavior(
1174 BrowserThread::GetBlockingPool()->GetNamedSequenceToken(token),
1175 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
1176 return file_task_runner_.get();
1179 extensions::ExtensionUpdater* ExtensionService::updater() {
1180 return updater_.get();
1183 void ExtensionService::CheckManagementPolicy() {
1184 std::vector<std::string> to_be_removed;
1186 // Loop through extensions list, unload installed extensions.
1187 for (ExtensionSet::const_iterator iter = extensions_.begin();
1188 iter != extensions_.end(); ++iter) {
1189 const Extension* extension = (iter->get());
1190 if (!system_->management_policy()->UserMayLoad(extension, NULL))
1191 to_be_removed.push_back(extension->id());
1194 // UnloadExtension will change the extensions_ list. So, we should
1195 // call it outside the iterator loop.
1196 for (size_t i = 0; i < to_be_removed.size(); ++i)
1197 UnloadExtension(to_be_removed[i], extension_misc::UNLOAD_REASON_DISABLE);
1200 void ExtensionService::CheckForUpdatesSoon() {
1201 if (updater()) {
1202 if (AreAllExternalProvidersReady()) {
1203 updater()->CheckSoon();
1204 } else {
1205 // Sync can start updating before all the external providers are ready
1206 // during startup. Start the update as soon as those providers are ready,
1207 // but not before.
1208 update_once_all_providers_are_ready_ = true;
1210 } else {
1211 LOG(WARNING) << "CheckForUpdatesSoon() called with auto-update turned off";
1215 syncer::SyncMergeResult ExtensionService::MergeDataAndStartSyncing(
1216 syncer::ModelType type,
1217 const syncer::SyncDataList& initial_sync_data,
1218 scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
1219 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) {
1220 CHECK(sync_processor.get());
1221 CHECK(sync_error_factory.get());
1223 switch (type) {
1224 case syncer::EXTENSIONS:
1225 extension_sync_bundle_.SetupSync(sync_processor.release(),
1226 sync_error_factory.release(),
1227 initial_sync_data);
1228 break;
1230 case syncer::APPS:
1231 app_sync_bundle_.SetupSync(sync_processor.release(),
1232 sync_error_factory.release(),
1233 initial_sync_data);
1234 break;
1236 default:
1237 LOG(FATAL) << "Got " << type << " ModelType";
1240 // Process local extensions.
1241 // TODO(yoz): Determine whether pending extensions should be considered too.
1242 // See crbug.com/104399.
1243 syncer::SyncDataList sync_data_list = GetAllSyncData(type);
1244 syncer::SyncChangeList sync_change_list;
1245 for (syncer::SyncDataList::const_iterator i = sync_data_list.begin();
1246 i != sync_data_list.end();
1247 ++i) {
1248 switch (type) {
1249 case syncer::EXTENSIONS:
1250 sync_change_list.push_back(
1251 extension_sync_bundle_.CreateSyncChange(*i));
1252 break;
1253 case syncer::APPS:
1254 sync_change_list.push_back(app_sync_bundle_.CreateSyncChange(*i));
1255 break;
1256 default:
1257 LOG(FATAL) << "Got " << type << " ModelType";
1262 if (type == syncer::EXTENSIONS) {
1263 extension_sync_bundle_.ProcessSyncChangeList(sync_change_list);
1264 } else if (type == syncer::APPS) {
1265 app_sync_bundle_.ProcessSyncChangeList(sync_change_list);
1268 return syncer::SyncMergeResult(type);
1271 void ExtensionService::StopSyncing(syncer::ModelType type) {
1272 if (type == syncer::APPS) {
1273 app_sync_bundle_.Reset();
1274 } else if (type == syncer::EXTENSIONS) {
1275 extension_sync_bundle_.Reset();
1279 syncer::SyncDataList ExtensionService::GetAllSyncData(
1280 syncer::ModelType type) const {
1281 if (type == syncer::EXTENSIONS)
1282 return extension_sync_bundle_.GetAllSyncData();
1283 if (type == syncer::APPS)
1284 return app_sync_bundle_.GetAllSyncData();
1286 // We should only get sync data for extensions and apps.
1287 NOTREACHED();
1289 return syncer::SyncDataList();
1292 syncer::SyncError ExtensionService::ProcessSyncChanges(
1293 const tracked_objects::Location& from_here,
1294 const syncer::SyncChangeList& change_list) {
1295 for (syncer::SyncChangeList::const_iterator i = change_list.begin();
1296 i != change_list.end();
1297 ++i) {
1298 syncer::ModelType type = i->sync_data().GetDataType();
1299 if (type == syncer::EXTENSIONS) {
1300 extension_sync_bundle_.ProcessSyncChange(
1301 extensions::ExtensionSyncData(*i));
1302 } else if (type == syncer::APPS) {
1303 app_sync_bundle_.ProcessSyncChange(extensions::AppSyncData(*i));
1307 extension_prefs()->extension_sorting()->FixNTPOrdinalCollisions();
1309 return syncer::SyncError();
1312 extensions::ExtensionSyncData ExtensionService::GetExtensionSyncData(
1313 const Extension& extension) const {
1314 return extensions::ExtensionSyncData(extension,
1315 IsExtensionEnabled(extension.id()),
1316 IsIncognitoEnabled(extension.id()));
1319 extensions::AppSyncData ExtensionService::GetAppSyncData(
1320 const Extension& extension) const {
1321 return extensions::AppSyncData(
1322 extension,
1323 IsExtensionEnabled(extension.id()),
1324 IsIncognitoEnabled(extension.id()),
1325 extension_prefs_->extension_sorting()->GetAppLaunchOrdinal(
1326 extension.id()),
1327 extension_prefs_->extension_sorting()->GetPageOrdinal(extension.id()));
1330 std::vector<extensions::ExtensionSyncData>
1331 ExtensionService::GetExtensionSyncDataList() const {
1332 std::vector<extensions::ExtensionSyncData> extension_sync_list;
1333 extension_sync_bundle_.GetExtensionSyncDataListHelper(extensions_,
1334 &extension_sync_list);
1335 extension_sync_bundle_.GetExtensionSyncDataListHelper(disabled_extensions_,
1336 &extension_sync_list);
1337 extension_sync_bundle_.GetExtensionSyncDataListHelper(terminated_extensions_,
1338 &extension_sync_list);
1340 std::vector<extensions::ExtensionSyncData> pending_extensions =
1341 extension_sync_bundle_.GetPendingData();
1342 extension_sync_list.insert(extension_sync_list.begin(),
1343 pending_extensions.begin(),
1344 pending_extensions.end());
1346 return extension_sync_list;
1349 std::vector<extensions::AppSyncData> ExtensionService::GetAppSyncDataList()
1350 const {
1351 std::vector<extensions::AppSyncData> app_sync_list;
1352 app_sync_bundle_.GetAppSyncDataListHelper(extensions_, &app_sync_list);
1353 app_sync_bundle_.GetAppSyncDataListHelper(disabled_extensions_,
1354 &app_sync_list);
1355 app_sync_bundle_.GetAppSyncDataListHelper(terminated_extensions_,
1356 &app_sync_list);
1358 std::vector<extensions::AppSyncData> pending_apps =
1359 app_sync_bundle_.GetPendingData();
1360 app_sync_list.insert(app_sync_list.begin(),
1361 pending_apps.begin(),
1362 pending_apps.end());
1364 return app_sync_list;
1367 bool ExtensionService::ProcessExtensionSyncData(
1368 const extensions::ExtensionSyncData& extension_sync_data) {
1369 if (!ProcessExtensionSyncDataHelper(extension_sync_data,
1370 syncer::EXTENSIONS)) {
1371 extension_sync_bundle_.AddPendingExtension(extension_sync_data.id(),
1372 extension_sync_data);
1373 CheckForUpdatesSoon();
1374 return false;
1377 return true;
1380 bool ExtensionService::ProcessAppSyncData(
1381 const extensions::AppSyncData& app_sync_data) {
1382 const std::string& id = app_sync_data.id();
1384 if (app_sync_data.app_launch_ordinal().IsValid() &&
1385 app_sync_data.page_ordinal().IsValid()) {
1386 extension_prefs_->extension_sorting()->SetAppLaunchOrdinal(
1388 app_sync_data.app_launch_ordinal());
1389 extension_prefs_->extension_sorting()->SetPageOrdinal(
1391 app_sync_data.page_ordinal());
1394 if (!ProcessExtensionSyncDataHelper(app_sync_data.extension_sync_data(),
1395 syncer::APPS)) {
1396 app_sync_bundle_.AddPendingApp(id, app_sync_data);
1397 CheckForUpdatesSoon();
1398 return false;
1401 return true;
1404 bool ExtensionService::IsCorrectSyncType(const Extension& extension,
1405 syncer::ModelType type) const {
1406 if (type == syncer::EXTENSIONS &&
1407 extensions::sync_helper::IsSyncableExtension(&extension)) {
1408 return true;
1411 if (type == syncer::APPS &&
1412 extensions::sync_helper::IsSyncableApp(&extension)) {
1413 return true;
1416 return false;
1419 bool ExtensionService::ProcessExtensionSyncDataHelper(
1420 const extensions::ExtensionSyncData& extension_sync_data,
1421 syncer::ModelType type) {
1422 const std::string& id = extension_sync_data.id();
1423 const Extension* extension = GetInstalledExtension(id);
1425 // TODO(bolms): we should really handle this better. The particularly bad
1426 // case is where an app becomes an extension or vice versa, and we end up with
1427 // a zombie extension that won't go away.
1428 if (extension && !IsCorrectSyncType(*extension, type))
1429 return true;
1431 // Handle uninstalls first.
1432 if (extension_sync_data.uninstalled()) {
1433 std::string error;
1434 if (!UninstallExtensionHelper(this, id)) {
1435 LOG(WARNING) << "Could not uninstall extension " << id
1436 << " for sync";
1438 return true;
1441 // Extension from sync was uninstalled by the user as external extensions.
1442 // Honor user choice and skip installation/enabling.
1443 if (IsExternalExtensionUninstalled(id)) {
1444 LOG(WARNING) << "Extension with id " << id
1445 << " from sync was uninstalled as external extension";
1446 return true;
1449 // Set user settings.
1450 // If the extension has been disabled from sync, it may not have
1451 // been installed yet, so we don't know if the disable reason was a
1452 // permissions increase. That will be updated once CheckPermissionsIncrease
1453 // is called for it.
1454 if (extension_sync_data.enabled())
1455 EnableExtension(id);
1456 else
1457 DisableExtension(id, Extension::DISABLE_UNKNOWN_FROM_SYNC);
1459 // We need to cache some version information here because setting the
1460 // incognito flag invalidates the |extension| pointer (it reloads the
1461 // extension).
1462 bool extension_installed = (extension != NULL);
1463 int result = extension ?
1464 extension->version()->CompareTo(extension_sync_data.version()) : 0;
1465 SetIsIncognitoEnabled(id, extension_sync_data.incognito_enabled());
1466 extension = NULL; // No longer safe to use.
1468 if (extension_installed) {
1469 // If the extension is already installed, check if it's outdated.
1470 if (result < 0) {
1471 // Extension is outdated.
1472 return false;
1474 } else {
1475 // TODO(akalin): Replace silent update with a list of enabled
1476 // permissions.
1477 const bool kInstallSilently = true;
1479 CHECK(type == syncer::EXTENSIONS || type == syncer::APPS);
1480 extensions::PendingExtensionInfo::ShouldAllowInstallPredicate filter =
1481 (type == syncer::APPS) ? extensions::sync_helper::IsSyncableApp :
1482 extensions::sync_helper::IsSyncableExtension;
1484 if (!pending_extension_manager()->AddFromSync(
1486 extension_sync_data.update_url(),
1487 filter,
1488 kInstallSilently)) {
1489 LOG(WARNING) << "Could not add pending extension for " << id;
1490 // This means that the extension is already pending installation, with a
1491 // non-INTERNAL location. Add to pending_sync_data, even though it will
1492 // never be removed (we'll never install a syncable version of the
1493 // extension), so that GetAllSyncData() continues to send it.
1495 // Track pending extensions so that we can return them in GetAllSyncData().
1496 return false;
1499 return true;
1502 bool ExtensionService::IsIncognitoEnabled(
1503 const std::string& extension_id) const {
1504 const Extension* extension = GetInstalledExtension(extension_id);
1505 if (extension && !extension->can_be_incognito_enabled())
1506 return false;
1507 // If this is an existing component extension we always allow it to
1508 // work in incognito mode.
1509 if (extension && extension->location() == Manifest::COMPONENT)
1510 return true;
1512 // Check the prefs.
1513 return extension_prefs_->IsIncognitoEnabled(extension_id);
1516 void ExtensionService::SetIsIncognitoEnabled(
1517 const std::string& extension_id, bool enabled) {
1518 const Extension* extension = GetInstalledExtension(extension_id);
1519 if (extension && !extension->can_be_incognito_enabled())
1520 return;
1521 if (extension && extension->location() == Manifest::COMPONENT) {
1522 // This shouldn't be called for component extensions unless they are
1523 // syncable.
1524 DCHECK(extensions::sync_helper::IsSyncable(extension));
1526 // If we are here, make sure the we aren't trying to change the value.
1527 DCHECK_EQ(enabled, IsIncognitoEnabled(extension_id));
1529 return;
1532 // Broadcast unloaded and loaded events to update browser state. Only bother
1533 // if the value changed and the extension is actually enabled, since there is
1534 // no UI otherwise.
1535 bool old_enabled = extension_prefs_->IsIncognitoEnabled(extension_id);
1536 if (enabled == old_enabled)
1537 return;
1539 extension_prefs_->SetIsIncognitoEnabled(extension_id, enabled);
1541 bool extension_is_enabled = extensions_.Contains(extension_id);
1543 // When we reload the extension the ID may be invalidated if we've passed it
1544 // by const ref everywhere. Make a copy to be safe.
1545 std::string id = extension_id;
1546 if (extension_is_enabled)
1547 ReloadExtension(id);
1549 // Reloading the extension invalidates the |extension| pointer.
1550 extension = GetInstalledExtension(id);
1551 if (extension)
1552 SyncExtensionChangeIfNeeded(*extension);
1555 bool ExtensionService::CanCrossIncognito(const Extension* extension) const {
1556 // We allow the extension to see events and data from another profile iff it
1557 // uses "spanning" behavior and it has incognito access. "split" mode
1558 // extensions only see events for a matching profile.
1559 CHECK(extension);
1560 return IsIncognitoEnabled(extension->id()) &&
1561 !extensions::IncognitoInfo::IsSplitMode(extension);
1564 bool ExtensionService::CanLoadInIncognito(const Extension* extension) const {
1565 if (extension->is_hosted_app())
1566 return true;
1567 // Packaged apps and regular extensions need to be enabled specifically for
1568 // incognito (and split mode should be set).
1569 return extensions::IncognitoInfo::IsSplitMode(extension) &&
1570 IsIncognitoEnabled(extension->id());
1573 void ExtensionService::OnExtensionMoved(
1574 const std::string& moved_extension_id,
1575 const std::string& predecessor_extension_id,
1576 const std::string& successor_extension_id) {
1577 extension_prefs_->extension_sorting()->OnExtensionMoved(
1578 moved_extension_id,
1579 predecessor_extension_id,
1580 successor_extension_id);
1582 const Extension* extension = GetInstalledExtension(moved_extension_id);
1583 if (extension)
1584 SyncExtensionChangeIfNeeded(*extension);
1587 bool ExtensionService::AllowFileAccess(const Extension* extension) const {
1588 return (CommandLine::ForCurrentProcess()->HasSwitch(
1589 switches::kDisableExtensionsFileAccessCheck) ||
1590 extension_prefs_->AllowFileAccess(extension->id()));
1593 void ExtensionService::SetAllowFileAccess(const Extension* extension,
1594 bool allow) {
1595 // Reload to update browser state. Only bother if the value changed and the
1596 // extension is actually enabled, since there is no UI otherwise.
1597 bool old_allow = AllowFileAccess(extension);
1598 if (allow == old_allow)
1599 return;
1601 extension_prefs_->SetAllowFileAccess(extension->id(), allow);
1603 bool extension_is_enabled = extensions_.Contains(extension->id());
1604 if (extension_is_enabled)
1605 ReloadExtension(extension->id());
1608 // Some extensions will autoupdate themselves externally from Chrome. These
1609 // are typically part of some larger client application package. To support
1610 // these, the extension will register its location in the the preferences file
1611 // (and also, on Windows, in the registry) and this code will periodically
1612 // check that location for a .crx file, which it will then install locally if
1613 // a new version is available.
1614 // Errors are reported through ExtensionErrorReporter. Succcess is not
1615 // reported.
1616 void ExtensionService::CheckForExternalUpdates() {
1617 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1619 // Note that this installation is intentionally silent (since it didn't
1620 // go through the front-end). Extensions that are registered in this
1621 // way are effectively considered 'pre-bundled', and so implicitly
1622 // trusted. In general, if something has HKLM or filesystem access,
1623 // they could install an extension manually themselves anyway.
1625 // Ask each external extension provider to give us a call back for each
1626 // extension they know about. See OnExternalExtension(File|UpdateUrl)Found.
1627 extensions::ProviderCollection::const_iterator i;
1628 for (i = external_extension_providers_.begin();
1629 i != external_extension_providers_.end(); ++i) {
1630 extensions::ExternalProviderInterface* provider = i->get();
1631 provider->VisitRegisteredExtension();
1634 // Do any required work that we would have done after completion of all
1635 // providers.
1636 if (external_extension_providers_.empty()) {
1637 OnAllExternalProvidersReady();
1641 void ExtensionService::OnExternalProviderReady(
1642 const extensions::ExternalProviderInterface* provider) {
1643 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1644 CHECK(provider->IsReady());
1646 // An external provider has finished loading. We only take action
1647 // if all of them are finished. So we check them first.
1648 if (AreAllExternalProvidersReady())
1649 OnAllExternalProvidersReady();
1652 bool ExtensionService::AreAllExternalProvidersReady() const {
1653 extensions::ProviderCollection::const_iterator i;
1654 for (i = external_extension_providers_.begin();
1655 i != external_extension_providers_.end(); ++i) {
1656 if (!i->get()->IsReady())
1657 return false;
1659 return true;
1662 void ExtensionService::OnAllExternalProvidersReady() {
1663 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1664 base::TimeDelta elapsed = base::Time::Now() - profile_->GetStartTime();
1665 UMA_HISTOGRAM_TIMES("Extension.ExternalProvidersReadyAfter", elapsed);
1667 // Install any pending extensions.
1668 if (update_once_all_providers_are_ready_ && updater()) {
1669 update_once_all_providers_are_ready_ = false;
1670 updater()->CheckNow(extensions::ExtensionUpdater::CheckParams());
1673 // Uninstall all the unclaimed extensions.
1674 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> extensions_info(
1675 extension_prefs_->GetInstalledExtensionsInfo());
1676 for (size_t i = 0; i < extensions_info->size(); ++i) {
1677 ExtensionInfo* info = extensions_info->at(i).get();
1678 if (Manifest::IsExternalLocation(info->extension_location))
1679 CheckExternalUninstall(info->extension_id);
1681 IdentifyAlertableExtensions();
1684 void ExtensionService::IdentifyAlertableExtensions() {
1685 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1687 // Build up the lists of extensions that require acknowledgment. If this is
1688 // the first time, grandfather extensions that would have caused
1689 // notification.
1690 extension_error_ui_.reset(ExtensionErrorUI::Create(this));
1692 bool did_show_alert = false;
1693 if (PopulateExtensionErrorUI(extension_error_ui_.get())) {
1694 if (!is_first_run_) {
1695 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1696 did_show_alert = extension_error_ui_->ShowErrorInBubbleView();
1697 } else {
1698 // First run. Just acknowledge all the extensions, silently, by
1699 // shortcutting the display of the UI and going straight to the
1700 // callback for pressing the Accept button.
1701 HandleExtensionAlertAccept();
1705 UpdateExternalExtensionAlert();
1707 if (!did_show_alert)
1708 extension_error_ui_.reset();
1711 bool ExtensionService::PopulateExtensionErrorUI(
1712 ExtensionErrorUI* extension_error_ui) {
1713 bool needs_alert = false;
1715 // Extensions that are blacklisted.
1716 for (ExtensionSet::const_iterator it = blacklisted_extensions_.begin();
1717 it != blacklisted_extensions_.end(); ++it) {
1718 std::string id = (*it)->id();
1719 if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(id)) {
1720 extension_error_ui->AddBlacklistedExtension(id);
1721 needs_alert = true;
1725 for (ExtensionSet::const_iterator iter = extensions_.begin();
1726 iter != extensions_.end(); ++iter) {
1727 const Extension* e = iter->get();
1729 // Extensions disabled by policy. Note: this no longer includes blacklisted
1730 // extensions, though we still show the same UI.
1731 if (!system_->management_policy()->UserMayLoad(e, NULL)) {
1732 if (!extension_prefs_->IsBlacklistedExtensionAcknowledged(e->id())) {
1733 extension_error_ui->AddBlacklistedExtension(e->id());
1734 needs_alert = true;
1739 return needs_alert;
1742 void ExtensionService::HandleExtensionAlertClosed() {
1743 const ExtensionIdSet* extension_ids =
1744 extension_error_ui_->get_blacklisted_extension_ids();
1745 for (ExtensionIdSet::const_iterator iter = extension_ids->begin();
1746 iter != extension_ids->end(); ++iter) {
1747 extension_prefs_->AcknowledgeBlacklistedExtension(*iter);
1749 extension_error_ui_.reset();
1752 void ExtensionService::HandleExtensionAlertAccept() {
1753 extension_error_ui_->Close();
1756 void ExtensionService::AcknowledgeExternalExtension(const std::string& id) {
1757 extension_prefs_->AcknowledgeExternalExtension(id);
1758 UpdateExternalExtensionAlert();
1761 bool ExtensionService::IsUnacknowledgedExternalExtension(
1762 const Extension* extension) {
1763 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1764 return false;
1766 return (Manifest::IsExternalLocation(extension->location()) &&
1767 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id()) &&
1768 !(extension_prefs_->GetDisableReasons(extension->id()) &
1769 Extension::DISABLE_SIDELOAD_WIPEOUT));
1772 void ExtensionService::HandleExtensionAlertDetails() {
1773 extension_error_ui_->ShowExtensions();
1774 // ShowExtensions may cause the error UI to close synchronously, e.g. if it
1775 // causes a navigation.
1776 if (extension_error_ui_)
1777 extension_error_ui_->Close();
1780 void ExtensionService::UpdateExternalExtensionAlert() {
1781 if (!FeatureSwitch::prompt_for_external_extensions()->IsEnabled())
1782 return;
1784 const Extension* extension = NULL;
1785 for (ExtensionSet::const_iterator iter = disabled_extensions_.begin();
1786 iter != disabled_extensions_.end(); ++iter) {
1787 const Extension* e = iter->get();
1788 if (IsUnacknowledgedExternalExtension(e)) {
1789 extension = e;
1790 break;
1794 if (extension) {
1795 if (!extensions::HasExternalInstallError(this)) {
1796 if (extension_prefs_->IncrementAcknowledgePromptCount(extension->id()) >
1797 kMaxExtensionAcknowledgePromptCount) {
1798 // Stop prompting for this extension, and check if there's another
1799 // one that needs prompting.
1800 extension_prefs_->AcknowledgeExternalExtension(extension->id());
1801 UpdateExternalExtensionAlert();
1802 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
1803 EXTERNAL_EXTENSION_IGNORED,
1804 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
1805 return;
1807 if (is_first_run_)
1808 extension_prefs_->SetExternalInstallFirstRun(extension->id());
1809 // first_run is true if the extension was installed during a first run
1810 // (even if it's post-first run now).
1811 bool first_run = extension_prefs_->IsExternalInstallFirstRun(
1812 extension->id());
1813 extensions::AddExternalInstallError(this, extension, first_run);
1815 } else {
1816 extensions::RemoveExternalInstallError(this);
1820 void ExtensionService::UnloadExtension(
1821 const std::string& extension_id,
1822 extension_misc::UnloadedExtensionReason reason) {
1823 // Make sure the extension gets deleted after we return from this function.
1824 int include_mask = INCLUDE_EVERYTHING & ~INCLUDE_TERMINATED;
1825 scoped_refptr<const Extension> extension(
1826 GetExtensionById(extension_id, include_mask));
1828 // This method can be called via PostTask, so the extension may have been
1829 // unloaded by the time this runs.
1830 if (!extension.get()) {
1831 // In case the extension may have crashed/uninstalled. Allow the profile to
1832 // clean up its RequestContexts.
1833 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1834 return;
1837 // If uninstalling let RuntimeEventRouter know.
1838 if (reason == extension_misc::UNLOAD_REASON_UNINSTALL)
1839 extensions::RuntimeEventRouter::OnExtensionUninstalled(
1840 profile_, extension_id);
1842 // Keep information about the extension so that we can reload it later
1843 // even if it's not permanently installed.
1844 unloaded_extension_paths_[extension->id()] = extension->path();
1846 // Clean up if the extension is meant to be enabled after a reload.
1847 reloading_extensions_.erase(extension->id());
1849 // Clean up runtime data.
1850 extension_runtime_data_.erase(extension_id);
1852 if (disabled_extensions_.Contains(extension->id())) {
1853 UnloadedExtensionInfo details(extension.get(), reason);
1854 details.already_disabled = true;
1855 disabled_extensions_.Remove(extension->id());
1856 content::NotificationService::current()->Notify(
1857 chrome::NOTIFICATION_EXTENSION_UNLOADED,
1858 content::Source<Profile>(profile_),
1859 content::Details<UnloadedExtensionInfo>(&details));
1860 // Make sure the profile cleans up its RequestContexts when an already
1861 // disabled extension is unloaded (since they are also tracking the disabled
1862 // extensions).
1863 system_->UnregisterExtensionWithRequestContexts(extension_id, reason);
1864 return;
1867 // Remove the extension from our list.
1868 extensions_.Remove(extension->id());
1870 NotifyExtensionUnloaded(extension.get(), reason);
1873 void ExtensionService::UnloadAllExtensions() {
1874 profile_->GetExtensionSpecialStoragePolicy()->RevokeRightsForAllExtensions();
1876 extensions_.Clear();
1877 disabled_extensions_.Clear();
1878 terminated_extensions_.Clear();
1879 extension_runtime_data_.clear();
1881 // TODO(erikkay) should there be a notification for this? We can't use
1882 // EXTENSION_UNLOADED since that implies that the extension has been disabled
1883 // or uninstalled, and UnloadAll is just part of shutdown.
1886 void ExtensionService::ReloadExtensions() {
1887 UnloadAllExtensions();
1888 component_loader_->LoadAll();
1889 extensions::InstalledLoader(this).LoadAllExtensions();
1890 // Don't call SetReadyAndNotifyListeners() since tests call this multiple
1891 // times.
1894 void ExtensionService::GarbageCollectExtensions() {
1895 if (extension_prefs_->pref_service()->ReadOnly())
1896 return;
1898 if (pending_extension_manager()->HasPendingExtensions()) {
1899 // Don't garbage collect while there are pending installations, which may
1900 // be using the temporary installation directory. Try to garbage collect
1901 // again later.
1902 base::MessageLoop::current()->PostDelayedTask(
1903 FROM_HERE,
1904 base::Bind(&ExtensionService::GarbageCollectExtensions, AsWeakPtr()),
1905 base::TimeDelta::FromSeconds(kGarbageCollectRetryDelay));
1906 return;
1909 scoped_ptr<extensions::ExtensionPrefs::ExtensionsInfo> info(
1910 extension_prefs_->GetInstalledExtensionsInfo());
1912 std::multimap<std::string, base::FilePath> extension_paths;
1913 for (size_t i = 0; i < info->size(); ++i)
1914 extension_paths.insert(std::make_pair(info->at(i)->extension_id,
1915 info->at(i)->extension_path));
1917 info = extension_prefs_->GetAllDelayedInstallInfo();
1918 for (size_t i = 0; i < info->size(); ++i)
1919 extension_paths.insert(std::make_pair(info->at(i)->extension_id,
1920 info->at(i)->extension_path));
1922 if (!GetFileTaskRunner()->PostTask(
1923 FROM_HERE,
1924 base::Bind(
1925 &extension_file_util::GarbageCollectExtensions,
1926 install_directory_,
1927 extension_paths))) {
1928 NOTREACHED();
1931 #if defined(ENABLE_THEMES)
1932 // Also garbage-collect themes. We check |profile_| to be
1933 // defensive; in the future, we may call GarbageCollectExtensions()
1934 // from somewhere other than Init() (e.g., in a timer).
1935 if (profile_) {
1936 ThemeServiceFactory::GetForProfile(profile_)->RemoveUnusedThemes();
1938 #endif
1941 void ExtensionService::SyncExtensionChangeIfNeeded(const Extension& extension) {
1942 if (app_sync_bundle_.HandlesApp(extension)) {
1943 app_sync_bundle_.SyncChangeIfNeeded(extension);
1944 } else if (extension_sync_bundle_.HandlesExtension(extension)) {
1945 extension_sync_bundle_.SyncChangeIfNeeded(extension);
1949 void ExtensionService::SetReadyAndNotifyListeners() {
1950 ready_->Signal();
1951 content::NotificationService::current()->Notify(
1952 chrome::NOTIFICATION_EXTENSIONS_READY,
1953 content::Source<Profile>(profile_),
1954 content::NotificationService::NoDetails());
1957 void ExtensionService::OnLoadedInstalledExtensions() {
1958 if (updater_)
1959 updater_->Start();
1961 OnBlacklistUpdated();
1964 void ExtensionService::AddExtension(const Extension* extension) {
1965 // TODO(jstritar): We may be able to get rid of this branch by overriding the
1966 // default extension state to DISABLED when the --disable-extensions flag
1967 // is set (http://crbug.com/29067).
1968 if (!extensions_enabled() &&
1969 !extension->is_theme() &&
1970 extension->location() != Manifest::COMPONENT &&
1971 !Manifest::IsExternalLocation(extension->location())) {
1972 return;
1975 bool is_extension_upgrade = false;
1976 if (const Extension* old = GetInstalledExtension(extension->id())) {
1977 is_extension_upgrade = true;
1978 DCHECK_NE(extension, old);
1979 // Other than for unpacked extensions, CrxInstaller should have guaranteed
1980 // that we aren't downgrading.
1981 if (!Manifest::IsUnpackedLocation(extension->location()))
1982 CHECK_GE(extension->version()->CompareTo(*(old->version())), 0);
1984 SetBeingUpgraded(extension, is_extension_upgrade);
1986 // The extension is now loaded, remove its data from unloaded extension map.
1987 unloaded_extension_paths_.erase(extension->id());
1989 // If a terminated extension is loaded, remove it from the terminated list.
1990 UntrackTerminatedExtension(extension->id());
1992 // If the extension was disabled for a reload, then enable it.
1993 bool reloading = reloading_extensions_.erase(extension->id()) > 0;
1995 // Check if the extension's privileges have changed and mark the
1996 // extension disabled if necessary.
1997 CheckPermissionsIncrease(extension, is_extension_upgrade);
1999 if (is_extension_upgrade && !reloading) {
2000 // To upgrade an extension in place, unload the old one and then load the
2001 // new one. ReloadExtension disables the extension, which is sufficient.
2002 UnloadExtension(extension->id(), extension_misc::UNLOAD_REASON_UPDATE);
2005 if (extension_prefs_->IsExtensionBlacklisted(extension->id())) {
2006 // Only prefs is checked for the blacklist. We rely on callers to check the
2007 // blacklist before calling into here, e.g. CrxInstaller checks before
2008 // installation, we check when loading installed extensions.
2009 blacklisted_extensions_.Insert(extension);
2010 } else if (!reloading &&
2011 extension_prefs_->IsExtensionDisabled(extension->id())) {
2012 disabled_extensions_.Insert(extension);
2013 SyncExtensionChangeIfNeeded(*extension);
2014 content::NotificationService::current()->Notify(
2015 chrome::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
2016 content::Source<Profile>(profile_),
2017 content::Details<const Extension>(extension));
2019 // Show the extension disabled error if a permissions increase was the
2020 // only reason it was disabled.
2021 if (extension_prefs_->GetDisableReasons(extension->id()) ==
2022 Extension::DISABLE_PERMISSIONS_INCREASE) {
2023 extensions::AddExtensionDisabledError(this, extension);
2025 } else if (reloading) {
2026 // Replace the old extension with the new version.
2027 CHECK(!disabled_extensions_.Insert(extension));
2028 EnableExtension(extension->id());
2029 } else {
2030 // All apps that are displayed in the launcher are ordered by their ordinals
2031 // so we must ensure they have valid ordinals.
2032 if (extension->RequiresSortOrdinal()) {
2033 if (!extension->ShouldDisplayInNewTabPage()) {
2034 extension_prefs_->extension_sorting()->MarkExtensionAsHidden(
2035 extension->id());
2037 extension_prefs_->extension_sorting()->EnsureValidOrdinals(
2038 extension->id(), syncer::StringOrdinal());
2041 extensions_.Insert(extension);
2042 SyncExtensionChangeIfNeeded(*extension);
2043 NotifyExtensionLoaded(extension);
2045 SetBeingUpgraded(extension, false);
2048 void ExtensionService::AddComponentExtension(const Extension* extension) {
2049 const std::string old_version_string(
2050 extension_prefs_->GetVersionString(extension->id()));
2051 const Version old_version(old_version_string);
2053 if (!old_version.IsValid() || !old_version.Equals(*extension->version())) {
2054 VLOG(1) << "Component extension " << extension->name() << " ("
2055 << extension->id() << ") installing/upgrading from '"
2056 << old_version_string << "' to " << extension->version()->GetString();
2058 AddNewOrUpdatedExtension(extension,
2059 Extension::ENABLED_COMPONENT,
2060 syncer::StringOrdinal());
2061 return;
2064 AddExtension(extension);
2067 void ExtensionService::UpdateActivePermissions(const Extension* extension) {
2068 // If the extension has used the optional permissions API, it will have a
2069 // custom set of active permissions defined in the extension prefs. Here,
2070 // we update the extension's active permissions based on the prefs.
2071 scoped_refptr<PermissionSet> active_permissions =
2072 extension_prefs()->GetActivePermissions(extension->id());
2074 if (active_permissions.get()) {
2075 // We restrict the active permissions to be within the bounds defined in the
2076 // extension's manifest.
2077 // a) active permissions must be a subset of optional + default permissions
2078 // b) active permissions must contains all default permissions
2079 scoped_refptr<PermissionSet> total_permissions =
2080 PermissionSet::CreateUnion(
2081 extensions::PermissionsData::GetRequiredPermissions(extension),
2082 extensions::PermissionsData::GetOptionalPermissions(extension));
2084 // Make sure the active permissions contain no more than optional + default.
2085 scoped_refptr<PermissionSet> adjusted_active =
2086 PermissionSet::CreateIntersection(
2087 total_permissions.get(), active_permissions.get());
2089 // Make sure the active permissions contain the default permissions.
2090 adjusted_active = PermissionSet::CreateUnion(
2091 extensions::PermissionsData::GetRequiredPermissions(extension),
2092 adjusted_active.get());
2094 extensions::PermissionsUpdater perms_updater(profile());
2095 perms_updater.UpdateActivePermissions(extension, adjusted_active.get());
2099 void ExtensionService::CheckPermissionsIncrease(const Extension* extension,
2100 bool is_extension_upgrade) {
2101 UpdateActivePermissions(extension);
2103 // We keep track of all permissions the user has granted each extension.
2104 // This allows extensions to gracefully support backwards compatibility
2105 // by including unknown permissions in their manifests. When the user
2106 // installs the extension, only the recognized permissions are recorded.
2107 // When the unknown permissions become recognized (e.g., through browser
2108 // upgrade), we can prompt the user to accept these new permissions.
2109 // Extensions can also silently upgrade to less permissions, and then
2110 // silently upgrade to a version that adds these permissions back.
2112 // For example, pretend that Chrome 10 includes a permission "omnibox"
2113 // for an API that adds suggestions to the omnibox. An extension can
2114 // maintain backwards compatibility while still having "omnibox" in the
2115 // manifest. If a user installs the extension on Chrome 9, the browser
2116 // will record the permissions it recognized, not including "omnibox."
2117 // When upgrading to Chrome 10, "omnibox" will be recognized and Chrome
2118 // will disable the extension and prompt the user to approve the increase
2119 // in privileges. The extension could then release a new version that
2120 // removes the "omnibox" permission. When the user upgrades, Chrome will
2121 // still remember that "omnibox" had been granted, so that if the
2122 // extension once again includes "omnibox" in an upgrade, the extension
2123 // can upgrade without requiring this user's approval.
2124 int disable_reasons = extension_prefs_->GetDisableReasons(extension->id());
2126 bool auto_grant_permission =
2127 (!is_extension_upgrade && extension->was_installed_by_default()) ||
2128 chrome::IsRunningInForcedAppMode();
2129 // Silently grant all active permissions to default apps only on install.
2130 // After install they should behave like other apps.
2131 // Silently grant all active permissions to apps install in kiosk mode on both
2132 // install and update.
2133 if (auto_grant_permission)
2134 GrantPermissions(extension);
2136 bool is_privilege_increase = false;
2137 // We only need to compare the granted permissions to the current permissions
2138 // if the extension is not allowed to silently increase its permissions.
2139 if (!extensions::PermissionsData::CanSilentlyIncreasePermissions(extension) &&
2140 !auto_grant_permission) {
2141 // Add all the recognized permissions if the granted permissions list
2142 // hasn't been initialized yet.
2143 scoped_refptr<PermissionSet> granted_permissions =
2144 extension_prefs_->GetGrantedPermissions(extension->id());
2145 CHECK(granted_permissions.get());
2147 // Here, we check if an extension's privileges have increased in a manner
2148 // that requires the user's approval. This could occur because the browser
2149 // upgraded and recognized additional privileges, or an extension upgrades
2150 // to a version that requires additional privileges.
2151 is_privilege_increase = granted_permissions->HasLessPrivilegesThan(
2152 extension->GetActivePermissions().get());
2155 if (is_extension_upgrade) {
2156 // If the extension was already disabled, suppress any alerts for becoming
2157 // disabled on permissions increase.
2158 bool previously_disabled =
2159 extension_prefs_->IsExtensionDisabled(extension->id());
2160 // Legacy disabled extensions do not have a disable reason. Infer that if
2161 // there was no permission increase, it was likely disabled by the user.
2162 if (previously_disabled && disable_reasons == Extension::DISABLE_NONE &&
2163 !extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
2164 disable_reasons |= Extension::DISABLE_USER_ACTION;
2166 // Extensions that came to us disabled from sync need a similar inference,
2167 // except based on the new version's permissions.
2168 if (previously_disabled &&
2169 disable_reasons == Extension::DISABLE_UNKNOWN_FROM_SYNC) {
2170 // Remove the DISABLE_UNKNOWN_FROM_SYNC reason.
2171 extension_prefs_->ClearDisableReasons(extension->id());
2172 if (!is_privilege_increase)
2173 disable_reasons |= Extension::DISABLE_USER_ACTION;
2175 disable_reasons &= ~Extension::DISABLE_UNKNOWN_FROM_SYNC;
2178 // Extension has changed permissions significantly. Disable it. A
2179 // notification should be sent by the caller.
2180 if (is_privilege_increase) {
2181 disable_reasons |= Extension::DISABLE_PERMISSIONS_INCREASE;
2182 if (!extension_prefs_->DidExtensionEscalatePermissions(extension->id())) {
2183 RecordPermissionMessagesHistogram(
2184 extension, "Extensions.Permissions_AutoDisable");
2186 extension_prefs_->SetExtensionState(extension->id(), Extension::DISABLED);
2187 extension_prefs_->SetDidExtensionEscalatePermissions(extension, true);
2189 if (disable_reasons != Extension::DISABLE_NONE) {
2190 extension_prefs_->AddDisableReason(
2191 extension->id(),
2192 static_cast<Extension::DisableReason>(disable_reasons));
2196 void ExtensionService::UpdateActiveExtensionsInCrashReporter() {
2197 std::set<std::string> extension_ids;
2198 for (ExtensionSet::const_iterator iter = extensions_.begin();
2199 iter != extensions_.end(); ++iter) {
2200 const Extension* extension = iter->get();
2201 if (!extension->is_theme() && extension->location() != Manifest::COMPONENT)
2202 extension_ids.insert(extension->id());
2205 child_process_logging::SetActiveExtensions(extension_ids);
2208 void ExtensionService::OnExtensionInstalled(
2209 const Extension* extension,
2210 const syncer::StringOrdinal& page_ordinal,
2211 bool has_requirement_errors,
2212 bool wait_for_idle) {
2213 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2215 const std::string& id = extension->id();
2216 bool initial_enable = ShouldEnableOnInstall(extension);
2217 const extensions::PendingExtensionInfo* pending_extension_info = NULL;
2218 if ((pending_extension_info = pending_extension_manager()->GetById(id))) {
2219 if (!pending_extension_info->ShouldAllowInstall(extension)) {
2220 pending_extension_manager()->Remove(id);
2222 LOG(WARNING) << "ShouldAllowInstall() returned false for "
2223 << id << " of type " << extension->GetType()
2224 << " and update URL "
2225 << extensions::ManifestURL::GetUpdateURL(extension).spec()
2226 << "; not installing";
2228 content::NotificationService::current()->Notify(
2229 chrome::NOTIFICATION_EXTENSION_INSTALL_NOT_ALLOWED,
2230 content::Source<Profile>(profile_),
2231 content::Details<const Extension>(extension));
2233 // Delete the extension directory since we're not going to
2234 // load it.
2235 if (!GetFileTaskRunner()->PostTask(
2236 FROM_HERE,
2237 base::Bind(&extension_file_util::DeleteFile,
2238 extension->path(), true))) {
2239 NOTREACHED();
2241 return;
2244 pending_extension_manager()->Remove(id);
2245 } else {
2246 // We explicitly want to re-enable an uninstalled external
2247 // extension; if we're here, that means the user is manually
2248 // installing the extension.
2249 if (IsExternalExtensionUninstalled(id)) {
2250 initial_enable = true;
2254 // Unsupported requirements overrides the management policy.
2255 if (has_requirement_errors) {
2256 initial_enable = false;
2257 extension_prefs_->AddDisableReason(
2258 id, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
2259 // If the extension was disabled because of unsupported requirements but
2260 // now supports all requirements after an update and there are not other
2261 // disable reasons, enable it.
2262 } else if (extension_prefs_->GetDisableReasons(id) ==
2263 Extension::DISABLE_UNSUPPORTED_REQUIREMENT) {
2264 initial_enable = true;
2265 extension_prefs_->ClearDisableReasons(id);
2268 if (!GetInstalledExtension(extension->id())) {
2269 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallType",
2270 extension->GetType(), 100);
2271 UMA_HISTOGRAM_ENUMERATION("Extensions.InstallSource",
2272 extension->location(), Manifest::NUM_LOCATIONS);
2273 RecordPermissionMessagesHistogram(
2274 extension, "Extensions.Permissions_Install");
2275 } else {
2276 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateType",
2277 extension->GetType(), 100);
2278 UMA_HISTOGRAM_ENUMERATION("Extensions.UpdateSource",
2279 extension->location(), Manifest::NUM_LOCATIONS);
2282 // Certain extension locations are specific enough that we can
2283 // auto-acknowledge any extension that came from one of them.
2284 if (extension->location() == Manifest::EXTERNAL_POLICY_DOWNLOAD)
2285 AcknowledgeExternalExtension(extension->id());
2286 const Extension::State initial_state =
2287 initial_enable ? Extension::ENABLED : Extension::DISABLED;
2288 if (ShouldDelayExtensionUpdate(id, wait_for_idle)) {
2289 extension_prefs_->SetDelayedInstallInfo(extension, initial_state,
2290 page_ordinal);
2292 // Transfer ownership of |extension|.
2293 delayed_updates_for_idle_.Insert(extension);
2295 // Notify extension of available update.
2296 extensions::RuntimeEventRouter::DispatchOnUpdateAvailableEvent(
2297 profile_, id, extension->manifest()->value());
2299 // Notify observers that app update is available.
2300 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2301 OnAppUpdateAvailable(extension->id()));
2302 return;
2305 if (installs_delayed()) {
2306 extension_prefs_->SetDelayedInstallInfo(extension, initial_state,
2307 page_ordinal);
2308 delayed_installs_.Insert(extension);
2309 } else {
2310 AddNewOrUpdatedExtension(extension, initial_state, page_ordinal);
2314 void ExtensionService::AddNewOrUpdatedExtension(
2315 const Extension* extension,
2316 Extension::State initial_state,
2317 const syncer::StringOrdinal& page_ordinal) {
2318 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2320 extension_prefs_->OnExtensionInstalled(
2321 extension,
2322 initial_state,
2323 page_ordinal);
2325 FinishInstallation(extension);
2328 void ExtensionService::MaybeFinishDelayedInstallation(
2329 const std::string& extension_id) {
2330 // Check if the extension already got updated.
2331 if (!delayed_updates_for_idle_.Contains(extension_id))
2332 return;
2333 // Check if the extension is idle.
2334 if (!IsExtensionIdle(extension_id))
2335 return;
2337 FinishDelayedInstallation(extension_id);
2340 void ExtensionService::FinishDelayedInstallation(
2341 const std::string& extension_id) {
2342 scoped_refptr<const Extension> extension(
2343 GetPendingExtensionUpdate(extension_id));
2344 CHECK(extension.get());
2345 delayed_updates_for_idle_.Remove(extension_id);
2347 if (!extension_prefs_->FinishDelayedInstallInfo(extension_id))
2348 NOTREACHED();
2350 FinishInstallation(extension.get());
2353 void ExtensionService::FinishInstallation(const Extension* extension) {
2354 const extensions::Extension* existing_extension =
2355 GetInstalledExtension(extension->id());
2356 bool is_update = false;
2357 std::string old_name;
2358 if (existing_extension) {
2359 is_update = true;
2360 old_name = existing_extension->name();
2362 extensions::InstalledExtensionInfo details(extension, is_update, old_name);
2363 content::NotificationService::current()->Notify(
2364 chrome::NOTIFICATION_EXTENSION_INSTALLED,
2365 content::Source<Profile>(profile_),
2366 content::Details<const extensions::InstalledExtensionInfo>(&details));
2368 bool unacknowledged_external = IsUnacknowledgedExternalExtension(extension);
2370 // Unpacked extensions default to allowing file access, but if that has been
2371 // overridden, don't reset the value.
2372 if (Manifest::ShouldAlwaysAllowFileAccess(extension->location()) &&
2373 !extension_prefs_->HasAllowFileAccessSetting(extension->id())) {
2374 extension_prefs_->SetAllowFileAccess(extension->id(), true);
2377 AddExtension(extension);
2379 #if defined(ENABLE_THEMES)
2380 // We do this here since AddExtension() is always called on browser startup,
2381 // and we only really care about the last theme installed.
2382 // If that ever changes and we have to move this code somewhere
2383 // else, it should be somewhere that's not in the startup path.
2384 if (extension->is_theme() && extensions_.GetByID(extension->id())) {
2385 DCHECK_EQ(extensions_.GetByID(extension->id()), extension);
2386 // Now that the theme extension is visible from outside the
2387 // ExtensionService, notify the ThemeService about the
2388 // newly-installed theme.
2389 ThemeServiceFactory::GetForProfile(profile_)->SetTheme(extension);
2391 #endif
2393 // If this is a new external extension that was disabled, alert the user
2394 // so he can reenable it. We do this last so that it has already been
2395 // added to our list of extensions.
2396 if (unacknowledged_external) {
2397 UpdateExternalExtensionAlert();
2398 UMA_HISTOGRAM_ENUMERATION("Extensions.ExternalExtensionEvent",
2399 EXTERNAL_EXTENSION_INSTALLED,
2400 EXTERNAL_EXTENSION_BUCKET_BOUNDARY);
2404 const Extension* ExtensionService::GetPendingExtensionUpdate(
2405 const std::string& id) const {
2406 return delayed_updates_for_idle_.GetByID(id);
2409 void ExtensionService::TrackTerminatedExtension(const Extension* extension) {
2410 if (!terminated_extensions_.Contains(extension->id()))
2411 terminated_extensions_.Insert(make_scoped_refptr(extension));
2413 UnloadExtension(extension->id(), extension_misc::UNLOAD_REASON_TERMINATE);
2416 void ExtensionService::UntrackTerminatedExtension(const std::string& id) {
2417 std::string lowercase_id = StringToLowerASCII(id);
2418 terminated_extensions_.Remove(lowercase_id);
2421 const Extension* ExtensionService::GetTerminatedExtension(
2422 const std::string& id) const {
2423 return GetExtensionById(id, INCLUDE_TERMINATED);
2426 const Extension* ExtensionService::GetInstalledExtension(
2427 const std::string& id) const {
2428 int include_mask = INCLUDE_ENABLED |
2429 INCLUDE_DISABLED |
2430 INCLUDE_TERMINATED |
2431 INCLUDE_BLACKLISTED;
2432 return GetExtensionById(id, include_mask);
2435 bool ExtensionService::ExtensionBindingsAllowed(const GURL& url) {
2436 // Allow bindings for all packaged extensions and component hosted apps.
2437 const Extension* extension = extensions_.GetExtensionOrAppByURL(
2438 ExtensionURLInfo(url));
2439 return extension && (!extension->is_hosted_app() ||
2440 extension->location() == Manifest::COMPONENT);
2443 bool ExtensionService::ShouldBlockUrlInBrowserTab(GURL* url) {
2444 const Extension* extension = extensions_.GetExtensionOrAppByURL(
2445 ExtensionURLInfo(*url));
2446 if (extension && extension->is_platform_app()) {
2447 *url = GURL(chrome::kExtensionInvalidRequestURL);
2448 return true;
2451 return false;
2454 bool ExtensionService::OnExternalExtensionFileFound(
2455 const std::string& id,
2456 const Version* version,
2457 const base::FilePath& path,
2458 Manifest::Location location,
2459 int creation_flags,
2460 bool mark_acknowledged) {
2461 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2462 CHECK(Extension::IdIsValid(id));
2463 if (extension_prefs_->IsExternalExtensionUninstalled(id))
2464 return false;
2466 // Before even bothering to unpack, check and see if we already have this
2467 // version. This is important because these extensions are going to get
2468 // installed on every startup.
2469 const Extension* existing = GetExtensionById(id, true);
2471 if (existing) {
2472 // The default apps will have the location set as INTERNAL. Since older
2473 // default apps are installed as EXTERNAL, we override them. However, if the
2474 // app is already installed as internal, then do the version check.
2475 // TODO(grv) : Remove after Q1-2013.
2476 bool is_default_apps_migration =
2477 (location == Manifest::INTERNAL &&
2478 Manifest::IsExternalLocation(existing->location()));
2480 if (!is_default_apps_migration) {
2481 DCHECK(version);
2483 switch (existing->version()->CompareTo(*version)) {
2484 case -1: // existing version is older, we should upgrade
2485 break;
2486 case 0: // existing version is same, do nothing
2487 return false;
2488 case 1: // existing version is newer, uh-oh
2489 LOG(WARNING) << "Found external version of extension " << id
2490 << "that is older than current version. Current version "
2491 << "is: " << existing->VersionString() << ". New "
2492 << "version is: " << version->GetString()
2493 << ". Keeping current version.";
2494 return false;
2499 // If the extension is already pending, don't start an install.
2500 if (!pending_extension_manager()->AddFromExternalFile(
2501 id, location, *version)) {
2502 return false;
2505 // no client (silent install)
2506 scoped_refptr<CrxInstaller> installer(CrxInstaller::Create(this, NULL));
2507 installer->set_install_source(location);
2508 installer->set_expected_id(id);
2509 installer->set_expected_version(*version);
2510 installer->set_install_cause(extension_misc::INSTALL_CAUSE_EXTERNAL_FILE);
2511 installer->set_creation_flags(creation_flags);
2512 #if defined(OS_CHROMEOS)
2513 extensions::InstallLimiter::Get(profile_)->Add(installer, path);
2514 #else
2515 installer->InstallCrx(path);
2516 #endif
2518 // Depending on the source, a new external extension might not need a user
2519 // notification on installation. For such extensions, mark them acknowledged
2520 // now to suppress the notification.
2521 if (mark_acknowledged)
2522 AcknowledgeExternalExtension(id);
2524 return true;
2527 void ExtensionService::ReportExtensionLoadError(
2528 const base::FilePath& extension_path,
2529 const std::string &error,
2530 bool be_noisy) {
2531 content::NotificationService::current()->Notify(
2532 chrome::NOTIFICATION_EXTENSION_LOAD_ERROR,
2533 content::Source<Profile>(profile_),
2534 content::Details<const std::string>(&error));
2536 std::string path_str = UTF16ToUTF8(extension_path.LossyDisplayName());
2537 string16 message = UTF8ToUTF16(base::StringPrintf(
2538 "Could not load extension from '%s'. %s",
2539 path_str.c_str(), error.c_str()));
2540 ExtensionErrorReporter::GetInstance()->ReportError(message, be_noisy);
2543 void ExtensionService::DidCreateRenderViewForBackgroundPage(
2544 extensions::ExtensionHost* host) {
2545 OrphanedDevTools::iterator iter =
2546 orphaned_dev_tools_.find(host->extension_id());
2547 if (iter == orphaned_dev_tools_.end())
2548 return;
2550 DevToolsAgentHost::ConnectRenderViewHost(iter->second,
2551 host->render_view_host());
2552 orphaned_dev_tools_.erase(iter);
2555 void ExtensionService::Observe(int type,
2556 const content::NotificationSource& source,
2557 const content::NotificationDetails& details) {
2558 switch (type) {
2559 case chrome::NOTIFICATION_APP_TERMINATING:
2560 // Shutdown has started. Don't start any more extension installs.
2561 // (We cannot use ExtensionService::Shutdown() for this because it
2562 // happens too late in browser teardown.)
2563 browser_terminating_ = true;
2564 break;
2565 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: {
2566 if (profile_ !=
2567 content::Source<Profile>(source).ptr()->GetOriginalProfile()) {
2568 break;
2571 extensions::ExtensionHost* host =
2572 content::Details<extensions::ExtensionHost>(details).ptr();
2574 // Mark the extension as terminated and Unload it. We want it to
2575 // be in a consistent state: either fully working or not loaded
2576 // at all, but never half-crashed. We do it in a PostTask so
2577 // that other handlers of this notification will still have
2578 // access to the Extension and ExtensionHost.
2579 base::MessageLoop::current()->PostTask(
2580 FROM_HERE,
2581 base::Bind(
2582 &ExtensionService::TrackTerminatedExtension,
2583 AsWeakPtr(),
2584 host->extension()));
2585 break;
2587 case content::NOTIFICATION_RENDERER_PROCESS_CREATED: {
2588 content::RenderProcessHost* process =
2589 content::Source<content::RenderProcessHost>(source).ptr();
2590 Profile* host_profile =
2591 Profile::FromBrowserContext(process->GetBrowserContext());
2592 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2593 break;
2595 // Extensions need to know the channel for API restrictions.
2596 process->Send(new ExtensionMsg_SetChannel(
2597 extensions::Feature::GetCurrentChannel()));
2599 // Platform apps need to know the system font.
2600 scoped_ptr<base::DictionaryValue> fonts(new base::DictionaryValue);
2601 webui::SetFontAndTextDirection(fonts.get());
2602 std::string font_family, font_size;
2603 fonts->GetString("fontfamily", &font_family);
2604 fonts->GetString("fontsize", &font_size);
2605 process->Send(new ExtensionMsg_SetSystemFont(
2606 font_family, font_size));
2608 // Valid extension function names, used to setup bindings in renderer.
2609 std::vector<std::string> function_names;
2610 ExtensionFunctionDispatcher::GetAllFunctionNames(&function_names);
2611 process->Send(new ExtensionMsg_SetFunctionNames(function_names));
2613 // Scripting whitelist. This is modified by tests and must be communicated
2614 // to renderers.
2615 process->Send(new ExtensionMsg_SetScriptingWhitelist(
2616 *Extension::GetScriptingWhitelist()));
2618 // Loaded extensions.
2619 std::vector<ExtensionMsg_Loaded_Params> loaded_extensions;
2620 for (ExtensionSet::const_iterator iter = extensions_.begin();
2621 iter != extensions_.end(); ++iter) {
2622 // Renderers don't need to know about themes.
2623 if (!(*iter)->is_theme())
2624 loaded_extensions.push_back(ExtensionMsg_Loaded_Params(iter->get()));
2626 process->Send(new ExtensionMsg_Loaded(loaded_extensions));
2627 break;
2629 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED: {
2630 content::RenderProcessHost* process =
2631 content::Source<content::RenderProcessHost>(source).ptr();
2632 Profile* host_profile =
2633 Profile::FromBrowserContext(process->GetBrowserContext());
2634 if (!profile_->IsSameProfile(host_profile->GetOriginalProfile()))
2635 break;
2637 process_map_.RemoveAllFromProcess(process->GetID());
2638 BrowserThread::PostTask(
2639 BrowserThread::IO, FROM_HERE,
2640 base::Bind(&ExtensionInfoMap::UnregisterAllExtensionsInProcess,
2641 system_->info_map(),
2642 process->GetID()));
2643 break;
2645 case chrome::NOTIFICATION_IMPORT_FINISHED: {
2646 InitAfterImport();
2647 break;
2649 case chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED: {
2650 extensions::ExtensionHost* host =
2651 content::Details<extensions::ExtensionHost>(details).ptr();
2652 std::string extension_id = host->extension_id();
2653 if (delayed_updates_for_idle_.Contains(extension_id)) {
2654 // We were waiting for this extension to become idle, it now might have,
2655 // so maybe finish installation.
2656 base::MessageLoop::current()->PostDelayedTask(
2657 FROM_HERE,
2658 base::Bind(&ExtensionService::MaybeFinishDelayedInstallation,
2659 AsWeakPtr(), extension_id),
2660 base::TimeDelta::FromSeconds(kUpdateIdleDelay));
2662 break;
2664 case chrome::NOTIFICATION_UPGRADE_RECOMMENDED: {
2665 // Notify extensions that chrome update is available.
2666 extensions::RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(
2667 profile_);
2669 // Notify observers that chrome update is available.
2670 FOR_EACH_OBSERVER(extensions::UpdateObserver, update_observers_,
2671 OnChromeUpdateAvailable());
2672 break;
2675 default:
2676 NOTREACHED() << "Unexpected notification type.";
2680 void ExtensionService::OnExtensionInstallPrefChanged() {
2681 IdentifyAlertableExtensions();
2682 CheckManagementPolicy();
2685 bool ExtensionService::HasApps() const {
2686 return !GetAppIds().empty();
2689 ExtensionIdSet ExtensionService::GetAppIds() const {
2690 ExtensionIdSet result;
2691 for (ExtensionSet::const_iterator it = extensions_.begin();
2692 it != extensions_.end(); ++it) {
2693 if ((*it)->is_app() && (*it)->location() != Manifest::COMPONENT)
2694 result.insert((*it)->id());
2697 return result;
2700 bool ExtensionService::IsBackgroundPageReady(const Extension* extension) const {
2701 if (!extensions::BackgroundInfo::HasPersistentBackgroundPage(extension))
2702 return true;
2703 ExtensionRuntimeDataMap::const_iterator it =
2704 extension_runtime_data_.find(extension->id());
2705 return it == extension_runtime_data_.end() ? false :
2706 it->second.background_page_ready;
2709 void ExtensionService::SetBackgroundPageReady(const Extension* extension) {
2710 DCHECK(extensions::BackgroundInfo::HasBackgroundPage(extension));
2711 extension_runtime_data_[extension->id()].background_page_ready = true;
2712 content::NotificationService::current()->Notify(
2713 chrome::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
2714 content::Source<const Extension>(extension),
2715 content::NotificationService::NoDetails());
2718 void ExtensionService::InspectBackgroundPage(const Extension* extension) {
2719 DCHECK(extension);
2721 ExtensionProcessManager* pm = system_->process_manager();
2722 extensions::LazyBackgroundTaskQueue* queue =
2723 system_->lazy_background_task_queue();
2725 extensions::ExtensionHost* host =
2726 pm->GetBackgroundHostForExtension(extension->id());
2727 if (host) {
2728 InspectExtensionHost(host);
2729 } else {
2730 queue->AddPendingTask(
2731 profile_, extension->id(),
2732 base::Bind(&ExtensionService::InspectExtensionHost,
2733 base::Unretained(this)));
2737 bool ExtensionService::IsBeingUpgraded(const Extension* extension) const {
2738 ExtensionRuntimeDataMap::const_iterator it =
2739 extension_runtime_data_.find(extension->id());
2740 return it == extension_runtime_data_.end() ? false :
2741 it->second.being_upgraded;
2744 void ExtensionService::SetBeingUpgraded(const Extension* extension,
2745 bool value) {
2746 extension_runtime_data_[extension->id()].being_upgraded = value;
2749 bool ExtensionService::HasUsedWebRequest(const Extension* extension) const {
2750 ExtensionRuntimeDataMap::const_iterator it =
2751 extension_runtime_data_.find(extension->id());
2752 return it == extension_runtime_data_.end() ? false :
2753 it->second.has_used_webrequest;
2756 void ExtensionService::SetHasUsedWebRequest(const Extension* extension,
2757 bool value) {
2758 extension_runtime_data_[extension->id()].has_used_webrequest = value;
2761 void ExtensionService::InspectExtensionHost(
2762 extensions::ExtensionHost* host) {
2763 if (host)
2764 DevToolsWindow::OpenDevToolsWindow(host->render_view_host());
2767 bool ExtensionService::ShouldEnableOnInstall(const Extension* extension) {
2768 // Extensions installed by policy can't be disabled. So even if a previous
2769 // installation disabled the extension, make sure it is now enabled.
2770 if (system_->management_policy()->MustRemainEnabled(extension, NULL))
2771 return true;
2773 if (extension_prefs_->IsExtensionDisabled(extension->id()))
2774 return false;
2776 if (FeatureSwitch::prompt_for_external_extensions()->IsEnabled()) {
2777 // External extensions are initially disabled. We prompt the user before
2778 // enabling them. Hosted apps are excepted because they are not dangerous
2779 // (they need to be launched by the user anyway).
2780 if (extension->GetType() != Manifest::TYPE_HOSTED_APP &&
2781 Manifest::IsExternalLocation(extension->location()) &&
2782 !extension_prefs_->IsExternalExtensionAcknowledged(extension->id())) {
2783 return false;
2787 return true;
2790 bool ExtensionService::IsExtensionIdle(const std::string& extension_id) const {
2791 ExtensionProcessManager* process_manager = system_->process_manager();
2792 DCHECK(process_manager);
2793 extensions::ExtensionHost* host =
2794 process_manager->GetBackgroundHostForExtension(extension_id);
2795 if (host)
2796 return false;
2797 return process_manager->GetRenderViewHostsForExtension(extension_id).empty();
2800 bool ExtensionService::ShouldDelayExtensionUpdate(
2801 const std::string& extension_id,
2802 bool wait_for_idle) const {
2803 const char kOnUpdateAvailableEvent[] = "runtime.onUpdateAvailable";
2805 // If delayed updates are globally disabled, or just for this extension,
2806 // don't delay.
2807 if (!install_updates_when_idle_ || !wait_for_idle)
2808 return false;
2810 const Extension* old = GetInstalledExtension(extension_id);
2811 // If there is no old extension, this is not an update, so don't delay.
2812 if (!old)
2813 return false;
2815 if (extensions::BackgroundInfo::HasPersistentBackgroundPage(old)) {
2816 // Delay installation if the extension listens for the onUpdateAvailable
2817 // event.
2818 return system_->event_router()->ExtensionHasEventListener(
2819 extension_id, kOnUpdateAvailableEvent);
2820 } else {
2821 // Delay installation if the extension is not idle.
2822 return !IsExtensionIdle(extension_id);
2826 void ExtensionService::GarbageCollectIsolatedStorage() {
2827 scoped_ptr<base::hash_set<base::FilePath> > active_paths(
2828 new base::hash_set<base::FilePath>());
2829 for (ExtensionSet::const_iterator it = extensions_.begin();
2830 it != extensions_.end(); ++it) {
2831 if (extensions::AppIsolationInfo::HasIsolatedStorage(it->get())) {
2832 active_paths->insert(BrowserContext::GetStoragePartitionForSite(
2833 profile_, GetSiteForExtensionId((*it)->id()))->GetPath());
2837 DCHECK(!installs_delayed());
2838 set_installs_delayed(true);
2839 BrowserContext::GarbageCollectStoragePartitions(
2840 profile_, active_paths.Pass(),
2841 base::Bind(&ExtensionService::OnGarbageCollectIsolatedStorageFinished,
2842 AsWeakPtr()));
2845 void ExtensionService::OnGarbageCollectIsolatedStorageFinished() {
2846 set_installs_delayed(false);
2847 for (ExtensionSet::const_iterator it = delayed_installs_.begin();
2848 it != delayed_installs_.end();
2849 ++it) {
2850 FinishDelayedInstallation((*it)->id());
2852 for (ExtensionSet::const_iterator it = delayed_updates_for_idle_.begin();
2853 it != delayed_updates_for_idle_.end();
2854 ++it) {
2855 MaybeFinishDelayedInstallation((*it)->id());
2857 delayed_installs_.Clear();
2860 void ExtensionService::OnNeedsToGarbageCollectIsolatedStorage() {
2861 extension_prefs_->SetNeedsStorageGarbageCollection(true);
2864 void ExtensionService::OnBlacklistUpdated() {
2865 blacklist_->GetBlacklistedIDs(
2866 GenerateInstalledExtensionsSet()->GetIDs(),
2867 base::Bind(&ExtensionService::ManageBlacklist,
2868 AsWeakPtr(),
2869 blacklisted_extensions_.GetIDs()));
2872 void ExtensionService::ManageBlacklist(
2873 const std::set<std::string>& old_blacklisted_ids,
2874 const std::set<std::string>& new_blacklisted_ids) {
2875 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
2877 std::set<std::string> no_longer_blacklisted;
2878 std::set_difference(old_blacklisted_ids.begin(), old_blacklisted_ids.end(),
2879 new_blacklisted_ids.begin(), new_blacklisted_ids.end(),
2880 std::inserter(no_longer_blacklisted,
2881 no_longer_blacklisted.begin()));
2882 std::set<std::string> not_yet_blacklisted;
2883 std::set_difference(new_blacklisted_ids.begin(), new_blacklisted_ids.end(),
2884 old_blacklisted_ids.begin(), old_blacklisted_ids.end(),
2885 std::inserter(not_yet_blacklisted,
2886 not_yet_blacklisted.begin()));
2888 for (std::set<std::string>::iterator it = no_longer_blacklisted.begin();
2889 it != no_longer_blacklisted.end(); ++it) {
2890 scoped_refptr<const Extension> extension =
2891 blacklisted_extensions_.GetByID(*it);
2892 DCHECK(extension.get());
2893 if (!extension.get())
2894 continue;
2895 blacklisted_extensions_.Remove(*it);
2896 AddExtension(extension.get());
2897 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.UnblacklistInstalled",
2898 extension->location(),
2899 Manifest::NUM_LOCATIONS);
2902 for (std::set<std::string>::iterator it = not_yet_blacklisted.begin();
2903 it != not_yet_blacklisted.end(); ++it) {
2904 scoped_refptr<const Extension> extension = GetInstalledExtension(*it);
2905 DCHECK(extension.get());
2906 if (!extension.get())
2907 continue;
2908 blacklisted_extensions_.Insert(extension);
2909 UnloadExtension(*it, extension_misc::UNLOAD_REASON_BLACKLIST);
2910 UMA_HISTOGRAM_ENUMERATION("ExtensionBlacklist.BlacklistInstalled",
2911 extension->location(), Manifest::NUM_LOCATIONS);
2914 IdentifyAlertableExtensions();
2917 void ExtensionService::AddUpdateObserver(extensions::UpdateObserver* observer) {
2918 update_observers_.AddObserver(observer);
2921 void ExtensionService::RemoveUpdateObserver(
2922 extensions::UpdateObserver* observer) {
2923 update_observers_.RemoveObserver(observer);