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