Home | History | Annotate | Download | only in common
      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 #ifndef EXTENSIONS_COMMON_EXTENSION_H_
      6 #define EXTENSIONS_COMMON_EXTENSION_H_
      7 
      8 #include <algorithm>
      9 #include <iosfwd>
     10 #include <map>
     11 #include <set>
     12 #include <string>
     13 #include <utility>
     14 #include <vector>
     15 
     16 #include "base/containers/hash_tables.h"
     17 #include "base/files/file_path.h"
     18 #include "base/memory/linked_ptr.h"
     19 #include "base/memory/ref_counted.h"
     20 #include "base/memory/scoped_ptr.h"
     21 #include "base/synchronization/lock.h"
     22 #include "base/threading/thread_checker.h"
     23 #include "extensions/common/extension_resource.h"
     24 #include "extensions/common/install_warning.h"
     25 #include "extensions/common/manifest.h"
     26 #include "extensions/common/url_pattern_set.h"
     27 #include "ui/base/accelerators/accelerator.h"
     28 #include "ui/gfx/size.h"
     29 #include "url/gurl.h"
     30 
     31 class ExtensionAction;
     32 class SkBitmap;
     33 
     34 namespace base {
     35 class DictionaryValue;
     36 class Version;
     37 }
     38 
     39 namespace gfx {
     40 class ImageSkia;
     41 }
     42 
     43 namespace extensions {
     44 class PermissionSet;
     45 class PermissionsData;
     46 class PermissionsParser;
     47 
     48 // Uniquely identifies an Extension, using 32 characters from the alphabet
     49 // 'a'-'p'.  An empty string represents "no extension".
     50 //
     51 // Note: If this gets used heavily in files that don't otherwise need to include
     52 // extension.h, we should pull it into a dedicated header.
     53 typedef std::string ExtensionId;
     54 
     55 // Represents a Chrome extension.
     56 // Once created, an Extension object is immutable, with the exception of its
     57 // RuntimeData. This makes it safe to use on any thread, since access to the
     58 // RuntimeData is protected by a lock.
     59 class Extension : public base::RefCountedThreadSafe<Extension> {
     60  public:
     61   struct ManifestData;
     62 
     63   typedef std::map<const std::string, linked_ptr<ManifestData> >
     64       ManifestDataMap;
     65 
     66   enum State {
     67     DISABLED = 0,
     68     ENABLED,
     69     // An external extension that the user uninstalled. We should not reinstall
     70     // such extensions on startup.
     71     EXTERNAL_EXTENSION_UNINSTALLED,
     72     // Special state for component extensions, since they are always loaded by
     73     // the component loader, and should never be auto-installed on startup.
     74     ENABLED_COMPONENT,
     75     NUM_STATES
     76   };
     77 
     78   // Used to record the reason an extension was disabled.
     79   enum DeprecatedDisableReason {
     80     DEPRECATED_DISABLE_UNKNOWN,
     81     DEPRECATED_DISABLE_USER_ACTION,
     82     DEPRECATED_DISABLE_PERMISSIONS_INCREASE,
     83     DEPRECATED_DISABLE_RELOAD,
     84     DEPRECATED_DISABLE_LAST,  // Not used.
     85   };
     86 
     87   enum DisableReason {
     88     DISABLE_NONE = 0,
     89     DISABLE_USER_ACTION = 1 << 0,
     90     DISABLE_PERMISSIONS_INCREASE = 1 << 1,
     91     DISABLE_RELOAD = 1 << 2,
     92     DISABLE_UNSUPPORTED_REQUIREMENT = 1 << 3,
     93     DISABLE_SIDELOAD_WIPEOUT = 1 << 4,
     94     DISABLE_UNKNOWN_FROM_SYNC = 1 << 5,
     95     DISABLE_PERMISSIONS_CONSENT = 1 << 6,  // Unused - abandoned experiment.
     96     DISABLE_KNOWN_DISABLED = 1 << 7,
     97     DISABLE_NOT_VERIFIED = 1 << 8,  // Disabled because we could not verify
     98                                     // the install.
     99     DISABLE_GREYLIST = 1 << 9,
    100     DISABLE_CORRUPTED = 1 << 10,
    101     DISABLE_REMOTE_INSTALL = 1 << 11
    102   };
    103 
    104   enum InstallType {
    105     INSTALL_ERROR,
    106     DOWNGRADE,
    107     REINSTALL,
    108     UPGRADE,
    109     NEW_INSTALL
    110   };
    111 
    112   // A base class for parsed manifest data that APIs want to store on
    113   // the extension. Related to base::SupportsUserData, but with an immutable
    114   // thread-safe interface to match Extension.
    115   struct ManifestData {
    116     virtual ~ManifestData() {}
    117   };
    118 
    119   // Do not change the order of entries or remove entries in this list
    120   // as this is used in UMA_HISTOGRAM_ENUMERATIONs about extensions.
    121   enum InitFromValueFlags {
    122     NO_FLAGS = 0,
    123 
    124     // Usually, the id of an extension is generated by the "key" property of
    125     // its manifest, but if |REQUIRE_KEY| is not set, a temporary ID will be
    126     // generated based on the path.
    127     REQUIRE_KEY = 1 << 0,
    128 
    129     // Requires the extension to have an up-to-date manifest version.
    130     // Typically, we'll support multiple manifest versions during a version
    131     // transition. This flag signals that we want to require the most modern
    132     // manifest version that Chrome understands.
    133     REQUIRE_MODERN_MANIFEST_VERSION = 1 << 1,
    134 
    135     // |ALLOW_FILE_ACCESS| indicates that the user is allowing this extension
    136     // to have file access. If it's not present, then permissions and content
    137     // scripts that match file:/// URLs will be filtered out.
    138     ALLOW_FILE_ACCESS = 1 << 2,
    139 
    140     // |FROM_WEBSTORE| indicates that the extension was installed from the
    141     // Chrome Web Store.
    142     FROM_WEBSTORE = 1 << 3,
    143 
    144     // |FROM_BOOKMARK| indicates the extension is a bookmark app which has been
    145     // generated from a web page. Bookmark apps have no permissions or extent
    146     // and launch the web page they are created from when run.
    147     FROM_BOOKMARK = 1 << 4,
    148 
    149     // |FOLLOW_SYMLINKS_ANYWHERE| means that resources can be symlinks to
    150     // anywhere in the filesystem, rather than being restricted to the
    151     // extension directory.
    152     FOLLOW_SYMLINKS_ANYWHERE = 1 << 5,
    153 
    154     // |ERROR_ON_PRIVATE_KEY| means that private keys inside an
    155     // extension should be errors rather than warnings.
    156     ERROR_ON_PRIVATE_KEY = 1 << 6,
    157 
    158     // |WAS_INSTALLED_BY_DEFAULT| installed by default when the profile was
    159     // created.
    160     WAS_INSTALLED_BY_DEFAULT = 1 << 7,
    161 
    162     // Unused - was part of an abandoned experiment.
    163     REQUIRE_PERMISSIONS_CONSENT = 1 << 8,
    164 
    165     // Unused - this flag has been moved to ExtensionPrefs.
    166     IS_EPHEMERAL = 1 << 9,
    167 
    168     // |WAS_INSTALLED_BY_OEM| installed by an OEM (e.g on Chrome OS) and should
    169     // be placed in a special OEM folder in the App Launcher. Note: OEM apps are
    170     // also installed by Default (i.e. WAS_INSTALLED_BY_DEFAULT is also true).
    171     WAS_INSTALLED_BY_OEM = 1 << 10,
    172 
    173     // When adding new flags, make sure to update kInitFromValueFlagBits.
    174   };
    175 
    176   // This is the highest bit index of the flags defined above.
    177   static const int kInitFromValueFlagBits;
    178 
    179   static scoped_refptr<Extension> Create(const base::FilePath& path,
    180                                          Manifest::Location location,
    181                                          const base::DictionaryValue& value,
    182                                          int flags,
    183                                          std::string* error);
    184 
    185   // In a few special circumstances, we want to create an Extension and give it
    186   // an explicit id. Most consumers should just use the other Create() method.
    187   static scoped_refptr<Extension> Create(const base::FilePath& path,
    188                                          Manifest::Location location,
    189                                          const base::DictionaryValue& value,
    190                                          int flags,
    191                                          const ExtensionId& explicit_id,
    192                                          std::string* error);
    193 
    194   // Valid schemes for web extent URLPatterns.
    195   static const int kValidWebExtentSchemes;
    196 
    197   // Valid schemes for host permission URLPatterns.
    198   static const int kValidHostPermissionSchemes;
    199 
    200   // The mimetype used for extensions.
    201   static const char kMimeType[];
    202 
    203   // Checks to see if the extension has a valid ID.
    204   static bool IdIsValid(const std::string& id);
    205 
    206   // See Type definition in Manifest.
    207   Manifest::Type GetType() const;
    208 
    209   // Returns an absolute url to a resource inside of an extension. The
    210   // |extension_url| argument should be the url() from an Extension object. The
    211   // |relative_path| can be untrusted user input. The returned URL will either
    212   // be invalid() or a child of |extension_url|.
    213   // NOTE: Static so that it can be used from multiple threads.
    214   static GURL GetResourceURL(const GURL& extension_url,
    215                              const std::string& relative_path);
    216   GURL GetResourceURL(const std::string& relative_path) const {
    217     return GetResourceURL(url(), relative_path);
    218   }
    219 
    220   // Returns true if the resource matches a pattern in the pattern_set.
    221   bool ResourceMatches(const URLPatternSet& pattern_set,
    222                        const std::string& resource) const;
    223 
    224   // Returns an extension resource object. |relative_path| should be UTF8
    225   // encoded.
    226   ExtensionResource GetResource(const std::string& relative_path) const;
    227 
    228   // As above, but with |relative_path| following the file system's encoding.
    229   ExtensionResource GetResource(const base::FilePath& relative_path) const;
    230 
    231   // |input| is expected to be the text of an rsa public or private key. It
    232   // tolerates the presence or absence of bracking header/footer like this:
    233   //     -----(BEGIN|END) [RSA PUBLIC/PRIVATE] KEY-----
    234   // and may contain newlines.
    235   static bool ParsePEMKeyBytes(const std::string& input, std::string* output);
    236 
    237   // Does a simple base64 encoding of |input| into |output|.
    238   static bool ProducePEM(const std::string& input, std::string* output);
    239 
    240   // Expects base64 encoded |input| and formats into |output| including
    241   // the appropriate header & footer.
    242   static bool FormatPEMForFileOutput(const std::string& input,
    243                                      std::string* output,
    244                                      bool is_public);
    245 
    246   // Returns the base extension url for a given |extension_id|.
    247   static GURL GetBaseURLFromExtensionId(const ExtensionId& extension_id);
    248 
    249   // Whether context menu should be shown for page and browser actions.
    250   bool ShowConfigureContextMenus() const;
    251 
    252   // Returns true if this extension or app includes areas within |origin|.
    253   bool OverlapsWithOrigin(const GURL& origin) const;
    254 
    255   // Returns true if the extension requires a valid ordinal for sorting, e.g.,
    256   // for displaying in a launcher or new tab page.
    257   bool RequiresSortOrdinal() const;
    258 
    259   // Returns true if the extension should be displayed in the app launcher.
    260   bool ShouldDisplayInAppLauncher() const;
    261 
    262   // Returns true if the extension should be displayed in the browser NTP.
    263   bool ShouldDisplayInNewTabPage() const;
    264 
    265   // Returns true if the extension should be displayed in the extension
    266   // settings page (i.e. chrome://extensions).
    267   bool ShouldDisplayInExtensionSettings() const;
    268 
    269   // Returns true if the extension should not be shown anywhere. This is
    270   // mostly the same as the extension being a component extension, but also
    271   // includes non-component apps that are hidden from the app launcher and ntp.
    272   bool ShouldNotBeVisible() const;
    273 
    274   // Get the manifest data associated with the key, or NULL if there is none.
    275   // Can only be called after InitValue is finished.
    276   ManifestData* GetManifestData(const std::string& key) const;
    277 
    278   // Sets |data| to be associated with the key. Takes ownership of |data|.
    279   // Can only be called before InitValue is finished. Not thread-safe;
    280   // all SetManifestData calls should be on only one thread.
    281   void SetManifestData(const std::string& key, ManifestData* data);
    282 
    283   // Accessors:
    284 
    285   const base::FilePath& path() const { return path_; }
    286   const GURL& url() const { return extension_url_; }
    287   Manifest::Location location() const;
    288   const ExtensionId& id() const;
    289   const base::Version* version() const { return version_.get(); }
    290   const std::string VersionString() const;
    291   const std::string& name() const { return name_; }
    292   const std::string& short_name() const { return short_name_; }
    293   const std::string& non_localized_name() const { return non_localized_name_; }
    294   // Base64-encoded version of the key used to sign this extension.
    295   // In pseudocode, returns
    296   // base::Base64Encode(RSAPrivateKey(pem_file).ExportPublicKey()).
    297   const std::string& public_key() const { return public_key_; }
    298   const std::string& description() const { return description_; }
    299   int manifest_version() const { return manifest_version_; }
    300   bool converted_from_user_script() const {
    301     return converted_from_user_script_;
    302   }
    303   PermissionsParser* permissions_parser() { return permissions_parser_.get(); }
    304   const PermissionsParser* permissions_parser() const {
    305     return permissions_parser_.get();
    306   }
    307 
    308   const PermissionsData* permissions_data() const {
    309     return permissions_data_.get();
    310   }
    311 
    312   // Appends |new_warning[s]| to install_warnings_.
    313   void AddInstallWarning(const InstallWarning& new_warning);
    314   void AddInstallWarnings(const std::vector<InstallWarning>& new_warnings);
    315   const std::vector<InstallWarning>& install_warnings() const {
    316     return install_warnings_;
    317   }
    318   const extensions::Manifest* manifest() const {
    319     return manifest_.get();
    320   }
    321   bool wants_file_access() const { return wants_file_access_; }
    322   // TODO(rdevlin.cronin): This is needed for ContentScriptsHandler, and should
    323   // be moved out as part of crbug.com/159265. This should not be used anywhere
    324   // else.
    325   void set_wants_file_access(bool wants_file_access) {
    326     wants_file_access_ = wants_file_access;
    327   }
    328   int creation_flags() const { return creation_flags_; }
    329   bool from_webstore() const { return (creation_flags_ & FROM_WEBSTORE) != 0; }
    330   bool from_bookmark() const { return (creation_flags_ & FROM_BOOKMARK) != 0; }
    331   bool was_installed_by_default() const {
    332     return (creation_flags_ & WAS_INSTALLED_BY_DEFAULT) != 0;
    333   }
    334   bool was_installed_by_oem() const {
    335     return (creation_flags_ & WAS_INSTALLED_BY_OEM) != 0;
    336   }
    337 
    338   // App-related.
    339   bool is_app() const;
    340   bool is_platform_app() const;
    341   bool is_hosted_app() const;
    342   bool is_legacy_packaged_app() const;
    343   bool is_extension() const;
    344   bool can_be_incognito_enabled() const;
    345 
    346   void AddWebExtentPattern(const URLPattern& pattern);
    347   const URLPatternSet& web_extent() const { return extent_; }
    348 
    349   // Theme-related.
    350   bool is_theme() const;
    351 
    352  private:
    353   friend class base::RefCountedThreadSafe<Extension>;
    354 
    355   // Chooses the extension ID for an extension based on a variety of criteria.
    356   // The chosen ID will be set in |manifest|.
    357   static bool InitExtensionID(extensions::Manifest* manifest,
    358                               const base::FilePath& path,
    359                               const ExtensionId& explicit_id,
    360                               int creation_flags,
    361                               base::string16* error);
    362 
    363   Extension(const base::FilePath& path,
    364             scoped_ptr<extensions::Manifest> manifest);
    365   virtual ~Extension();
    366 
    367   // Initialize the extension from a parsed manifest.
    368   // TODO(aa): Rename to just Init()? There's no Value here anymore.
    369   // TODO(aa): It is really weird the way this class essentially contains a copy
    370   // of the underlying DictionaryValue in its members. We should decide to
    371   // either wrap the DictionaryValue and go with that only, or we should parse
    372   // into strong types and discard the value. But doing both is bad.
    373   bool InitFromValue(int flags, base::string16* error);
    374 
    375   // The following are helpers for InitFromValue to load various features of the
    376   // extension from the manifest.
    377 
    378   bool LoadRequiredFeatures(base::string16* error);
    379   bool LoadName(base::string16* error);
    380   bool LoadVersion(base::string16* error);
    381 
    382   bool LoadAppFeatures(base::string16* error);
    383   bool LoadExtent(const char* key,
    384                   URLPatternSet* extent,
    385                   const char* list_error,
    386                   const char* value_error,
    387                   base::string16* error);
    388 
    389   bool LoadSharedFeatures(base::string16* error);
    390   bool LoadDescription(base::string16* error);
    391   bool LoadManifestVersion(base::string16* error);
    392   bool LoadShortName(base::string16* error);
    393 
    394   bool CheckMinimumChromeVersion(base::string16* error) const;
    395 
    396   // The extension's human-readable name. Name is used for display purpose. It
    397   // might be wrapped with unicode bidi control characters so that it is
    398   // displayed correctly in RTL context.
    399   // NOTE: Name is UTF-8 and may contain non-ascii characters.
    400   std::string name_;
    401 
    402   // A non-localized version of the extension's name. This is useful for
    403   // debug output.
    404   std::string non_localized_name_;
    405 
    406   // A short version of the extension's name. This can be used as an alternative
    407   // to the name where there is insufficient space to display the full name. If
    408   // an extension has not explicitly specified a short name, the value of this
    409   // member variable will be the full name rather than an empty string.
    410   std::string short_name_;
    411 
    412   // The version of this extension's manifest. We increase the manifest
    413   // version when making breaking changes to the extension system.
    414   // Version 1 was the first manifest version (implied by a lack of a
    415   // manifest_version attribute in the extension's manifest). We initialize
    416   // this member variable to 0 to distinguish the "uninitialized" case from
    417   // the case when we know the manifest version actually is 1.
    418   int manifest_version_;
    419 
    420   // The absolute path to the directory the extension is stored in.
    421   base::FilePath path_;
    422 
    423   // Defines the set of URLs in the extension's web content.
    424   URLPatternSet extent_;
    425 
    426   // The parser for the manifest's permissions. This is NULL anytime not during
    427   // initialization.
    428   // TODO(rdevlin.cronin): This doesn't really belong here.
    429   scoped_ptr<PermissionsParser> permissions_parser_;
    430 
    431   // The active permissions for the extension.
    432   scoped_ptr<PermissionsData> permissions_data_;
    433 
    434   // Any warnings that occurred when trying to create/parse the extension.
    435   std::vector<InstallWarning> install_warnings_;
    436 
    437   // The base extension url for the extension.
    438   GURL extension_url_;
    439 
    440   // The extension's version.
    441   scoped_ptr<base::Version> version_;
    442 
    443   // An optional longer description of the extension.
    444   std::string description_;
    445 
    446   // True if the extension was generated from a user script. (We show slightly
    447   // different UI if so).
    448   bool converted_from_user_script_;
    449 
    450   // The public key used to sign the contents of the crx package.
    451   std::string public_key_;
    452 
    453   // The manifest from which this extension was created.
    454   scoped_ptr<Manifest> manifest_;
    455 
    456   // Stored parsed manifest data.
    457   ManifestDataMap manifest_data_;
    458 
    459   // Set to true at the end of InitValue when initialization is finished.
    460   bool finished_parsing_manifest_;
    461 
    462   // Ensures that any call to GetManifestData() prior to finishing
    463   // initialization happens from the same thread (this can happen when certain
    464   // parts of the initialization process need information from previous parts).
    465   base::ThreadChecker thread_checker_;
    466 
    467   // Should this app be shown in the app launcher.
    468   bool display_in_launcher_;
    469 
    470   // Should this app be shown in the browser New Tab Page.
    471   bool display_in_new_tab_page_;
    472 
    473   // Whether the extension has host permissions or user script patterns that
    474   // imply access to file:/// scheme URLs (the user may not have actually
    475   // granted it that access).
    476   bool wants_file_access_;
    477 
    478   // The flags that were passed to InitFromValue.
    479   int creation_flags_;
    480 
    481   DISALLOW_COPY_AND_ASSIGN(Extension);
    482 };
    483 
    484 typedef std::vector<scoped_refptr<const Extension> > ExtensionList;
    485 typedef std::set<ExtensionId> ExtensionIdSet;
    486 typedef std::vector<ExtensionId> ExtensionIdList;
    487 
    488 // Handy struct to pass core extension info around.
    489 struct ExtensionInfo {
    490   ExtensionInfo(const base::DictionaryValue* manifest,
    491                 const ExtensionId& id,
    492                 const base::FilePath& path,
    493                 Manifest::Location location);
    494   ~ExtensionInfo();
    495 
    496   scoped_ptr<base::DictionaryValue> extension_manifest;
    497   ExtensionId extension_id;
    498   base::FilePath extension_path;
    499   Manifest::Location extension_location;
    500 
    501  private:
    502   DISALLOW_COPY_AND_ASSIGN(ExtensionInfo);
    503 };
    504 
    505 struct InstalledExtensionInfo {
    506   // The extension being installed - this should always be non-NULL.
    507   const Extension* extension;
    508 
    509   // True if the extension is being updated; false if it is being installed.
    510   bool is_update;
    511 
    512   // True if the extension was previously installed ephemerally and is now
    513   // a regular installed extension.
    514   bool from_ephemeral;
    515 
    516   // The name of the extension prior to this update. Will be empty if
    517   // |is_update| is false.
    518   std::string old_name;
    519 
    520   InstalledExtensionInfo(const Extension* extension,
    521                          bool is_update,
    522                          bool from_ephemeral,
    523                          const std::string& old_name);
    524 };
    525 
    526 struct UnloadedExtensionInfo {
    527   // TODO(DHNishi): Move this enum to ExtensionRegistryObserver.
    528   enum Reason {
    529     REASON_UNDEFINED,         // Undefined state used to initialize variables.
    530     REASON_DISABLE,           // Extension is being disabled.
    531     REASON_UPDATE,            // Extension is being updated to a newer version.
    532     REASON_UNINSTALL,         // Extension is being uninstalled.
    533     REASON_TERMINATE,         // Extension has terminated.
    534     REASON_BLACKLIST,         // Extension has been blacklisted.
    535     REASON_PROFILE_SHUTDOWN,  // Profile is being shut down.
    536   };
    537 
    538   Reason reason;
    539 
    540   // The extension being unloaded - this should always be non-NULL.
    541   const Extension* extension;
    542 
    543   UnloadedExtensionInfo(const Extension* extension, Reason reason);
    544 };
    545 
    546 // The details sent for EXTENSION_PERMISSIONS_UPDATED notifications.
    547 struct UpdatedExtensionPermissionsInfo {
    548   enum Reason {
    549     ADDED,    // The permissions were added to the extension.
    550     REMOVED,  // The permissions were removed from the extension.
    551   };
    552 
    553   Reason reason;
    554 
    555   // The extension who's permissions have changed.
    556   const Extension* extension;
    557 
    558   // The permissions that have changed. For Reason::ADDED, this would contain
    559   // only the permissions that have added, and for Reason::REMOVED, this would
    560   // only contain the removed permissions.
    561   const PermissionSet* permissions;
    562 
    563   UpdatedExtensionPermissionsInfo(
    564       const Extension* extension,
    565       const PermissionSet* permissions,
    566       Reason reason);
    567 };
    568 
    569 }  // namespace extensions
    570 
    571 #endif  // EXTENSIONS_COMMON_EXTENSION_H_
    572