Home | History | Annotate | Download | only in extensions
      1 // Copyright (c) 2012 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 #ifndef CHROME_BROWSER_EXTENSIONS_EXTENSION_SERVICE_H_
      6 #define CHROME_BROWSER_EXTENSIONS_EXTENSION_SERVICE_H_
      7 
      8 #include <map>
      9 #include <set>
     10 #include <string>
     11 #include <vector>
     12 
     13 #include "base/compiler_specific.h"
     14 #include "base/files/file_path.h"
     15 #include "base/gtest_prod_util.h"
     16 #include "base/memory/ref_counted.h"
     17 #include "base/memory/weak_ptr.h"
     18 #include "base/prefs/pref_change_registrar.h"
     19 #include "base/strings/string16.h"
     20 #include "chrome/browser/extensions/app_sync_bundle.h"
     21 #include "chrome/browser/extensions/blacklist.h"
     22 #include "chrome/browser/extensions/extension_function_histogram_value.h"
     23 #include "chrome/browser/extensions/extension_icon_manager.h"
     24 #include "chrome/browser/extensions/extension_prefs.h"
     25 #include "chrome/browser/extensions/extension_process_manager.h"
     26 #include "chrome/browser/extensions/extension_sync_bundle.h"
     27 #include "chrome/browser/extensions/extension_toolbar_model.h"
     28 #include "chrome/browser/extensions/extensions_quota_service.h"
     29 #include "chrome/browser/extensions/external_provider_interface.h"
     30 #include "chrome/browser/extensions/menu_manager.h"
     31 #include "chrome/browser/extensions/pending_extension_manager.h"
     32 #include "chrome/browser/extensions/process_map.h"
     33 #include "chrome/browser/extensions/update_observer.h"
     34 #include "chrome/common/extensions/extension.h"
     35 #include "chrome/common/extensions/extension_constants.h"
     36 #include "chrome/common/extensions/extension_set.h"
     37 #include "chrome/common/extensions/manifest.h"
     38 #include "content/public/browser/devtools_agent_host.h"
     39 #include "content/public/browser/notification_observer.h"
     40 #include "content/public/browser/notification_registrar.h"
     41 #include "extensions/common/one_shot_event.h"
     42 #include "sync/api/string_ordinal.h"
     43 #include "sync/api/sync_change.h"
     44 #include "sync/api/syncable_service.h"
     45 
     46 class CommandLine;
     47 class ExtensionErrorUI;
     48 class ExtensionSyncData;
     49 class ExtensionToolbarModel;
     50 class GURL;
     51 class Profile;
     52 
     53 namespace base {
     54 class SequencedTaskRunner;
     55 class Version;
     56 }
     57 
     58 namespace extensions {
     59 class AppSyncData;
     60 class BrowserEventRouter;
     61 class ComponentLoader;
     62 class ContentSettingsStore;
     63 class CrxInstaller;
     64 class ExtensionActionStorageManager;
     65 class ExtensionSyncData;
     66 class ExtensionSystem;
     67 class ExtensionUpdater;
     68 class PendingExtensionManager;
     69 class SettingsFrontend;
     70 }  // namespace extensions
     71 
     72 namespace syncer {
     73 class SyncErrorFactory;
     74 }
     75 
     76 // This is an interface class to encapsulate the dependencies that
     77 // various classes have on ExtensionService. This allows easy mocking.
     78 class ExtensionServiceInterface : public syncer::SyncableService {
     79  public:
     80   virtual ~ExtensionServiceInterface() {}
     81   virtual const ExtensionSet* extensions() const = 0;
     82   virtual const ExtensionSet* disabled_extensions() const = 0;
     83   virtual extensions::PendingExtensionManager* pending_extension_manager() = 0;
     84 
     85   // Install an update.  Return true if the install can be started.
     86   // Set out_crx_installer to the installer if one was started.
     87   virtual bool UpdateExtension(
     88       const std::string& id,
     89       const base::FilePath& path,
     90       const GURL& download_url,
     91       extensions::CrxInstaller** out_crx_installer) = 0;
     92   virtual const extensions::Extension* GetExtensionById(
     93       const std::string& id,
     94       bool include_disabled) const = 0;
     95   virtual const extensions::Extension* GetInstalledExtension(
     96       const std::string& id) const = 0;
     97 
     98   virtual const extensions::Extension* GetPendingExtensionUpdate(
     99       const std::string& extension_id) const = 0;
    100   virtual void FinishDelayedInstallation(const std::string& extension_id) = 0;
    101 
    102   virtual bool IsExtensionEnabled(const std::string& extension_id) const = 0;
    103   virtual bool IsExternalExtensionUninstalled(
    104       const std::string& extension_id) const = 0;
    105 
    106   virtual void CheckManagementPolicy() = 0;
    107 
    108   // Safe to call multiple times in a row.
    109   //
    110   // TODO(akalin): Remove this method (and others) once we refactor
    111   // themes sync to not use it directly.
    112   virtual void CheckForUpdatesSoon() = 0;
    113 
    114   virtual void AddExtension(const extensions::Extension* extension) = 0;
    115   virtual void AddComponentExtension(
    116       const extensions::Extension* extension) = 0;
    117 
    118   virtual void UnloadExtension(
    119       const std::string& extension_id,
    120       extension_misc::UnloadedExtensionReason reason) = 0;
    121 
    122   virtual void SyncExtensionChangeIfNeeded(
    123       const extensions::Extension& extension) = 0;
    124 
    125   virtual bool is_ready() = 0;
    126 
    127   // Returns task runner for crx installation file I/O operations.
    128   virtual base::SequencedTaskRunner* GetFileTaskRunner() = 0;
    129 };
    130 
    131 // Manages installed and running Chromium extensions.
    132 class ExtensionService
    133     : public ExtensionServiceInterface,
    134       public extensions::ExternalProviderInterface::VisitorInterface,
    135       public content::NotificationObserver,
    136       public extensions::Blacklist::Observer {
    137  public:
    138   // If auto-updates are turned on, default to running every 5 hours.
    139   static const int kDefaultUpdateFrequencySeconds = 60 * 60 * 5;
    140 
    141   // The name of the directory inside the profile where per-app local settings
    142   // are stored.
    143   static const char kLocalAppSettingsDirectoryName[];
    144 
    145   // The name of the directory inside the profile where per-extension local
    146   // settings are stored.
    147   static const char kLocalExtensionSettingsDirectoryName[];
    148 
    149   // The name of the directory inside the profile where per-app synced settings
    150   // are stored.
    151   static const char kSyncAppSettingsDirectoryName[];
    152 
    153   // The name of the directory inside the profile where per-extension synced
    154   // settings are stored.
    155   static const char kSyncExtensionSettingsDirectoryName[];
    156 
    157   // The name of the directory inside the profile where per-extension persistent
    158   // managed settings are stored.
    159   static const char kManagedSettingsDirectoryName[];
    160 
    161   // The name of the database inside the profile where chrome-internal
    162   // extension state resides.
    163   static const char kStateStoreName[];
    164 
    165   // The name of the database inside the profile where declarative extension
    166   // rules are stored.
    167   static const char kRulesStoreName[];
    168 
    169   // Returns the Extension of hosted or packaged apps, NULL otherwise.
    170   const extensions::Extension* GetInstalledApp(const GURL& url) const;
    171 
    172   // Returns whether the URL is from either a hosted or packaged app.
    173   bool IsInstalledApp(const GURL& url) const;
    174 
    175   // If the renderer is hosting an installed app with isolated storage,
    176   // returns it, otherwise returns NULL.
    177   const extensions::Extension* GetIsolatedAppForRenderer(
    178       int renderer_child_id) const;
    179 
    180   // Attempts to uninstall an extension from a given ExtensionService. Returns
    181   // true iff the target extension exists.
    182   static bool UninstallExtensionHelper(ExtensionService* extensions_service,
    183                                        const std::string& extension_id);
    184 
    185   // Constructor stores pointers to |profile| and |extension_prefs| but
    186   // ownership remains at caller.
    187   ExtensionService(Profile* profile,
    188                    const CommandLine* command_line,
    189                    const base::FilePath& install_directory,
    190                    extensions::ExtensionPrefs* extension_prefs,
    191                    extensions::Blacklist* blacklist,
    192                    bool autoupdate_enabled,
    193                    bool extensions_enabled,
    194                    extensions::OneShotEvent* ready);
    195 
    196   virtual ~ExtensionService();
    197 
    198   // Gets the list of currently installed extensions.
    199   virtual const ExtensionSet* extensions() const OVERRIDE;
    200   virtual const ExtensionSet* disabled_extensions() const OVERRIDE;
    201   const ExtensionSet* terminated_extensions() const;
    202   const ExtensionSet* blacklisted_extensions() const;
    203   const ExtensionSet* delayed_installs() const;
    204 
    205   // Returns a set of all installed, disabled, blacklisted, and terminated
    206   // extensions.
    207   scoped_ptr<const ExtensionSet> GenerateInstalledExtensionsSet() const;
    208 
    209   // Gets the object managing the set of pending extensions.
    210   virtual extensions::PendingExtensionManager*
    211       pending_extension_manager() OVERRIDE;
    212 
    213   const base::FilePath& install_directory() const { return install_directory_; }
    214 
    215   extensions::ProcessMap* process_map() { return &process_map_; }
    216 
    217   // Whether this extension can run in an incognito window.
    218   virtual bool IsIncognitoEnabled(const std::string& extension_id) const;
    219   virtual void SetIsIncognitoEnabled(const std::string& extension_id,
    220                                      bool enabled);
    221 
    222   // Updates the app launcher value for the moved extension so that it is now
    223   // located after the given predecessor and before the successor. This will
    224   // trigger a sync if needed. Empty strings are used to indicate no successor
    225   // or predecessor.
    226   void OnExtensionMoved(const std::string& moved_extension_id,
    227                         const std::string& predecessor_extension_id,
    228                         const std::string& successor_extension_id);
    229 
    230   // Returns true if the given extension can see events and data from another
    231   // sub-profile (incognito to original profile, or vice versa).
    232   bool CanCrossIncognito(const extensions::Extension* extension) const;
    233 
    234   // Returns true if the given extension can be loaded in incognito.
    235   bool CanLoadInIncognito(const extensions::Extension* extension) const;
    236 
    237   // Whether this extension can inject scripts into pages with file URLs.
    238   bool AllowFileAccess(const extensions::Extension* extension) const;
    239   // Will reload the extension since this permission is applied at loading time
    240   // only.
    241   void SetAllowFileAccess(const extensions::Extension* extension, bool allow);
    242 
    243   // Whether the persistent background page, if any, is ready. We don't load
    244   // other components until then. If there is no background page, or if it is
    245   // non-persistent (lazy), we consider it to be ready.
    246   bool IsBackgroundPageReady(const extensions::Extension* extension) const;
    247   void SetBackgroundPageReady(const extensions::Extension* extension);
    248 
    249   // Getter and setter for the flag that specifies whether the extension is
    250   // being upgraded.
    251   bool IsBeingUpgraded(const extensions::Extension* extension) const;
    252   void SetBeingUpgraded(const extensions::Extension* extension, bool value);
    253 
    254   // Getter and setter for the flag that specifies whether the extension is
    255   // being reloaded.
    256   bool IsBeingReloaded(const std::string& extension_name) const;
    257   void SetBeingReloaded(const std::string& extension_id, bool value);
    258 
    259   // Getter and setter for the flag that specifies if the extension has used
    260   // the webrequest API.
    261   // TODO(mpcomplete): remove. http://crbug.com/100411
    262   bool HasUsedWebRequest(const extensions::Extension* extension) const;
    263   void SetHasUsedWebRequest(const extensions::Extension* extension, bool value);
    264 
    265   // Initialize and start all installed extensions.
    266   void Init();
    267 
    268   // Start up the extension event routers.
    269   void InitEventRouters();
    270 
    271   // Called when the associated Profile is going to be destroyed.
    272   void Shutdown();
    273 
    274   // Look up an extension by ID. Does not include terminated
    275   // extensions.
    276   virtual const extensions::Extension* GetExtensionById(
    277       const std::string& id, bool include_disabled) const OVERRIDE;
    278 
    279   enum IncludeFlag {
    280     INCLUDE_NONE        = 0,
    281     INCLUDE_ENABLED     = 1 << 0,
    282     INCLUDE_DISABLED    = 1 << 1,
    283     INCLUDE_TERMINATED  = 1 << 2,
    284     INCLUDE_BLACKLISTED = 1 << 3,
    285     INCLUDE_EVERYTHING = (1 << 4) - 1,
    286   };
    287 
    288   // Look up an extension by ID, selecting which sets to look in:
    289   //  * extensions()             --> INCLUDE_ENABLED
    290   //  * disabled_extensions()    --> INCLUDE_DISABLED
    291   //  * terminated_extensions()  --> INCLUDE_TERMINATED
    292   //  * blacklisted_extensions() --> INCLUDE_BLACKLISTED
    293   const extensions::Extension* GetExtensionById(const std::string& id,
    294                                                 int include_mask) const;
    295 
    296   // Returns the site of the given |extension_id|. Suitable for use with
    297   // BrowserContext::GetStoragePartitionForSite().
    298   GURL GetSiteForExtensionId(const std::string& extension_id);
    299 
    300   // Looks up a terminated (crashed) extension by ID.
    301   const extensions::Extension*
    302       GetTerminatedExtension(const std::string& id) const;
    303 
    304   // Looks up an extension by ID, regardless of whether it's enabled,
    305   // disabled, blacklisted, or terminated.
    306   virtual const extensions::Extension* GetInstalledExtension(
    307       const std::string& id) const OVERRIDE;
    308 
    309   // Updates a currently-installed extension with the contents from
    310   // |extension_path|.
    311   // TODO(aa): This method can be removed. ExtensionUpdater could use
    312   // CrxInstaller directly instead.
    313   virtual bool UpdateExtension(
    314       const std::string& id,
    315       const base::FilePath& extension_path,
    316       const GURL& download_url,
    317       extensions::CrxInstaller** out_crx_installer) OVERRIDE;
    318 
    319   // Reloads the specified extension, sending the onLaunched() event to it if it
    320   // currently has any window showing.
    321   void ReloadExtension(const std::string extension_id);
    322 
    323   // Uninstalls the specified extension. Callers should only call this method
    324   // with extensions that exist. |external_uninstall| is a magical parameter
    325   // that is only used to send information to ExtensionPrefs, which external
    326   // callers should never set to true.
    327   //
    328   // We pass the |extension_id| by value to avoid having it deleted from under
    329   // us incase someone calls it with Extension::id() or another string that we
    330   // are going to delete in this function.
    331   //
    332   // TODO(aa): Remove |external_uninstall| -- this information should be passed
    333   // to ExtensionPrefs some other way.
    334   virtual bool UninstallExtension(std::string extension_id,
    335                                   bool external_uninstall,
    336                                   string16* error);
    337 
    338   virtual bool IsExtensionEnabled(
    339       const std::string& extension_id) const OVERRIDE;
    340   virtual bool IsExternalExtensionUninstalled(
    341       const std::string& extension_id) const OVERRIDE;
    342 
    343   // Whether the extension should show as enabled state in launcher.
    344   bool IsExtensionEnabledForLauncher(const std::string& extension_id) const;
    345 
    346   // Enables the extension.  If the extension is already enabled, does
    347   // nothing.
    348   virtual void EnableExtension(const std::string& extension_id);
    349 
    350   // Disables the extension.  If the extension is already disabled, or
    351   // cannot be disabled, does nothing.
    352   virtual void DisableExtension(const std::string& extension_id,
    353       extensions::Extension::DisableReason disable_reason);
    354 
    355   // Disable non-default and non-managed extensions with ids not in
    356   // |except_ids|. Default extensions are those from the Web Store with
    357   // |was_installed_by_default| flag.
    358   void DisableUserExtensions(const std::vector<std::string>& except_ids);
    359 
    360   // Updates the |extension|'s granted permissions lists to include all
    361   // permissions in the |extension|'s manifest and re-enables the
    362   // extension.
    363   void GrantPermissionsAndEnableExtension(
    364       const extensions::Extension* extension);
    365 
    366   // Updates the |extension|'s granted permissions lists to include all
    367   // permissions in the |extensions|'s manifest.
    368   void GrantPermissions(
    369       const extensions::Extension* extension);
    370 
    371   // Check for updates (or potentially new extensions from external providers)
    372   void CheckForExternalUpdates();
    373 
    374   // Unload the specified extension.
    375   virtual void UnloadExtension(
    376       const std::string& extension_id,
    377       extension_misc::UnloadedExtensionReason reason) OVERRIDE;
    378 
    379   // Unload all extensions. This is currently only called on shutdown, and
    380   // does not send notifications.
    381   void UnloadAllExtensions();
    382 
    383   // Called only by testing.
    384   void ReloadExtensions();
    385 
    386   // Scan the extension directory and clean up the cruft.
    387   void GarbageCollectExtensions();
    388 
    389   // Notifies Sync (if needed) of a newly-installed extension or a change to
    390   // an existing extension.
    391   virtual void SyncExtensionChangeIfNeeded(
    392       const extensions::Extension& extension) OVERRIDE;
    393 
    394   // Returns true if |url| should get extension api bindings and be permitted
    395   // to make api calls. Note that this is independent of what extension
    396   // permissions the given extension has been granted.
    397   bool ExtensionBindingsAllowed(const GURL& url);
    398 
    399   // Returns true if a normal browser window should avoid showing |url| in a
    400   // tab. In this case, |url| is also rewritten to an error URL.
    401   bool ShouldBlockUrlInBrowserTab(GURL* url);
    402 
    403   // Called when the initial extensions load has completed.
    404   virtual void OnLoadedInstalledExtensions();
    405 
    406   // Adds |extension| to this ExtensionService and notifies observers that the
    407   // extensions have been loaded.
    408   virtual void AddExtension(const extensions::Extension* extension) OVERRIDE;
    409 
    410   // Check if we have preferences for the component extension and, if not or if
    411   // the stored version differs, install the extension (without requirements
    412   // checking) before calling AddExtension.
    413   virtual void AddComponentExtension(const extensions::Extension* extension)
    414       OVERRIDE;
    415 
    416   enum ImportStatus {
    417    IMPORT_STATUS_OK,
    418    IMPORT_STATUS_UNSATISFIED,
    419    IMPORT_STATUS_UNRECOVERABLE
    420   };
    421 
    422   // Checks an extension's shared module imports to see if they are satisfied.
    423   // If they are not, this function adds the dependencies to the pending install
    424   // list if |extension| came from the webstore.
    425   ImportStatus SatisfyImports(const extensions::Extension* extension);
    426 
    427   // Returns a set of extensions that import a given extension.
    428   scoped_ptr<const ExtensionSet> GetDependentExtensions(
    429       const extensions::Extension* extension);
    430 
    431   // Uninstalls shared modules that were only referenced by |extension|.
    432   void PruneSharedModulesOnUninstall(const extensions::Extension* extension);
    433 
    434   // Informs the service that an extension's files are in place for loading.
    435   //
    436   // |page_ordinal| is the location of the extension in the app launcher.
    437   // |has_requirement_errors| is true if requirements of the extension weren't
    438   // met (for example graphics capabilities).
    439   // |blacklist_state| will be BLACKLISTED if the extension is blacklisted.
    440   // |wait_for_idle| may be false to install the extension immediately.
    441   void OnExtensionInstalled(
    442       const extensions::Extension* extension,
    443       const syncer::StringOrdinal& page_ordinal,
    444       bool has_requirement_errors,
    445       extensions::Blacklist::BlacklistState blacklist_state,
    446       bool wait_for_idle);
    447 
    448   // Checks for delayed installation for all pending installs.
    449   void MaybeFinishDelayedInstallations();
    450 
    451   // Similar to FinishInstallation, but first checks if there still is an update
    452   // pending for the extension, and makes sure the extension is still idle.
    453   void MaybeFinishDelayedInstallation(const std::string& extension_id);
    454 
    455   // Finishes installation of an update for an extension with the specified id,
    456   // when installation of that extension was previously delayed because the
    457   // extension was in use.
    458   virtual void FinishDelayedInstallation(
    459      const std::string& extension_id) OVERRIDE;
    460 
    461   // Returns an update for an extension with the specified id, if installation
    462   // of that update was previously delayed because the extension was in use. If
    463   // no updates are pending for the extension returns NULL.
    464   virtual const extensions::Extension* GetPendingExtensionUpdate(
    465       const std::string& extension_id) const OVERRIDE;
    466 
    467   // Go through each extension and unload those that are not allowed to run by
    468   // management policy providers (ie. network admin and Google-managed
    469   // blacklist).
    470   virtual void CheckManagementPolicy() OVERRIDE;
    471 
    472   virtual void CheckForUpdatesSoon() OVERRIDE;
    473 
    474   // syncer::SyncableService implementation.
    475   virtual syncer::SyncMergeResult MergeDataAndStartSyncing(
    476       syncer::ModelType type,
    477       const syncer::SyncDataList& initial_sync_data,
    478       scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
    479       scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) OVERRIDE;
    480   virtual void StopSyncing(syncer::ModelType type) OVERRIDE;
    481   virtual syncer::SyncDataList GetAllSyncData(
    482       syncer::ModelType type) const OVERRIDE;
    483   virtual syncer::SyncError ProcessSyncChanges(
    484       const tracked_objects::Location& from_here,
    485       const syncer::SyncChangeList& change_list) OVERRIDE;
    486 
    487   // Gets the sync data for the given extension, assuming that the extension is
    488   // syncable.
    489   extensions::ExtensionSyncData GetExtensionSyncData(
    490       const extensions::Extension& extension) const;
    491 
    492   // Gets the sync data for the given app, assuming that the app is
    493   // syncable.
    494   extensions::AppSyncData GetAppSyncData(
    495       const extensions::Extension& extension) const;
    496 
    497   // Gets the ExtensionSyncData for all extensions.
    498   std::vector<extensions::ExtensionSyncData> GetExtensionSyncDataList() const;
    499 
    500   // Gets the AppSyncData for all extensions.
    501   std::vector<extensions::AppSyncData> GetAppSyncDataList() const;
    502 
    503   // Applies the change specified passed in by either ExtensionSyncData or
    504   // AppSyncData to the current system.
    505   // Returns false if the changes were not completely applied and were added
    506   // to the pending list to be tried again.
    507   bool ProcessExtensionSyncData(
    508       const extensions::ExtensionSyncData& extension_sync_data);
    509   bool ProcessAppSyncData(const extensions::AppSyncData& app_sync_data);
    510 
    511 
    512   void set_extensions_enabled(bool enabled) { extensions_enabled_ = enabled; }
    513   bool extensions_enabled() { return extensions_enabled_; }
    514 
    515   void set_show_extensions_prompts(bool enabled) {
    516     show_extensions_prompts_ = enabled;
    517   }
    518 
    519   bool show_extensions_prompts() {
    520     return show_extensions_prompts_;
    521   }
    522 
    523   Profile* profile();
    524 
    525   // TODO(skerner): Change to const ExtensionPrefs& extension_prefs() const,
    526   // ExtensionPrefs* mutable_extension_prefs().
    527   extensions::ExtensionPrefs* extension_prefs();
    528 
    529   extensions::SettingsFrontend* settings_frontend();
    530 
    531   extensions::ContentSettingsStore* GetContentSettingsStore();
    532 
    533   // Whether the extension service is ready.
    534   virtual bool is_ready() OVERRIDE;
    535 
    536   virtual base::SequencedTaskRunner* GetFileTaskRunner() OVERRIDE;
    537 
    538   extensions::ComponentLoader* component_loader() {
    539     return component_loader_.get();
    540   }
    541 
    542   // Note that this may return NULL if autoupdate is not turned on.
    543   extensions::ExtensionUpdater* updater();
    544 
    545   ExtensionToolbarModel* toolbar_model() { return &toolbar_model_; }
    546 
    547   ExtensionsQuotaService* quota_service() { return &quota_service_; }
    548 
    549   extensions::MenuManager* menu_manager() { return &menu_manager_; }
    550 
    551   extensions::BrowserEventRouter* browser_event_router() {
    552     return browser_event_router_.get();
    553   }
    554 
    555   // Notify the frontend that there was an error loading an extension.
    556   // This method is public because UnpackedInstaller and InstalledLoader
    557   // can post to here.
    558   // TODO(aa): Remove this. It doesn't do enough to be worth the dependency
    559   // of these classes on ExtensionService.
    560   void ReportExtensionLoadError(const base::FilePath& extension_path,
    561                                 const std::string& error,
    562                                 bool be_noisy);
    563 
    564   // ExtensionHost of background page calls this method right after its render
    565   // view has been created.
    566   void DidCreateRenderViewForBackgroundPage(extensions::ExtensionHost* host);
    567 
    568   // For the extension in |version_path| with |id|, check to see if it's an
    569   // externally managed extension.  If so, uninstall it.
    570   void CheckExternalUninstall(const std::string& id);
    571 
    572   // Changes sequenced task runner for crx installation tasks to |task_runner|.
    573   void SetFileTaskRunnerForTesting(base::SequencedTaskRunner* task_runner);
    574 
    575   // Clear all ExternalProviders.
    576   void ClearProvidersForTesting();
    577 
    578   // Adds an ExternalProviderInterface for the service to use during testing.
    579   // Takes ownership of |test_provider|.
    580   void AddProviderForTesting(
    581       extensions::ExternalProviderInterface* test_provider);
    582 
    583   // ExternalProvider::Visitor implementation.
    584   virtual bool OnExternalExtensionFileFound(
    585       const std::string& id,
    586       const base::Version* version,
    587       const base::FilePath& path,
    588       extensions::Manifest::Location location,
    589       int creation_flags,
    590       bool mark_acknowledged) OVERRIDE;
    591 
    592   virtual bool OnExternalExtensionUpdateUrlFound(
    593       const std::string& id,
    594       const GURL& update_url,
    595       extensions::Manifest::Location location) OVERRIDE;
    596 
    597   virtual void OnExternalProviderReady(
    598       const extensions::ExternalProviderInterface* provider) OVERRIDE;
    599 
    600   // Returns true when all the external extension providers are ready.
    601   bool AreAllExternalProvidersReady() const;
    602 
    603   void OnAllExternalProvidersReady();
    604 
    605   // Once all external providers are done, generates any needed alerts about
    606   // extensions.
    607   void IdentifyAlertableExtensions();
    608 
    609   // Given an ExtensionErrorUI alert, populates it with any extensions that
    610   // need alerting. Returns true if the alert should be displayed at all.
    611   //
    612   // This method takes the extension_error_ui argument rather than using
    613   // the member variable to make it easier to test the method in isolation.
    614   bool PopulateExtensionErrorUI(ExtensionErrorUI* extension_error_ui);
    615 
    616   // Checks if there are any new external extensions to notify the user about.
    617   void UpdateExternalExtensionAlert();
    618 
    619   // Given a (presumably just-installed) extension id, mark that extension as
    620   // acknowledged.
    621   void AcknowledgeExternalExtension(const std::string& id);
    622 
    623   // Returns true if this extension is an external one that has yet to be
    624   // marked as acknowledged.
    625   bool IsUnacknowledgedExternalExtension(
    626       const extensions::Extension* extension);
    627 
    628   // Opens the Extensions page because the user wants to get more details
    629   // about the alerts.
    630   void HandleExtensionAlertDetails();
    631 
    632   // Called when the extension alert is closed. Updates prefs and deletes
    633   // the active |extension_error_ui_|.
    634   void HandleExtensionAlertClosed();
    635 
    636   // Marks alertable extensions as acknowledged, after the user presses the
    637   // accept button.
    638   void HandleExtensionAlertAccept();
    639 
    640   // content::NotificationObserver
    641   virtual void Observe(int type,
    642                        const content::NotificationSource& source,
    643                        const content::NotificationDetails& details) OVERRIDE;
    644 
    645   // Whether there are any apps installed. Component apps are not included.
    646   bool HasApps() const;
    647 
    648   // Gets the set of loaded app ids. Component apps are not included.
    649   extensions::ExtensionIdSet GetAppIds() const;
    650 
    651   // Record a histogram using the PermissionMessage enum values for each
    652   // permission in |e|.
    653   // NOTE: If this is ever called with high frequency, the implementation may
    654   // need to be made more efficient.
    655   static void RecordPermissionMessagesHistogram(
    656       const extensions::Extension* e, const char* histogram);
    657 
    658   // Open a dev tools window for the background page for the given extension,
    659   // starting the background page first if necessary.
    660   void InspectBackgroundPage(const extensions::Extension* extension);
    661 
    662 #if defined(UNIT_TEST)
    663   void TrackTerminatedExtensionForTest(const extensions::Extension* extension) {
    664     TrackTerminatedExtension(extension);
    665   }
    666 
    667   void FinishInstallationForTest(const extensions::Extension* extension) {
    668     FinishInstallation(extension);
    669   }
    670 #endif
    671 
    672   // Specialization of syncer::SyncableService::AsWeakPtr.
    673   base::WeakPtr<ExtensionService> AsWeakPtr() { return base::AsWeakPtr(this); }
    674 
    675   bool browser_terminating() const { return browser_terminating_; }
    676 
    677   // For testing.
    678   void set_browser_terminating_for_test(bool value) {
    679     browser_terminating_ = value;
    680   }
    681 
    682   // By default ExtensionService will wait with installing an updated extension
    683   // until the extension is idle. Tests might not like this behavior, so you can
    684   // disable it with this method.
    685   void set_install_updates_when_idle_for_test(bool value) {
    686     install_updates_when_idle_ = value;
    687   }
    688 
    689   // Adds/Removes update observers.
    690   void AddUpdateObserver(extensions::UpdateObserver* observer);
    691   void RemoveUpdateObserver(extensions::UpdateObserver* observer);
    692 
    693   // |flare| provides a StartSyncFlare to the SyncableService. See
    694   // sync_start_util for more.
    695   void SetSyncStartFlare(const syncer::SyncableService::StartSyncFlare& flare);
    696 
    697 #if defined(OS_CHROMEOS)
    698   void disable_garbage_collection() {
    699     disable_garbage_collection_ = true;
    700   }
    701   void enable_garbage_collection() {
    702     disable_garbage_collection_ = false;
    703   }
    704 #endif
    705 
    706  private:
    707   // Contains Extension data that can change during the life of the process,
    708   // but does not persist across restarts.
    709   struct ExtensionRuntimeData {
    710     // True if the background page is ready.
    711     bool background_page_ready;
    712 
    713     // True while the extension is being upgraded.
    714     bool being_upgraded;
    715 
    716     // True if the extension has used the webRequest API.
    717     bool has_used_webrequest;
    718 
    719     ExtensionRuntimeData();
    720     ~ExtensionRuntimeData();
    721   };
    722   typedef std::map<std::string, ExtensionRuntimeData> ExtensionRuntimeDataMap;
    723 
    724   // Signals *ready_ and sends a notification to the listeners.
    725   void SetReadyAndNotifyListeners();
    726 
    727   // Return true if the sync type of |extension| matches |type|.
    728   bool IsCorrectSyncType(const extensions::Extension& extension,
    729                          syncer::ModelType type)
    730       const;
    731 
    732   void OnExtensionInstallPrefChanged();
    733 
    734   // Handles setting the extension specific values in |extension_sync_data| to
    735   // the current system.
    736   // Returns false if the changes were not completely applied and need to be
    737   // tried again later.
    738   bool ProcessExtensionSyncDataHelper(
    739       const extensions::ExtensionSyncData& extension_sync_data,
    740       syncer::ModelType type);
    741 
    742   // Adds the given extension to the list of terminated extensions if
    743   // it is not already there and unloads it.
    744   void TrackTerminatedExtension(const extensions::Extension* extension);
    745 
    746   // Removes the extension with the given id from the list of
    747   // terminated extensions if it is there.
    748   void UntrackTerminatedExtension(const std::string& id);
    749 
    750   // Update preferences for a new or updated extension; notify observers that
    751   // the extension is installed, e.g., to update event handlers on background
    752   // pages; and perform other extension install tasks before calling
    753   // AddExtension.
    754   void AddNewOrUpdatedExtension(
    755       const extensions::Extension* extension,
    756       extensions::Extension::State initial_state,
    757       extensions::Blacklist::BlacklistState blacklist_state,
    758       const syncer::StringOrdinal& page_ordinal);
    759 
    760   // Handles sending notification that |extension| was loaded.
    761   void NotifyExtensionLoaded(const extensions::Extension* extension);
    762 
    763   // Handles sending notification that |extension| was unloaded.
    764   void NotifyExtensionUnloaded(const extensions::Extension* extension,
    765                                extension_misc::UnloadedExtensionReason reason);
    766 
    767   // Common helper to finish installing the given extension.
    768   void FinishInstallation(const extensions::Extension* extension);
    769 
    770   // Updates the |extension|'s active permission set to include only permissions
    771   // currently requested by the extension and all the permissions required by
    772   // the extension.
    773   void UpdateActivePermissions(const extensions::Extension* extension);
    774 
    775   // Disables the extension if the privilege level has increased
    776   // (e.g., due to an upgrade).
    777   void CheckPermissionsIncrease(const extensions::Extension* extension,
    778                                 bool is_extension_installed);
    779 
    780   // Helper that updates the active extension list used for crash reporting.
    781   void UpdateActiveExtensionsInCrashReporter();
    782 
    783   // Helper to inspect an ExtensionHost after it has been loaded.
    784   void InspectExtensionHost(extensions::ExtensionHost* host);
    785 
    786   // Helper to determine whether we should initially enable an installed
    787   // (or upgraded) extension.
    788   bool ShouldEnableOnInstall(const extensions::Extension* extension);
    789 
    790   // Helper to determine if an extension is idle, and it should be safe
    791   // to update the extension.
    792   bool IsExtensionIdle(const std::string& extension_id) const;
    793 
    794   // Helper to determine if updating an extensions should proceed immediately,
    795   // or if we should delay the update until further notice.
    796   bool ShouldDelayExtensionUpdate(const std::string& extension_id,
    797                                   bool wait_for_idle) const;
    798 
    799   // Helper to search storage directories for extensions with isolated storage
    800   // that have been orphaned by an uninstall.
    801   void GarbageCollectIsolatedStorage();
    802   void OnGarbageCollectIsolatedStorageFinished();
    803   void OnNeedsToGarbageCollectIsolatedStorage();
    804 
    805   // extensions::Blacklist::Observer implementation.
    806   virtual void OnBlacklistUpdated() OVERRIDE;
    807 
    808   // Manages the blacklisted extensions, intended as callback from
    809   // Blacklist::GetBlacklistedIDs.
    810   void ManageBlacklist(const std::set<std::string>& old_blacklisted_ids,
    811                        const std::set<std::string>& new_blacklisted_ids);
    812 
    813   // Controls if installs are delayed. See comment for
    814   // |installs_delayed_for_gc_|.
    815   void set_installs_delayed_for_gc(bool value) {
    816     installs_delayed_for_gc_ = value;
    817   }
    818   bool installs_delayed_for_gc() const { return installs_delayed_for_gc_; }
    819 
    820   // The normal profile associated with this ExtensionService.
    821   Profile* profile_;
    822 
    823   // The ExtensionSystem for the profile above.
    824   extensions::ExtensionSystem* system_;
    825 
    826   // Preferences for the owning profile.
    827   extensions::ExtensionPrefs* extension_prefs_;
    828 
    829   // Blacklist for the owning profile.
    830   extensions::Blacklist* blacklist_;
    831 
    832   // Settings for the owning profile.
    833   scoped_ptr<extensions::SettingsFrontend> settings_frontend_;
    834 
    835   // The current list of installed extensions.
    836   ExtensionSet extensions_;
    837 
    838   // The list of installed extensions that have been disabled.
    839   ExtensionSet disabled_extensions_;
    840 
    841   // The list of installed extensions that have been terminated.
    842   ExtensionSet terminated_extensions_;
    843 
    844   // The list of installed extensions that have been blacklisted. Generally
    845   // these shouldn't be considered as installed by the extension platform: we
    846   // only keep them around so that if extensions are blacklisted by mistake
    847   // they can easily be un-blacklisted.
    848   ExtensionSet blacklisted_extensions_;
    849 
    850   // The list of extension installs delayed for various reasons.  The reason
    851   // for delayed install is stored in ExtensionPrefs.
    852   ExtensionSet delayed_installs_;
    853 
    854   // Hold the set of pending extensions.
    855   extensions::PendingExtensionManager pending_extension_manager_;
    856 
    857   // The map of extension IDs to their runtime data.
    858   ExtensionRuntimeDataMap extension_runtime_data_;
    859 
    860   // The full path to the directory where extensions are installed.
    861   base::FilePath install_directory_;
    862 
    863   // Whether or not extensions are enabled.
    864   bool extensions_enabled_;
    865 
    866   // Whether to notify users when they attempt to install an extension.
    867   bool show_extensions_prompts_;
    868 
    869   // Whether to delay installing of extension updates until the extension is
    870   // idle.
    871   bool install_updates_when_idle_;
    872 
    873   // Used by dispatchers to limit API quota for individual extensions.
    874   ExtensionsQuotaService quota_service_;
    875 
    876   // Signaled when all extensions are loaded.
    877   extensions::OneShotEvent* const ready_;
    878 
    879   // Our extension updater, if updates are turned on.
    880   scoped_ptr<extensions::ExtensionUpdater> updater_;
    881 
    882   // The model that tracks extensions with BrowserAction buttons.
    883   ExtensionToolbarModel toolbar_model_;
    884 
    885   // Map unloaded extensions' ids to their paths. When a temporarily loaded
    886   // extension is unloaded, we lose the information about it and don't have
    887   // any in the extension preferences file.
    888   typedef std::map<std::string, base::FilePath> UnloadedExtensionPathMap;
    889   UnloadedExtensionPathMap unloaded_extension_paths_;
    890 
    891   // Store the ids of reloading extensions.
    892   std::set<std::string> reloading_extensions_;
    893 
    894   // Map of DevToolsAgentHost instances that are detached,
    895   // waiting for an extension to be reloaded.
    896   typedef std::map<std::string, scoped_refptr<content::DevToolsAgentHost> >
    897       OrphanedDevTools;
    898   OrphanedDevTools orphaned_dev_tools_;
    899 
    900   content::NotificationRegistrar registrar_;
    901   PrefChangeRegistrar pref_change_registrar_;
    902 
    903   // Keeps track of loading and unloading component extensions.
    904   scoped_ptr<extensions::ComponentLoader> component_loader_;
    905 
    906   // Keeps track of menu items added by extensions.
    907   extensions::MenuManager menu_manager_;
    908 
    909   // Flag to make sure event routers are only initialized once.
    910   bool event_routers_initialized_;
    911 
    912   // TODO(yoz): None of these should be owned by ExtensionService.
    913   // crbug.com/159265
    914   scoped_ptr<extensions::BrowserEventRouter> browser_event_router_;
    915 
    916   // A collection of external extension providers.  Each provider reads
    917   // a source of external extension information.  Examples include the
    918   // windows registry and external_extensions.json.
    919   extensions::ProviderCollection external_extension_providers_;
    920 
    921   // Set to true by OnExternalExtensionUpdateUrlFound() when an external
    922   // extension URL is found, and by CheckForUpdatesSoon() when an update check
    923   // has to wait for the external providers.  Used in
    924   // OnAllExternalProvidersReady() to determine if an update check is needed to
    925   // install pending extensions.
    926   bool update_once_all_providers_are_ready_;
    927 
    928   // Set when the browser is terminating. Prevents us from installing or
    929   // updating additional extensions and allows in-progress installations to
    930   // decide to abort.
    931   bool browser_terminating_;
    932 
    933   // Set to true to delay all new extension installations. Acts as a lock to
    934   // allow background processing of garbage collection of on-disk state without
    935   // needing to worry about race conditions caused by extension installation and
    936   // reinstallation.
    937   bool installs_delayed_for_gc_;
    938 
    939   // Set to true if this is the first time this ExtensionService has run.
    940   // Used for specially handling external extensions that are installed the
    941   // first time.
    942   bool is_first_run_;
    943 
    944   extensions::AppSyncBundle app_sync_bundle_;
    945   extensions::ExtensionSyncBundle extension_sync_bundle_;
    946 
    947   extensions::ProcessMap process_map_;
    948 
    949   // A set of the extension ids currently being reloaded.  We use this to
    950   // avoid showing a "new install" notice for an extension reinstall.
    951   std::set<std::string> extensions_being_reloaded_;
    952 
    953   scoped_ptr<ExtensionErrorUI> extension_error_ui_;
    954   // Sequenced task runner for extension related file operations.
    955   scoped_refptr<base::SequencedTaskRunner> file_task_runner_;
    956 
    957 #if defined(ENABLE_EXTENSIONS)
    958   scoped_ptr<extensions::ExtensionActionStorageManager>
    959       extension_action_storage_manager_;
    960 #endif
    961 
    962   ObserverList<extensions::UpdateObserver, true> update_observers_;
    963 
    964   // Run()ning tells sync to try and start soon, because syncable changes
    965   // have started happening. It will cause sync to call us back
    966   // asynchronously via MergeDataAndStartSyncing as soon as possible.
    967   syncer::SyncableService::StartSyncFlare flare_;
    968 
    969 #if defined(OS_CHROMEOS)
    970   // TODO(rkc): HACK alert - this is only in place to allow the
    971   // kiosk_mode_screensaver to prevent its extension from getting garbage
    972   // collected. Remove this once KioskModeScreensaver is removed.
    973   // See crbug.com/280363
    974   bool disable_garbage_collection_;
    975 #endif
    976 
    977   FRIEND_TEST_ALL_PREFIXES(ExtensionServiceTest,
    978                            InstallAppsWithUnlimtedStorage);
    979   FRIEND_TEST_ALL_PREFIXES(ExtensionServiceTest,
    980                            InstallAppsAndCheckStorageProtection);
    981   DISALLOW_COPY_AND_ASSIGN(ExtensionService);
    982 };
    983 
    984 #endif  // CHROME_BROWSER_EXTENSIONS_EXTENSION_SERVICE_H_
    985