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