Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / extensions / common / extension.h
blobc8d169090d605a003a97e610926fbc5297dd9e6f
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.
5 #ifndef EXTENSIONS_COMMON_EXTENSION_H_
6 #define EXTENSIONS_COMMON_EXTENSION_H_
8 #include <algorithm>
9 #include <iosfwd>
10 #include <map>
11 #include <set>
12 #include <string>
13 #include <utility>
14 #include <vector>
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 "url/gurl.h"
30 #if !defined(ENABLE_EXTENSIONS)
31 #error "Extensions must be enabled"
32 #endif
34 namespace base {
35 class DictionaryValue;
36 class Version;
39 namespace extensions {
40 class PermissionSet;
41 class PermissionsData;
42 class PermissionsParser;
44 // Uniquely identifies an Extension, using 32 characters from the alphabet
45 // 'a'-'p'. An empty string represents "no extension".
47 // Note: If this gets used heavily in files that don't otherwise need to include
48 // extension.h, we should pull it into a dedicated header.
49 typedef std::string ExtensionId;
51 // Represents a Chrome extension.
52 // Once created, an Extension object is immutable, with the exception of its
53 // RuntimeData. This makes it safe to use on any thread, since access to the
54 // RuntimeData is protected by a lock.
55 class Extension : public base::RefCountedThreadSafe<Extension> {
56 public:
57 struct ManifestData;
59 typedef std::map<const std::string, linked_ptr<ManifestData> >
60 ManifestDataMap;
62 enum State {
63 DISABLED = 0,
64 ENABLED,
65 // An external extension that the user uninstalled. We should not reinstall
66 // such extensions on startup.
67 EXTERNAL_EXTENSION_UNINSTALLED,
68 // DEPRECATED: Special state for component extensions.
69 // Maintained as a placeholder since states may be stored to disk.
70 ENABLED_COMPONENT_DEPRECATED,
71 // Add new states here as this enum is stored in prefs.
72 NUM_STATES
75 // Used to record the reason an extension was disabled.
76 enum DeprecatedDisableReason {
77 DEPRECATED_DISABLE_UNKNOWN,
78 DEPRECATED_DISABLE_USER_ACTION,
79 DEPRECATED_DISABLE_PERMISSIONS_INCREASE,
80 DEPRECATED_DISABLE_RELOAD,
81 DEPRECATED_DISABLE_LAST, // Not used.
84 // Reasons an extension may be disabled. These are used in histograms, so do
85 // not remove/reorder entries - only add at the end just before
86 // DISABLE_REASON_LAST (and update the shift value for it). Also remember to
87 // update the enum listing in tools/metrics/histograms.xml.
88 enum DisableReason {
89 DISABLE_NONE = 0,
90 DISABLE_USER_ACTION = 1 << 0,
91 DISABLE_PERMISSIONS_INCREASE = 1 << 1,
92 DISABLE_RELOAD = 1 << 2,
93 DISABLE_UNSUPPORTED_REQUIREMENT = 1 << 3,
94 DISABLE_SIDELOAD_WIPEOUT = 1 << 4,
95 DISABLE_UNKNOWN_FROM_SYNC = 1 << 5,
96 // DISABLE_PERMISSIONS_CONSENT = 1 << 6, // Deprecated.
97 // DISABLE_KNOWN_DISABLED = 1 << 7, // Deprecated.
98 DISABLE_NOT_VERIFIED = 1 << 8, // Disabled because we could not verify
99 // the install.
100 DISABLE_GREYLIST = 1 << 9,
101 DISABLE_CORRUPTED = 1 << 10,
102 DISABLE_REMOTE_INSTALL = 1 << 11,
103 DISABLE_INACTIVE_EPHEMERAL_APP = 1 << 12, // Cached ephemeral apps are
104 // disabled to prevent activity.
105 DISABLE_EXTERNAL_EXTENSION = 1 << 13, // External extensions might be
106 // disabled for user prompting.
107 DISABLE_UPDATE_REQUIRED_BY_POLICY = 1 << 14, // Doesn't meet minimum
108 // version requirement.
109 DISABLE_REASON_LAST = 1 << 15, // This should always be the last value
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() {}
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,
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,
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,
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,
140 // |FROM_WEBSTORE| indicates that the extension was installed from the
141 // Chrome Web Store.
142 FROM_WEBSTORE = 1 << 3,
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,
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,
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,
158 // |WAS_INSTALLED_BY_DEFAULT| installed by default when the profile was
159 // created.
160 WAS_INSTALLED_BY_DEFAULT = 1 << 7,
162 // Unused - was part of an abandoned experiment.
163 REQUIRE_PERMISSIONS_CONSENT = 1 << 8,
165 // Unused - this flag has been moved to ExtensionPrefs.
166 IS_EPHEMERAL = 1 << 9,
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,
173 // |WAS_INSTALLED_BY_CUSTODIAN| means this extension was installed by the
174 // custodian of a supervised user.
175 WAS_INSTALLED_BY_CUSTODIAN = 1 << 11,
177 // |MAY_BE_UNTRUSTED| indicates that this extension came from a potentially
178 // unsafe source (e.g., sideloaded from a local CRX file via the Windows
179 // registry). Such extensions may be subjected to additional constraints
180 // before they are fully installed and enabled.
181 MAY_BE_UNTRUSTED = 1 << 12,
183 // When adding new flags, make sure to update kInitFromValueFlagBits.
186 // This is the highest bit index of the flags defined above.
187 static const int kInitFromValueFlagBits;
189 static scoped_refptr<Extension> Create(const base::FilePath& path,
190 Manifest::Location location,
191 const base::DictionaryValue& value,
192 int flags,
193 std::string* error);
195 // In a few special circumstances, we want to create an Extension and give it
196 // an explicit id. Most consumers should just use the other Create() method.
197 static scoped_refptr<Extension> Create(const base::FilePath& path,
198 Manifest::Location location,
199 const base::DictionaryValue& value,
200 int flags,
201 const ExtensionId& explicit_id,
202 std::string* error);
204 // Valid schemes for web extent URLPatterns.
205 static const int kValidWebExtentSchemes;
207 // Valid schemes for host permission URLPatterns.
208 static const int kValidHostPermissionSchemes;
210 // The mimetype used for extensions.
211 static const char kMimeType[];
213 // See Type definition in Manifest.
214 Manifest::Type GetType() const;
216 // Returns an absolute url to a resource inside of an extension. The
217 // |extension_url| argument should be the url() from an Extension object. The
218 // |relative_path| can be untrusted user input. The returned URL will either
219 // be invalid() or a child of |extension_url|.
220 // NOTE: Static so that it can be used from multiple threads.
221 static GURL GetResourceURL(const GURL& extension_url,
222 const std::string& relative_path);
223 GURL GetResourceURL(const std::string& relative_path) const {
224 return GetResourceURL(url(), relative_path);
227 // Returns true if the resource matches a pattern in the pattern_set.
228 bool ResourceMatches(const URLPatternSet& pattern_set,
229 const std::string& resource) const;
231 // Returns an extension resource object. |relative_path| should be UTF8
232 // encoded.
233 ExtensionResource GetResource(const std::string& relative_path) const;
235 // As above, but with |relative_path| following the file system's encoding.
236 ExtensionResource GetResource(const base::FilePath& relative_path) const;
238 // |input| is expected to be the text of an rsa public or private key. It
239 // tolerates the presence or absence of bracking header/footer like this:
240 // -----(BEGIN|END) [RSA PUBLIC/PRIVATE] KEY-----
241 // and may contain newlines.
242 static bool ParsePEMKeyBytes(const std::string& input, std::string* output);
244 // Does a simple base64 encoding of |input| into |output|.
245 static bool ProducePEM(const std::string& input, std::string* output);
247 // Expects base64 encoded |input| and formats into |output| including
248 // the appropriate header & footer.
249 static bool FormatPEMForFileOutput(const std::string& input,
250 std::string* output,
251 bool is_public);
253 // Returns the base extension url for a given |extension_id|.
254 static GURL GetBaseURLFromExtensionId(const ExtensionId& extension_id);
256 // Whether context menu should be shown for page and browser actions.
257 bool ShowConfigureContextMenus() const;
259 // Returns true if this extension or app includes areas within |origin|.
260 bool OverlapsWithOrigin(const GURL& origin) const;
262 // Returns true if the extension requires a valid ordinal for sorting, e.g.,
263 // for displaying in a launcher or new tab page.
264 bool RequiresSortOrdinal() const;
266 // Returns true if the extension should be displayed in the app launcher.
267 bool ShouldDisplayInAppLauncher() const;
269 // Returns true if the extension should be displayed in the browser NTP.
270 bool ShouldDisplayInNewTabPage() const;
272 // Returns true if the extension should be displayed in the extension
273 // settings page (i.e. chrome://extensions).
274 bool ShouldDisplayInExtensionSettings() const;
276 // Returns true if the extension should not be shown anywhere. This is
277 // mostly the same as the extension being a component extension, but also
278 // includes non-component apps that are hidden from the app launcher and ntp.
279 bool ShouldNotBeVisible() const;
281 // Get the manifest data associated with the key, or NULL if there is none.
282 // Can only be called after InitValue is finished.
283 ManifestData* GetManifestData(const std::string& key) const;
285 // Sets |data| to be associated with the key. Takes ownership of |data|.
286 // Can only be called before InitValue is finished. Not thread-safe;
287 // all SetManifestData calls should be on only one thread.
288 void SetManifestData(const std::string& key, ManifestData* data);
290 // Accessors:
292 const base::FilePath& path() const { return path_; }
293 const GURL& url() const { return extension_url_; }
294 Manifest::Location location() const;
295 const ExtensionId& id() const;
296 const base::Version* version() const { return version_.get(); }
297 const std::string VersionString() const;
298 const std::string GetVersionForDisplay() const;
299 const std::string& name() const { return name_; }
300 const std::string& short_name() const { return short_name_; }
301 const std::string& non_localized_name() const { return non_localized_name_; }
302 // Base64-encoded version of the key used to sign this extension.
303 // In pseudocode, returns
304 // base::Base64Encode(RSAPrivateKey(pem_file).ExportPublicKey()).
305 const std::string& public_key() const { return public_key_; }
306 const std::string& description() const { return description_; }
307 int manifest_version() const { return manifest_version_; }
308 bool converted_from_user_script() const {
309 return converted_from_user_script_;
311 PermissionsParser* permissions_parser() { return permissions_parser_.get(); }
312 const PermissionsParser* permissions_parser() const {
313 return permissions_parser_.get();
316 const PermissionsData* permissions_data() const {
317 return permissions_data_.get();
320 // Appends |new_warning[s]| to install_warnings_.
321 void AddInstallWarning(const InstallWarning& new_warning);
322 void AddInstallWarnings(const std::vector<InstallWarning>& new_warnings);
323 const std::vector<InstallWarning>& install_warnings() const {
324 return install_warnings_;
326 const extensions::Manifest* manifest() const {
327 return manifest_.get();
329 bool wants_file_access() const { return wants_file_access_; }
330 // TODO(rdevlin.cronin): This is needed for ContentScriptsHandler, and should
331 // be moved out as part of crbug.com/159265. This should not be used anywhere
332 // else.
333 void set_wants_file_access(bool wants_file_access) {
334 wants_file_access_ = wants_file_access;
336 int creation_flags() const { return creation_flags_; }
337 bool from_webstore() const { return (creation_flags_ & FROM_WEBSTORE) != 0; }
338 bool from_bookmark() const { return (creation_flags_ & FROM_BOOKMARK) != 0; }
339 bool was_installed_by_default() const {
340 return (creation_flags_ & WAS_INSTALLED_BY_DEFAULT) != 0;
342 bool was_installed_by_oem() const {
343 return (creation_flags_ & WAS_INSTALLED_BY_OEM) != 0;
345 bool was_installed_by_custodian() const {
346 return (creation_flags_ & WAS_INSTALLED_BY_CUSTODIAN) != 0;
349 // Type-related queries.
350 bool is_app() const;
351 bool is_platform_app() const;
352 bool is_hosted_app() const;
353 bool is_legacy_packaged_app() const;
354 bool is_extension() const;
355 bool is_shared_module() const;
356 bool is_theme() const;
358 bool can_be_incognito_enabled() const;
360 void AddWebExtentPattern(const URLPattern& pattern);
361 const URLPatternSet& web_extent() const { return extent_; }
363 private:
364 friend class base::RefCountedThreadSafe<Extension>;
366 // Chooses the extension ID for an extension based on a variety of criteria.
367 // The chosen ID will be set in |manifest|.
368 static bool InitExtensionID(extensions::Manifest* manifest,
369 const base::FilePath& path,
370 const ExtensionId& explicit_id,
371 int creation_flags,
372 base::string16* error);
374 Extension(const base::FilePath& path,
375 scoped_ptr<extensions::Manifest> manifest);
376 virtual ~Extension();
378 // Initialize the extension from a parsed manifest.
379 // TODO(aa): Rename to just Init()? There's no Value here anymore.
380 // TODO(aa): It is really weird the way this class essentially contains a copy
381 // of the underlying DictionaryValue in its members. We should decide to
382 // either wrap the DictionaryValue and go with that only, or we should parse
383 // into strong types and discard the value. But doing both is bad.
384 bool InitFromValue(int flags, base::string16* error);
386 // The following are helpers for InitFromValue to load various features of the
387 // extension from the manifest.
389 bool LoadRequiredFeatures(base::string16* error);
390 bool LoadName(base::string16* error);
391 bool LoadVersion(base::string16* error);
393 bool LoadAppFeatures(base::string16* error);
394 bool LoadExtent(const char* key,
395 URLPatternSet* extent,
396 const char* list_error,
397 const char* value_error,
398 base::string16* error);
400 bool LoadSharedFeatures(base::string16* error);
401 bool LoadDescription(base::string16* error);
402 bool LoadManifestVersion(base::string16* error);
403 bool LoadShortName(base::string16* error);
405 bool CheckMinimumChromeVersion(base::string16* error) const;
407 // The extension's human-readable name. Name is used for display purpose. It
408 // might be wrapped with unicode bidi control characters so that it is
409 // displayed correctly in RTL context.
410 // NOTE: Name is UTF-8 and may contain non-ascii characters.
411 std::string name_;
413 // A non-localized version of the extension's name. This is useful for
414 // debug output.
415 std::string non_localized_name_;
417 // A short version of the extension's name. This can be used as an alternative
418 // to the name where there is insufficient space to display the full name. If
419 // an extension has not explicitly specified a short name, the value of this
420 // member variable will be the full name rather than an empty string.
421 std::string short_name_;
423 // The version of this extension's manifest. We increase the manifest
424 // version when making breaking changes to the extension system.
425 // Version 1 was the first manifest version (implied by a lack of a
426 // manifest_version attribute in the extension's manifest). We initialize
427 // this member variable to 0 to distinguish the "uninitialized" case from
428 // the case when we know the manifest version actually is 1.
429 int manifest_version_;
431 // The absolute path to the directory the extension is stored in.
432 base::FilePath path_;
434 // Defines the set of URLs in the extension's web content.
435 URLPatternSet extent_;
437 // The parser for the manifest's permissions. This is NULL anytime not during
438 // initialization.
439 // TODO(rdevlin.cronin): This doesn't really belong here.
440 scoped_ptr<PermissionsParser> permissions_parser_;
442 // The active permissions for the extension.
443 scoped_ptr<PermissionsData> permissions_data_;
445 // Any warnings that occurred when trying to create/parse the extension.
446 std::vector<InstallWarning> install_warnings_;
448 // The base extension url for the extension.
449 GURL extension_url_;
451 // The extension's version.
452 scoped_ptr<base::Version> version_;
454 // The extension's user visible version name.
455 std::string version_name_;
457 // An optional longer description of the extension.
458 std::string description_;
460 // True if the extension was generated from a user script. (We show slightly
461 // different UI if so).
462 bool converted_from_user_script_;
464 // The public key used to sign the contents of the crx package.
465 std::string public_key_;
467 // The manifest from which this extension was created.
468 scoped_ptr<Manifest> manifest_;
470 // Stored parsed manifest data.
471 ManifestDataMap manifest_data_;
473 // Set to true at the end of InitValue when initialization is finished.
474 bool finished_parsing_manifest_;
476 // Ensures that any call to GetManifestData() prior to finishing
477 // initialization happens from the same thread (this can happen when certain
478 // parts of the initialization process need information from previous parts).
479 base::ThreadChecker thread_checker_;
481 // Should this app be shown in the app launcher.
482 bool display_in_launcher_;
484 // Should this app be shown in the browser New Tab Page.
485 bool display_in_new_tab_page_;
487 // Whether the extension has host permissions or user script patterns that
488 // imply access to file:/// scheme URLs (the user may not have actually
489 // granted it that access).
490 bool wants_file_access_;
492 // The flags that were passed to InitFromValue.
493 int creation_flags_;
495 DISALLOW_COPY_AND_ASSIGN(Extension);
498 typedef std::vector<scoped_refptr<const Extension> > ExtensionList;
499 typedef std::set<ExtensionId> ExtensionIdSet;
500 typedef std::vector<ExtensionId> ExtensionIdList;
502 // Handy struct to pass core extension info around.
503 struct ExtensionInfo {
504 ExtensionInfo(const base::DictionaryValue* manifest,
505 const ExtensionId& id,
506 const base::FilePath& path,
507 Manifest::Location location);
508 ~ExtensionInfo();
510 scoped_ptr<base::DictionaryValue> extension_manifest;
511 ExtensionId extension_id;
512 base::FilePath extension_path;
513 Manifest::Location extension_location;
515 private:
516 DISALLOW_COPY_AND_ASSIGN(ExtensionInfo);
519 struct InstalledExtensionInfo {
520 // The extension being installed - this should always be non-NULL.
521 const Extension* extension;
523 // True if the extension is being updated; false if it is being installed.
524 bool is_update;
526 // True if the extension was previously installed ephemerally and is now
527 // a regular installed extension.
528 bool from_ephemeral;
530 // The name of the extension prior to this update. Will be empty if
531 // |is_update| is false.
532 std::string old_name;
534 InstalledExtensionInfo(const Extension* extension,
535 bool is_update,
536 bool from_ephemeral,
537 const std::string& old_name);
540 struct UnloadedExtensionInfo {
541 // TODO(DHNishi): Move this enum to ExtensionRegistryObserver.
542 enum Reason {
543 REASON_UNDEFINED, // Undefined state used to initialize variables.
544 REASON_DISABLE, // Extension is being disabled.
545 REASON_UPDATE, // Extension is being updated to a newer version.
546 REASON_UNINSTALL, // Extension is being uninstalled.
547 REASON_TERMINATE, // Extension has terminated.
548 REASON_BLACKLIST, // Extension has been blacklisted.
549 REASON_PROFILE_SHUTDOWN, // Profile is being shut down.
550 REASON_LOCK_ALL, // All extensions for the profile are blocked.
553 Reason reason;
555 // The extension being unloaded - this should always be non-NULL.
556 const Extension* extension;
558 UnloadedExtensionInfo(const Extension* extension, Reason reason);
561 // The details sent for EXTENSION_PERMISSIONS_UPDATED notifications.
562 struct UpdatedExtensionPermissionsInfo {
563 enum Reason {
564 ADDED, // The permissions were added to the extension.
565 REMOVED, // The permissions were removed from the extension.
568 Reason reason;
570 // The extension who's permissions have changed.
571 const Extension* extension;
573 // The permissions that have changed. For Reason::ADDED, this would contain
574 // only the permissions that have added, and for Reason::REMOVED, this would
575 // only contain the removed permissions.
576 const PermissionSet* permissions;
578 UpdatedExtensionPermissionsInfo(
579 const Extension* extension,
580 const PermissionSet* permissions,
581 Reason reason);
584 } // namespace extensions
586 #endif // EXTENSIONS_COMMON_EXTENSION_H_