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