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