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